context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
#if MS_IO_REDIST
using Microsoft.IO.Enumeration;
namespace Microsoft.IO
#else
using System.IO.Enumeration;
namespace System.IO
#endif
{
public sealed partial class DirectoryInfo : FileSystemInfo
{
private bool _isNormalized;
public DirectoryInfo(string path)
{
Init(originalPath: path,
fullPath: Path.GetFullPath(path),
isNormalized: true);
}
internal DirectoryInfo(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
{
Init(originalPath, fullPath, fileName, isNormalized);
}
private void Init(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
{
// Want to throw the original argument name
OriginalPath = originalPath ?? throw new ArgumentNullException("path");
fullPath = fullPath ?? originalPath;
fullPath = isNormalized ? fullPath : Path.GetFullPath(fullPath);
_name = fileName ?? (PathInternal.IsRoot(fullPath.AsSpan()) ?
fullPath.AsSpan() :
Path.GetFileName(Path.TrimEndingDirectorySeparator(fullPath.AsSpan()))).ToString();
FullPath = fullPath;
_isNormalized = isNormalized;
}
public DirectoryInfo Parent
{
get
{
// FullPath might end in either "parent\child" or "parent\child\", and in either case we want
// the parent of child, not the child. Trim off an ending directory separator if there is one,
// but don't mangle the root.
string parentName = Path.GetDirectoryName(PathInternal.IsRoot(FullPath.AsSpan()) ? FullPath : Path.TrimEndingDirectorySeparator(FullPath));
return parentName != null ?
new DirectoryInfo(parentName, isNormalized: true) :
null;
}
}
public DirectoryInfo CreateSubdirectory(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (PathInternal.IsEffectivelyEmpty(path.AsSpan()))
throw new ArgumentException(SR.Argument_PathEmpty, nameof(path));
if (Path.IsPathRooted(path))
throw new ArgumentException(SR.Arg_Path2IsRooted, nameof(path));
string newPath = Path.GetFullPath(Path.Combine(FullPath, path));
ReadOnlySpan<char> trimmedNewPath = Path.TrimEndingDirectorySeparator(newPath.AsSpan());
ReadOnlySpan<char> trimmedCurrentPath = Path.TrimEndingDirectorySeparator(FullPath.AsSpan());
// We want to make sure the requested directory is actually under the subdirectory.
if (trimmedNewPath.StartsWith(trimmedCurrentPath, PathInternal.StringComparison)
// Allow the exact same path, but prevent allowing "..\FooBar" through when the directory is "Foo"
&& ((trimmedNewPath.Length == trimmedCurrentPath.Length) || PathInternal.IsDirectorySeparator(newPath[trimmedCurrentPath.Length])))
{
FileSystem.CreateDirectory(newPath);
return new DirectoryInfo(newPath);
}
// We weren't nested
throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, FullPath), nameof(path));
}
public void Create()
{
FileSystem.CreateDirectory(FullPath);
Invalidate();
}
// Returns an array of Files in the DirectoryInfo specified by path
public FileInfo[] GetFiles() => GetFiles("*", enumerationOptions: EnumerationOptions.Compatible);
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
public FileInfo[] GetFiles(string searchPattern) => GetFiles(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption)
=> GetFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public FileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions)
=> ((IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions)).ToArray();
// Returns an array of strongly typed FileSystemInfo entries which will contain a listing
// of all the files and directories.
public FileSystemInfo[] GetFileSystemInfos() => GetFileSystemInfos("*", enumerationOptions: EnumerationOptions.Compatible);
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
public FileSystemInfo[] GetFileSystemInfos(string searchPattern)
=> GetFileSystemInfos(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption)
=> GetFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public FileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions).ToArray();
// Returns an array of Directories in the current directory.
public DirectoryInfo[] GetDirectories() => GetDirectories("*", enumerationOptions: EnumerationOptions.Compatible);
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32 directories).
public DirectoryInfo[] GetDirectories(string searchPattern) => GetDirectories(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption)
=> GetDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public DirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions)
=> ((IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Directories, enumerationOptions)).ToArray();
public IEnumerable<DirectoryInfo> EnumerateDirectories()
=> EnumerateDirectories("*", enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern)
=> EnumerateDirectories(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption)
=> EnumerateDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions)
=> (IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Directories, enumerationOptions);
public IEnumerable<FileInfo> EnumerateFiles()
=> EnumerateFiles("*", enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern) => EnumerateFiles(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption)
=> EnumerateFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions)
=> (IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions);
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() => EnumerateFileSystemInfos("*", enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern)
=> EnumerateFileSystemInfos(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption)
=> EnumerateFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions);
private IEnumerable<FileSystemInfo> InternalEnumerateInfos(
string path,
string searchPattern,
SearchTarget searchTarget,
EnumerationOptions options)
{
Debug.Assert(path != null);
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
_isNormalized &= FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options.MatchType);
return searchTarget switch
{
SearchTarget.Directories => FileSystemEnumerableFactory.DirectoryInfos(path, searchPattern, options, _isNormalized),
SearchTarget.Files => FileSystemEnumerableFactory.FileInfos(path, searchPattern, options, _isNormalized),
SearchTarget.Both => FileSystemEnumerableFactory.FileSystemInfos(path, searchPattern, options, _isNormalized),
_ => throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget)),
};
}
public DirectoryInfo Root => new DirectoryInfo(Path.GetPathRoot(FullPath));
public void MoveTo(string destDirName)
{
if (destDirName == null)
throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName));
string destination = Path.GetFullPath(destDirName);
string destinationWithSeparator = PathInternal.EnsureTrailingSeparator(destination);
string sourceWithSeparator = PathInternal.EnsureTrailingSeparator(FullPath);
if (string.Equals(sourceWithSeparator, destinationWithSeparator, PathInternal.StringComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
string sourceRoot = Path.GetPathRoot(sourceWithSeparator);
string destinationRoot = Path.GetPathRoot(destinationWithSeparator);
if (!string.Equals(sourceRoot, destinationRoot, PathInternal.StringComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
// Windows will throw if the source file/directory doesn't exist, we preemptively check
// to make sure our cross platform behavior matches NetFX behavior.
if (!Exists && !FileSystem.FileExists(FullPath))
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath));
if (FileSystem.DirectoryExists(destination))
throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator));
FileSystem.MoveDirectory(FullPath, destination);
Init(originalPath: destDirName,
fullPath: destinationWithSeparator,
fileName: null,
isNormalized: true);
// Flush any cached information about the directory.
Invalidate();
}
public override void Delete() => FileSystem.RemoveDirectory(FullPath, recursive: false);
public void Delete(bool recursive) => FileSystem.RemoveDirectory(FullPath, recursive);
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Trace.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Trace.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>Generated snippets</summary>
public class GeneratedTraceServiceClientSnippets
{
/// <summary>Snippet for PatchTracesAsync</summary>
public async Task PatchTracesAsync()
{
// Snippet: PatchTracesAsync(string,Traces,CallSettings)
// Additional: PatchTracesAsync(string,Traces,CancellationToken)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
Traces traces = new Traces();
// Make the request
await traceServiceClient.PatchTracesAsync(projectId, traces);
// End snippet
}
/// <summary>Snippet for PatchTraces</summary>
public void PatchTraces()
{
// Snippet: PatchTraces(string,Traces,CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
string projectId = "";
Traces traces = new Traces();
// Make the request
traceServiceClient.PatchTraces(projectId, traces);
// End snippet
}
/// <summary>Snippet for PatchTracesAsync</summary>
public async Task PatchTracesAsync_RequestObject()
{
// Snippet: PatchTracesAsync(PatchTracesRequest,CallSettings)
// Additional: PatchTracesAsync(PatchTracesRequest,CancellationToken)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
PatchTracesRequest request = new PatchTracesRequest
{
ProjectId = "",
Traces = new Traces(),
};
// Make the request
await traceServiceClient.PatchTracesAsync(request);
// End snippet
}
/// <summary>Snippet for PatchTraces</summary>
public void PatchTraces_RequestObject()
{
// Snippet: PatchTraces(PatchTracesRequest,CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
PatchTracesRequest request = new PatchTracesRequest
{
ProjectId = "",
Traces = new Traces(),
};
// Make the request
traceServiceClient.PatchTraces(request);
// End snippet
}
/// <summary>Snippet for GetTraceAsync</summary>
public async Task GetTraceAsync()
{
// Snippet: GetTraceAsync(string,string,CallSettings)
// Additional: GetTraceAsync(string,string,CancellationToken)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
string traceId = "";
// Make the request
Trace response = await traceServiceClient.GetTraceAsync(projectId, traceId);
// End snippet
}
/// <summary>Snippet for GetTrace</summary>
public void GetTrace()
{
// Snippet: GetTrace(string,string,CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
string projectId = "";
string traceId = "";
// Make the request
Trace response = traceServiceClient.GetTrace(projectId, traceId);
// End snippet
}
/// <summary>Snippet for GetTraceAsync</summary>
public async Task GetTraceAsync_RequestObject()
{
// Snippet: GetTraceAsync(GetTraceRequest,CallSettings)
// Additional: GetTraceAsync(GetTraceRequest,CancellationToken)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
GetTraceRequest request = new GetTraceRequest
{
ProjectId = "",
TraceId = "",
};
// Make the request
Trace response = await traceServiceClient.GetTraceAsync(request);
// End snippet
}
/// <summary>Snippet for GetTrace</summary>
public void GetTrace_RequestObject()
{
// Snippet: GetTrace(GetTraceRequest,CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
GetTraceRequest request = new GetTraceRequest
{
ProjectId = "",
TraceId = "",
};
// Make the request
Trace response = traceServiceClient.GetTrace(request);
// End snippet
}
/// <summary>Snippet for ListTracesAsync</summary>
public async Task ListTracesAsync()
{
// Snippet: ListTracesAsync(string,string,int?,CallSettings)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
// Make the request
PagedAsyncEnumerable<ListTracesResponse, Trace> response =
traceServiceClient.ListTracesAsync(projectId);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Trace item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTracesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trace item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trace> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trace item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTraces</summary>
public void ListTraces()
{
// Snippet: ListTraces(string,string,int?,CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
string projectId = "";
// Make the request
PagedEnumerable<ListTracesResponse, Trace> response =
traceServiceClient.ListTraces(projectId);
// Iterate over all response items, lazily performing RPCs as required
foreach (Trace item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTracesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trace item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trace> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trace item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTracesAsync</summary>
public async Task ListTracesAsync_RequestObject()
{
// Snippet: ListTracesAsync(ListTracesRequest,CallSettings)
// Create client
TraceServiceClient traceServiceClient = await TraceServiceClient.CreateAsync();
// Initialize request argument(s)
ListTracesRequest request = new ListTracesRequest
{
ProjectId = "",
};
// Make the request
PagedAsyncEnumerable<ListTracesResponse, Trace> response =
traceServiceClient.ListTracesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Trace item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTracesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trace item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trace> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trace item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTraces</summary>
public void ListTraces_RequestObject()
{
// Snippet: ListTraces(ListTracesRequest,CallSettings)
// Create client
TraceServiceClient traceServiceClient = TraceServiceClient.Create();
// Initialize request argument(s)
ListTracesRequest request = new ListTracesRequest
{
ProjectId = "",
};
// Make the request
PagedEnumerable<ListTracesResponse, Trace> response =
traceServiceClient.ListTraces(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Trace item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTracesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Trace item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Trace> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Trace item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V10.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="GoogleAdsFieldServiceClient"/> instances.</summary>
public sealed partial class GoogleAdsFieldServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="GoogleAdsFieldServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="GoogleAdsFieldServiceSettings"/>.</returns>
public static GoogleAdsFieldServiceSettings GetDefault() => new GoogleAdsFieldServiceSettings();
/// <summary>
/// Constructs a new <see cref="GoogleAdsFieldServiceSettings"/> object with default settings.
/// </summary>
public GoogleAdsFieldServiceSettings()
{
}
private GoogleAdsFieldServiceSettings(GoogleAdsFieldServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetGoogleAdsFieldSettings = existing.GetGoogleAdsFieldSettings;
SearchGoogleAdsFieldsSettings = existing.SearchGoogleAdsFieldsSettings;
OnCopy(existing);
}
partial void OnCopy(GoogleAdsFieldServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GoogleAdsFieldServiceClient.GetGoogleAdsField</c> and
/// <c>GoogleAdsFieldServiceClient.GetGoogleAdsFieldAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetGoogleAdsFieldSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GoogleAdsFieldServiceClient.SearchGoogleAdsFields</c> and
/// <c>GoogleAdsFieldServiceClient.SearchGoogleAdsFieldsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings SearchGoogleAdsFieldsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="GoogleAdsFieldServiceSettings"/> object.</returns>
public GoogleAdsFieldServiceSettings Clone() => new GoogleAdsFieldServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="GoogleAdsFieldServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class GoogleAdsFieldServiceClientBuilder : gaxgrpc::ClientBuilderBase<GoogleAdsFieldServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public GoogleAdsFieldServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public GoogleAdsFieldServiceClientBuilder()
{
UseJwtAccessWithScopes = GoogleAdsFieldServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref GoogleAdsFieldServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<GoogleAdsFieldServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override GoogleAdsFieldServiceClient Build()
{
GoogleAdsFieldServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<GoogleAdsFieldServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<GoogleAdsFieldServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private GoogleAdsFieldServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return GoogleAdsFieldServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<GoogleAdsFieldServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return GoogleAdsFieldServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => GoogleAdsFieldServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => GoogleAdsFieldServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => GoogleAdsFieldServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>GoogleAdsFieldService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch Google Ads API fields.
/// </remarks>
public abstract partial class GoogleAdsFieldServiceClient
{
/// <summary>
/// The default endpoint for the GoogleAdsFieldService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default GoogleAdsFieldService scopes.</summary>
/// <remarks>
/// The default GoogleAdsFieldService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="GoogleAdsFieldServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="GoogleAdsFieldServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="GoogleAdsFieldServiceClient"/>.</returns>
public static stt::Task<GoogleAdsFieldServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new GoogleAdsFieldServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="GoogleAdsFieldServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="GoogleAdsFieldServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="GoogleAdsFieldServiceClient"/>.</returns>
public static GoogleAdsFieldServiceClient Create() => new GoogleAdsFieldServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="GoogleAdsFieldServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="GoogleAdsFieldServiceSettings"/>.</param>
/// <returns>The created <see cref="GoogleAdsFieldServiceClient"/>.</returns>
internal static GoogleAdsFieldServiceClient Create(grpccore::CallInvoker callInvoker, GoogleAdsFieldServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
GoogleAdsFieldService.GoogleAdsFieldServiceClient grpcClient = new GoogleAdsFieldService.GoogleAdsFieldServiceClient(callInvoker);
return new GoogleAdsFieldServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC GoogleAdsFieldService client</summary>
public virtual GoogleAdsFieldService.GoogleAdsFieldServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::GoogleAdsField GetGoogleAdsField(GetGoogleAdsFieldRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::GoogleAdsField> GetGoogleAdsFieldAsync(GetGoogleAdsFieldRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::GoogleAdsField> GetGoogleAdsFieldAsync(GetGoogleAdsFieldRequest request, st::CancellationToken cancellationToken) =>
GetGoogleAdsFieldAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the field to get.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::GoogleAdsField GetGoogleAdsField(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetGoogleAdsField(new GetGoogleAdsFieldRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the field to get.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::GoogleAdsField> GetGoogleAdsFieldAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetGoogleAdsFieldAsync(new GetGoogleAdsFieldRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the field to get.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::GoogleAdsField> GetGoogleAdsFieldAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetGoogleAdsFieldAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the field to get.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::GoogleAdsField GetGoogleAdsField(gagvr::GoogleAdsFieldName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetGoogleAdsField(new GetGoogleAdsFieldRequest
{
ResourceNameAsGoogleAdsFieldName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the field to get.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::GoogleAdsField> GetGoogleAdsFieldAsync(gagvr::GoogleAdsFieldName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetGoogleAdsFieldAsync(new GetGoogleAdsFieldRequest
{
ResourceNameAsGoogleAdsFieldName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the field to get.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::GoogleAdsField> GetGoogleAdsFieldAsync(gagvr::GoogleAdsFieldName resourceName, st::CancellationToken cancellationToken) =>
GetGoogleAdsFieldAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns all fields that match the search query.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QueryError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="gagvr::GoogleAdsField"/> resources.</returns>
public virtual gax::PagedEnumerable<SearchGoogleAdsFieldsResponse, gagvr::GoogleAdsField> SearchGoogleAdsFields(SearchGoogleAdsFieldsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns all fields that match the search query.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QueryError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="gagvr::GoogleAdsField"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<SearchGoogleAdsFieldsResponse, gagvr::GoogleAdsField> SearchGoogleAdsFieldsAsync(SearchGoogleAdsFieldsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns all fields that match the search query.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QueryError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="query">
/// Required. The query string.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="gagvr::GoogleAdsField"/> resources.</returns>
public virtual gax::PagedEnumerable<SearchGoogleAdsFieldsResponse, gagvr::GoogleAdsField> SearchGoogleAdsFields(string query, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
SearchGoogleAdsFields(new SearchGoogleAdsFieldsRequest
{
Query = gax::GaxPreconditions.CheckNotNullOrEmpty(query, nameof(query)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Returns all fields that match the search query.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QueryError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="query">
/// Required. The query string.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="gagvr::GoogleAdsField"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<SearchGoogleAdsFieldsResponse, gagvr::GoogleAdsField> SearchGoogleAdsFieldsAsync(string query, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
SearchGoogleAdsFieldsAsync(new SearchGoogleAdsFieldsRequest
{
Query = gax::GaxPreconditions.CheckNotNullOrEmpty(query, nameof(query)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
}
/// <summary>GoogleAdsFieldService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch Google Ads API fields.
/// </remarks>
public sealed partial class GoogleAdsFieldServiceClientImpl : GoogleAdsFieldServiceClient
{
private readonly gaxgrpc::ApiCall<GetGoogleAdsFieldRequest, gagvr::GoogleAdsField> _callGetGoogleAdsField;
private readonly gaxgrpc::ApiCall<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse> _callSearchGoogleAdsFields;
/// <summary>
/// Constructs a client wrapper for the GoogleAdsFieldService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="GoogleAdsFieldServiceSettings"/> used within this client.</param>
public GoogleAdsFieldServiceClientImpl(GoogleAdsFieldService.GoogleAdsFieldServiceClient grpcClient, GoogleAdsFieldServiceSettings settings)
{
GrpcClient = grpcClient;
GoogleAdsFieldServiceSettings effectiveSettings = settings ?? GoogleAdsFieldServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetGoogleAdsField = clientHelper.BuildApiCall<GetGoogleAdsFieldRequest, gagvr::GoogleAdsField>(grpcClient.GetGoogleAdsFieldAsync, grpcClient.GetGoogleAdsField, effectiveSettings.GetGoogleAdsFieldSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetGoogleAdsField);
Modify_GetGoogleAdsFieldApiCall(ref _callGetGoogleAdsField);
_callSearchGoogleAdsFields = clientHelper.BuildApiCall<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse>(grpcClient.SearchGoogleAdsFieldsAsync, grpcClient.SearchGoogleAdsFields, effectiveSettings.SearchGoogleAdsFieldsSettings);
Modify_ApiCall(ref _callSearchGoogleAdsFields);
Modify_SearchGoogleAdsFieldsApiCall(ref _callSearchGoogleAdsFields);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetGoogleAdsFieldApiCall(ref gaxgrpc::ApiCall<GetGoogleAdsFieldRequest, gagvr::GoogleAdsField> call);
partial void Modify_SearchGoogleAdsFieldsApiCall(ref gaxgrpc::ApiCall<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse> call);
partial void OnConstruction(GoogleAdsFieldService.GoogleAdsFieldServiceClient grpcClient, GoogleAdsFieldServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC GoogleAdsFieldService client</summary>
public override GoogleAdsFieldService.GoogleAdsFieldServiceClient GrpcClient { get; }
partial void Modify_GetGoogleAdsFieldRequest(ref GetGoogleAdsFieldRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_SearchGoogleAdsFieldsRequest(ref SearchGoogleAdsFieldsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::GoogleAdsField GetGoogleAdsField(GetGoogleAdsFieldRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetGoogleAdsFieldRequest(ref request, ref callSettings);
return _callGetGoogleAdsField.Sync(request, callSettings);
}
/// <summary>
/// Returns just the requested field.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::GoogleAdsField> GetGoogleAdsFieldAsync(GetGoogleAdsFieldRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetGoogleAdsFieldRequest(ref request, ref callSettings);
return _callGetGoogleAdsField.Async(request, callSettings);
}
/// <summary>
/// Returns all fields that match the search query.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QueryError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="gagvr::GoogleAdsField"/> resources.</returns>
public override gax::PagedEnumerable<SearchGoogleAdsFieldsResponse, gagvr::GoogleAdsField> SearchGoogleAdsFields(SearchGoogleAdsFieldsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SearchGoogleAdsFieldsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse, gagvr::GoogleAdsField>(_callSearchGoogleAdsFields, request, callSettings);
}
/// <summary>
/// Returns all fields that match the search query.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QueryError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="gagvr::GoogleAdsField"/> resources.</returns>
public override gax::PagedAsyncEnumerable<SearchGoogleAdsFieldsResponse, gagvr::GoogleAdsField> SearchGoogleAdsFieldsAsync(SearchGoogleAdsFieldsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SearchGoogleAdsFieldsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse, gagvr::GoogleAdsField>(_callSearchGoogleAdsFields, request, callSettings);
}
}
public partial class SearchGoogleAdsFieldsRequest : gaxgrpc::IPageRequest
{
}
public partial class SearchGoogleAdsFieldsResponse : gaxgrpc::IPageResponse<gagvr::GoogleAdsField>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<gagvr::GoogleAdsField> GetEnumerator() => Results.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System.Collections.Generic;
using Microsoft.Boogie;
using System.Diagnostics;
using System.Linq;
using System.IO;
namespace Symbooglix
{
public class Memory : Util.IYAMLWriter
{
public Memory()
{
Stack = new List<StackFrame>();
Globals = new SimpleVariableStore();
}
public Memory Clone()
{
Memory other = (Memory) this.MemberwiseClone();
other.Stack = new List<StackFrame>();
foreach (var sf in this.Stack)
{
other.Stack.Add(sf.Clone());
}
other.Globals = this.Globals.Clone();
return other;
}
public void WriteAsYAML(System.CodeDom.Compiler.IndentedTextWriter TW)
{
WriteAsYAML(TW, false);
}
public void WriteAsYAML(System.CodeDom.Compiler.IndentedTextWriter TW, bool showVariables)
{
// Globals
TW.WriteLine("num_globals: {0}", Globals.Count);
if (showVariables)
{
TW.WriteLine("globals:");
TW.Indent += 1;
if (Globals.Count == 0)
{
TW.WriteLine("{}"); // Emtpy dictionary
}
else
{
foreach (var pair in Globals)
{
TW.WriteLine("\"{0}\":", pair.Key.ToString());
TW.Indent += 1;
TW.WriteLine("type: \"{0}\"", pair.Key.TypedIdent.Type);
TW.WriteLine("expr: \"{0}\"", pair.Value);
TW.Indent -= 1;
}
}
TW.Indent -= 1;
}
// Stackframe
int depth = Stack.Count;
TW.WriteLine("stack_depth: {0}", depth);
TW.WriteLine("stack:");
TW.Indent += 1;
for (int index = depth -1; index >= 0; --index)
{
TW.WriteLine("-");
TW.Indent += 1;
Stack[index].WriteAsYAML(TW, showVariables);
TW.Indent -= 1;
}
TW.Indent -= 1;
}
public override string ToString()
{
string result = null;
using (var SW = new StringWriter())
{
using (var ITW = new System.CodeDom.Compiler.IndentedTextWriter(SW))
{
WriteAsYAML(ITW);
}
result = SW.ToString();
}
return result;
}
public void PopStackFrame()
{
Stack.RemoveAt(Stack.Count - 1);
}
public List<StackFrame> Stack;
public IVariableStore Globals;
}
public class StackFrame : Util.IYAMLWriter
{
public IVariableStore Locals;
public Implementation Impl;
public Procedure Proc;
public BlockCmdEnumerator CurrentInstruction;
// FIXME: Make this thread safe
// Lazy initialisation
private IVariableStore InternalOldGlobals;
public IVariableStore OldGlobals
{
get
{
if (InternalOldGlobals == null)
{
InternalOldGlobals = new SimpleVariableStore();
}
return InternalOldGlobals;
}
private set { InternalOldGlobals = OldGlobals; }
}
public StackFrame(Implementation impl)
{
Locals = new SimpleVariableStore();
InternalOldGlobals = null;
this.Impl = impl;
this.Proc = null;
TransferToBlock(impl.Blocks[0]);
}
// This is a dummy stack frame
public StackFrame(Procedure proc)
{
Locals = new SimpleVariableStore();
InternalOldGlobals = null;
this.Proc = proc;
this.Impl = null;
this.CurrentInstruction = null;
}
public bool IsDummy
{
get { return this.Impl == null && this.CurrentInstruction == null; }
}
public Block CurrentBlock
{
get;
private set;
}
public StackFrame Clone()
{
StackFrame other = (StackFrame) this.MemberwiseClone();
// procedure/implementation does not need to cloned
other.Locals = this.Locals.Clone();
if (this.OldGlobals != null)
other.InternalOldGlobals = this.InternalOldGlobals.Clone();
// A dummy stack frame doesn't have an instruction iterator
if (IsDummy)
return other;
// Clone instruction iterator
other.CurrentInstruction = CurrentInstruction.Clone();
return other;
}
public void WriteAsYAML(System.CodeDom.Compiler.IndentedTextWriter TW)
{
WriteAsYAML(TW, /*showVariables=*/false);
}
public void WriteAsYAML(System.CodeDom.Compiler.IndentedTextWriter TW, bool showVariables)
{
TW.WriteLine("procedure: \"{0}\"", IsDummy? Proc.Name : Impl.Name);
if (!IsDummy)
{
TW.WriteLine("current_block: \"{0}\"", CurrentBlock);
TW.Write("current_instruction:");
if (CurrentInstruction.Current != null)
{
TW.WriteLine("");
TW.Indent += 1;
// Should we mention the filename too?
TW.WriteLine("line: {0}", CurrentInstruction.Current.tok.line);
TW.WriteLine("instruction: \"{0}\"", CurrentInstruction.Current.ToString().TrimEnd('\n'));
TW.Indent -= 1;
}
else
{
TW.WriteLine(" null");
}
}
TW.WriteLine("num_locals: {0}", Locals.Count);
if (showVariables)
{
TW.WriteLine("locals:");
TW.Indent += 1;
if (Locals.Count == 0)
{
TW.WriteLine("{}");
}
else
{
foreach (var pair in Locals)
{
TW.WriteLine("\"{0}\":", pair.Key.ToString());
TW.Indent += 1;
TW.WriteLine("type: \"{0}\"", pair.Key.TypedIdent.Type);
TW.WriteLine("expr: \"{0}\"", pair.Value);
TW.Indent -= 1;
}
}
TW.Indent -= 1;
}
}
public override string ToString()
{
string result = null;
using (var SW = new StringWriter())
{
using (var ITW = new System.CodeDom.Compiler.IndentedTextWriter(SW))
{
WriteAsYAML(ITW);
}
result = SW.ToString();
}
return result;
}
public void TransferToBlock(Block BB)
{
// Update GotoCmd stats
if (CurrentInstruction != null)
{
var gotoCmd = CurrentInstruction.Current as GotoCmd;
Debug.Assert(gotoCmd != null, "Expected GotoCmd at current instruction");
(gotoCmd.GetInstructionStatistics() as GotoInstructionStatistics).IncrementJumpTo(BB);
}
// Check if BB is in procedure
Debug.Assert(Impl.Blocks.Contains(BB));
CurrentBlock = BB;
CurrentInstruction = new BlockCmdEnumerator(CurrentBlock);
}
}
}
| |
// Copyright (C) 2004 Kevin Downs
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
namespace NDoc.Core.Reflection
{
/// <summary>
/// Handles the resolution and loading of assemblies.
/// </summary>
internal class AssemblyLoader
{
/// <summary>primary search directories.</summary>
private ReferencePathCollection SearchDirectories;
/// <summary>List of subdirectory lists already scanned.</summary>
private Hashtable directoryLists;
/// <summary>List of directories already scanned.</summary>
private Hashtable searchedDirectories;
/// <summary>List of Assemblies that could not be resolved.</summary>
private Hashtable unresolvedAssemblies;
/// <summary>assemblies already scanned, but not loaded.</summary>
/// <remarks>Maps Assembly FullName to Filename for assemblies scanned,
/// but not loaded because they were not a match to the required FullName.
/// <p>This list is scanned twice,</p>
/// <list type="unordered">
/// <term>If the requested assembly has not been loaded, but is in this list, then the file is loaded.</term>
/// <term>Once all search paths have been exhausted in an exact name match, this list is checked for a 'partial' match.</term>
/// </list></remarks>
private Hashtable AssemblyNameFileNameMap;
// loaded assembly cache keyed by Assembly FileName
private Hashtable assemblysLoadedFileName;
/// <summary>
/// Initializes a new instance of the <see cref="AssemblyLoader"/> class.
/// </summary>
/// <param name="referenceDirectories">Reference directories.</param>
public AssemblyLoader(ReferencePathCollection referenceDirectories)
{
this.assemblysLoadedFileName = new Hashtable();
this.AssemblyNameFileNameMap = new Hashtable();
this.directoryLists = new Hashtable();
this.unresolvedAssemblies = new Hashtable();
this.searchedDirectories = new Hashtable();
this.SearchDirectories = referenceDirectories;
}
/// <summary>
/// Directories Searched for assemblies.
/// </summary>
public ICollection SearchedDirectories
{
get { return searchedDirectories.Keys; }
}
/// <summary>
/// Assemblies that could not be resolved.
/// </summary>
public ICollection UnresolvedAssemblies
{
get { return unresolvedAssemblies.Keys; }
}
/// <summary>
/// Installs the assembly resolver by hooking up to the AppDomain's AssemblyResolve event.
/// </summary>
public void Install()
{
AppDomain.CurrentDomain.AssemblyResolve +=
new ResolveEventHandler(this.ResolveAssembly);
}
/// <summary>
/// Deinstalls the assembly resolver.
/// </summary>
public void Deinstall()
{
AppDomain.CurrentDomain.AssemblyResolve -=
new ResolveEventHandler(this.ResolveAssembly);
}
/// <summary>Loads an assembly.</summary>
/// <param name="fileName">The assembly filename.</param>
/// <returns>The assembly object.</returns>
/// <remarks>This method loads an assembly into memory. If you
/// use Assembly.Load or Assembly.LoadFrom the assembly file locks.
/// This method doesn't lock the assembly file.</remarks>
public Assembly LoadAssembly(string fileName)
{
// have we already loaded this assembly?
Assembly assy = assemblysLoadedFileName[fileName] as Assembly;
//double check assy not already loaded
if (assy == null)
{
AssemblyName assyName = AssemblyName.GetAssemblyName(fileName);
foreach (Assembly loadedAssy in AppDomain.CurrentDomain.GetAssemblies())
{
if (assyName.FullName == loadedAssy.FullName)
{
assy = loadedAssy;
break;
}
}
}
// Assembly not loaded, so we must go a get it
if (assy == null)
{
Trace.WriteLine(String.Format("LoadAssembly: {0}", fileName));
// we will load the assembly image into a byte array, then get the CLR to load it
// This allows us to side-step the host permissions which would otherwise prevent
// loading from a network share...also we don't have the overhead over shadow-copying
// to avoid assembly locking
FileStream assyFile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 16384);
byte[] bin = new byte[16384];
long rdlen = 0;
long total = assyFile.Length;
int len;
MemoryStream memStream = new MemoryStream((int)total);
rdlen = 0;
while (rdlen < total)
{
len = assyFile.Read(bin, 0, 16384);
memStream.Write(bin, 0, len);
rdlen = rdlen + len;
}
// done with input file
assyFile.Close();
// Now we have the assembly image, try to load it into the CLR
try
{
Evidence evidence = CreateAssemblyEvidence(fileName);
assy = Assembly.Load(memStream.ToArray(), null, evidence);
// If the assembly loaded OK, cache the Assembly ref using the fileName as key.
assemblysLoadedFileName.Add(fileName, assy);
}
catch (System.Security.SecurityException e)
{
if (e.Message.IndexOf("0x8013141A") != -1)
{
throw new System.Security.SecurityException(String.Format("Strong name validation failed for assembly '{0}'.", fileName));
}
else
throw;
}
catch (System.IO.FileLoadException e)
{
// HACK: replace the text comparison with non-localized test when further details are available
if ((e.Message.IndexOf("0x80131019") != -1) ||
(e.Message.IndexOf("contains extra relocations") != -1))
{
try
{
// LoadFile is really preferable,
// but since .Net 1.0 doesn't have it,
// we have to use LoadFrom on that framework...
#if (NET_1_0)
assy = Assembly.LoadFrom(fileName);
#else
assy = Assembly.LoadFile(fileName);
#endif
}
catch (Exception e2)
{
throw new DocumenterException(string.Format(CultureInfo.InvariantCulture, "Unable to load assembly '{0}'", fileName), e2);
}
}
else
throw new DocumenterException(string.Format(CultureInfo.InvariantCulture, "Unable to load assembly '{0}'", fileName), e);
}
catch (Exception e)
{
throw new DocumenterException(string.Format(CultureInfo.InvariantCulture, "Unable to load assembly '{0}'", fileName), e);
}
}
return assy;
}
static Evidence CreateAssemblyEvidence(string fileName)
{
//HACK: I am unsure whether 'Hash' evidence is required - since this will be difficult to obtain, we will not supply it...
Evidence newEvidence = new Evidence();
//We must have zone evidence, or we will get a policy exception
Zone zone = new Zone(SecurityZone.MyComputer);
newEvidence.AddHost(zone);
//If the assembly is strong-named, we must supply this evidence
//for StrongNameIdentityPermission demands
AssemblyName assemblyName = AssemblyName.GetAssemblyName(fileName);
byte[] pk = assemblyName.GetPublicKey();
if (pk!=null && pk.Length != 0)
{
StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(pk);
StrongName strongName = new StrongName(blob, assemblyName.Name, assemblyName.Version);
newEvidence.AddHost(strongName);
}
return newEvidence;
}
/// <summary>
/// Resolves the location and loads an assembly not found by the system.
/// </summary>
/// <remarks>The CLR will take care of loading Framework and GAC assemblies.
/// <p>The resolution process uses the following heuristic</p>
/// </remarks>
/// <param name="sender">the sender of the event</param>
/// <param name="args">event arguments</param>
/// <returns>the loaded assembly, null, if not found</returns>
protected Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
// first, have we already loaded the required assembly?
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly a in assemblies)
{
if (IsAssemblyNameEquivalent(a.FullName, args.Name))
{
return a;
}
}
Debug.WriteLine(
"Attempting to resolve assembly " + args.Name + ".",
"AssemblyResolver");
string fileName;
// we may have already located the assembly but not loaded it...
fileName = (string)AssemblyNameFileNameMap[args.Name];
if (fileName != null && fileName.Length > 0)
{
return LoadAssembly((string)AssemblyNameFileNameMap[args.Name]);
}
string[] assemblyInfo = args.Name.Split(new char[] {','});
string fullName = args.Name;
Assembly assy = null;
// first we will try filenames derived from the assembly name.
// Project Path DLLs
if (assy == null)
{
fileName = assemblyInfo[0] + ".dll";
assy = LoadAssemblyFrom(fullName, fileName);
}
// Project Path Exes
if (assy == null)
{
fileName = assemblyInfo[0] + ".exe";
assy = LoadAssemblyFrom(fullName, fileName);
}
// Reference Path DLLs
if (assy == null)
{
fileName = assemblyInfo[0] + ".dll";
assy = LoadAssemblyFrom(fullName, fileName);
}
// Reference Path Exes
if (assy == null)
{
fileName = assemblyInfo[0] + ".exe";
assy = LoadAssemblyFrom(fullName, fileName);
}
//if the requested assembly did not have a strong name, we can
//get even more desperate and start looking for partial name matches
if (assemblyInfo.Length < 4 || assemblyInfo[3].Trim() == "PublicKeyToken=null")
{
if (assy == null)
{
//start looking for partial name matches in
//the assemblies we have already loaded...
assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly a in assemblies)
{
string[] assemblyNameParts = a.FullName.Split(new char[] {','});
if (assemblyNameParts[0] == assemblyInfo[0])
{
assy = a;
break;
}
}
}
if (assy == null)
{
//get even more desperate and start looking for partial name matches
//the assemblies we have already scanned...
foreach (string assemblyName in AssemblyNameFileNameMap.Keys)
{
string[] assemblyNameParts = assemblyName.Split(new char[] {','});
if (assemblyNameParts[0] == assemblyInfo[0])
{
assy = LoadAssembly((string)AssemblyNameFileNameMap[assemblyName]);
break;
}
}
}
}
if (assy == null)
{
if (!unresolvedAssemblies.ContainsKey(args.Name))
unresolvedAssemblies.Add(args.Name, null);
}
return assy;
}
/// <summary>
/// Search for and load the specified assembly in a set of directories.
/// This will optionally search recursively.
/// </summary>
/// <param name="fullName">
/// Fully qualified assembly name. If not empty, the full name of each assembly found is
/// compared to this name and the assembly is accepted only, if the names match.
/// </param>
/// <param name="fileName">The name of the assembly.</param>
/// <returns>The assembly, or null if not found.</returns>
private Assembly LoadAssemblyFrom(string fullName, string fileName)
{
Assembly assy = null;
if ((SearchDirectories == null) || (SearchDirectories.Count == 0)) return (null);
foreach (ReferencePath rp in SearchDirectories)
{
if (Directory.Exists(rp.Path))
{
assy = LoadAssemblyFrom(fullName, fileName, rp.Path, rp.IncludeSubDirectories);
if (assy != null) return assy;
}
}
return null;
}
/// <summary>
/// Search for and load the specified assembly in a given directory.
/// This will optionally search recursively into sub-directories if requested.
/// </summary>
/// <param name="path">The directory to look in.</param>
/// <param name="fullName">
/// Fully qualified assembly name. If not empty, the full name of each assembly found is
/// compared to this name and the assembly is accepted only, if the names match.
/// </param>
/// <param name="fileName">The name of the assembly.</param>
/// <param name="includeSubDirs">true, search subdirectories.</param>
/// <returns>The assembly, or null if not found.</returns>
private Assembly LoadAssemblyFrom(string fullName, string fileName, string path, bool includeSubDirs)
{
Assembly assembly = null;
if (!searchedDirectories.ContainsKey(path))
{
searchedDirectories.Add(path, null);
}
string fn = Path.Combine(path, fileName);
if (File.Exists(fn))
{
// file exists, check it's the right assembly
try
{
AssemblyName assyName = AssemblyName.GetAssemblyName(fn);
if (IsAssemblyNameEquivalent(assyName.FullName, fullName))
{
//This looks like the right assembly, try loading it
try
{
assembly = LoadAssembly(fn);
return (assembly);
}
catch (Exception e)
{
Debug.WriteLine("Assembly Load Error: " + e.Message, "AssemblyResolver");
}
}
else
{
//nope, names don't match; save the FileName and AssemblyName map
//in case we need this assembly later...
//only first found occurence of fully-qualifed assembly name is cached
if (!AssemblyNameFileNameMap.ContainsKey(assyName.FullName))
{
AssemblyNameFileNameMap.Add(assyName.FullName, fn);
}
}
}
catch (Exception e)
{
//oops this wasn't a valid assembly
Debug.WriteLine("AssemblyResolver: File " + fn + " not a valid assembly");
Debug.WriteLine(e.Message);
}
}
else
{
Debug.WriteLine("AssemblyResolver: File " + fileName + " not in " + path);
}
// not in this dir (or load failed), scan subdirectories
if (includeSubDirs)
{
string[] subdirs = GetSubDirectories(path);
foreach (string subdir in subdirs)
{
Assembly assy = LoadAssemblyFrom(fullName, fileName, subdir, true);
if (assy != null) return assy;
}
}
return null;
}
private string[] GetSubDirectories(string parentDir)
{
string[] subdirs = (string[])this.directoryLists[parentDir];
if (null == subdirs)
{
subdirs = Directory.GetDirectories(parentDir);
this.directoryLists.Add(parentDir, subdirs);
}
return subdirs;
}
/// <summary>
///
/// </summary>
private bool IsAssemblyNameEquivalent(string AssyFullName, string RequiredAssyName)
{
if (RequiredAssyName.Length < AssyFullName.Length)
return (AssyFullName.Substring(0, RequiredAssyName.Length) == RequiredAssyName);
else
return (AssyFullName == RequiredAssyName.Substring(0, AssyFullName.Length));
}
}
}
| |
// 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.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.Isam.Esent;
using Microsoft.Isam.Esent.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Esent
{
internal partial class EsentPersistentStorage : AbstractPersistentStorage
{
private const string StorageExtension = "vbcs.cache";
private const string PersistentStorageFileName = "storage.ide";
private readonly ConcurrentDictionary<string, int> _nameTableCache;
private readonly EsentStorage _esentStorage;
public EsentPersistentStorage(
IOptionService optionService, string workingFolderPath, string solutionFilePath, Action<AbstractPersistentStorage> disposer) :
base(optionService, workingFolderPath, solutionFilePath, disposer)
{
// solution must exist in disk. otherwise, we shouldn't be here at all.
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(solutionFilePath));
var databaseFile = GetDatabaseFile(workingFolderPath);
this.EsentDirectory = Path.GetDirectoryName(databaseFile);
if (!Directory.Exists(this.EsentDirectory))
{
Directory.CreateDirectory(this.EsentDirectory);
}
_nameTableCache = new ConcurrentDictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var enablePerformanceMonitor = optionService.GetOption(InternalFeatureOnOffOptions.EsentPerformanceMonitor);
_esentStorage = new EsentStorage(databaseFile, enablePerformanceMonitor);
}
public static string GetDatabaseFile(string workingFolderPath)
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(workingFolderPath));
return Path.Combine(workingFolderPath, StorageExtension, PersistentStorageFileName);
}
public void Initialize()
{
_esentStorage.Initialize();
}
public string EsentDirectory { get; private set; }
public override Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
int projectId;
int documentId;
int nameId;
if (!TryGetProjectAndDocumentId(document, out projectId, out documentId) ||
!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(projectId, documentId, nameId, ReadStream, cancellationToken);
return Task.FromResult(stream);
}
private Stream ReadStream(int projectId, int documentId, int nameId, object unused1, object unused2, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetDocumentTableAccessor())
using (var esentStream = accessor.GetReadStream(projectId, documentId, nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
public override Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
if (!IsSupported(project))
{
return SpecializedTasks.Default<Stream>();
}
int projectId;
int nameId;
if (!TryGetUniqueFileId(project.FilePath, out projectId) ||
!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(projectId, nameId, ReadStream, cancellationToken);
return Task.FromResult(stream);
}
private Stream ReadStream(int projectId, int nameId, object unused1, object unused2, object unused3, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetProjectTableAccessor())
using (var esentStream = accessor.GetReadStream(projectId, nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
public override Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
int nameId;
if (!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(nameId, ReadStream, cancellationToken);
return Task.FromResult(stream);
}
private Stream ReadStream(int nameId, object unused1, object unused2, object unused3, object unused4, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetSolutionTableAccessor())
using (var esentStream = accessor.GetReadStream(nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
public override Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
int projectId;
int documentId;
int nameId;
if (!TryGetProjectAndDocumentId(document, out projectId, out documentId) ||
!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(projectId, documentId, nameId, stream, WriteStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
private bool WriteStream(int projectId, int documentId, int nameId, Stream stream, object unused1, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetDocumentTableAccessor())
using (var esentStream = accessor.GetWriteStream(projectId, documentId, nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
public override Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
if (!IsSupported(project))
{
return SpecializedTasks.False;
}
int projectId;
int nameId;
if (!TryGetUniqueFileId(project.FilePath, out projectId) ||
!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(projectId, nameId, stream, WriteStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
private bool WriteStream(int projectId, int nameId, Stream stream, object unused1, object unused2, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetProjectTableAccessor())
using (var esentStream = accessor.GetWriteStream(projectId, nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
public override Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
int nameId;
if (!TryGetUniqueNameId(name, out nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(nameId, stream, WriteStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
private bool WriteStream(int nameId, Stream stream, object unused1, object unused2, object unused3, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetSolutionTableAccessor())
using (var esentStream = accessor.GetWriteStream(nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
public override void Close()
{
_esentStorage.Close();
}
private bool IsSupported(Project project)
{
// TODO: figure out a proper way to support project K scenario where we can't use path as a unique key
// https://github.com/dotnet/roslyn/issues/1860
return !LinkedFileUtilities.IsProjectKProject(project);
}
private bool TryGetUniqueNameId(string name, out int id)
{
return TryGetUniqueId(name, false, out id);
}
private bool TryGetUniqueFileId(string path, out int id)
{
return TryGetUniqueId(path, true, out id);
}
private bool TryGetUniqueId(string value, bool fileCheck, out int id)
{
id = default(int);
if (string.IsNullOrWhiteSpace(value))
{
return false;
}
// if we already know, get the id
if (_nameTableCache.TryGetValue(value, out id))
{
return true;
}
// we only persist for things that actually exist
if (fileCheck && !File.Exists(value))
{
return false;
}
try
{
id = _nameTableCache.GetOrAdd(value, v =>
{
// okay, get one from esent
var uniqueIdValue = fileCheck ? FilePathUtilities.GetRelativePath(Path.GetDirectoryName(SolutionFilePath), v) : v;
return _esentStorage.GetUniqueId(uniqueIdValue);
});
}
catch (Exception ex)
{
// if we get fatal errors from esent such as disk out of space or log file corrupted by other process and etc
// don't crash VS, but let VS know it can't use esent. we will gracefully recover issue by using memory.
EsentLogger.LogException(ex);
return false;
}
return true;
}
private static void WriteToStream(Stream inputStream, Stream esentStream, CancellationToken cancellationToken)
{
var buffer = SharedPools.ByteArray.Allocate();
try
{
int bytesRead;
do
{
cancellationToken.ThrowIfCancellationRequested();
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
esentStream.Write(buffer, 0, bytesRead);
}
}
while (bytesRead > 0);
// flush the data and trim column size of necessary
esentStream.Flush();
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
private bool TryGetProjectAndDocumentId(Document document, out int projectId, out int documentId)
{
projectId = default(int);
documentId = default(int);
if (!IsSupported(document.Project))
{
return false;
}
return TryGetUniqueFileId(document.Project.FilePath, out projectId) && TryGetUniqueFileId(document.FilePath, out documentId);
}
private TResult EsentExceptionWrapper<TArg1, TResult>(TArg1 arg1, Func<TArg1, object, object, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TResult>(
TArg1 arg1, TArg2 arg2, Func<TArg1, TArg2, object, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, Func<TArg1, TArg2, TArg3, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, arg3, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TArg4, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, Func<TArg1, TArg2, TArg3, TArg4, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, arg3, arg4, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TArg4, TArg5, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, Func<TArg1, TArg2, TArg3, TArg4, TArg5, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
try
{
return func(arg1, arg2, arg3, arg4, arg5, cancellationToken);
}
catch (EsentInvalidSesidException)
{
// operation was in-fly when Esent instance was shutdown - ignore the error
}
catch (OperationCanceledException)
{
}
catch (EsentException ex)
{
if (!_esentStorage.IsClosed)
{
// ignore esent exception if underlying storage was closed
// there is not much we can do here.
// internally we use it as a way to cache information between sessions anyway.
// no functionality will be affected by this except perf
Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Esent Failed : " + ex.Message);
}
}
catch (Exception ex)
{
// ignore exception
// there is not much we can do here.
// internally we use it as a way to cache information between sessions anyway.
// no functionality will be affected by this except perf
Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Failed : " + ex.Message);
}
return default(TResult);
}
}
}
| |
// 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.Immutable;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
namespace System.Diagnostics
{
internal class StackTraceSymbols : IDisposable
{
private sealed class OpenedReader : IDisposable
{
public readonly MetadataReaderProvider Provider;
public readonly MetadataReader Reader;
public OpenedReader(MetadataReaderProvider provider, MetadataReader reader)
{
Debug.Assert(provider != null);
Debug.Assert(reader != null);
Provider = provider;
Reader = reader;
}
public void Dispose() => Provider.Dispose();
}
private readonly Dictionary<IntPtr, OpenedReader> _readerCache;
/// <summary>
/// Create an instance of this class.
/// </summary>
public StackTraceSymbols()
{
_readerCache = new Dictionary<IntPtr, OpenedReader>();
}
/// <summary>
/// Clean up any cached providers.
/// </summary>
void IDisposable.Dispose()
{
foreach (OpenedReader reader in _readerCache.Values)
{
reader.Dispose();
}
_readerCache.Clear();
}
/// <summary>
/// Returns the source file and line number information for the method.
/// </summary>
/// <param name="assemblyPath">file path of the assembly or null</param>
/// <param name="loadedPeAddress">loaded PE image address or zero</param>
/// <param name="loadedPeSize">loaded PE image size</param>
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <param name="methodToken">method token</param>
/// <param name="ilOffset">il offset of the stack frame</param>
/// <param name="sourceFile">source file return</param>
/// <param name="sourceLine">line number return</param>
/// <param name="sourceColumn">column return</param>
internal void GetSourceLineInfo(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize,
IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
out string sourceFile, out int sourceLine, out int sourceColumn)
{
sourceFile = null;
sourceLine = 0;
sourceColumn = 0;
MetadataReader reader = GetReader(assemblyPath, loadedPeAddress, loadedPeSize, inMemoryPdbAddress, inMemoryPdbSize);
if (reader != null)
{
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind == HandleKind.MethodDefinition)
{
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
MethodDebugInformation methodInfo = reader.GetMethodDebugInformation(methodDebugHandle);
if (!methodInfo.SequencePointsBlob.IsNil)
{
SequencePointCollection sequencePoints = methodInfo.GetSequencePoints();
SequencePoint? bestPointSoFar = null;
foreach (SequencePoint point in sequencePoints)
{
if (point.Offset > ilOffset)
break;
if (point.StartLine != SequencePoint.HiddenLine)
bestPointSoFar = point;
}
if (bestPointSoFar.HasValue)
{
sourceLine = bestPointSoFar.Value.StartLine;
sourceColumn = bestPointSoFar.Value.StartColumn;
sourceFile = reader.GetString(reader.GetDocument(bestPointSoFar.Value.Document).Name);
}
}
}
}
}
/// <summary>
/// Returns the portable PDB reader for the assembly path
/// </summary>
/// <param name="assemblyPath">
/// File path of the assembly or null if the module is dynamic (generated by Reflection.Emit).
/// </param>
/// <param name="loadedPeAddress">
/// Loaded PE image address or zero if the module is dynamic (generated by Reflection.Emit).
/// Dynamic modules have their PDBs (if any) generated to an in-memory stream
/// (pointed to by <paramref name="inMemoryPdbAddress"/> and <paramref name="inMemoryPdbSize"/>).
/// </param>
/// <param name="loadedPeSize">loaded PE image size</param>
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <param name="reader">returns the reader</param>
/// <returns>reader</returns>
/// <remarks>
/// Assumes that neither PE image nor PDB loaded into memory can be unloaded or moved around.
/// </remarks>
private unsafe MetadataReader GetReader(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize)
{
if ((loadedPeAddress == IntPtr.Zero || assemblyPath == null) && inMemoryPdbAddress == IntPtr.Zero)
{
// Dynamic or in-memory module without symbols (they would be in-memory if they were available).
return null;
}
IntPtr cacheKey = (inMemoryPdbAddress != IntPtr.Zero) ? inMemoryPdbAddress : loadedPeAddress;
OpenedReader openedReader;
if (_readerCache.TryGetValue(cacheKey, out openedReader))
{
return openedReader.Reader;
}
openedReader = (inMemoryPdbAddress != IntPtr.Zero) ?
TryOpenReaderForInMemoryPdb(inMemoryPdbAddress, inMemoryPdbSize) :
TryOpenReaderFromAssemblyFile(assemblyPath, loadedPeAddress, loadedPeSize);
if (openedReader == null)
{
return null;
}
_readerCache.Add(cacheKey, openedReader);
return openedReader.Reader;
}
private unsafe static OpenedReader TryOpenReaderForInMemoryPdb(IntPtr inMemoryPdbAddress, int inMemoryPdbSize)
{
Debug.Assert(inMemoryPdbAddress != IntPtr.Zero);
// quick check to avoid throwing exceptions below in common cases:
const uint ManagedMetadataSignature = 0x424A5342;
if (inMemoryPdbSize < sizeof(uint) || *(uint*)inMemoryPdbAddress != ManagedMetadataSignature)
{
// not a Portable PDB
return null;
}
OpenedReader result = null;
MetadataReaderProvider provider = null;
try
{
provider = MetadataReaderProvider.FromMetadataImage((byte*)inMemoryPdbAddress, inMemoryPdbSize);
result = new OpenedReader(provider, provider.GetMetadataReader());
}
catch (BadImageFormatException)
{
return null;
}
finally
{
if (result == null)
{
provider?.Dispose();
}
}
return result;
}
private static OpenedReader TryOpenReaderFromAssemblyFile(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize)
{
Debug.Assert(assemblyPath != null);
Debug.Assert(loadedPeAddress != IntPtr.Zero);
// TODO: When/if PEReader supports reading loaded PE files use loadedPeAddress and loadedPeSize instead of opening the file again.
Stream peStream = TryOpenFile(assemblyPath);
if (peStream == null)
{
return null;
}
try
{
using (var peReader = new PEReader(peStream))
{
DebugDirectoryEntry codeViewEntry, embeddedPdbEntry;
ReadPortableDebugTableEntries(peReader, out codeViewEntry, out embeddedPdbEntry);
// First try .pdb file specified in CodeView data (we prefer .pdb file on disk over embedded PDB
// since embedded PDB needs decompression which is less efficient than memory-mapping the file).
if (codeViewEntry.DataSize != 0)
{
var result = TryOpenReaderFromCodeView(peReader, codeViewEntry, assemblyPath);
if (result != null)
{
return result;
}
}
// if it failed try Embedded Portable PDB (if available):
if (embeddedPdbEntry.DataSize != 0)
{
return TryOpenReaderFromEmbeddedPdb(peReader, embeddedPdbEntry);
}
}
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
// nop
}
return null;
}
private static void ReadPortableDebugTableEntries(PEReader peReader, out DebugDirectoryEntry codeViewEntry, out DebugDirectoryEntry embeddedPdbEntry)
{
// See spec: https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PE-COFF.md
codeViewEntry = default(DebugDirectoryEntry);
embeddedPdbEntry = default(DebugDirectoryEntry);
foreach (DebugDirectoryEntry entry in peReader.ReadDebugDirectory())
{
if (entry.Type == DebugDirectoryEntryType.CodeView)
{
const ushort PortableCodeViewVersionMagic = 0x504d;
if (entry.MinorVersion != PortableCodeViewVersionMagic)
{
continue;
}
codeViewEntry = entry;
}
else if (entry.Type == DebugDirectoryEntryType.EmbeddedPortablePdb)
{
embeddedPdbEntry = entry;
}
}
}
private static OpenedReader TryOpenReaderFromCodeView(PEReader peReader, DebugDirectoryEntry codeViewEntry, string assemblyPath)
{
OpenedReader result = null;
MetadataReaderProvider provider = null;
try
{
var data = peReader.ReadCodeViewDebugDirectoryData(codeViewEntry);
string pdbPath;
try
{
pdbPath = Path.Combine(Path.GetDirectoryName(assemblyPath), Path.GetFileName(data.Path));
}
catch
{
// invalid characters in CodeView path
return null;
}
var pdbStream = TryOpenFile(pdbPath);
if (pdbStream == null)
{
return null;
}
provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream);
var reader = provider.GetMetadataReader();
// Validate that the PDB matches the assembly version
if (data.Age == 1 && new BlobContentId(reader.DebugMetadataHeader.Id) == new BlobContentId(data.Guid, codeViewEntry.Stamp))
{
result = new OpenedReader(provider, reader);
}
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
return null;
}
finally
{
if (result == null)
{
provider?.Dispose();
}
}
return result;
}
private static OpenedReader TryOpenReaderFromEmbeddedPdb(PEReader peReader, DebugDirectoryEntry embeddedPdbEntry)
{
OpenedReader result = null;
MetadataReaderProvider provider = null;
try
{
// TODO: We might want to cache this provider globally (accross stack traces),
// since decompressing embedded PDB takes some time.
provider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedPdbEntry);
result = new OpenedReader(provider, provider.GetMetadataReader());
}
catch (Exception e) when (e is BadImageFormatException || e is IOException)
{
return null;
}
finally
{
if (result == null)
{
provider?.Dispose();
}
}
return result;
}
private static Stream TryOpenFile(string path)
{
if (!File.Exists(path))
{
return null;
}
try
{
return File.OpenRead(path);
}
catch
{
return 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.Runtime.InteropServices;
using System.Threading;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.TextManager.Interop;
using TestUtilities;
using TestUtilities.Mocks;
using IServiceProvider = System.IServiceProvider;
namespace Microsoft.VisualStudioTools.MockVsTests
{
public class MockVsTextView : IVsTextView, IFocusable, IEditor, IOleCommandTarget, IDisposable
{
private readonly MockTextView _view;
private readonly IEditorOperations _editorOps;
private readonly IServiceProvider _serviceProvider;
private readonly MockVs _vs;
private IOleCommandTarget _commandTarget;
private bool _isDisposed;
public MockVsTextView(IServiceProvider serviceProvier, MockVs vs, MockTextView view)
{
_view = view;
_serviceProvider = serviceProvier;
_vs = vs;
var compModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
var editorOpsFact = compModel.GetService<IEditorOperationsFactoryService>();
_editorOps = editorOpsFact.GetEditorOperations(_view);
_commandTarget = new EditorCommandTarget(this);
}
public MockTextView View
{
get
{
return _view;
}
}
public void Dispose()
{
if (!_isDisposed)
{
_isDisposed = true;
Close();
}
}
public IIntellisenseSessionStack IntellisenseSessionStack
{
get
{
var compModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
var stackMap = compModel.GetService<IIntellisenseSessionStackMapService>();
return stackMap.GetStackForTextView(View);
}
}
public IIntellisenseSession TopSession
{
get
{
return IntellisenseSessionStack.TopSession;
}
}
public string Text
{
get
{
return View.TextBuffer.CurrentSnapshot.GetText();
}
}
int IVsTextView.AddCommandFilter(IOleCommandTarget pNewCmdTarg, out IOleCommandTarget ppNextCmdTarg)
{
ppNextCmdTarg = _commandTarget;
_commandTarget = pNewCmdTarg;
return VSConstants.S_OK;
}
int IVsTextView.CenterColumns(int iLine, int iLeftCol, int iColCount)
{
throw new NotImplementedException();
}
int IVsTextView.CenterLines(int iTopLine, int iCount)
{
throw new NotImplementedException();
}
int IVsTextView.ClearSelection(int fMoveToAnchor)
{
throw new NotImplementedException();
}
public void Close()
{
var rdt = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable));
rdt.UnlockDocument(0, ((MockVsTextLines)GetBuffer())._docCookie);
_view.Close();
}
int IVsTextView.CloseView()
{
Close();
return VSConstants.S_OK;
}
int IVsTextView.EnsureSpanVisible(TextSpan span)
{
throw new NotImplementedException();
}
int IVsTextView.GetBuffer(out IVsTextLines ppBuffer)
{
ppBuffer = GetBuffer();
return VSConstants.S_OK;
}
private IVsTextLines GetBuffer()
{
IVsTextLines ppBuffer;
var compModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
ppBuffer = (IVsTextLines)compModel.GetService<IVsEditorAdaptersFactoryService>().GetBufferAdapter(_view.TextBuffer);
return ppBuffer;
}
int IVsTextView.GetCaretPos(out int piLine, out int piColumn)
{
throw new NotImplementedException();
}
int IVsTextView.GetLineAndColumn(int iPos, out int piLine, out int piIndex)
{
throw new NotImplementedException();
}
int IVsTextView.GetLineHeight(out int piLineHeight)
{
throw new NotImplementedException();
}
int IVsTextView.GetNearestPosition(int iLine, int iCol, out int piPos, out int piVirtualSpaces)
{
throw new NotImplementedException();
}
int IVsTextView.GetPointOfLineColumn(int iLine, int iCol, VisualStudio.OLE.Interop.POINT[] ppt)
{
throw new NotImplementedException();
}
int IVsTextView.GetScrollInfo(int iBar, out int piMinUnit, out int piMaxUnit, out int piVisibleUnits, out int piFirstVisibleUnit)
{
throw new NotImplementedException();
}
int IVsTextView.GetSelectedText(out string pbstrText)
{
throw new NotImplementedException();
}
int IVsTextView.GetSelection(out int piAnchorLine, out int piAnchorCol, out int piEndLine, out int piEndCol)
{
throw new NotImplementedException();
}
int IVsTextView.GetSelectionDataObject(out VisualStudio.OLE.Interop.IDataObject ppIDataObject)
{
throw new NotImplementedException();
}
TextSelMode IVsTextView.GetSelectionMode()
{
throw new NotImplementedException();
}
int IVsTextView.GetSelectionSpan(TextSpan[] pSpan)
{
throw new NotImplementedException();
}
int IVsTextView.GetTextStream(int iTopLine, int iTopCol, int iBottomLine, int iBottomCol, out string pbstrText)
{
throw new NotImplementedException();
}
IntPtr IVsTextView.GetWindowHandle()
{
throw new NotImplementedException();
}
int IVsTextView.GetWordExtent(int iLine, int iCol, uint dwFlags, TextSpan[] pSpan)
{
throw new NotImplementedException();
}
int IVsTextView.HighlightMatchingBrace(uint dwFlags, uint cSpans, TextSpan[] rgBaseSpans)
{
throw new NotImplementedException();
}
int IVsTextView.Initialize(IVsTextLines pBuffer, IntPtr hwndParent, uint InitFlags, INITVIEW[] pInitView)
{
throw new NotImplementedException();
}
int IVsTextView.PositionCaretForEditing(int iLine, int cIndentLevels)
{
throw new NotImplementedException();
}
int IVsTextView.RemoveCommandFilter(VisualStudio.OLE.Interop.IOleCommandTarget pCmdTarg)
{
throw new NotImplementedException();
}
int IVsTextView.ReplaceTextOnLine(int iLine, int iStartCol, int iCharsToReplace, string pszNewText, int iNewLen)
{
throw new NotImplementedException();
}
int IVsTextView.RestrictViewRange(int iMinLine, int iMaxLine, IVsViewRangeClient pClient)
{
throw new NotImplementedException();
}
int IVsTextView.SendExplicitFocus()
{
throw new NotImplementedException();
}
int IVsTextView.SetBuffer(IVsTextLines pBuffer)
{
throw new NotImplementedException();
}
int IVsTextView.SetCaretPos(int iLine, int iColumn)
{
throw new NotImplementedException();
}
int IVsTextView.SetScrollPosition(int iBar, int iFirstVisibleUnit)
{
throw new NotImplementedException();
}
int IVsTextView.SetSelection(int iAnchorLine, int iAnchorCol, int iEndLine, int iEndCol)
{
throw new NotImplementedException();
}
int IVsTextView.SetSelectionMode(TextSelMode iSelMode)
{
throw new NotImplementedException();
}
int IVsTextView.SetTopLine(int iBaseLine)
{
throw new NotImplementedException();
}
int IVsTextView.UpdateCompletionStatus(IVsCompletionSet pCompSet, uint dwFlags)
{
throw new NotImplementedException();
}
int IVsTextView.UpdateTipWindow(IVsTipWindow pTipWindow, uint dwFlags)
{
throw new NotImplementedException();
}
int IVsTextView.UpdateViewFrameCaption()
{
throw new NotImplementedException();
}
private class EditorCommandTarget : IOleCommandTarget
{
private readonly MockVsTextView _view;
public EditorCommandTarget(MockVsTextView view)
{
_view = view;
}
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (pguidCmdGroup == VSConstants.VSStd2K)
{
switch ((VSConstants.VSStd2KCmdID)nCmdID)
{
case VSConstants.VSStd2KCmdID.TYPECHAR:
var ch = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
_view._editorOps.InsertText(ch.ToString());
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.RETURN:
_view._editorOps.InsertNewLine();
return VSConstants.S_OK;
}
}
return NativeMethods.OLECMDERR_E_NOTSUPPORTED;
}
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
throw new NotImplementedException();
}
}
public void GetFocus()
{
_view.OnGotAggregateFocus();
}
public void LostFocus()
{
_view.OnLostAggregateFocus();
}
public void Type(string text)
{
_commandTarget.Type(text);
}
int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
return _commandTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
return _commandTarget.QueryStatus(pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
public IWpfTextView TextView
{
get
{
return _view;
}
}
public void Select(int line, int column, int length)
{
throw new NotImplementedException();
}
public void WaitForText(string text)
{
for (int i = 0; i < 100; i++)
{
if (Text != text)
{
System.Threading.Thread.Sleep(100);
}
else
{
break;
}
}
Assert.AreEqual(text, Text);
}
public void MoveCaret(int line, int column)
{
var textLine = _view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(line - 1);
if (column - 1 == textLine.Length)
{
MoveCaret(textLine.End);
}
else
{
MoveCaret(new SnapshotPoint(_view.TextBuffer.CurrentSnapshot, textLine.Start + column - 1));
}
}
public CaretPosition MoveCaret(SnapshotPoint newPoint)
{
return _vs.Invoke(() => _view.Caret.MoveTo(newPoint.TranslateTo(newPoint.Snapshot.TextBuffer.CurrentSnapshot, PointTrackingMode.Positive)));
}
public void SetFocus()
{
}
public void Invoke(Action action)
{
_vs.Invoke(action);
}
public IClassifier Classifier
{
get
{
var compModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
var provider = compModel.GetService<IClassifierAggregatorService>();
return provider.GetClassifier(TextView.TextBuffer);
}
}
public SessionHolder<T> WaitForSession<T>() where T : IIntellisenseSession
{
return WaitForSession<T>(true);
}
public SessionHolder<T> WaitForSession<T>(bool assertIfNoSession) where T : IIntellisenseSession
{
var sessionStack = IntellisenseSessionStack;
for (int i = 0; i < 40; i++)
{
if (sessionStack.TopSession is T)
{
break;
}
System.Threading.Thread.Sleep(25);
}
if (!(sessionStack.TopSession is T))
{
if (assertIfNoSession)
{
Console.WriteLine("Buffer text:\r\n{0}", Text);
Console.WriteLine("-----");
Assert.Fail("failed to find session " + typeof(T).FullName);
}
else
{
return null;
}
}
return new SessionHolder<T>((T)sessionStack.TopSession, this);
}
public void AssertNoIntellisenseSession()
{
Thread.Sleep(500);
var session = IntellisenseSessionStack.TopSession;
if (session != null)
{
Assert.Fail("Expected no Intellisense session, but got " + session.GetType().ToString());
}
}
}
}
| |
namespace android.view
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.view.LayoutInflater_))]
public abstract partial class LayoutInflater : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected LayoutInflater(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.LayoutInflater.Factory_))]
public partial interface Factory : global::MonoJavaBridge.IJavaObject
{
global::android.view.View onCreateView(java.lang.String arg0, android.content.Context arg1, android.util.AttributeSet arg2);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.LayoutInflater.Factory))]
internal sealed partial class Factory_ : java.lang.Object, Factory
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Factory_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
global::android.view.View android.view.LayoutInflater.Factory.onCreateView(java.lang.String arg0, android.content.Context arg1, android.util.AttributeSet arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater.Factory_.staticClass, "onCreateView", "(Ljava/lang/String;Landroid/content/Context;Landroid/util/AttributeSet;)Landroid/view/View;", ref global::android.view.LayoutInflater.Factory_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.view.View;
}
static Factory_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.LayoutInflater.Factory_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/LayoutInflater$Factory"));
}
}
public delegate android.view.View FactoryDelegate(java.lang.String arg0, android.content.Context arg1, android.util.AttributeSet arg2);
internal partial class FactoryDelegateWrapper : java.lang.Object, Factory
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected FactoryDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public FactoryDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.LayoutInflater.FactoryDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.view.LayoutInflater.FactoryDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.view.LayoutInflater.FactoryDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.LayoutInflater.FactoryDelegateWrapper.staticClass, global::android.view.LayoutInflater.FactoryDelegateWrapper._m0);
Init(@__env, handle);
}
static FactoryDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.LayoutInflater.FactoryDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/LayoutInflater_FactoryDelegateWrapper"));
}
}
internal partial class FactoryDelegateWrapper
{
private FactoryDelegate myDelegate;
public android.view.View onCreateView(java.lang.String arg0, android.content.Context arg1, android.util.AttributeSet arg2)
{
return myDelegate(arg0, arg1, arg2);
}
public static implicit operator FactoryDelegateWrapper(FactoryDelegate d)
{
global::android.view.LayoutInflater.FactoryDelegateWrapper ret = new global::android.view.LayoutInflater.FactoryDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.LayoutInflater.Filter_))]
public partial interface Filter : global::MonoJavaBridge.IJavaObject
{
bool onLoadClass(java.lang.Class arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.LayoutInflater.Filter))]
internal sealed partial class Filter_ : java.lang.Object, Filter
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Filter_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
bool android.view.LayoutInflater.Filter.onLoadClass(java.lang.Class arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.LayoutInflater.Filter_.staticClass, "onLoadClass", "(Ljava/lang/Class;)Z", ref global::android.view.LayoutInflater.Filter_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static Filter_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.LayoutInflater.Filter_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/LayoutInflater$Filter"));
}
}
public delegate bool FilterDelegate(java.lang.Class arg0);
internal partial class FilterDelegateWrapper : java.lang.Object, Filter
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected FilterDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public FilterDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.LayoutInflater.FilterDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.view.LayoutInflater.FilterDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.view.LayoutInflater.FilterDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.LayoutInflater.FilterDelegateWrapper.staticClass, global::android.view.LayoutInflater.FilterDelegateWrapper._m0);
Init(@__env, handle);
}
static FilterDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.LayoutInflater.FilterDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/LayoutInflater_FilterDelegateWrapper"));
}
}
internal partial class FilterDelegateWrapper
{
private FilterDelegate myDelegate;
public bool onLoadClass(java.lang.Class arg0)
{
return myDelegate(arg0);
}
public static implicit operator FilterDelegateWrapper(FilterDelegate d)
{
global::android.view.LayoutInflater.FilterDelegateWrapper ret = new global::android.view.LayoutInflater.FilterDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::android.view.LayoutInflater from(android.content.Context arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.LayoutInflater._m0.native == global::System.IntPtr.Zero)
global::android.view.LayoutInflater._m0 = @__env.GetStaticMethodIDNoThrow(global::android.view.LayoutInflater.staticClass, "from", "(Landroid/content/Context;)Landroid/view/LayoutInflater;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.view.LayoutInflater.staticClass, global::android.view.LayoutInflater._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.LayoutInflater;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::android.view.LayoutInflater.Factory getFactory()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.LayoutInflater.Factory>(this, global::android.view.LayoutInflater.staticClass, "getFactory", "()Landroid/view/LayoutInflater$Factory;", ref global::android.view.LayoutInflater._m1) as android.view.LayoutInflater.Factory;
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual global::android.content.Context getContext()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater.staticClass, "getContext", "()Landroid/content/Context;", ref global::android.view.LayoutInflater._m2) as android.content.Context;
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual global::android.view.View inflate(org.xmlpull.v1.XmlPullParser arg0, android.view.ViewGroup arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater.staticClass, "inflate", "(Lorg/xmlpull/v1/XmlPullParser;Landroid/view/ViewGroup;)Landroid/view/View;", ref global::android.view.LayoutInflater._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual global::android.view.View inflate(org.xmlpull.v1.XmlPullParser arg0, android.view.ViewGroup arg1, bool arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater.staticClass, "inflate", "(Lorg/xmlpull/v1/XmlPullParser;Landroid/view/ViewGroup;Z)Landroid/view/View;", ref global::android.view.LayoutInflater._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::android.view.View inflate(int arg0, android.view.ViewGroup arg1, bool arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater.staticClass, "inflate", "(ILandroid/view/ViewGroup;Z)Landroid/view/View;", ref global::android.view.LayoutInflater._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::android.view.View inflate(int arg0, android.view.ViewGroup arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater.staticClass, "inflate", "(ILandroid/view/ViewGroup;)Landroid/view/View;", ref global::android.view.LayoutInflater._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m7;
protected virtual global::android.view.View onCreateView(java.lang.String arg0, android.util.AttributeSet arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater.staticClass, "onCreateView", "(Ljava/lang/String;Landroid/util/AttributeSet;)Landroid/view/View;", ref global::android.view.LayoutInflater._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m8;
public abstract global::android.view.LayoutInflater cloneInContext(android.content.Context arg0);
private static global::MonoJavaBridge.MethodId _m9;
public virtual void setFactory(android.view.LayoutInflater.Factory arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.LayoutInflater.staticClass, "setFactory", "(Landroid/view/LayoutInflater$Factory;)V", ref global::android.view.LayoutInflater._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setFactory(global::android.view.LayoutInflater.FactoryDelegate arg0)
{
setFactory((global::android.view.LayoutInflater.FactoryDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual global::android.view.LayoutInflater.Filter getFilter()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.LayoutInflater.Filter>(this, global::android.view.LayoutInflater.staticClass, "getFilter", "()Landroid/view/LayoutInflater$Filter;", ref global::android.view.LayoutInflater._m10) as android.view.LayoutInflater.Filter;
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual void setFilter(android.view.LayoutInflater.Filter arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.LayoutInflater.staticClass, "setFilter", "(Landroid/view/LayoutInflater$Filter;)V", ref global::android.view.LayoutInflater._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setFilter(global::android.view.LayoutInflater.FilterDelegate arg0)
{
setFilter((global::android.view.LayoutInflater.FilterDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual global::android.view.View createView(java.lang.String arg0, java.lang.String arg1, android.util.AttributeSet arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater.staticClass, "createView", "(Ljava/lang/String;Ljava/lang/String;Landroid/util/AttributeSet;)Landroid/view/View;", ref global::android.view.LayoutInflater._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m13;
protected LayoutInflater(android.view.LayoutInflater arg0, android.content.Context arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.LayoutInflater._m13.native == global::System.IntPtr.Zero)
global::android.view.LayoutInflater._m13 = @__env.GetMethodIDNoThrow(global::android.view.LayoutInflater.staticClass, "<init>", "(Landroid/view/LayoutInflater;Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.LayoutInflater.staticClass, global::android.view.LayoutInflater._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m14;
protected LayoutInflater(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.LayoutInflater._m14.native == global::System.IntPtr.Zero)
global::android.view.LayoutInflater._m14 = @__env.GetMethodIDNoThrow(global::android.view.LayoutInflater.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.LayoutInflater.staticClass, global::android.view.LayoutInflater._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static LayoutInflater()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.LayoutInflater.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/LayoutInflater"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.LayoutInflater))]
internal sealed partial class LayoutInflater_ : android.view.LayoutInflater
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal LayoutInflater_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::android.view.LayoutInflater cloneInContext(android.content.Context arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.LayoutInflater_.staticClass, "cloneInContext", "(Landroid/content/Context;)Landroid/view/LayoutInflater;", ref global::android.view.LayoutInflater_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.LayoutInflater;
}
static LayoutInflater_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.LayoutInflater_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/LayoutInflater"));
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: folio/rpc/group_booking_folio_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Folio.RPC {
public static partial class GroupBookingFolioSvc
{
static readonly string __ServiceName = "holms.types.folio.rpc.GroupBookingFolioSvc";
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator> __Marshaller_GroupBookingIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.GroupBookingFolioState> __Marshaller_GroupBookingFolioState = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.GroupBookingFolioState.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> __Marshaller_FolioSvcGetOnFileCardsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest> __Marshaller_GroupBookingFolioSvcCardAuthorizationFromTokenRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> __Marshaller_CardAuthorizationResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest> __Marshaller_GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest> __Marshaller_GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest> __Marshaller_FolioSvcAuthorizationModificationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> __Marshaller_FolioSvcAuthorizationModificationResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest> __Marshaller_GroupBookingFolioSvcPostCardPaymentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> __Marshaller_FolioSvcPostCardPaymentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest> __Marshaller_GroupBookingFolioSvcPostCheckPaymentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> __Marshaller_FolioSvcPostCheckPaymentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest> __Marshaller_GroupBookingFolioSvcPostCashPaymentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> __Marshaller_FolioSvcPostCashResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator> __Marshaller_FolioCheckCashPaymentIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator> __Marshaller_PaymentCardSaleIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> __Marshaller_FolioSvcCancelPaymentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest> __Marshaller_GroupBookingFolioSvcPaymentCardRefundRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> __Marshaller_FolioSvcRefundResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest> __Marshaller_GroupBookingFolioSvcPostCashRefundRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest> __Marshaller_GroupBookingFolioSvcPostLodgingChargeCorrectionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest> __Marshaller_GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest> __Marshaller_GroupBookingFolioSvcPostMiscChargeCorrectionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator> __Marshaller_PaymentCardRefundIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.MonetaryAmount> __Marshaller_MonetaryAmount = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.MonetaryAmount.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest> __Marshaller_GetFolioBalanceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioBalancesResponse> __Marshaller_FolioBalancesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioBalancesResponse.Parser.ParseFrom);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Folio.GroupBookingFolioState> __Method_GetGroupBookingFolioState = new grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Folio.GroupBookingFolioState>(
grpc::MethodType.Unary,
__ServiceName,
"GetGroupBookingFolioState",
__Marshaller_GroupBookingIndicator,
__Marshaller_GroupBookingFolioState);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> __Method_GetOnFileCards = new grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetOnFileCards",
__Marshaller_GroupBookingIndicator,
__Marshaller_FolioSvcGetOnFileCardsResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> __Method_AddCardAuthorizationFromStoredCard = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AddCardAuthorizationFromStoredCard",
__Marshaller_GroupBookingFolioSvcCardAuthorizationFromTokenRequest,
__Marshaller_CardAuthorizationResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> __Method_AddCardAuthorizationFromPresentedCard = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AddCardAuthorizationFromPresentedCard",
__Marshaller_GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest,
__Marshaller_CardAuthorizationResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> __Method_AddCardAuthorizationFromNotPresentCard = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AddCardAuthorizationFromNotPresentCard",
__Marshaller_GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest,
__Marshaller_CardAuthorizationResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest, global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> __Method_ChangeAuthorizationAmount = new grpc::Method<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest, global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ChangeAuthorizationAmount",
__Marshaller_FolioSvcAuthorizationModificationRequest,
__Marshaller_FolioSvcAuthorizationModificationResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> __Method_PostCardPayment = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"PostCardPayment",
__Marshaller_GroupBookingFolioSvcPostCardPaymentRequest,
__Marshaller_FolioSvcPostCardPaymentResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> __Method_PostCheckPayment = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"PostCheckPayment",
__Marshaller_GroupBookingFolioSvcPostCheckPaymentRequest,
__Marshaller_FolioSvcPostCheckPaymentResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> __Method_PostCashPayment = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse>(
grpc::MethodType.Unary,
__ServiceName,
"PostCashPayment",
__Marshaller_GroupBookingFolioSvcPostCashPaymentRequest,
__Marshaller_FolioSvcPostCashResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator, global::Google.Protobuf.WellKnownTypes.Empty> __Method_CancelCashCheckPayment = new grpc::Method<global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"CancelCashCheckPayment",
__Marshaller_FolioCheckCashPaymentIndicator,
__Marshaller_Empty);
static readonly grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> __Method_CancelCardPayment = new grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"CancelCardPayment",
__Marshaller_PaymentCardSaleIndicator,
__Marshaller_FolioSvcCancelPaymentResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest, global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> __Method_RefundTokenizedCard = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest, global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse>(
grpc::MethodType.Unary,
__ServiceName,
"RefundTokenizedCard",
__Marshaller_GroupBookingFolioSvcPaymentCardRefundRequest,
__Marshaller_FolioSvcRefundResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> __Method_PostCashRefund = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse>(
grpc::MethodType.Unary,
__ServiceName,
"PostCashRefund",
__Marshaller_GroupBookingFolioSvcPostCashRefundRequest,
__Marshaller_FolioSvcPostCashResponse);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PostLodgingChargeCorrection = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"PostLodgingChargeCorrection",
__Marshaller_GroupBookingFolioSvcPostLodgingChargeCorrectionRequest,
__Marshaller_Empty);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PostIncidentalChargeCorrection = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"PostIncidentalChargeCorrection",
__Marshaller_GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest,
__Marshaller_Empty);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PostMiscChargeCorrection = new grpc::Method<global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"PostMiscChargeCorrection",
__Marshaller_GroupBookingFolioSvcPostMiscChargeCorrectionRequest,
__Marshaller_Empty);
static readonly grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> __Method_CancelCardRefund = new grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"CancelCardRefund",
__Marshaller_PaymentCardRefundIndicator,
__Marshaller_FolioSvcCancelPaymentResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Primitive.MonetaryAmount> __Method_SuggestAuthorizationAmount = new grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Primitive.MonetaryAmount>(
grpc::MethodType.Unary,
__ServiceName,
"SuggestAuthorizationAmount",
__Marshaller_GroupBookingIndicator,
__Marshaller_MonetaryAmount);
static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest, global::HOLMS.Types.Folio.RPC.FolioBalancesResponse> __Method_GetFolioBalances = new grpc::Method<global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest, global::HOLMS.Types.Folio.RPC.FolioBalancesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetFolioBalances",
__Marshaller_GetFolioBalanceRequest,
__Marshaller_FolioBalancesResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of GroupBookingFolioSvc</summary>
public abstract partial class GroupBookingFolioSvcBase
{
/// <summary>
/// Get info
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.GroupBookingFolioState> GetGroupBookingFolioState(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCards(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Card authorization
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromStoredCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromPresentedCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromNotPresentCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> ChangeAuthorizationAmount(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Payment application/cancellation/refund
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> PostCardPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> PostCheckPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> CancelCashCheckPayment(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardPayment(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> RefundTokenizedCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashRefund(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Charge corrections
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PostLodgingChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PostIncidentalChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PostMiscChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
///Card Refund Cancelation
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.MonetaryAmount> SuggestAuthorizationAmount(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioBalancesResponse> GetFolioBalances(global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for GroupBookingFolioSvc</summary>
public partial class GroupBookingFolioSvcClient : grpc::ClientBase<GroupBookingFolioSvcClient>
{
/// <summary>Creates a new client for GroupBookingFolioSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public GroupBookingFolioSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for GroupBookingFolioSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public GroupBookingFolioSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected GroupBookingFolioSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected GroupBookingFolioSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Get info
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Folio.GroupBookingFolioState GetGroupBookingFolioState(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetGroupBookingFolioState(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get info
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Folio.GroupBookingFolioState GetGroupBookingFolioState(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetGroupBookingFolioState, null, options, request);
}
/// <summary>
/// Get info
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.GroupBookingFolioState> GetGroupBookingFolioStateAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetGroupBookingFolioStateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get info
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.GroupBookingFolioState> GetGroupBookingFolioStateAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetGroupBookingFolioState, null, options, request);
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse GetOnFileCards(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetOnFileCards(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse GetOnFileCards(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetOnFileCards, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCardsAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetOnFileCardsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCardsAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetOnFileCards, null, options, request);
}
/// <summary>
/// Card authorization
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromStoredCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AddCardAuthorizationFromStoredCard(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Card authorization
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromStoredCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AddCardAuthorizationFromStoredCard, null, options, request);
}
/// <summary>
/// Card authorization
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromStoredCardAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AddCardAuthorizationFromStoredCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Card authorization
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromStoredCardAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromTokenRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AddCardAuthorizationFromStoredCard, null, options, request);
}
public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromPresentedCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AddCardAuthorizationFromPresentedCard(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromPresentedCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AddCardAuthorizationFromPresentedCard, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromPresentedCardAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AddCardAuthorizationFromPresentedCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromPresentedCardAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromPresentCardRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AddCardAuthorizationFromPresentedCard, null, options, request);
}
public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromNotPresentCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AddCardAuthorizationFromNotPresentCard(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromNotPresentCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AddCardAuthorizationFromNotPresentCard, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromNotPresentCardAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AddCardAuthorizationFromNotPresentCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromNotPresentCardAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcCardAuthorizationFromNotPresentCardRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AddCardAuthorizationFromNotPresentCard, null, options, request);
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse ChangeAuthorizationAmount(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ChangeAuthorizationAmount(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse ChangeAuthorizationAmount(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ChangeAuthorizationAmount, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> ChangeAuthorizationAmountAsync(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ChangeAuthorizationAmountAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> ChangeAuthorizationAmountAsync(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ChangeAuthorizationAmount, null, options, request);
}
/// <summary>
/// Payment application/cancellation/refund
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse PostCardPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostCardPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Payment application/cancellation/refund
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse PostCardPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PostCardPayment, null, options, request);
}
/// <summary>
/// Payment application/cancellation/refund
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> PostCardPaymentAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostCardPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Payment application/cancellation/refund
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> PostCardPaymentAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCardPaymentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PostCardPayment, null, options, request);
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse PostCheckPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostCheckPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse PostCheckPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PostCheckPayment, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> PostCheckPaymentAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostCheckPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> PostCheckPaymentAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCheckPaymentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PostCheckPayment, null, options, request);
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse PostCashPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostCashPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse PostCashPayment(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PostCashPayment, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashPaymentAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostCashPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashPaymentAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashPaymentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PostCashPayment, null, options, request);
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty CancelCashCheckPayment(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CancelCashCheckPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty CancelCashCheckPayment(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CancelCashCheckPayment, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CancelCashCheckPaymentAsync(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CancelCashCheckPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CancelCashCheckPaymentAsync(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CancelCashCheckPayment, null, options, request);
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse CancelCardPayment(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CancelCardPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse CancelCardPayment(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CancelCardPayment, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardPaymentAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CancelCardPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardPaymentAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CancelCardPayment, null, options, request);
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse RefundTokenizedCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RefundTokenizedCard(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse RefundTokenizedCard(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_RefundTokenizedCard, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> RefundTokenizedCardAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RefundTokenizedCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> RefundTokenizedCardAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPaymentCardRefundRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_RefundTokenizedCard, null, options, request);
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse PostCashRefund(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostCashRefund(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse PostCashRefund(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PostCashRefund, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashRefundAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostCashRefundAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashRefundAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostCashRefundRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PostCashRefund, null, options, request);
}
/// <summary>
/// Charge corrections
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty PostLodgingChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostLodgingChargeCorrection(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Charge corrections
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty PostLodgingChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PostLodgingChargeCorrection, null, options, request);
}
/// <summary>
/// Charge corrections
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostLodgingChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostLodgingChargeCorrectionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Charge corrections
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostLodgingChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostLodgingChargeCorrectionRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PostLodgingChargeCorrection, null, options, request);
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty PostIncidentalChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostIncidentalChargeCorrection(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty PostIncidentalChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PostIncidentalChargeCorrection, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostIncidentalChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostIncidentalChargeCorrectionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostIncidentalChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PostIncidentalChargeCorrection, null, options, request);
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty PostMiscChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostMiscChargeCorrection(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Google.Protobuf.WellKnownTypes.Empty PostMiscChargeCorrection(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PostMiscChargeCorrection, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostMiscChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostMiscChargeCorrectionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostMiscChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.GroupBookingFolioSvcPostMiscChargeCorrectionRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PostMiscChargeCorrection, null, options, request);
}
/// <summary>
///Card Refund Cancelation
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse CancelCardRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CancelCardRefund(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
///Card Refund Cancelation
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse CancelCardRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CancelCardRefund, null, options, request);
}
/// <summary>
///Card Refund Cancelation
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardRefundAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CancelCardRefundAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
///Card Refund Cancelation
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardRefundAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CancelCardRefund, null, options, request);
}
public virtual global::HOLMS.Types.Primitive.MonetaryAmount SuggestAuthorizationAmount(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SuggestAuthorizationAmount(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Primitive.MonetaryAmount SuggestAuthorizationAmount(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SuggestAuthorizationAmount, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.MonetaryAmount> SuggestAuthorizationAmountAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SuggestAuthorizationAmountAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.MonetaryAmount> SuggestAuthorizationAmountAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SuggestAuthorizationAmount, null, options, request);
}
public virtual global::HOLMS.Types.Folio.RPC.FolioBalancesResponse GetFolioBalances(global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetFolioBalances(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Folio.RPC.FolioBalancesResponse GetFolioBalances(global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetFolioBalances, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioBalancesResponse> GetFolioBalancesAsync(global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetFolioBalancesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioBalancesResponse> GetFolioBalancesAsync(global::HOLMS.Types.Folio.RPC.GetFolioBalanceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetFolioBalances, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override GroupBookingFolioSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new GroupBookingFolioSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(GroupBookingFolioSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetGroupBookingFolioState, serviceImpl.GetGroupBookingFolioState)
.AddMethod(__Method_GetOnFileCards, serviceImpl.GetOnFileCards)
.AddMethod(__Method_AddCardAuthorizationFromStoredCard, serviceImpl.AddCardAuthorizationFromStoredCard)
.AddMethod(__Method_AddCardAuthorizationFromPresentedCard, serviceImpl.AddCardAuthorizationFromPresentedCard)
.AddMethod(__Method_AddCardAuthorizationFromNotPresentCard, serviceImpl.AddCardAuthorizationFromNotPresentCard)
.AddMethod(__Method_ChangeAuthorizationAmount, serviceImpl.ChangeAuthorizationAmount)
.AddMethod(__Method_PostCardPayment, serviceImpl.PostCardPayment)
.AddMethod(__Method_PostCheckPayment, serviceImpl.PostCheckPayment)
.AddMethod(__Method_PostCashPayment, serviceImpl.PostCashPayment)
.AddMethod(__Method_CancelCashCheckPayment, serviceImpl.CancelCashCheckPayment)
.AddMethod(__Method_CancelCardPayment, serviceImpl.CancelCardPayment)
.AddMethod(__Method_RefundTokenizedCard, serviceImpl.RefundTokenizedCard)
.AddMethod(__Method_PostCashRefund, serviceImpl.PostCashRefund)
.AddMethod(__Method_PostLodgingChargeCorrection, serviceImpl.PostLodgingChargeCorrection)
.AddMethod(__Method_PostIncidentalChargeCorrection, serviceImpl.PostIncidentalChargeCorrection)
.AddMethod(__Method_PostMiscChargeCorrection, serviceImpl.PostMiscChargeCorrection)
.AddMethod(__Method_CancelCardRefund, serviceImpl.CancelCardRefund)
.AddMethod(__Method_SuggestAuthorizationAmount, serviceImpl.SuggestAuthorizationAmount)
.AddMethod(__Method_GetFolioBalances, serviceImpl.GetFolioBalances).Build();
}
}
}
#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;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
using osuTK;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A list container that enables its children to be rearranged via dragging.
/// </summary>
/// <remarks>
/// Adding duplicate items is not currently supported.
/// </remarks>
/// <typeparam name="TModel">The type of rearrangeable item.</typeparam>
public abstract class RearrangeableListContainer<TModel> : CompositeDrawable
{
private const float exp_base = 1.05f;
/// <summary>
/// The items contained by this <see cref="RearrangeableListContainer{TModel}"/>, in the order they are arranged.
/// </summary>
public readonly BindableList<TModel> Items = new BindableList<TModel>();
/// <summary>
/// The maximum exponent of the automatic scroll speed at the boundaries of this <see cref="RearrangeableListContainer{TModel}"/>.
/// </summary>
protected float MaxExponent = 50;
/// <summary>
/// The <see cref="ScrollContainer"/> containing the flow of items.
/// </summary>
protected readonly ScrollContainer<Drawable> ScrollContainer;
/// <summary>
/// The <see cref="FillFlowContainer"/> containing of all the <see cref="RearrangeableListItem{TModel}"/>s.
/// </summary>
protected readonly FillFlowContainer<RearrangeableListItem<TModel>> ListContainer;
/// <summary>
/// The mapping of <typeparamref name="TModel"/> to <see cref="RearrangeableListItem{TModel}"/>.
/// </summary>
protected IReadOnlyDictionary<TModel, RearrangeableListItem<TModel>> ItemMap => itemMap;
private readonly Dictionary<TModel, RearrangeableListItem<TModel>> itemMap = new Dictionary<TModel, RearrangeableListItem<TModel>>();
private RearrangeableListItem<TModel> currentlyDraggedItem;
private Vector2 screenSpaceDragPosition;
/// <summary>
/// Creates a new <see cref="RearrangeableListContainer{TModel}"/>.
/// </summary>
protected RearrangeableListContainer()
{
ListContainer = CreateListFillFlowContainer().With(d =>
{
d.RelativeSizeAxes = Axes.X;
d.AutoSizeAxes = Axes.Y;
d.Direction = FillDirection.Vertical;
});
InternalChild = ScrollContainer = CreateScrollContainer().With(d =>
{
d.RelativeSizeAxes = Axes.Both;
d.Child = ListContainer;
});
Items.CollectionChanged += collectionChanged;
}
private void collectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
addItems(e.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
removeItems(e.OldItems);
// Explicitly reset scroll position here so that ScrollContainer doesn't retain our
// scroll position if we quickly add new items after calling a Clear().
if (Items.Count == 0)
ScrollContainer.ScrollToStart();
break;
case NotifyCollectionChangedAction.Reset:
currentlyDraggedItem = null;
ListContainer.Clear();
itemMap.Clear();
break;
case NotifyCollectionChangedAction.Replace:
removeItems(e.OldItems);
addItems(e.NewItems);
break;
}
}
private void removeItems(IList items)
{
foreach (var item in items.Cast<TModel>())
{
if (currentlyDraggedItem != null && EqualityComparer<TModel>.Default.Equals(currentlyDraggedItem.Model, item))
currentlyDraggedItem = null;
ListContainer.Remove(itemMap[item]);
itemMap.Remove(item);
}
reSort();
}
private void addItems(IList items)
{
var drawablesToAdd = new List<Drawable>();
foreach (var item in items.Cast<TModel>())
{
if (itemMap.ContainsKey(item))
{
throw new InvalidOperationException(
$"Duplicate items cannot be added to a {nameof(BindableList<TModel>)} that is currently bound with a {nameof(RearrangeableListContainer<TModel>)}.");
}
var drawable = CreateDrawable(item).With(d =>
{
d.StartArrangement += startArrangement;
d.Arrange += arrange;
d.EndArrangement += endArrangement;
});
drawablesToAdd.Add(drawable);
itemMap[item] = drawable;
}
if (!IsLoaded)
addToHierarchy(drawablesToAdd);
else
LoadComponentsAsync(drawablesToAdd, addToHierarchy);
void addToHierarchy(IEnumerable<Drawable> drawables)
{
foreach (var d in drawables.Cast<RearrangeableListItem<TModel>>())
{
// Don't add drawables whose models were removed during the async load, or drawables that are no longer attached to the contained model.
if (itemMap.TryGetValue(d.Model, out var modelDrawable) && modelDrawable == d)
ListContainer.Add(d);
}
reSort();
}
}
private void reSort()
{
for (int i = 0; i < Items.Count; i++)
{
var drawable = itemMap[Items[i]];
// If the async load didn't complete, the item wouldn't exist in the container and an exception would be thrown
if (drawable.Parent == ListContainer)
ListContainer.SetLayoutPosition(drawable, i);
}
}
private void startArrangement(RearrangeableListItem<TModel> item, DragStartEvent e)
{
currentlyDraggedItem = item;
screenSpaceDragPosition = e.ScreenSpaceMousePosition;
}
private void arrange(RearrangeableListItem<TModel> item, DragEvent e) => screenSpaceDragPosition = e.ScreenSpaceMousePosition;
private void endArrangement(RearrangeableListItem<TModel> item, DragEndEvent e) => currentlyDraggedItem = null;
protected override void Update()
{
base.Update();
if (currentlyDraggedItem != null)
updateScrollPosition();
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
if (currentlyDraggedItem != null)
updateArrangement();
}
private void updateScrollPosition()
{
Vector2 localPos = ScrollContainer.ToLocalSpace(screenSpaceDragPosition);
float scrollSpeed = 0;
if (localPos.Y < 0)
{
var power = Math.Min(MaxExponent, Math.Abs(localPos.Y));
scrollSpeed = (float)(-MathF.Pow(exp_base, power) * Clock.ElapsedFrameTime * 0.1);
}
else if (localPos.Y > ScrollContainer.DrawHeight)
{
var power = Math.Min(MaxExponent, Math.Abs(ScrollContainer.DrawHeight - localPos.Y));
scrollSpeed = (float)(MathF.Pow(exp_base, power) * Clock.ElapsedFrameTime * 0.1);
}
if ((scrollSpeed < 0 && ScrollContainer.Current > 0) || (scrollSpeed > 0 && !ScrollContainer.IsScrolledToEnd()))
ScrollContainer.ScrollBy(scrollSpeed);
}
private void updateArrangement()
{
var localPos = ListContainer.ToLocalSpace(screenSpaceDragPosition);
int srcIndex = Items.IndexOf(currentlyDraggedItem.Model);
// Find the last item with position < mouse position. Note we can't directly use
// the item positions as they are being transformed
float heightAccumulator = 0;
int dstIndex = 0;
for (; dstIndex < Items.Count; dstIndex++)
{
var drawable = itemMap[Items[dstIndex]];
if (!drawable.IsLoaded || !drawable.IsPresent)
continue;
// Using BoundingBox here takes care of scale, paddings, etc...
float height = drawable.BoundingBox.Height;
// Rearrangement should occur only after the mid-point of items is crossed
heightAccumulator += height / 2;
// Check if the midpoint has been crossed (i.e. cursor is located above the midpoint)
if (heightAccumulator > localPos.Y)
{
if (dstIndex > srcIndex)
{
// Suppose an item is dragged just slightly below its own midpoint. The rearrangement condition (accumulator > pos) will be satisfied for the next immediate item
// but not the currently-dragged item, which will invoke a rearrangement. This is an off-by-one condition.
// Rearrangement should not occur until the midpoint of the next item is crossed, and so to fix this the next item's index is discarded.
dstIndex--;
}
break;
}
// Add the remainder of the height of the current item
heightAccumulator += height / 2 + ListContainer.Spacing.Y;
}
dstIndex = Math.Clamp(dstIndex, 0, Items.Count - 1);
if (srcIndex == dstIndex)
return;
Items.Move(srcIndex, dstIndex);
// Todo: this could be optimised, but it's a very simple iteration over all the items
reSort();
}
/// <summary>
/// Creates the <see cref="FillFlowContainer{DrawableRearrangeableListItem}"/> for the items.
/// </summary>
protected virtual FillFlowContainer<RearrangeableListItem<TModel>> CreateListFillFlowContainer() => new FillFlowContainer<RearrangeableListItem<TModel>>();
/// <summary>
/// Creates the <see cref="ScrollContainer"/> for the list of items.
/// </summary>
protected abstract ScrollContainer<Drawable> CreateScrollContainer();
/// <summary>
/// Creates the <see cref="Drawable"/> representation of an item.
/// </summary>
/// <param name="item">The item to create the <see cref="Drawable"/> representation of.</param>
/// <returns>The <see cref="RearrangeableListItem{TModel}"/>.</returns>
protected abstract RearrangeableListItem<TModel> CreateDrawable(TModel item);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Hosting;
using RoutingWebSite;
using Xunit;
namespace Microsoft.AspNetCore.Routing.FunctionalTests
{
public class EndpointRoutingSampleTest : IDisposable
{
private readonly HttpClient _client;
private readonly IHost _host;
private readonly TestServer _testServer;
public EndpointRoutingSampleTest()
{
var hostBuilder = Program.GetHostBuilder(new[] { Program.EndpointRoutingScenario, });
_host = hostBuilder.Build();
_testServer = _host.GetTestServer();
_host.Start();
_client = _testServer.CreateClient();
_client.BaseAddress = new Uri("http://localhost");
}
[Theory]
[InlineData("Branch1")]
[InlineData("Branch2")]
public async Task Routing_CanRouteRequest_ToBranchRouter(string branch)
{
// Arrange
var message = new HttpRequestMessage(HttpMethod.Get, $"{branch}/api/get/5");
// Act
var response = await _client.SendAsync(message);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal($"{branch} - API Get 5", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task MatchesRootPath_AndReturnsPlaintext()
{
// Arrange
var expectedContentType = "text/plain";
// Act
var response = await _client.GetAsync("/");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.NotNull(response.Content.Headers.ContentType);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType.MediaType);
}
[Fact]
public async Task MatchesStaticRouteTemplate_AndReturnsPlaintext()
{
// Arrange
var expectedContentType = "text/plain";
var expectedContent = "Plain text!";
// Act
var response = await _client.GetAsync("/plaintext");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.NotNull(response.Content.Headers.ContentType);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType.MediaType);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedContent, actualContent);
}
[Fact]
public async Task MatchesHelloMiddleware_AndReturnsPlaintext()
{
// Arrange
var expectedContentType = "text/plain";
var expectedContent = "Hello World";
// Act
var response = await _client.GetAsync("/helloworld");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.NotNull(response.Content.Headers.ContentType);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType.MediaType);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedContent, actualContent);
}
[Fact]
public async Task MatchesEndpoint_WithSuccessfulConstraintMatch()
{
// Arrange
var expectedContent = "WithConstraints";
// Act
var response = await _client.GetAsync("/withconstraints/555_001");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedContent, actualContent);
}
[Fact]
public async Task DoesNotMatchEndpoint_IfConstraintMatchFails()
{
// Arrange & Act
var response = await _client.GetAsync("/withconstraints/555");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task MatchesEndpoint_WithSuccessful_OptionalConstraintMatch()
{
// Arrange
var expectedContent = "withoptionalconstraints";
// Act
var response = await _client.GetAsync("/withoptionalconstraints/555_001");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedContent, actualContent);
}
[Fact]
public async Task MatchesEndpoint_WithSuccessful_OptionalConstraintMatch_NoValueForParameter()
{
// Arrange
var expectedContent = "withoptionalconstraints";
// Act
var response = await _client.GetAsync("/withoptionalconstraints");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedContent, actualContent);
}
[Fact]
public async Task DoesNotMatchEndpoint_IfOptionalConstraintMatchFails()
{
// Arrange & Act
var response = await _client.GetAsync("/withoptionalconstraints/555");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Theory]
[InlineData("/WithSingleAsteriskCatchAll/a/b/c", "Link: /WithSingleAsteriskCatchAll/a%2Fb%2Fc")]
[InlineData("/WithSingleAsteriskCatchAll/a/b b1/c c1", "Link: /WithSingleAsteriskCatchAll/a%2Fb%20b1%2Fc%20c1")]
public async Task GeneratesLink_ToEndpointWithSingleAsteriskCatchAllParameter_EncodesValue(
string url,
string expected)
{
// Arrange & Act
var response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expected, actualContent);
}
[Theory]
[InlineData("/WithDoubleAsteriskCatchAll/a/b/c", "Link: /WithDoubleAsteriskCatchAll/a/b/c")]
[InlineData("/WithDoubleAsteriskCatchAll/a/b/c/", "Link: /WithDoubleAsteriskCatchAll/a/b/c/")]
[InlineData("/WithDoubleAsteriskCatchAll/a//b/c", "Link: /WithDoubleAsteriskCatchAll/a//b/c")]
public async Task GeneratesLink_ToEndpointWithDoubleAsteriskCatchAllParameter_DoesNotEncodeSlashes(
string url,
string expected)
{
// Arrange & Act
var response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expected, actualContent);
}
[Fact]
public async Task GeneratesLink_ToEndpointWithDoubleAsteriskCatchAllParameter_EncodesContentOtherThanSlashes()
{
// Arrange & Act
var response = await _client.GetAsync("/WithDoubleAsteriskCatchAll/a/b b1/c c1");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal("Link: /WithDoubleAsteriskCatchAll/a/b%20b1/c%20c1", actualContent);
}
[Fact]
public async Task MapGet_HasConventionMetadata()
{
// Arrange & Act
var response = await _client.GetAsync("/convention");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var actualContent = await response.Content.ReadAsStringAsync();
Assert.Equal("Has metadata", actualContent);
}
public void Dispose()
{
_testServer.Dispose();
_client.Dispose();
_host.Dispose();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using CryptographicException = System.Security.Cryptography.CryptographicException;
using SafeBCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeBCryptKeyHandle;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using X509KeyUsageFlags = System.Security.Cryptography.X509Certificates.X509KeyUsageFlags;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
internal static partial class Interop
{
public static partial class crypt32
{
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
out CertEncodingType pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
out FormatType pdwFormatType,
out SafeCertStoreHandle phCertStore,
out SafeCryptMsgHandle phMsg,
out SafeCertContextHandle ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
IntPtr phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
out SafeCertStoreHandle phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] byte[] pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out CRYPTOAPI_BLOB pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetCertificateContextProperty")]
public static extern bool CertGetCertificateContextPropertyString(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] StringBuilder pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPTOAPI_BLOB* pvData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPT_KEY_PROV_INFO* pvData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")]
public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStringType pvTypePara, [Out] StringBuilder pszNameString, int cchNameString);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertContextHandle CertDuplicateCertificateContext(IntPtr pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertDuplicateCertificateContext")]
public static extern SafeCertContextHandleWithKeyContainerDeletion CertDuplicateCertificateContextWithKeyContainerDeletion(IntPtr pCertContext);
public static SafeCertStoreHandle CertOpenStore(CertStoreProvider lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, String pvPara)
{
return CertOpenStore((IntPtr)lpszStoreProvider, dwMsgAndCertEncodingType, hCryptProv, dwFlags, pvPara);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeCertStoreHandle CertOpenStore(IntPtr lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, [MarshalAs(UnmanagedType.LPWStr)] String pvPara);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertAddCertificateContextToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertAddCertificateLinkToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext);
/// <summary>
/// A less error-prone wrapper for CertEnumCertificatesInStore().
///
/// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with
/// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle
/// and returns "false" to indicate the the end of the store has been reached.
/// </summary>
public static bool CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, ref SafeCertContextHandle pCertContext)
{
unsafe
{
CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect();
pCertContext = CertEnumCertificatesInStore(hCertStore, pPrevCertContext);
return !pCertContext.IsInvalid;
}
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe SafeCertContextHandle CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, CERT_CONTEXT* pPrevCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertStoreHandle PFXImportCertStore([In] ref CRYPTOAPI_BLOB pPFX, String szPassword, PfxCertStoreFlags dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, [Out] byte[] pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, out int pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertSerializeCertificateStoreElement(SafeCertContextHandle pCertContext, int dwFlags, [Out] byte[] pbElement, [In, Out] ref int pcbElement);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool PFXExportCertStore(SafeCertStoreHandle hStore, [In, Out] ref CRYPTOAPI_BLOB pPFX, String szPassword, PFXExportFlags dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertNameToStrW")]
public static extern int CertNameToStr(CertEncodingType dwCertEncodingType, [In] ref CRYPTOAPI_BLOB pName, CertNameStrTypeAndFlags dwStrType, StringBuilder psz, int csz);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertStrToNameW")]
public static extern bool CertStrToName(CertEncodingType dwCertEncodingType, String pszX500, CertNameStrTypeAndFlags dwStrType, IntPtr pvReserved, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded, IntPtr ppszError);
public static bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, FormatObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, StringBuilder pbFormat, ref int pcbFormat)
{
return CryptFormatObject(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, (IntPtr)lpszStructType, pbEncoded, cbEncoded, pbFormat, ref pcbFormat);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, [Out] StringBuilder pbFormat, [In, Out] ref int pcbFormat);
public static bool CryptDecodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, byte[] pvStructInfo, ref int pcbStructInfo)
{
return CryptDecodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptDecodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] byte[] pvStructInfo, [In, Out] ref int pcbStructInfo);
public static unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, void* pvStructInfo, ref int pcbStructInfo)
{
return CryptDecodeObjectPointer(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")]
private static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")]
public static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] String lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo);
public static unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[] pbEncoded, ref int pcbEncoded)
{
return CryptEncodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pvStructInfo, pbEncoded, ref pcbEncoded);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] String lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded);
public static unsafe byte[] EncodeObject(CryptDecodeObjectStructType lpszStructType, void* decoded)
{
int cb = 0;
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] encoded = new byte[cb];
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return encoded;
}
public static unsafe byte[] EncodeObject(String lpszStructType, void* decoded)
{
int cb = 0;
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] encoded = new byte[cb];
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return encoded;
}
public static unsafe bool CertGetCertificateChain(ChainEngine hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext)
{
return CertGetCertificateChain((IntPtr)hChainEngine, pCertContext, pTime, hStore, ref pChainPara, dwFlags, pvReserved, out ppChainContext);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe bool CertGetCertificateChain(IntPtr hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptHashPublicKeyInfo(IntPtr hCryptProv, int algId, int dwFlags, CertEncodingType dwCertEncodingType, [In] ref CERT_PUBLIC_KEY_INFO pInfo, [Out] byte[] pbComputedHash, [In, Out] ref int pcbComputedHash);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")]
public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStrTypeAndFlags pvPara, [Out] StringBuilder pszNameString, int cchNameString);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertSaveStore(SafeCertStoreHandle hCertStore, CertEncodingType dwMsgAndCertEncodingType, CertStoreSaveAs dwSaveAs, CertStoreSaveTo dwSaveTo, ref CRYPTOAPI_BLOB pvSaveToPara, int dwFlags);
/// <summary>
/// A less error-prone wrapper for CertEnumCertificatesInStore().
///
/// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with
/// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle
/// and returns "false" to indicate the the end of the store has been reached.
/// </summary>
public static unsafe bool CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertFindType dwFindType, void* pvFindPara, ref SafeCertContextHandle pCertContext)
{
CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect();
pCertContext = CertFindCertificateInStore(hCertStore, CertEncodingType.All, CertFindFlags.None, dwFindType, pvFindPara, pPrevCertContext);
return !pCertContext.IsInvalid;
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static unsafe extern SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertEncodingType dwCertEncodingType, CertFindFlags dwFindFlags, CertFindType dwFindType, void* pvFindPara, CERT_CONTEXT* pPrevCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern int CertVerifyTimeValidity([In] ref FILETIME pTimeToVerify, [In] CERT_INFO* pCertInfo);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern CERT_EXTENSION* CertFindExtension([MarshalAs(UnmanagedType.LPStr)] String pszObjId, int cExtensions, CERT_EXTENSION* rgExtensions);
// Note: It's somewhat unusual to use an API enum as a parameter type to a P/Invoke but in this case, X509KeyUsageFlags was intentionally designed as bit-wise
// identical to the wincrypt CERT_*_USAGE values.
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CertGetIntendedKeyUsage(CertEncodingType dwCertEncodingType, CERT_INFO* pCertInfo, out X509KeyUsageFlags pbKeyUsage, int cbKeyUsage);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static unsafe extern bool CertGetValidUsages(int cCerts, [In] ref SafeCertContextHandle rghCerts, out int cNumOIDs, [Out] void* rghOIDs, [In, Out] ref int pcbOIDs);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertControlStore(SafeCertStoreHandle hCertStore, CertControlStoreFlags dwFlags, CertControlStoreType dwControlType, IntPtr pvCtrlPara);
// Note: CertDeleteCertificateFromStore always calls CertFreeCertificateContext on pCertContext, even if an error is encountered.
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertDeleteCertificateFromStore(CERT_CONTEXT* pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern void CertFreeCertificateChain(IntPtr pChainContext);
public static bool CertVerifyCertificateChainPolicy(ChainPolicy pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus)
{
return CertVerifyCertificateChainPolicy((IntPtr)pszPolicyOID, pChainContext, ref pPolicyPara, ref pPolicyStatus);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CertVerifyCertificateChainPolicy(IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In, Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertFreeCertificateContext(IntPtr pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgClose(IntPtr hCryptMsg);
#if !NETNATIVE
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptImportPublicKeyInfoEx2(CertEncodingType dwCertEncodingType, CERT_PUBLIC_KEY_INFO* pInfo, int dwFlags, void* pvAuxInfo, out SafeBCryptKeyHandle phKey);
#endif
}
}
| |
/*
* 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.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Data.Null
{
/// <summary>
/// NULL DataStore, do not store anything
/// </summary>
public class NullSimulationData : ISimulationDataStore
{
public NullSimulationData()
{
}
public NullSimulationData(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string dbfile)
{
return;
}
public void Dispose()
{
}
public void StoreRegionSettings(RegionSettings rs)
{
}
public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
{
//This connector doesn't support the windlight module yet
//Return default LL windlight settings
return new RegionLightShareData();
}
public void RemoveRegionWindlightSettings(UUID regionID)
{
}
public void StoreRegionWindlightSettings(RegionLightShareData wl)
{
//This connector doesn't support the windlight module yet
}
#region Environment Settings
private Dictionary<UUID, string> EnvironmentSettings = new Dictionary<UUID, string>();
public string LoadRegionEnvironmentSettings(UUID regionUUID)
{
lock (EnvironmentSettings)
{
if (EnvironmentSettings.ContainsKey(regionUUID))
return EnvironmentSettings[regionUUID];
}
return string.Empty;
}
public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings)
{
lock (EnvironmentSettings)
{
EnvironmentSettings[regionUUID] = settings;
}
}
public void RemoveRegionEnvironmentSettings(UUID regionUUID)
{
lock (EnvironmentSettings)
{
if (EnvironmentSettings.ContainsKey(regionUUID))
EnvironmentSettings.Remove(regionUUID);
}
}
#endregion
public RegionSettings LoadRegionSettings(UUID regionUUID)
{
RegionSettings rs = new RegionSettings();
rs.RegionUUID = regionUUID;
return rs;
}
public void StoreObject(SceneObjectGroup obj, UUID regionUUID)
{
}
public void RemoveObject(UUID obj, UUID regionUUID)
{
}
public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items)
{
}
public List<SceneObjectGroup> LoadObjects(UUID regionUUID)
{
return new List<SceneObjectGroup>();
}
Dictionary<UUID, TerrainData> m_terrains = new Dictionary<UUID, TerrainData>();
Dictionary<UUID, TerrainData> m_bakedterrains = new Dictionary<UUID, TerrainData>();
public void StoreTerrain(TerrainData ter, UUID regionID)
{
if (m_terrains.ContainsKey(regionID))
m_terrains.Remove(regionID);
m_terrains.Add(regionID, ter);
}
public void StoreBakedTerrain(TerrainData ter, UUID regionID)
{
if (m_bakedterrains.ContainsKey(regionID))
m_bakedterrains.Remove(regionID);
m_bakedterrains.Add(regionID, ter);
}
// Legacy. Just don't do this.
public void StoreTerrain(double[,] ter, UUID regionID)
{
TerrainData terrData = new HeightmapTerrainData(ter);
StoreTerrain(terrData, regionID);
}
// Legacy. Just don't do this.
// Returns 'null' if region not found
public double[,] LoadTerrain(UUID regionID)
{
if (m_terrains.ContainsKey(regionID))
{
return m_terrains[regionID].GetDoubles();
}
return null;
}
public TerrainData LoadTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ)
{
if (m_terrains.ContainsKey(regionID))
{
return m_terrains[regionID];
}
return null;
}
public TerrainData LoadBakedTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ)
{
if (m_bakedterrains.ContainsKey(regionID))
{
return m_bakedterrains[regionID];
}
return null;
}
public void RemoveLandObject(UUID globalID)
{
}
public void StoreLandObject(ILandObject land)
{
}
public List<LandData> LoadLandObjects(UUID regionUUID)
{
return new List<LandData>();
}
public void Shutdown()
{
}
public UUID[] GetObjectIDs(UUID regionID)
{
return new UUID[0];
}
public void SaveExtra(UUID regionID, string name, string value)
{
}
public void RemoveExtra(UUID regionID, string name)
{
}
public Dictionary<string, string> GetExtra(UUID regionID)
{
return null;
}
}
}
| |
using System;
using System.Reactive.Linq;
using Foundation;
using AppKit;
using CoreGraphics;
using MusicPlayer.Managers;
using MusicPlayer.Models;
using MusicPlayer.Data;
using SDWebImage;
namespace MusicPlayer
{
//[Register("PlaybackBar")]
public class PlaybackBar : NSColorView
{
NSImageView AlbumArt;
NSButton previous;
NSButton next;
NSButton play;
TwoLabelView textView;
ProgressView progress;
VideoView videoView;
NSSlider volumeSlider;
NSButton shuffle;
NSButton repeat;
NSTextField remaining;
NSTextField time;
NSButton thumbsDown;
NSButton thumbsUp;
public PlaybackBar (IntPtr handle) : base (handle)
{
AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable;
}
public PlaybackBar (CGRect rect) : base (rect)
{
BackgroundColor = NSColor.ControlBackground;
AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable;
AddSubview (AlbumArt = new NSImageView (new CGRect (0, 0, 67, 67)));
videoView = new VideoView { WantsLayer = true, Hidden = true };
videoView.MakeBackingLayer ();
AddSubview (previous = CreateButton ("SVG/previous.svg", PlaybackManager.Shared.Previous));
AddSubview (play = CreateButton ("SVG/playButtonBordered.svg",()=>{
if(playing)
PlaybackManager.Shared.Pause();
else
PlaybackManager.Shared.Play();
}));
AddSubview (next = CreateButton ("SVG/next.svg",()=>PlaybackManager.Shared.NextTrack()));
AddSubview (textView = new TwoLabelView ());
AddSubview (progress = new ProgressView());
AddSubview(shuffle = CreateButton("SVG/shuffle.svg",25,PlaybackManager.Shared.ToggleRandom));
AddSubview(repeat = CreateButton("SVG/repeat.svg",25,PlaybackManager.Shared.ToggleRepeat));
AddSubview(time = new NSTextField{StringValue = "0000:00"}.StyleAsSubText());
time.SizeToFit();
AddSubview(remaining = new NSTextField{StringValue = "0000:00", Alignment = NSTextAlignment.Right}.StyleAsSubText());
remaining.SizeToFit();
AddSubview(volumeSlider = new NSSlider {DoubleValue = Settings.CurrentVolume, MinValue = 0, MaxValue = 1});
volumeSlider.Activated += (object sender, EventArgs e) =>
{
Settings.CurrentVolume = (float)volumeSlider.DoubleValue;
};
volumeSlider.SizeToFit();
AddSubview(thumbsDown = CreateButton("SVG/thumbsDown.svg", 30, async () =>
{
var song = MusicManager.Shared.GetCurrentSong();
if(song.Rating != 1)
await MusicManager.Shared.ThumbsDown(song);
else
{
await MusicManager.Shared.Unrate(song);
}
SetThumbsState(song);
}));
AddSubview(thumbsUp = CreateButton("SVG/thumbsUp.svg", 30, async () =>
{
var song = MusicManager.Shared.GetCurrentSong();
if (song.Rating != 5)
await MusicManager.Shared.ThumbsUp(song);
else
await MusicManager.Shared.Unrate(song);
SetThumbsState(song);
}));
Update (PlaybackManager.Shared.NativePlayer.CurrentSong);
var dropShadow = new NSShadow{
ShadowColor = NSColor.Black,
};
this.WantsLayer = true;
this.Shadow = dropShadow;
NotificationManager.Shared.CurrentSongChanged += (sender, e) => Update (e.Data);
NotificationManager.Shared.PlaybackStateChanged += (sender, e) => SetState (e.Data);
NotificationManager.Shared.VideoPlaybackChanged += (sender, e) => SetVideoState (Settings.CurrentPlaybackIsVideo);
NotificationManager.Shared.CurrentTrackPositionChanged += (object sender, SimpleTables.EventArgs<TrackPosition> e) => {
var data = e.Data;
//timeLabel.Text = data.CurrentTimeString;
//remainingTimeLabel.Text = data.RemainingTimeString;
progress.Progress = data.Percent;
time.StringValue = data.CurrentTimeString;
remaining.StringValue = data.RemainingTimeString;
};
NotificationManager.Shared.ShuffleChanged += (sender, args) => SetShuffleState(args.Data);
NotificationManager.Shared.RepeatChanged += (sender, args) => SetRepeatState(args.Data);
NotificationManager.Shared.SongDownloadPulsed += (object sender, NotificationManager.SongDowloadEventArgs e) => {
if (e.SongId != Settings.CurrentSong)
return;
progress.DownloadProgress = e.Percent;
};
// NotificationManager.Shared.ToggleFullScreenVideo += (s, a) => ToggleFullScreenVideo();
SetState (PlaybackState.Stopped);
SetShuffleState(Settings.ShuffleSongs);
SetRepeatState(Settings.RepeatMode);
}
const float buttonSize = 50f;
NSButton CreateButton (string svg, Action clicked)
{
var button = CreateButton(svg, buttonSize, clicked);
return button;
}
NSButton CreateButton (string svg,float size , Action clicked)
{
var button = new NSButton (new CGRect (0, 0, size, size));
button.Image = svg.LoadImageFromSvg (new NGraphics.Size (25, 25), NSColor.ControlText);
button.Bordered = false;
button.Activated += (sender, e) => clicked();
button.ImagePosition = NSCellImagePosition.ImageOnly;
return button;
}
public async void Update (Song song)
{
textView.TopLabel.StringValue = song?.Name ?? "";
textView.BottomLabel.StringValue = song?.DetailText ?? "";
textView.ResizeSubviewsWithOldSize (CGSize.Empty);
progress.DownloadProgress = 1f;
SetThumbsState(song);
//TODO: default album art;
await AlbumArt.LoadFromItem (song);
}
bool playing;
void SetState (PlaybackState state)
{
switch (state) {
case PlaybackState.Paused:
case PlaybackState.Stopped:
playing = false;
play.Image = "SVG/playButtonBordered.svg".LoadImageFromSvg (new NGraphics.Size (50, 50), NSColor.ControlText);
break;
default:
CheckVideoStatus();
playing = true;
play.Image = "SVG/pauseButtonBordered.svg".LoadImageFromSvg (new NGraphics.Size (50, 50), NSColor.ControlText);
SetVideoState (Settings.CurrentPlaybackIsVideo);
break;
}
}
bool isSetup;
void CheckVideoStatus()
{
if (isSetup)
return;
AddSubview(videoView);
SetVideoState(IsVideo);
}
void SetShuffleState (bool shuffleSongs)
{
const float imageSize = 20;
shuffle.Image = shuffleSongs ? Images.GetShuffleOnImage(imageSize) : Images.GetShuffleOffImage(imageSize);
}
void SetRepeatState (RepeatMode repeatMode)
{
const float imageSize =15;
NSImage image = null;
switch (repeatMode)
{
case RepeatMode.RepeatAll:
image = Images.GetRepeatOnImage(imageSize);
break;
case RepeatMode.RepeatOne:
image = Images.GetRepeatOneImage(imageSize);
break;
default:
image = Images.GetRepeatImage(imageSize);
break;
}
repeat.Image = image;
}
bool IsVideo;
void SetVideoState(bool isVideo)
{
IsVideo = isVideo;
videoView.Hidden = !isVideo || VideoPlaybackWindowController.IsVisible;
if (!videoView.Hidden)
videoView.Show ();
}
public void SetThumbsState(Song song)
{
const float imageSize = 25;
thumbsDown.Image = song?.Rating == 1 ? Images.GetThumbsDownOnImage(imageSize) : Images.GetThumbsDownOffImage(imageSize);
thumbsUp.Image = song?.Rating == 5 ? Images.GetThumbsUpOnImage(imageSize) : Images.GetThumbsUpOffImage(imageSize);
}
public override bool IsFlipped {
get {
return true;
}
}
const float padding = 5;
const float minWidth = 250;
const float progressHeight = 15f;
const float volumeWidth = 150f;
public override void ResizeSubviewsWithOldSize (CGSize oldSize)
{
base.ResizeSubviewsWithOldSize (oldSize);
var bounds = Bounds;
var frame = bounds;
frame.Width = bounds.Height;
if (AlbumArt == null)
return;
AlbumArt.Frame = videoView.Frame = frame;
videoView.ResizeSubviewsWithOldSize (videoView.Bounds.Size);
var left = frame.Right + padding;
var midY = bounds.Height / 2;
var buttonx = NMath.Max((bounds.Width / 2) - (buttonSize * 1.5f) - padding*2 - 30, minWidth);
frame.Y += 5;
frame.Height -= 5;
frame.X = left;
frame.Width = buttonx - left;
textView.Frame = frame;
left = frame.Right + padding;
frame = thumbsDown.Frame;
frame.X = left;
frame.Y = midY - (frame.Height/2) + padding;
thumbsDown.Frame = frame;
left = frame.Right + padding;
frame = new CGRect (left, 0, bounds.Height, bounds.Height);
previous.Frame = frame;
frame.X = frame.Right + padding;
play.Frame = frame;
frame.X = frame.Right + padding;
next.Frame = frame;
var right = frame.Right + padding;
frame = thumbsUp.Frame;
frame.X = right;
frame.Y = midY - (frame.Height/2) - padding;
thumbsUp.Frame = frame;
right = frame.Right + padding;
frame = shuffle.Frame;
frame.X = right;
frame.Y = midY - frame.Height;
shuffle.Frame = frame;
frame.Y = midY;
repeat.Frame = frame;
frame = bounds;
frame.Height = progressHeight;
frame.X = AlbumArt.Frame.Right;
frame.Width -= frame.X;
progress.Frame = frame;
left = frame.Left;
right = frame.Right;
frame = time.Frame;
frame.X = left + padding;
frame.Y = 3;
time.Frame = frame;
frame.X = right - (frame.Width + padding);
remaining.Frame = frame;
frame = volumeSlider.Frame;
frame.Width = volumeWidth;
frame.X = bounds.Right - volumeWidth - padding;
frame.Y = midY - (frame.Height / 2) + padding;
volumeSlider.Frame = frame;
}
}
}
| |
// 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 lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.NetworkSecurity.V1Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedNetworkSecurityClientTest
{
[xunit::FactAttribute]
public void GetAuthorizationPolicyRequestObject()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
};
AuthorizationPolicy expectedResponse = new AuthorizationPolicy
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Action = AuthorizationPolicy.Types.Action.Deny,
Rules =
{
new AuthorizationPolicy.Types.Rule(),
},
};
mockGrpcClient.Setup(x => x.GetAuthorizationPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
AuthorizationPolicy response = client.GetAuthorizationPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAuthorizationPolicyRequestObjectAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
};
AuthorizationPolicy expectedResponse = new AuthorizationPolicy
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Action = AuthorizationPolicy.Types.Action.Deny,
Rules =
{
new AuthorizationPolicy.Types.Rule(),
},
};
mockGrpcClient.Setup(x => x.GetAuthorizationPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
AuthorizationPolicy responseCallSettings = await client.GetAuthorizationPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AuthorizationPolicy responseCancellationToken = await client.GetAuthorizationPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAuthorizationPolicy()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
};
AuthorizationPolicy expectedResponse = new AuthorizationPolicy
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Action = AuthorizationPolicy.Types.Action.Deny,
Rules =
{
new AuthorizationPolicy.Types.Rule(),
},
};
mockGrpcClient.Setup(x => x.GetAuthorizationPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
AuthorizationPolicy response = client.GetAuthorizationPolicy(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAuthorizationPolicyAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
};
AuthorizationPolicy expectedResponse = new AuthorizationPolicy
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Action = AuthorizationPolicy.Types.Action.Deny,
Rules =
{
new AuthorizationPolicy.Types.Rule(),
},
};
mockGrpcClient.Setup(x => x.GetAuthorizationPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
AuthorizationPolicy responseCallSettings = await client.GetAuthorizationPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AuthorizationPolicy responseCancellationToken = await client.GetAuthorizationPolicyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAuthorizationPolicyResourceNames()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
};
AuthorizationPolicy expectedResponse = new AuthorizationPolicy
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Action = AuthorizationPolicy.Types.Action.Deny,
Rules =
{
new AuthorizationPolicy.Types.Rule(),
},
};
mockGrpcClient.Setup(x => x.GetAuthorizationPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
AuthorizationPolicy response = client.GetAuthorizationPolicy(request.AuthorizationPolicyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAuthorizationPolicyResourceNamesAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
};
AuthorizationPolicy expectedResponse = new AuthorizationPolicy
{
AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Action = AuthorizationPolicy.Types.Action.Deny,
Rules =
{
new AuthorizationPolicy.Types.Rule(),
},
};
mockGrpcClient.Setup(x => x.GetAuthorizationPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
AuthorizationPolicy responseCallSettings = await client.GetAuthorizationPolicyAsync(request.AuthorizationPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AuthorizationPolicy responseCancellationToken = await client.GetAuthorizationPolicyAsync(request.AuthorizationPolicyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServerTlsPolicyRequestObject()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
};
ServerTlsPolicy expectedResponse = new ServerTlsPolicy
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AllowOpen = false,
ServerCertificate = new CertificateProvider(),
MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(),
};
mockGrpcClient.Setup(x => x.GetServerTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ServerTlsPolicy response = client.GetServerTlsPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServerTlsPolicyRequestObjectAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
};
ServerTlsPolicy expectedResponse = new ServerTlsPolicy
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AllowOpen = false,
ServerCertificate = new CertificateProvider(),
MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(),
};
mockGrpcClient.Setup(x => x.GetServerTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServerTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ServerTlsPolicy responseCallSettings = await client.GetServerTlsPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ServerTlsPolicy responseCancellationToken = await client.GetServerTlsPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServerTlsPolicy()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
};
ServerTlsPolicy expectedResponse = new ServerTlsPolicy
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AllowOpen = false,
ServerCertificate = new CertificateProvider(),
MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(),
};
mockGrpcClient.Setup(x => x.GetServerTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ServerTlsPolicy response = client.GetServerTlsPolicy(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServerTlsPolicyAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
};
ServerTlsPolicy expectedResponse = new ServerTlsPolicy
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AllowOpen = false,
ServerCertificate = new CertificateProvider(),
MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(),
};
mockGrpcClient.Setup(x => x.GetServerTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServerTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ServerTlsPolicy responseCallSettings = await client.GetServerTlsPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ServerTlsPolicy responseCancellationToken = await client.GetServerTlsPolicyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServerTlsPolicyResourceNames()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
};
ServerTlsPolicy expectedResponse = new ServerTlsPolicy
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AllowOpen = false,
ServerCertificate = new CertificateProvider(),
MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(),
};
mockGrpcClient.Setup(x => x.GetServerTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ServerTlsPolicy response = client.GetServerTlsPolicy(request.ServerTlsPolicyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServerTlsPolicyResourceNamesAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
};
ServerTlsPolicy expectedResponse = new ServerTlsPolicy
{
ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AllowOpen = false,
ServerCertificate = new CertificateProvider(),
MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(),
};
mockGrpcClient.Setup(x => x.GetServerTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServerTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ServerTlsPolicy responseCallSettings = await client.GetServerTlsPolicyAsync(request.ServerTlsPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ServerTlsPolicy responseCancellationToken = await client.GetServerTlsPolicyAsync(request.ServerTlsPolicyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetClientTlsPolicyRequestObject()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
};
ClientTlsPolicy expectedResponse = new ClientTlsPolicy
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Sni = "snif6a20ff7",
ClientCertificate = new CertificateProvider(),
ServerValidationCa = { new ValidationCA(), },
};
mockGrpcClient.Setup(x => x.GetClientTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ClientTlsPolicy response = client.GetClientTlsPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetClientTlsPolicyRequestObjectAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
};
ClientTlsPolicy expectedResponse = new ClientTlsPolicy
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Sni = "snif6a20ff7",
ClientCertificate = new CertificateProvider(),
ServerValidationCa = { new ValidationCA(), },
};
mockGrpcClient.Setup(x => x.GetClientTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ClientTlsPolicy responseCallSettings = await client.GetClientTlsPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ClientTlsPolicy responseCancellationToken = await client.GetClientTlsPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetClientTlsPolicy()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
};
ClientTlsPolicy expectedResponse = new ClientTlsPolicy
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Sni = "snif6a20ff7",
ClientCertificate = new CertificateProvider(),
ServerValidationCa = { new ValidationCA(), },
};
mockGrpcClient.Setup(x => x.GetClientTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ClientTlsPolicy response = client.GetClientTlsPolicy(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetClientTlsPolicyAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
};
ClientTlsPolicy expectedResponse = new ClientTlsPolicy
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Sni = "snif6a20ff7",
ClientCertificate = new CertificateProvider(),
ServerValidationCa = { new ValidationCA(), },
};
mockGrpcClient.Setup(x => x.GetClientTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ClientTlsPolicy responseCallSettings = await client.GetClientTlsPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ClientTlsPolicy responseCancellationToken = await client.GetClientTlsPolicyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetClientTlsPolicyResourceNames()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
};
ClientTlsPolicy expectedResponse = new ClientTlsPolicy
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Sni = "snif6a20ff7",
ClientCertificate = new CertificateProvider(),
ServerValidationCa = { new ValidationCA(), },
};
mockGrpcClient.Setup(x => x.GetClientTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ClientTlsPolicy response = client.GetClientTlsPolicy(request.ClientTlsPolicyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetClientTlsPolicyResourceNamesAsync()
{
moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
};
ClientTlsPolicy expectedResponse = new ClientTlsPolicy
{
ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Sni = "snif6a20ff7",
ClientCertificate = new CertificateProvider(),
ServerValidationCa = { new ValidationCA(), },
};
mockGrpcClient.Setup(x => x.GetClientTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null);
ClientTlsPolicy responseCallSettings = await client.GetClientTlsPolicyAsync(request.ClientTlsPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ClientTlsPolicy responseCancellationToken = await client.GetClientTlsPolicyAsync(request.ClientTlsPolicyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
namespace MvcContrib.UI.Grid
{
/// <summary>
/// Base class for Grid Renderers.
/// </summary>
public abstract class GridRenderer<T> : IGridRenderer<T> where T : class
{
protected IGridModel<T> GridModel { get; private set; }
protected IEnumerable<T> DataSource { get; private set; }
protected ViewContext Context { get; private set; }
private TextWriter _writer;
private readonly ViewEngineCollection _engines;
protected TextWriter Writer
{
get { return _writer; }
}
protected GridRenderer() : this(ViewEngines.Engines) {}
protected GridRenderer(ViewEngineCollection engines)
{
_engines = engines;
}
public void Render(IGridModel<T> gridModel, IEnumerable<T> dataSource, TextWriter output, ViewContext context)
{
_writer = output;
GridModel = gridModel;
DataSource = dataSource;
Context = context;
RenderGridStart();
bool hasItems = RenderHeader();
if(hasItems)
{
RenderItems();
}
else
{
RenderEmpty();
}
RenderGridEnd(!hasItems);
}
protected void RenderText(string text)
{
Writer.Write(text);
}
protected virtual void RenderItems()
{
RenderBodyStart();
bool isAlternate = false;
foreach(var item in DataSource)
{
RenderItem(new GridRowViewData<T>(item, isAlternate));
isAlternate = !isAlternate;
}
RenderBodyEnd();
}
protected virtual void RenderItem(GridRowViewData<T> rowData)
{
BaseRenderRowStart(rowData);
foreach(var column in VisibleColumns())
{
//A custom item section has been specified - render it and continue to the next iteration.
#pragma warning disable 612,618
// TODO: CustomItemRenderer is obsolete in favour of custom columns. Remove this after next release.
if (column.CustomItemRenderer != null)
{
column.CustomItemRenderer(new RenderingContext(Writer, Context, _engines), rowData.Item);
continue;
}
#pragma warning restore 612,618
RenderStartCell(column, rowData);
RenderCellValue(column, rowData);
RenderEndCell();
}
BaseRenderRowEnd(rowData);
}
protected virtual void RenderCellValue(GridColumn<T> column, GridRowViewData<T> rowData)
{
var cellValue = column.GetValue(rowData.Item);
if(cellValue != null)
{
RenderText(cellValue.ToString());
}
}
protected virtual bool RenderHeader()
{
//No items - do not render a header.
if(! ShouldRenderHeader()) return false;
RenderHeadStart();
foreach(var column in VisibleColumns())
{
//Allow for custom header overrides.
#pragma warning disable 612,618
if(column.CustomHeaderRenderer != null)
{
column.CustomHeaderRenderer(new RenderingContext(Writer, Context, _engines));
}
#pragma warning restore 612,618
else
{
RenderHeaderCellStart(column);
RenderHeaderText(column);
RenderHeaderCellEnd();
}
}
RenderHeadEnd();
return true;
}
protected virtual void RenderHeaderText(GridColumn<T> column)
{
var customHeader = column.GetHeader();
if (customHeader != null)
{
RenderText(customHeader);
}
else
{
RenderText(column.DisplayName);
}
}
protected virtual bool ShouldRenderHeader()
{
return !IsDataSourceEmpty();
}
protected bool IsDataSourceEmpty()
{
return DataSource == null || !DataSource.Any();
}
protected IEnumerable<GridColumn<T>> VisibleColumns()
{
return GridModel.Columns.Where(x => x.Visible);
}
protected void BaseRenderRowStart(GridRowViewData<T> rowData)
{
bool rendered = GridModel.Sections.Row.StartSectionRenderer(rowData, new RenderingContext(Writer, Context, _engines));
if(! rendered)
{
RenderRowStart(rowData);
}
}
protected void BaseRenderRowEnd(GridRowViewData<T> rowData)
{
bool rendered = GridModel.Sections.Row.EndSectionRenderer(rowData, new RenderingContext(Writer, Context, _engines));
if(! rendered)
{
RenderRowEnd();
}
}
protected bool IsSortingEnabled
{
get { return GridModel.SortOptions != null; }
}
protected abstract void RenderHeaderCellEnd();
protected abstract void RenderHeaderCellStart(GridColumn<T> column);
protected abstract void RenderRowStart(GridRowViewData<T> rowData);
protected abstract void RenderRowEnd();
protected abstract void RenderEndCell();
protected abstract void RenderStartCell(GridColumn<T> column, GridRowViewData<T> rowViewData);
protected abstract void RenderHeadStart();
protected abstract void RenderHeadEnd();
protected abstract void RenderGridStart();
protected abstract void RenderGridEnd(bool isEmpty);
protected abstract void RenderEmpty();
protected abstract void RenderBodyStart();
protected abstract void RenderBodyEnd();
}
}
| |
//
// Document.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2010 Jonathan Pobst
//
// 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 Mono.Unix;
using Gdk;
using Gtk;
using System.Collections.Generic;
using Cairo;
using System.ComponentModel;
using Pinta;
namespace Pinta.Core
{
// The differentiation between Document and DocumentWorkspace is
// somewhat arbitrary. In general:
// Document - Data about the image itself
// Workspace - Data about Pinta's state for the image
public class Document
{
private string filename;
private bool is_dirty;
private int layer_name_int = 2;
private int current_layer = -1;
// The layer for tools to use until their output is committed
private Layer tool_layer;
// The layer used for selections
private Layer selection_layer;
private bool show_selection;
public DocumentSelection Selection = new DocumentSelection();
public Document (Gdk.Size size)
{
Guid = Guid.NewGuid ();
Workspace = new DocumentWorkspace (this);
IsDirty = false;
HasFile = false;
HasBeenSavedInSession = false;
ImageSize = size;
UserLayers = new List<UserLayer>();
tool_layer = CreateLayer ("Tool Layer");
tool_layer.Hidden = true;
selection_layer = CreateLayer ("Selection Layer");
selection_layer.Hidden = true;
ResetSelectionPath ();
}
#region Public Properties
public UserLayer CurrentUserLayer
{
get { return UserLayers[current_layer]; }
}
public int CurrentUserLayerIndex {
get { return current_layer; }
}
/// <summary>
/// Just the file name, like "dog.jpg".
/// </summary>
public string Filename {
get { return filename; }
set {
if (filename != value) {
filename = value;
OnRenamed ();
}
}
}
public Guid Guid { get; private set; }
public bool HasFile { get; set; }
//Determines whether or not the Document has been saved to the file that it is currently associated with in the
//current session. This should be false if the Document has not yet been saved, if it was just loaded into
//Pinta from a file, or if the user just clicked Save As.
public bool HasBeenSavedInSession { get; set; }
public DocumentWorkspaceHistory History { get { return Workspace.History; } }
public Gdk.Size ImageSize { get; set; }
public bool IsDirty {
get { return is_dirty; }
set {
if (is_dirty != value) {
is_dirty = value;
OnIsDirtyChanged ();
}
}
}
public List<UserLayer> UserLayers { get; private set; }
/// <summary>
/// Just the directory name, like "C:\MyPictures".
/// </summary>
public string Pathname { get; set; }
/// <summary>
/// Directory and file name, like "C:\MyPictures\dog.jpg".
/// </summary>
public string PathAndFileName {
get { return System.IO.Path.Combine (Pathname, Filename); }
set {
if (string.IsNullOrEmpty (value)) {
Pathname = string.Empty;
Filename = string.Empty;
} else {
Pathname = System.IO.Path.GetDirectoryName (value);
Filename = System.IO.Path.GetFileName (value);
}
}
}
public Layer SelectionLayer {
get { return selection_layer; }
}
public bool ShowSelection {
get { return show_selection; }
set {
show_selection = value;
PintaCore.Actions.Edit.Deselect.Sensitive = show_selection;
PintaCore.Actions.Edit.EraseSelection.Sensitive = show_selection;
PintaCore.Actions.Edit.FillSelection.Sensitive = show_selection;
PintaCore.Actions.Image.CropToSelection.Sensitive = show_selection;
PintaCore.Actions.Edit.InvertSelection.Sensitive = show_selection;
}
}
public bool ShowSelectionLayer { get; set; }
public Layer ToolLayer {
get {
if (tool_layer.Surface.Width != ImageSize.Width || tool_layer.Surface.Height != ImageSize.Height) {
(tool_layer.Surface as IDisposable).Dispose ();
tool_layer = CreateLayer ("Tool Layer");
tool_layer.Hidden = true;
}
return tool_layer;
}
}
public DocumentWorkspace Workspace { get; private set; }
public delegate void LayerCloneEvent();
#endregion
#region Public Methods
// Adds a new layer above the current one
public UserLayer AddNewLayer(string name)
{
UserLayer layer;
if (string.IsNullOrEmpty (name))
layer = CreateLayer ();
else
layer = CreateLayer (name);
UserLayers.Insert (current_layer + 1, layer);
if (UserLayers.Count == 1)
current_layer = 0;
layer.PropertyChanged += RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerAdded ();
return layer;
}
public Gdk.Rectangle ClampToImageSize (Gdk.Rectangle r)
{
int x = Utility.Clamp (r.X, 0, ImageSize.Width);
int y = Utility.Clamp (r.Y, 0, ImageSize.Height);
int width = Math.Min (r.Width, ImageSize.Width - x);
int height = Math.Min (r.Height, ImageSize.Height - y);
return new Gdk.Rectangle (x, y, width, height);
}
public void Clear ()
{
while (UserLayers.Count > 0) {
Layer l = UserLayers[UserLayers.Count - 1];
UserLayers.RemoveAt (UserLayers.Count - 1);
(l.Surface as IDisposable).Dispose ();
}
current_layer = -1;
PintaCore.Layers.OnLayerRemoved ();
}
// Clean up any native resources we had
public void Close ()
{
// Dispose all of our layers
while (UserLayers.Count > 0) {
Layer l = UserLayers[UserLayers.Count - 1];
UserLayers.RemoveAt (UserLayers.Count - 1);
(l.Surface as IDisposable).Dispose ();
}
current_layer = -1;
if (tool_layer != null)
(tool_layer.Surface as IDisposable).Dispose ();
if (selection_layer != null)
(selection_layer.Surface as IDisposable).Dispose ();
Selection.DisposeSelection();
Workspace.History.Clear ();
}
public Context CreateClippedContext ()
{
Context g = new Context (CurrentUserLayer.Surface);
Selection.Clip (g);
return g;
}
public Context CreateClippedContext (bool antialias)
{
Context g = new Context (CurrentUserLayer.Surface);
Selection.Clip (g);
g.Antialias = antialias ? Antialias.Subpixel : Antialias.None;
return g;
}
public Context CreateClippedToolContext ()
{
Context g = new Context (ToolLayer.Surface);
Selection.Clip (g);
return g;
}
public Context CreateClippedToolContext (bool antialias)
{
Context g = new Context (ToolLayer.Surface);
Selection.Clip (g);
g.Antialias = antialias ? Antialias.Subpixel : Antialias.None;
return g;
}
public UserLayer CreateLayer ()
{
return CreateLayer (string.Format ("{0} {1}", Catalog.GetString ("Layer"), layer_name_int++));
}
public UserLayer CreateLayer (int width, int height)
{
return CreateLayer (string.Format ("{0} {1}", Catalog.GetString ("Layer"), layer_name_int++), width, height);
}
public UserLayer CreateLayer (string name)
{
return CreateLayer (name, ImageSize.Width, ImageSize.Height);
}
public UserLayer CreateLayer(string name, int width, int height)
{
Cairo.ImageSurface surface = new Cairo.ImageSurface (Cairo.Format.ARGB32, width, height);
UserLayer layer = new UserLayer(surface) { Name = name };
return layer;
}
public void CreateSelectionLayer ()
{
Layer old = selection_layer;
selection_layer = CreateLayer ();
if (old != null)
(old.Surface as IDisposable).Dispose ();
}
public void CreateSelectionLayer (int width, int height)
{
Layer old = selection_layer;
selection_layer = CreateLayer (width, height);
if (old != null)
(old.Surface as IDisposable).Dispose ();
}
// Delete the current layer
public void DeleteCurrentLayer ()
{
Layer layer = CurrentUserLayer;
UserLayers.RemoveAt (current_layer);
// Only change this if this wasn't already the bottom layer
if (current_layer > 0)
current_layer--;
layer.PropertyChanged -= RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerRemoved ();
}
// Delete the layer
public void DeleteLayer (int index, bool dispose)
{
Layer layer = UserLayers[index];
UserLayers.RemoveAt (index);
if (dispose)
(layer.Surface as IDisposable).Dispose ();
// Only change this if this wasn't already the bottom layer
if (current_layer > 0)
current_layer--;
layer.PropertyChanged -= RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerRemoved ();
}
public void DestroySelectionLayer ()
{
ShowSelectionLayer = false;
SelectionLayer.Clear ();
SelectionLayer.Transform.InitIdentity();
}
// Duplicate current layer
public UserLayer DuplicateCurrentLayer()
{
UserLayer source = CurrentUserLayer;
UserLayer layer = CreateLayer(string.Format("{0} {1}", source.Name, Catalog.GetString("copy")));
using (Cairo.Context g = new Cairo.Context (layer.Surface)) {
g.SetSource (source.Surface);
g.Paint ();
}
layer.Hidden = source.Hidden;
layer.Opacity = source.Opacity;
layer.Tiled = source.Tiled;
UserLayers.Insert (++current_layer, layer);
layer.PropertyChanged += RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerAdded ();
return layer;
}
public void FinishSelection ()
{
// We don't have an uncommitted layer, abort
if (!ShowSelectionLayer)
return;
FinishPixelsHistoryItem hist = new FinishPixelsHistoryItem ();
hist.TakeSnapshot ();
Layer layer = SelectionLayer;
using (Cairo.Context g = new Cairo.Context (CurrentUserLayer.Surface)) {
layer.Draw(g);
}
DestroySelectionLayer ();
Workspace.Invalidate ();
Workspace.History.PushNewItem (hist);
}
// Flatten image
public void FlattenImage ()
{
if (UserLayers.Count < 2)
throw new InvalidOperationException ("Cannot flatten image because there is only one layer.");
// Find the "bottom" layer
var bottom_layer = UserLayers[0];
var old_surf = bottom_layer.Surface;
// Replace the bottom surface with the flattened image,
// and dispose the old surface
bottom_layer.Surface = GetFlattenedImage ();
(old_surf as IDisposable).Dispose ();
// Reset our layer pointer to the only remaining layer
current_layer = 0;
// Delete all other layers
while (UserLayers.Count > 1)
UserLayers.RemoveAt (1);
PintaCore.Layers.OnLayerRemoved ();
Workspace.Invalidate ();
}
// Flip image horizontally
public void FlipImageHorizontal ()
{
foreach (var layer in UserLayers)
layer.FlipHorizontal ();
Workspace.Invalidate ();
}
// Flip image vertically
public void FlipImageVertical ()
{
foreach (var layer in UserLayers)
layer.FlipVertical ();
Workspace.Invalidate ();
}
public ImageSurface GetClippedLayer (int index)
{
Cairo.ImageSurface surf = new Cairo.ImageSurface (Cairo.Format.Argb32, ImageSize.Width, ImageSize.Height);
using (Cairo.Context g = new Cairo.Context (surf)) {
g.AppendPath(Selection.SelectionPath);
g.Clip ();
g.SetSource (UserLayers[index].Surface);
g.Paint ();
}
return surf;
}
/// <summary>
/// Gets the final pixel color for the given point, taking layers, opacity, and blend modes into account.
/// </summary>
public ColorBgra GetComputedPixel (int x, int y)
{
var pixel = ColorBgra.Zero;
foreach (var layer in GetLayersToPaint ()) {
var blend_op = UserBlendOps.GetBlendOp (layer.BlendMode, layer.Opacity);
pixel = blend_op.Apply (pixel, layer.Surface.GetColorBgraUnchecked (x, y));
}
return pixel;
}
public ImageSurface GetFlattenedImage ()
{
// Create a new image surface
var surf = new Cairo.ImageSurface (Cairo.Format.Argb32, ImageSize.Width, ImageSize.Height);
// Blend each visible layer onto our surface
foreach (var layer in GetLayersToPaint ()) {
var blendop = UserBlendOps.GetBlendOp (layer.BlendMode, layer.Opacity);
blendop.Apply (surf, layer.Surface);
}
surf.MarkDirty ();
return surf;
}
public List<Layer> GetLayersToPaint ()
{
List<Layer> paint = new List<Layer> ();
foreach (var layer in UserLayers) {
if (!layer.Hidden)
paint.Add (layer);
if (layer == CurrentUserLayer) {
if (!ToolLayer.Hidden)
paint.Add (ToolLayer);
if (ShowSelectionLayer)
paint.Add (SelectionLayer);
}
//Make sure that the UserLayer's TextLayer is in use.
if (!layer.Hidden && layer.IsTextLayerSetup)
{
paint.Add(layer.TextLayer);
}
}
return paint;
}
/// <param name="canvasOnly">false for the whole selection, true for the part only on our canvas</param>
public Gdk.Rectangle GetSelectedBounds (bool canvasOnly)
{
var bounds = Selection.SelectionPath.GetBounds();
if (canvasOnly)
bounds = ClampToImageSize (bounds);
return bounds;
}
public int IndexOf(UserLayer layer)
{
return UserLayers.IndexOf (layer);
}
// Adds a new layer above the current one
public void Insert(UserLayer layer, int index)
{
UserLayers.Insert (index, layer);
if (UserLayers.Count == 1)
current_layer = 0;
layer.PropertyChanged += RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerAdded ();
}
// Flatten current layer
public void MergeCurrentLayerDown ()
{
if (current_layer == 0)
throw new InvalidOperationException ("Cannot flatten layer because current layer is the bottom layer.");
// Get our source and destination layers
var source = CurrentUserLayer;
var dest = UserLayers[current_layer - 1];
// Blend the layers
var blendop = UserBlendOps.GetBlendOp (source.BlendMode, source.Opacity);
blendop.Apply (dest.Surface, source.Surface);
DeleteCurrentLayer ();
}
// Move current layer down
public void MoveCurrentLayerDown ()
{
if (current_layer == 0)
throw new InvalidOperationException ("Cannot move layer down because current layer is the bottom layer.");
UserLayer layer = CurrentUserLayer;
UserLayers.RemoveAt (current_layer);
UserLayers.Insert (--current_layer, layer);
PintaCore.Layers.OnSelectedLayerChanged ();
Workspace.Invalidate ();
}
// Move current layer up
public void MoveCurrentLayerUp ()
{
if (current_layer == UserLayers.Count)
throw new InvalidOperationException ("Cannot move layer up because current layer is the top layer.");
UserLayer layer = CurrentUserLayer;
UserLayers.RemoveAt (current_layer);
UserLayers.Insert (++current_layer, layer);
PintaCore.Layers.OnSelectedLayerChanged ();
Workspace.Invalidate ();
}
public void ResetSelectionPath()
{
Selection.DisposeSelectionPreserve();
Selection.ResetSelection(selection_layer.Surface, ImageSize);
ShowSelection = false;
}
/// <summary>
/// Resizes the canvas.
/// </summary>
/// <param name="width">The new width of the canvas.</param>
/// <param name="height">The new height of the canvas.</param>
/// <param name="anchor">Direction in which to adjust the canvas</param>
/// <param name='compoundAction'>
/// Optionally, the history item for resizing the canvas can be added to
/// a CompoundHistoryItem if it is part of a larger action (e.g. pasting an image).
/// </param>
public void ResizeCanvas (int width, int height, Anchor anchor, CompoundHistoryItem compoundAction)
{
double scale;
if (ImageSize.Width == width && ImageSize.Height == height)
return;
PintaCore.Tools.Commit ();
ResizeHistoryItem hist = new ResizeHistoryItem (ImageSize);
hist.Icon = "Menu.Image.CanvasSize.png";
hist.Text = Catalog.GetString ("Resize Canvas");
hist.StartSnapshotOfImage ();
scale = Workspace.Scale;
ImageSize = new Gdk.Size (width, height);
foreach (var layer in UserLayers)
layer.ResizeCanvas (width, height, anchor);
hist.FinishSnapshotOfImage ();
if (compoundAction != null) {
compoundAction.Push (hist);
} else {
Workspace.History.PushNewItem (hist);
}
ResetSelectionPath ();
Workspace.Scale = scale;
}
public void ResizeImage (int width, int height)
{
double scale;
if (ImageSize.Width == width && ImageSize.Height == height)
return;
PintaCore.Tools.Commit ();
ResizeHistoryItem hist = new ResizeHistoryItem (ImageSize);
hist.StartSnapshotOfImage ();
scale = Workspace.Scale;
ImageSize = new Gdk.Size (width, height);
foreach (var layer in UserLayers)
layer.Resize (width, height);
hist.FinishSnapshotOfImage ();
Workspace.History.PushNewItem (hist);
ResetSelectionPath ();
Workspace.Scale = scale;
}
// Rotate image 180 degrees (flip H+V)
public void RotateImage180 ()
{
RotateImage (180);
}
public void RotateImageCW ()
{
RotateImage (90);
}
public void RotateImageCCW ()
{
RotateImage (-90);
}
/// <summary>
/// Rotates the image by the specified angle (in degrees)
/// </summary>
private void RotateImage (double angle)
{
foreach (var layer in UserLayers)
{
layer.Rotate (angle);
}
ImageSize = Layer.RotateDimensions (ImageSize, angle);
Workspace.CanvasSize = Layer.RotateDimensions (Workspace.CanvasSize, angle);
PintaCore.Actions.View.UpdateCanvasScale ();
Workspace.Invalidate ();
}
// Returns true if successful, false if canceled
public bool Save (bool saveAs)
{
return PintaCore.Actions.File.RaiseSaveDocument (this, saveAs);
}
public void SetCurrentUserLayer (int i)
{
// Ensure that the current tool's modifications are finalized before
// switching layers.
PintaCore.Tools.CurrentTool.DoCommit ();
current_layer = i;
PintaCore.Layers.OnSelectedLayerChanged ();
}
public void SetCurrentUserLayer(UserLayer layer)
{
SetCurrentUserLayer (UserLayers.IndexOf (layer));
}
/// <summary>
/// Pastes an image from the clipboard.
/// </summary>
/// <param name="toNewLayer">Set to TRUE to paste into a
/// new layer. Otherwise, will paste to the current layer.</param>
/// <param name="x">Optional. Location within image to paste to.
/// Position will be adjusted if pasted image would hang
/// over right or bottom edges of canvas.</param>
/// <param name="y">Optional. Location within image to paste to.
/// Position will be adjusted if pasted image would hang
/// over right or bottom edges of canvas.</param>
public void Paste (bool toNewLayer, int x = 0, int y = 0)
{
// Create a compound history item for recording several
// operations so that they can all be undone/redone together.
CompoundHistoryItem paste_action;
if (toNewLayer)
{
paste_action = new CompoundHistoryItem (Stock.Paste, Catalog.GetString ("Paste Into New Layer"));
}
else
{
paste_action = new CompoundHistoryItem (Stock.Paste, Catalog.GetString ("Paste"));
}
Gtk.Clipboard cb = Gtk.Clipboard.Get (Gdk.Atom.Intern ("CLIPBOARD", false));
// See if the current tool wants to handle the paste
// operation (e.g., the text tool could paste text)
if (!toNewLayer)
{
if (PintaCore.Tools.CurrentTool.TryHandlePaste (cb))
return;
}
PintaCore.Tools.Commit ();
// Don't dispose this, as we're going to give it to the history
Gdk.Pixbuf cbImage = null;
if (cb.WaitIsImageAvailable ()) {
cbImage = cb.WaitForImage ();
}
if (cbImage == null)
{
ShowClipboardEmptyDialog();
return;
}
Gdk.Size canvas_size = PintaCore.Workspace.ImageSize;
// If the image being pasted is larger than the canvas size, allow the user to optionally resize the canvas
if (cbImage.Width > canvas_size.Width || cbImage.Height > canvas_size.Height)
{
ResponseType response = ShowExpandCanvasDialog ();
if (response == ResponseType.Accept)
{
PintaCore.Workspace.ResizeCanvas (cbImage.Width, cbImage.Height,
Pinta.Core.Anchor.Center, paste_action);
PintaCore.Actions.View.UpdateCanvasScale ();
}
else if (response == ResponseType.Cancel || response == ResponseType.DeleteEvent)
{
return;
}
}
// If the pasted image would fall off bottom- or right-
// side of image, adjust paste position
x = Math.Max (0, Math.Min (x, canvas_size.Width - cbImage.Width));
y = Math.Max (0, Math.Min (y, canvas_size.Height - cbImage.Height));
// If requested, create a new layer, make it the current
// layer and record it's creation in the history
if (toNewLayer)
{
UserLayer l = AddNewLayer (string.Empty);
SetCurrentUserLayer (l);
paste_action.Push (new AddLayerHistoryItem ("Menu.Layers.AddNewLayer.png", Catalog.GetString ("Add New Layer"), UserLayers.IndexOf (l)));
}
// Copy the paste to the temp layer, which should be at least the size of this document.
CreateSelectionLayer (Math.Max(ImageSize.Width, cbImage.Width),
Math.Max(ImageSize.Height, cbImage.Height));
ShowSelectionLayer = true;
using (Cairo.Context g = new Cairo.Context (SelectionLayer.Surface))
{
g.DrawPixbuf (cbImage, new Cairo.Point (0, 0));
}
SelectionLayer.Transform.InitIdentity();
SelectionLayer.Transform.Translate (x, y);
PintaCore.Tools.SetCurrentTool (Catalog.GetString ("Move Selected Pixels"));
DocumentSelection old_selection = Selection.Clone();
bool old_show_selection = ShowSelection;
Selection.CreateRectangleSelection (SelectionLayer.Surface,
new Cairo.Rectangle (x, y, cbImage.Width, cbImage.Height));
ShowSelection = true;
Workspace.Invalidate ();
paste_action.Push (new PasteHistoryItem (cbImage, old_selection, old_show_selection));
History.PushNewItem (paste_action);
}
private ResponseType ShowExpandCanvasDialog ()
{
const string markup = "<span weight=\"bold\" size=\"larger\">{0}</span>\n\n{1}";
string primary = Catalog.GetString ("Image larger than canvas");
string secondary = Catalog.GetString ("The image being pasted is larger than the canvas size. What would you like to do?");
string message = string.Format (markup, primary, secondary);
var enlarge_dialog = new MessageDialog (PintaCore.Chrome.MainWindow, DialogFlags.Modal, MessageType.Question, ButtonsType.None, message);
enlarge_dialog.AddButton (Catalog.GetString ("Expand canvas"), ResponseType.Accept);
enlarge_dialog.AddButton (Catalog.GetString ("Don't change canvas size"), ResponseType.Reject);
enlarge_dialog.AddButton (Stock.Cancel, ResponseType.Cancel);
enlarge_dialog.DefaultResponse = ResponseType.Accept;
ResponseType response = (ResponseType)enlarge_dialog.Run ();
enlarge_dialog.Destroy ();
return response;
}
public static void ShowClipboardEmptyDialog()
{
var primary = Catalog.GetString ("Image cannot be pasted");
var secondary = Catalog.GetString ("The clipboard does not contain an image.");
var markup = "<span weight=\"bold\" size=\"larger\">{0}</span>\n\n{1}\n";
markup = string.Format (markup, primary, secondary);
var md = new MessageDialog (Pinta.Core.PintaCore.Chrome.MainWindow, DialogFlags.Modal,
MessageType.Error, ButtonsType.None, true,
markup);
md.AddButton (Stock.Ok, ResponseType.Yes);
md.Run ();
md.Destroy ();
}
/// <summary>
/// Signal to the TextTool that an ImageSurface was cloned.
/// </summary>
public void SignalSurfaceCloned()
{
if (LayerCloned != null)
{
LayerCloned();
}
}
#endregion
#region Protected Methods
protected void OnIsDirtyChanged ()
{
if (IsDirtyChanged != null)
IsDirtyChanged (this, EventArgs.Empty);
}
protected void OnRenamed ()
{
if (Renamed != null)
Renamed (this, EventArgs.Empty);
}
#endregion
#region Private Methods
private void RaiseLayerPropertyChangedEvent (object sender, PropertyChangedEventArgs e)
{
PintaCore.Layers.RaiseLayerPropertyChangedEvent (sender, e);
}
#endregion
#region Public Events
public event EventHandler IsDirtyChanged;
public event EventHandler Renamed;
public event LayerCloneEvent LayerCloned;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Paramol;
namespace Projac.Tests
{
public class HandlerResolutionCases
{
public static IEnumerable<TestCaseData> WhenEqualToHandlerMessageTypeCases()
{
// * Matches *
//Exact message type resolution
var handler1 = HandlerFor<Message1>();
yield return new TestCaseData(
new[] { handler1 },
new Message1(),
new[] { handler1 }).SetDescription("Exact message type resolution");
//Exact message envelope type resolution
var handler2 = HandlerFor<MessageEnvelope<Message1>>();
yield return new TestCaseData(
new[] { handler2 },
new MessageEnvelope<Message1>(),
new[] { handler2 }).SetDescription("Exact message envelope type resolution");
//Partial match resolution
var handler3 = HandlerFor<Message1>();
var handler4 = HandlerFor<Message2>();
yield return new TestCaseData(
new[] { handler3, handler4 },
new Message2(),
new[] { handler4 }).SetDescription("Partial match resolution");
// * Mismatches *
//Envelope with derived type resolution
var handler10 = HandlerFor<Envelope<Message1>>();
yield return new TestCaseData(
new[] { handler10 },
new MessageEnvelope<Message1>(),
new SqlProjectionHandler[0]).SetDescription("Envelope with derived type resolution");
//No match resolution
var handler11 = HandlerFor<OtherMessage>();
yield return new TestCaseData(
new[] { handler11 },
new Message1(),
new SqlProjectionHandler[0]).SetDescription("No match resolution");
// * Handler order */
//Handler order is preserved resolution
var handler20 = HandlerFor<Message1>();
var handler21 = HandlerFor<Message1>();
yield return new TestCaseData(
new[] { handler20, handler21 },
new Message1(),
new[] { handler20, handler21 }).SetDescription("Handler order is preserved resolution");
yield return new TestCaseData(
new[] { handler21, handler20 },
new Message1(),
new[] { handler21, handler20 }).SetDescription("Handler order is preserved resolution");
}
public static IEnumerable<TestCaseData> WhenAssignableToHandlerMessageTypeCases()
{
// * Matches *
//Exact message type resolution
var handler1 = HandlerFor<Message1>();
yield return new TestCaseData(
new[] { handler1 },
new Message1(),
new[] { handler1 }).SetDescription("Exact message type resolution");
//Message interface type resolution
var handler2 = HandlerFor<IMessage>();
yield return new TestCaseData(
new[] { handler2 },
new Message1(),
new[] { handler2 }).SetDescription("Message interface type resolution");
//Exact envelope and message type resolution
var handler3 = HandlerFor<MessageEnvelope<Message1>>();
yield return new TestCaseData(
new[] { handler3 },
new MessageEnvelope<Message1>(),
new[] { handler3 }).SetDescription("Exact envelope and message type resolution");
//Envelope interface and exact message type resolution
var handler4 = HandlerFor<Envelope<Message1>>();
yield return new TestCaseData(
new[] { handler4 },
new MessageEnvelope<Message1>(),
new[] { handler4 }).SetDescription("Envelope interface and exact message type resolution");
//Envelope and message interface type resolution
var handler5 = HandlerFor<Envelope<IMessage>>();
yield return new TestCaseData(
new[] { handler5 },
new MessageEnvelope<Message1>(),
new[] { handler5 }).SetDescription("Envelope and message interface type resolution");
//Mismatch ignored resolution
var handler6 = HandlerFor<Envelope<OtherMessage>>();
var handler7 = HandlerFor<Envelope<IMessage>>();
yield return new TestCaseData(
new[] { handler6, handler7 },
new MessageEnvelope<Message1>(),
new[] { handler7 }).SetDescription("Mismatch ignored resolution");
//Multimatch resolution
var handler8 = HandlerFor<Envelope<IMessage>>();
var handler9 = HandlerFor<Envelope<Message1>>();
yield return new TestCaseData(
new[] { handler8, handler9 },
new MessageEnvelope<Message1>(),
new[] { handler8, handler9 }).SetDescription("Multimatch resolution");
//Derived multimatch resolution
var handler10 = HandlerFor<Envelope<IMessage>>();
var handler11 = HandlerFor<Envelope<Message1>>();
yield return new TestCaseData(
new[] { handler10, handler11 },
new MessageEnvelope<Message2>(),
new[] { handler10, handler11 }).SetDescription("Derived multimatch resolution");
//Value type resolution
var handler12 = HandlerFor<Int32>();
yield return new TestCaseData(
new[] { handler12 },
42,
new[] { handler12 }).SetDescription("Value type resolution");
//Reference type resolution
var handler13 = HandlerFor<String>();
yield return new TestCaseData(
new[] { handler13 },
"42",
new[] { handler13 }).SetDescription("Reference type resolution");
//Envelope with value type resolution
var handler14 = HandlerFor<Envelope<Int32>>();
yield return new TestCaseData(
new[] { handler14 },
new MessageEnvelope<Int32>(),
new[] { handler14 }).SetDescription("Envelope with value type resolution");
//Envelope with reference type resolution
var handler16 = HandlerFor<Envelope<String>>();
yield return new TestCaseData(
new[] { handler16 },
new MessageEnvelope<String>(),
new[] { handler16 }).SetDescription("Envelope with reference type resolution");
//Envelope with reference type's interface resolution
var handler17 = HandlerFor<Envelope<IConvertible>>();
yield return new TestCaseData(
new[] { handler17 },
new MessageEnvelope<String>(),
new[] { handler17 }).SetDescription("Envelope with reference type's interface resolution");
//Envelope with contravariant message type resolution
var handler18 = HandlerFor<Envelope<IEnumerable<object>>>();
yield return new TestCaseData(
new[] { handler18 },
new MessageEnvelope<IEnumerable<object>>(),
new[] { handler18 }).SetDescription("Envelope with contravariant message type resolution");
//Envelope with contravariant derived message type resolution
var handler19 = HandlerFor<Envelope<IEnumerable<IMessage>>>();
yield return new TestCaseData(
new[] { handler19 },
new MessageEnvelope<IEnumerable<Message1>>(),
new[] { handler19 }).SetDescription("Envelope with contravariant derived message type resolution");
//Envelope base type resolution
var handler20 = HandlerFor<Envelope>();
yield return new TestCaseData(
new[] { handler20 },
new MessageEnvelope<Message2>(),
new[] { handler20 }).SetDescription("Envelope base type resolution");
//Envelope mismatch ignored resolution
var handler21 = HandlerFor<MessageEnvelope<Message1>>();
var handler22 = HandlerFor<MessageEnvelope<OtherMessage>>();
yield return new TestCaseData(
new[] { handler21, handler22 },
new MessageEnvelope<Message1>(),
new[] { handler21 }).SetDescription("Envelope mismatch ignored resolution");
// * Mismatches *
//Envelope with value type's interface resolution
var handler15 = HandlerFor<Envelope<IConvertible>>();
yield return new TestCaseData(
new[] { handler15 },
new MessageEnvelope<Int32>(),
new SqlProjectionHandler[0]).SetDescription("Envelope with value type's interface resolution");
//Envelope and message interface type resolution
var handler30 = HandlerFor<Envelope<OtherMessage>>();
yield return new TestCaseData(
new[] { handler30 },
new MessageEnvelope<Message1>(),
new SqlProjectionHandler[0]).SetDescription("Envelope and message interface type resolution");
//Concrete envelope with message base type resolution
var handler31 = HandlerFor<MessageEnvelope<IMessage>>();
yield return new TestCaseData(
new[] { handler31 },
new MessageEnvelope<Message1>(),
new SqlProjectionHandler[0]).SetDescription("Concrete envelope with message base type resolution");
// * Handler order */
//Handler order is preserved resolution
var handler40 = HandlerFor<Envelope<Message1>>();
var handler41 = HandlerFor<Envelope<IMessage>>();
yield return new TestCaseData(
new[] { handler40, handler41 },
new MessageEnvelope<Message1>(),
new[] { handler40, handler41 }).SetDescription("Handler order is preserved resolution");
yield return new TestCaseData(
new[] { handler41, handler40 },
new MessageEnvelope<Message1>(),
new[] { handler41, handler40 }).SetDescription("Handler order is preserved resolution");
}
private static SqlProjectionHandler HandlerFor<TMessage>()
{
return new SqlProjectionHandler(typeof(TMessage), _ => new SqlNonQueryCommand[0]);
}
private interface IMessage { }
private class Message1 : IMessage { }
private class Message2 : Message1 { }
private class OtherMessage { }
private interface Envelope { }
private interface Envelope<out TMessage> : Envelope { TMessage Message { get; } }
private class MessageEnvelope<TMessage> : Envelope<TMessage>
{
public TMessage Message
{
get { return default(TMessage); }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace IoC.Tests
{
[TestFixture]
public class IoCFixture
{
#region SetUp / TearDown
[SetUp]
public void Init()
{ }
[TearDown]
public void Dispose()
{ }
#endregion
#region Tests
[Test(Description = "You can register an object as a singleton")]
public void ResolveExistingSingletonTest()
{
var container = new Container();
var obj = new MockSimpleObject();
container.Register<MockSimpleObject>().To(obj);
var res = container.Resolve<MockSimpleObject>();
Assert.That(res, Is.SameAs(obj));
}
[Test(Description = "You can change the singleton object by overriding the registration")]
public void ResolveReregisteredSingletonTest()
{
var container = new Container();
var obj1 = new MockSimpleObject();
var obj2 = new MockSimpleObject();
container.Register<MockSimpleObject>().To(obj1);
container.Register<MockSimpleObject>().To(obj2);
var res = container.Resolve<MockSimpleObject>();
Assert.That(res, Is.SameAs(obj2));
}
[Test(Description = "You can register a structure instance as a singleton")]
public void ResolveReregisteredSingletonStructureTest()
{
var container = new Container();
var s1 = new MyStucture();
var obj = new MockSimpleObject();
s1.Object = obj;
container.Register<MyStucture>().ToValue(s1);
var res = container.Resolve<MyStucture>();
Assert.That(res, Is.Not.SameAs(s1));
Assert.That(res.Object, Is.SameAs(s1.Object));
Assert.That(res, Is.EqualTo(s1));
}
[Test(Description = "You can instruct the container how to build the objects")]
public void ResolveUsingFuncTest()
{
var container = new Container();
var obj = new MockSimpleObject();
container.Register<MockSimpleObject>().To<MockSimpleObject>().ConstructAs(j => obj);
var res = container.Resolve<MockSimpleObject>();
Assert.That(res, Is.SameAs(obj));
}
[Test(Description = "You can name a registration to allow multiple registrations for a single type")]
public void ResolveNamedInstanceTest()
{
var container = new Container();
var obj = new MockSimpleObject();
container.Register<MockSimpleObject>().To<MockSimpleObject>();
container.Register<MockSimpleObject>().Named("test").To<MockSimpleObject>().ConstructAs(j => obj);
var res = container.Resolve<MockSimpleObject>("test");
Assert.That(res, Is.SameAs(obj));
}
[Test(Description = "You can resolve the container, the container is auto registered for you as a singleton")]
public void ResolveContainerTest()
{
var container = new Container();
var res = container.Resolve<Container>();
Assert.That(res, Is.SameAs(container));
}
[Test(Description = "You can resolve an object with a dependency on the container, the container is auto registered for you")]
public void ResolveWithContainerOnlyTest()
{
var container = new Container();
container.Register<MockContainerObject>().To<MockContainerObject>();
var res = container.Resolve<MockContainerObject>();
Assert.That(res.Container, Is.SameAs(container));
}
[Test(Description = "You can change registrations by performing them again")]
public void OverrideRegistrationTest()
{
var container = new Container();
var obj = new MockContainerObject(container);
container.Register<MockContainerObject>().To<MockContainerObject>();
var res1 = container.Resolve<MockContainerObject>();
container.Register<MockContainerObject>().To(obj);
var res2 = container.Resolve<MockContainerObject>();
Assert.That(res1.Container, Is.SameAs(container));
Assert.That(res1, Is.Not.SameAs(obj));
Assert.That(res2, Is.SameAs(obj));
}
[Test(Description = "You can resolve an interface that is registered to a type, basic IoC")]
public void ResolveComplexTypeWithCompleteRegistrationTest()
{
var container = new Container();
var so = container.Resolve<MockSimpleObject>();
var co = container.Resolve<MockContainerObject>();
container.Register<MockSimpleObject>().To(so);
container.Register<MockContainerObject>().To(co);
container.Register<IMyInterface>().To<MyClass>();
var res = container.Resolve<IMyInterface>() as MyClass;
Assert.That(res, Is.Not.Null);
Assert.That(res.CObject, Is.SameAs(co));
Assert.That(res.Object, Is.SameAs(so));
}
[Test(Description = "You cannot resolve a concrete type if the container cannot satisfy dependencies")]
[ExpectedException(typeof(ResolutionException))]
public void ResolveClassWithUnregisteredParameters()
{
var container = new Container();
container.Resolve<MyDependencyClass>();
Assert.Fail();
}
[Test(Description = "You can resolve a concrete type if the container can satisfy dependencies")]
public void ResolveUnregisteredClassTest()
{
var container = new Container();
var res = container.Resolve<MockSimpleObject>();
Assert.That(res, Is.Not.Null);
}
[Test(Description = "You can resolve a named concrete type if the container can satisfy dependencies")]
public void ResolveUnregisteredClassWithNameTest()
{
var container = new Container();
var res = container.Resolve<MockSimpleObject>("test");
Assert.That(res, Is.Not.Null);
}
[Test(Description = "The container will select the constructor with the most parameters that it can satisfy (Greedy)")]
public void ResolveGreedyConstructorTest()
{
var container = new Container();
container.Register<MockSimpleObject>().ToItsSelf();
var res = container.Resolve<GreedyObject>();
Assert.That(res, Is.Not.Null);
Assert.That(res.Obj1, Is.Not.Null);
Assert.That(res.Obj2, Is.Not.Null);
}
[Test(Description = "You cannot resolve an object with unknown dependencies")]
[ExpectedException(typeof(ResolutionException))]
public void AutoRegisterSimpleDIFailsTest()
{
var container = new Container();
var res = container.Resolve<SimpleDIObject>();
Assert.Fail("Should not be auto registering dependencies");
}
[Test(Description = "You can resolve a concrete type if the container can satisfy dependencies")]
public void ContainerRemembersAutoRegisterTest()
{
var container = new Container();
container.Resolve<MockSimpleObject>();
var res = container.Resolve<SimpleDIObject>();
Assert.That(res, Is.Not.Null);
}
[Test(Description = "You can register an interface to itself as a singleton")]
public void ContainerRegisterInterfaceSingletonTest()
{
var container = new Container();
IMyInterface obj = new MyClass(new MockSimpleObject(), new MockContainerObject(container));
container.Register<IMyInterface>().To(obj);
var res = container.Resolve<IMyInterface>();
Assert.That(res, Is.SameAs(obj));
}
[Test(Description = "You can register an interface to itself as a singleton")]
public void ContainerQuickRegisterInterfaceSingletonTest()
{
var container = new Container();
IMyInterface obj = new MyClass(new MockSimpleObject(), new MockContainerObject(container));
container.Register(obj);
var res = container.Resolve<IMyInterface>();
Assert.That(res, Is.SameAs(obj));
}
[Test(Description = "You can register an interface to itself if you tell the container how to build it")]
public void ContainerRegisterInterfaceWithBuilderTest()
{
var container = new Container();
container.Register<IMyInterface>().As(c => (IMyInterface)new MyClass(new MockSimpleObject(), new MockContainerObject(c)));
var res = container.Resolve<IMyInterface>();
Assert.That(res, Is.Not.Null);
}
[Test(Description = "You cannot register an interface to itself as a transient")]
[ExpectedException(typeof(RegistrationException))]
public void ContainerRegisterInterfaceTransientTest()
{
var container = new Container();
IMyInterface obj = new MyClass(new MockSimpleObject(), new MockContainerObject(container));
container.Register<IMyInterface>().To(obj).AsTransient();
Assert.Fail();
}
[Test(Description = "You can register an interface to itself as a transient if you define a custom builder")]
public void ContainerRegisterInterfaceTransientWithCustomBuilderTest()
{
var container = new Container();
IMyInterface obj = new MyClass(new MockSimpleObject(), new MockContainerObject(container));
container.Register<IMyInterface>().To(obj).ConstructAs(c => obj).AsTransient();
var res = container.Resolve<IMyInterface>();
Assert.That(res, Is.SameAs(obj));
}
[Test(Description = "You cannot register an abstract class to its self")]
[ExpectedException(typeof(RegistrationException))]
public void RegisteredAbstractClassTest()
{
var container = new Container();
container.Register<MyAbstractClass>().To<MyAbstractClass>();
Assert.Fail();
}
[Test(Description = "You cannot resolve an interface without registering it")]
[ExpectedException(typeof(ResolutionException))]
public void UnregisteredInterfacedTest()
{
var container = new Container();
container.Resolve<IMyInterface>();
Assert.Fail();
}
[Test(Description = "You cannot register an interface to its self")]
[ExpectedException(typeof(RegistrationException))]
public void RegisteredInterfaceTest()
{
var container = new Container();
container.Register<IMyInterface>().To<IMyInterface>();
Assert.Fail();
}
[Test(Description = "You can resolve all registrations, default is returned first in IEnumerable")]
public void ResolveAllWithDefaultImplementationTest()
{
var container = new Container();
var first = new MockSimpleObject();
var other = new MockSimpleObject();
container.Register<MockSimpleObject>().To(first);
container.Register<MockSimpleObject>().Named("test1").ToItsSelf();
container.Register<MockSimpleObject>().Named("test3").ToItsSelf();
container.Register<MockSimpleObject>().Named("test2").To(other);
var result = container.ResolveAll<MockSimpleObject>().ToList();
Assert.That(result.Count, Is.EqualTo(4));
Assert.That(result.First(), Is.SameAs(first));
Assert.That(result.Contains(other));
}
[Test(Description = "You can resolve all registrations, no guarantee of ordering")]
public void ResolveAllWithoutDefaultImplementationTest()
{
var container = new Container();
var first = new MockSimpleObject();
var other = new MockSimpleObject();
container.Register<MockSimpleObject>().Named("test").To(first);
container.Register<MockSimpleObject>().Named("test1").ToItsSelf();
container.Register<MockSimpleObject>().Named("test3").ToItsSelf();
container.Register<MockSimpleObject>().Named("test2").To(other);
var result = container.ResolveAll<MockSimpleObject>().ToList();
Assert.That(result.Count, Is.EqualTo(4));
Assert.That(result.Contains(first));
Assert.That(result.Contains(other));
}
[Test(Description = "You can dispose the container")]
public void DisposeReuseTest()
{
var container = new Container();
container.Register<MockContainerObject>().ToItsSelf().AsSingleton();
var target = container.Resolve<MockContainerObject>();
Assert.That(target.Disposed, Is.False);
container.Dispose();
Assert.That(target.Disposed, Is.True);
}
[Test(Description = "You can not use a disposed container")]
[ExpectedException(typeof(ResolutionException))]
public void DisposeTest()
{
var container = new Container();
container.Register<MockContainerObject>().ToItsSelf().AsSingleton();
container.Dispose();
container.Resolve<MockContainerObject>();
}
#endregion
#region Mock Classes
private interface IMyInterface
{ }
private abstract class MyAbstractClass { }
private class MyClass : IMyInterface
{
public readonly MockSimpleObject Object;
public readonly MockContainerObject CObject;
public MyClass(MockSimpleObject obj, MockContainerObject cobj)
{
Object = obj;
CObject = cobj;
}
}
private class MyDependencyClass
{
public MyDependencyClass(IMyInterface mi)
{
}
}
private class MockSimpleObject
{
}
private class SimpleDIObject
{
public SimpleDIObject(MockSimpleObject obj)
{
}
}
private class GreedyObject
{
public MockSimpleObject Obj1 { get; set; }
public MockSimpleObject Obj2 { get; set; }
public GreedyObject(MockSimpleObject o1)
{
Obj1 = o1;
Obj2 = null;
}
public GreedyObject(MockSimpleObject o1, MockSimpleObject o2)
{
Obj1 = o1;
Obj2 = o2;
}
}
private struct MyStucture
{
public MockSimpleObject Object { get; set; }
}
private class MockContainerObject : IDisposable
{
public bool Disposed { get; private set; }
public readonly Container Container;
public MockContainerObject(Container container)
{
Container = container;
Disposed = false;
}
public void Dispose()
{
Disposed = true;
}
}
#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 System.Threading;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Objects.Legacy;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.UI;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestScenePoolingRuleset : OsuTestScene
{
private const double time_between_objects = 1000;
private TestDrawablePoolingRuleset drawableRuleset;
[Test]
public void TestReusedWithHitObjectsSpacedFarApart()
{
ManualClock clock = null;
createTest(new Beatmap
{
HitObjects =
{
new HitObject(),
new HitObject { StartTime = time_between_objects }
}
}, 1, () => new FramedClock(clock = new ManualClock()));
DrawableTestHitObject firstObject = null;
AddUntilStep("first object shown", () => this.ChildrenOfType<DrawableTestHitObject>().SingleOrDefault()?.HitObject == drawableRuleset.Beatmap.HitObjects[0]);
AddStep("get DHO", () => firstObject = this.ChildrenOfType<DrawableTestHitObject>().Single());
AddStep("fast forward to second object", () => clock.CurrentTime = drawableRuleset.Beatmap.HitObjects[1].StartTime);
AddUntilStep("second object shown", () => this.ChildrenOfType<DrawableTestHitObject>().SingleOrDefault()?.HitObject == drawableRuleset.Beatmap.HitObjects[1]);
AddAssert("DHO reused", () => this.ChildrenOfType<DrawableTestHitObject>().Single() == firstObject);
}
[Test]
public void TestCustomTransformsClearedBetweenReuses()
{
ManualClock clock = null;
createTest(new Beatmap
{
HitObjects =
{
new HitObject(),
new HitObject { StartTime = 2000 }
}
}, 1, () => new FramedClock(clock = new ManualClock()));
DrawableTestHitObject firstObject = null;
Vector2 position = default;
AddUntilStep("first object shown", () => this.ChildrenOfType<DrawableTestHitObject>().SingleOrDefault()?.HitObject == drawableRuleset.Beatmap.HitObjects[0]);
AddStep("get DHO", () => firstObject = this.ChildrenOfType<DrawableTestHitObject>().Single());
AddStep("store position", () => position = firstObject.Position);
AddStep("add custom transform", () => firstObject.ApplyCustomUpdateState += onStateUpdate);
AddStep("fast forward past first object", () => clock.CurrentTime = 1500);
AddStep("unapply custom transform", () => firstObject.ApplyCustomUpdateState -= onStateUpdate);
AddStep("fast forward to second object", () => clock.CurrentTime = drawableRuleset.Beatmap.HitObjects[1].StartTime);
AddUntilStep("second object shown", () => this.ChildrenOfType<DrawableTestHitObject>().SingleOrDefault()?.HitObject == drawableRuleset.Beatmap.HitObjects[1]);
AddAssert("DHO reused", () => this.ChildrenOfType<DrawableTestHitObject>().Single() == firstObject);
AddAssert("object in new position", () => firstObject.Position != position);
void onStateUpdate(DrawableHitObject hitObject, ArmedState state)
{
using (hitObject.BeginAbsoluteSequence(hitObject.StateUpdateTime))
hitObject.MoveToOffset(new Vector2(-100, 0));
}
}
[Test]
public void TestNotReusedWithHitObjectsSpacedClose()
{
ManualClock clock = null;
createTest(new Beatmap
{
HitObjects =
{
new HitObject(),
new HitObject { StartTime = 250 }
}
}, 2, () => new FramedClock(clock = new ManualClock()));
AddStep("fast forward to second object", () => clock.CurrentTime = drawableRuleset.Beatmap.HitObjects[1].StartTime);
AddUntilStep("two DHOs shown", () => this.ChildrenOfType<DrawableTestHitObject>().Count() == 2);
AddAssert("DHOs have different hitobjects",
() => this.ChildrenOfType<DrawableTestHitObject>().ElementAt(0).HitObject != this.ChildrenOfType<DrawableTestHitObject>().ElementAt(1).HitObject);
}
[Test]
public void TestManyHitObjects()
{
var beatmap = new Beatmap();
for (int i = 0; i < 500; i++)
beatmap.HitObjects.Add(new HitObject { StartTime = i * 10 });
createTest(beatmap, 100);
AddUntilStep("any DHOs shown", () => this.ChildrenOfType<DrawableTestHitObject>().Any());
AddUntilStep("no DHOs shown", () => !this.ChildrenOfType<DrawableTestHitObject>().Any());
}
[Test]
public void TestApplyHitResultOnKilled()
{
ManualClock clock = null;
bool anyJudged = false;
void onNewResult(JudgementResult _) => anyJudged = true;
var beatmap = new Beatmap();
beatmap.HitObjects.Add(new TestKilledHitObject { Duration = 20 });
createTest(beatmap, 10, () => new FramedClock(clock = new ManualClock()));
AddStep("subscribe to new result", () =>
{
anyJudged = false;
drawableRuleset.NewResult += onNewResult;
});
AddStep("skip past object", () => clock.CurrentTime = beatmap.HitObjects[0].GetEndTime() + 1000);
AddAssert("object judged", () => anyJudged);
AddStep("clean up", () => drawableRuleset.NewResult -= onNewResult);
}
private void createTest(IBeatmap beatmap, int poolSize, Func<IFrameBasedClock> createClock = null) => AddStep("create test", () =>
{
var ruleset = new TestPoolingRuleset();
drawableRuleset = (TestDrawablePoolingRuleset)ruleset.CreateDrawableRulesetWith(CreateWorkingBeatmap(beatmap).GetPlayableBeatmap(ruleset.RulesetInfo));
drawableRuleset.FrameStablePlayback = true;
drawableRuleset.PoolSize = poolSize;
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Clock = createClock?.Invoke() ?? new FramedOffsetClock(Clock, false) { Offset = -Clock.CurrentTime },
Child = drawableRuleset
};
});
#region Ruleset
private class TestPoolingRuleset : Ruleset
{
public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException();
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => new TestDrawablePoolingRuleset(this, beatmap, mods);
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => new TestBeatmapConverter(beatmap, this);
public override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => throw new NotImplementedException();
public override string Description { get; } = string.Empty;
public override string ShortName { get; } = string.Empty;
}
private class TestDrawablePoolingRuleset : DrawableRuleset<TestHitObject>
{
public int PoolSize;
public TestDrawablePoolingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
}
public override DrawableHitObject<TestHitObject> CreateDrawableRepresentation(TestHitObject h) => null;
protected override PassThroughInputManager CreateInputManager() => new PassThroughInputManager();
protected override Playfield CreatePlayfield() => new TestPlayfield(PoolSize);
}
private class TestPlayfield : Playfield
{
private readonly int poolSize;
public TestPlayfield(int poolSize)
{
this.poolSize = poolSize;
AddInternal(HitObjectContainer);
}
[BackgroundDependencyLoader]
private void load()
{
RegisterPool<TestHitObject, DrawableTestHitObject>(poolSize);
RegisterPool<TestKilledHitObject, DrawableTestKilledHitObject>(poolSize);
}
protected override HitObjectLifetimeEntry CreateLifetimeEntry(HitObject hitObject) => new TestHitObjectLifetimeEntry(hitObject);
protected override GameplayCursorContainer CreateCursor() => null;
}
private class TestHitObjectLifetimeEntry : HitObjectLifetimeEntry
{
public TestHitObjectLifetimeEntry(HitObject hitObject)
: base(hitObject)
{
}
protected override double InitialLifetimeOffset => 0;
}
private class TestBeatmapConverter : BeatmapConverter<TestHitObject>
{
public TestBeatmapConverter(IBeatmap beatmap, Ruleset ruleset)
: base(beatmap, ruleset)
{
}
public override bool CanConvert() => true;
protected override IEnumerable<TestHitObject> ConvertHitObject(HitObject original, IBeatmap beatmap, CancellationToken cancellationToken)
{
switch (original)
{
case TestKilledHitObject h:
yield return h;
break;
default:
yield return new TestHitObject
{
StartTime = original.StartTime,
Duration = 250
};
break;
}
}
}
#endregion
#region HitObjects
private class TestHitObject : ConvertHitObject, IHasDuration
{
public double EndTime => StartTime + Duration;
public double Duration { get; set; }
}
private class DrawableTestHitObject : DrawableHitObject<TestHitObject>
{
public DrawableTestHitObject()
: base(null)
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Size = new Vector2(50, 50);
Colour = new Color4(RNG.NextSingle(), RNG.NextSingle(), RNG.NextSingle(), 1f);
}
[BackgroundDependencyLoader]
private void load()
{
AddInternal(new Circle
{
RelativeSizeAxes = Axes.Both,
});
}
protected override void OnApply()
{
base.OnApply();
Position = new Vector2(RNG.Next(-200, 200), RNG.Next(-200, 200));
}
protected override void CheckForResult(bool userTriggered, double timeOffset)
{
if (timeOffset > HitObject.Duration)
ApplyResult(r => r.Type = r.Judgement.MaxResult);
}
protected override void UpdateHitStateTransforms(ArmedState state)
{
base.UpdateHitStateTransforms(state);
switch (state)
{
case ArmedState.Hit:
case ArmedState.Miss:
this.FadeOut(250);
break;
}
}
}
private class TestKilledHitObject : TestHitObject
{
}
private class DrawableTestKilledHitObject : DrawableHitObject<TestKilledHitObject>
{
public DrawableTestKilledHitObject()
: base(null)
{
}
protected override void UpdateHitStateTransforms(ArmedState state)
{
base.UpdateHitStateTransforms(state);
Expire();
}
public override void OnKilled()
{
base.OnKilled();
ApplyResult(r => r.Type = r.Judgement.MinResult);
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// A virtual machine disk associated with your subscription.
/// </summary>
public partial class VirtualMachineDiskGetDiskResponse : OperationResponse
{
private string _affinityGroup;
/// <summary>
/// The affinity group in which the disk is located. The AffinityGroup
/// value is derived from storage account that contains the blob in
/// which the media is located. If the storage account does not belong
/// to an affinity group the value is NULL.
/// </summary>
public string AffinityGroup
{
get { return this._affinityGroup; }
set { this._affinityGroup = value; }
}
private bool? _isCorrupted;
/// <summary>
/// Specifies thether the disk is known to be corrupt.
/// </summary>
public bool? IsCorrupted
{
get { return this._isCorrupted; }
set { this._isCorrupted = value; }
}
private bool? _isPremium;
/// <summary>
/// Specifies whether or not the disk contains a premium virtual
/// machine image.
/// </summary>
public bool? IsPremium
{
get { return this._isPremium; }
set { this._isPremium = value; }
}
private string _label;
/// <summary>
/// The friendly name of the disk.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _location;
/// <summary>
/// The geo-location in which the disk is located. The Location value
/// is derived from storage account that contains the blob in which
/// the disk is located. If the storage account belongs to an affinity
/// group the value is NULL.
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
private double _logicalSizeInGB;
/// <summary>
/// The size, in GB, of the disk.
/// </summary>
public double LogicalSizeInGB
{
get { return this._logicalSizeInGB; }
set { this._logicalSizeInGB = value; }
}
private Uri _mediaLinkUri;
/// <summary>
/// The location of the blob in the blob store in which the media for
/// the disk is located. The blob location belongs to a storage
/// account in the subscription specified by the SubscriptionId value
/// in the operation call. Example:
/// http://example.blob.core.windows.net/disks/mydisk.vhd
/// </summary>
public Uri MediaLinkUri
{
get { return this._mediaLinkUri; }
set { this._mediaLinkUri = value; }
}
private string _name;
/// <summary>
/// The name of the disk. This is the name that is used when creating
/// one or more virtual machines using the disk.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _operatingSystemType;
/// <summary>
/// The operating system type of the OS image. Possible Values are:
/// Linux, Windows, NULL.
/// </summary>
public string OperatingSystemType
{
get { return this._operatingSystemType; }
set { this._operatingSystemType = value; }
}
private string _sourceImageName;
/// <summary>
/// The name of the OS Image from which the disk was created. This
/// property is populated automatically when a disk is created from an
/// OS image by calling the Add Role, Create Deployment, or Provision
/// Disk operations.
/// </summary>
public string SourceImageName
{
get { return this._sourceImageName; }
set { this._sourceImageName = value; }
}
private VirtualMachineDiskGetDiskResponse.VirtualMachineDiskUsageDetails _usageDetails;
/// <summary>
/// Contains properties that specify a virtual machine that currently
/// using the disk. A disk cannot be deleted as long as it is attached
/// to a virtual machine.
/// </summary>
public VirtualMachineDiskGetDiskResponse.VirtualMachineDiskUsageDetails UsageDetails
{
get { return this._usageDetails; }
set { this._usageDetails = value; }
}
/// <summary>
/// Initializes a new instance of the VirtualMachineDiskGetDiskResponse
/// class.
/// </summary>
public VirtualMachineDiskGetDiskResponse()
{
}
/// <summary>
/// Contains properties that specify a virtual machine that currently
/// using the disk. A disk cannot be deleted as long as it is attached
/// to a virtual machine.
/// </summary>
public partial class VirtualMachineDiskUsageDetails
{
private string _deploymentName;
/// <summary>
/// The deployment in which the disk is being used.
/// </summary>
public string DeploymentName
{
get { return this._deploymentName; }
set { this._deploymentName = value; }
}
private string _hostedServiceName;
/// <summary>
/// The hosted service in which the disk is being used.
/// </summary>
public string HostedServiceName
{
get { return this._hostedServiceName; }
set { this._hostedServiceName = value; }
}
private string _roleName;
/// <summary>
/// The virtual machine that the disk is attached to.
/// </summary>
public string RoleName
{
get { return this._roleName; }
set { this._roleName = value; }
}
/// <summary>
/// Initializes a new instance of the
/// VirtualMachineDiskUsageDetails class.
/// </summary>
public VirtualMachineDiskUsageDetails()
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace System.Reflection.Tests
{
public class ParamInfoPropertyTests
{
//Verify Member
[Fact]
public static void TestParamMember1()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 0);
MemberInfo mi = pi.Member;
Assert.NotNull(mi);
}
//Verify Member
[Fact]
public static void TestParamMember2()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "virtualMethod", 0);
MemberInfo mi = pi.Member;
Assert.NotNull(mi);
}
//Verify Member
[Fact]
public static void TestParamMember3()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithRefKW", 0);
MemberInfo mi = pi.Member;
Assert.NotNull(mi);
}
//Verify Member
[Fact]
public static void TestParamMember4()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 0);
MemberInfo mi = pi.Member;
Assert.NotNull(mi);
}
//Verify Member
[Fact]
public static void TestParamMember5()
{
ParameterInfo pi = getParamInfo(typeof(GenericClass<string>), "genericMethod", 0);
MemberInfo mi = pi.Member;
Assert.NotNull(mi);
}
//Verify HasDefaultValue for return param
[Fact]
public static void TestHasDefaultValue1()
{
ParameterInfo pi = getReturnParam(typeof(MyClass), "Method1");
Assert.True(pi.HasDefaultValue);
}
//Verify HasDefaultValue for param that has default
[Fact]
public static void TestHasDefaultValue2()
{
Assert.True(getParamInfo(typeof(MyClass), "MethodWithdefault1", 1).HasDefaultValue);
}
//Verify HasDefaultValue for different types of default values
[Fact]
public static void TestHasDefaultValue3()
{
Assert.True(getParamInfo(typeof(MyClass), "MethodWithdefault2", 0).HasDefaultValue);
Assert.True(getParamInfo(typeof(MyClass), "MethodWithdefault3", 0).HasDefaultValue);
Assert.True(getParamInfo(typeof(MyClass), "MethodWithdefault4", 0).HasDefaultValue);
}
//Verify HasDefaultValue for generic method
[Fact]
public static void TestHasDefaultValue4()
{
Assert.True(getParamInfo(typeof(GenericClass<int>), "genericMethodWithdefault", 1).HasDefaultValue);
}
//Verify HasDefaultValue for methods that do not have default
[Fact]
public static void TestHasDefaultValue5()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 1);
Assert.False(pi.HasDefaultValue);
}
//Verify HasDefaultValue for methods that do not have default
[Fact]
public static void TestHasDefaultValue6()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithRefKW", 0);
Assert.False(pi.HasDefaultValue);
}
//Verify HasDefaultValue for methods that do not have default
[Fact]
public static void TestHasDefaultValue7()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 1);
Assert.False(pi.HasDefaultValue);
}
//Verify HasDefaultValue for methods that do not have default
[Fact]
public static void TestHasDefaultValue8()
{
ParameterInfo pi = getParamInfo(typeof(GenericClass<int>), "genericMethod", 0);
Assert.False(pi.HasDefaultValue);
}
//Verify IsOut
[Fact]
public static void TestIsOut1()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithRefKW", 0);
Assert.False(pi.IsOut);
}
//Verify IsOut
[Fact]
public static void TestIsOut2()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 1);
Assert.True(pi.IsOut);
}
//Verify IsOut
[Fact]
public static void TestIsOut3()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 1);
Assert.False(pi.IsOut);
}
//Verify IsIN
[Fact]
public static void TestIsIN1()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 1);
Assert.False(pi.IsIn);
}
//Verify DefaultValue for param that has default
[Fact]
public static void TestDefaultValue1()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault1", 1);
int value = (int)pi.DefaultValue;
Assert.Equal(0, value);
}
//Verify DefaultValue for param that has default
[Fact]
public static void TestDefaultValue2()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault2", 0);
string value = (string)pi.DefaultValue;
Assert.Equal("abc", value);
}
//Verify DefaultValue for param that has default
[Fact]
public static void TestDefaultValue3()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault3", 0);
bool value = (bool)pi.DefaultValue;
Assert.Equal(false, value);
}
//Verify DefaultValue for param that has default
[Fact]
public static void TestDefaultValue4()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault4", 0);
char value = (char)pi.DefaultValue;
Assert.Equal('\0', value);
}
[Fact]
public static void TestDefaultValue5()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOptionalAndNoDefault", 0);
Object defaultValue = pi.DefaultValue;
Assert.Equal(Missing.Value, defaultValue);
}
//Verify IsOptional
[Fact]
public static void TestIsOptional1()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 1);
Assert.False(pi.IsOptional);
}
//Verify IsOptional
[Fact]
public static void TestIsOptional2()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOutKW", 1);
Assert.False(pi.IsOptional);
}
//Verify IsRetval
[Fact]
public static void TestIsRetval1()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "Method1", 1);
Assert.False(pi.IsRetval);
}
//Verify IsRetval
[Fact]
public static void TestIsRetval2()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithdefault2", 0);
Assert.False(pi.IsRetval);
}
[Fact]
public static void AttributesTest()
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOptionalDefaultOutInMarshalParam", 0);
Assert.True(pi.Attributes.HasFlag(ParameterAttributes.Optional));
Assert.True(pi.Attributes.HasFlag(ParameterAttributes.HasDefault));
Assert.True(pi.Attributes.HasFlag(ParameterAttributes.HasFieldMarshal));
Assert.True(pi.Attributes.HasFlag(ParameterAttributes.Out));
Assert.True(pi.Attributes.HasFlag(ParameterAttributes.In));
}
[Theory]
[InlineData(typeof(OptionalAttribute))]
[InlineData(typeof(MarshalAsAttribute))]
[InlineData(typeof(OutAttribute))]
[InlineData(typeof(InAttribute))]
public static void CustomAttributesTest(Type attrType)
{
ParameterInfo pi = getParamInfo(typeof(MyClass), "MethodWithOptionalDefaultOutInMarshalParam", 0);
CustomAttributeData attribute = pi.CustomAttributes.SingleOrDefault(a => a.AttributeType.Equals(attrType));
Assert.NotNull(attribute);
}
//Helper Method to get ParameterInfo object based on index
private static ParameterInfo getParamInfo(Type type, string methodName, int index)
{
MethodInfo mi = getMethod(type, methodName);
Assert.NotNull(mi);
ParameterInfo[] allparams = mi.GetParameters();
Assert.NotNull(allparams);
if (index < allparams.Length)
return allparams[index];
else
return null;
}
private static ParameterInfo getReturnParam(Type type, string methodName)
{
MethodInfo mi = getMethod(type, methodName);
Assert.NotNull(mi);
return mi.ReturnParameter;
}
private static MethodInfo getMethod(Type t, string method)
{
TypeInfo ti = t.GetTypeInfo();
IEnumerator<MethodInfo> alldefinedMethods = ti.DeclaredMethods.GetEnumerator();
MethodInfo mi = null;
while (alldefinedMethods.MoveNext())
{
if (alldefinedMethods.Current.Name.Equals(method))
{
//found method
mi = alldefinedMethods.Current;
break;
}
}
return mi;
}
// Class For Reflection Metadata
public class MyClass
{
public int Method1(String str, int iValue, long lValue)
{
return 1;
}
public string Method2()
{
return "somestring";
}
public int MethodWithArray(String[] strArray)
{
for (int ii = 0; ii < strArray.Length; ++ii)
{
}
return strArray.Length;
}
public virtual void virtualMethod(long data)
{
}
public bool MethodWithRefKW(ref String str)
{
str = "newstring";
return true;
}
public Object MethodWithOutKW(int i, out String str)
{
str = "newstring";
return (object)str;
}
public int MethodWithdefault1(long lValue, int iValue = 0)
{
return 1;
}
public int MethodWithdefault2(string str = "abc")
{
return 1;
}
public int MethodWithdefault3(bool result = false)
{
return 1;
}
public int MethodWithdefault4(char c = '\0')
{
return 1;
}
public int MethodWithOptionalAndNoDefault([Optional] Object o)
{
return 1;
}
public int MethodWithOptionalDefaultOutInMarshalParam([MarshalAs(UnmanagedType.LPWStr)][Out][In] string str = "")
{
return 1;
}
}
public class GenericClass<T>
{
public string genericMethod(T t) { return "somestring"; }
public string genericMethodWithdefault(int i, T t = default(T)) { return "somestring"; }
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Collections.Specialized.Tests
{
public static class StringCollectionTests
{
private const string ElementNotPresent = "element-not-present";
/// <summary>
/// Data used for testing with Insert.
/// </summary>
/// Format is:
/// 1. initial Collection
/// 2. internal data
/// 3. data to insert (ElementNotPresent or null)
/// 4. location to insert (0, count / 2, count)
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Insert_Data()
{
foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data()))
{
string[] d = (string[])(data[1]);
foreach (string element in new[] { ElementNotPresent, null })
{
foreach (int location in new[] { 0, d.Length / 2, d.Length }.Distinct())
{
StringCollection initial = new StringCollection();
initial.AddRange(d);
yield return new object[] { initial, d, element, location };
}
}
}
}/// <summary>
/// Data used for testing with RemoveAt.
/// </summary>
/// Format is:
/// 1. initial Collection
/// 2. internal data
/// 3. location to remove (0, count / 2, count)
/// <returns>Row of data</returns>
public static IEnumerable<object[]> RemoveAt_Data()
{
foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data()))
{
string[] d = (string[])(data[1]);
if (d.Length > 0)
{
foreach (int location in new[] { 0, d.Length / 2, d.Length - 1 }.Distinct())
{
StringCollection initial = new StringCollection();
initial.AddRange(d);
yield return new object[] { initial, d, location };
}
}
}
}
/// <summary>
/// Data used for testing with a set of collections.
/// </summary>
/// Format is:
/// 1. Collection
/// 2. internal data
/// <returns>Row of data</returns>
public static IEnumerable<object[]> StringCollection_Data()
{
yield return ConstructRow(new string[] { /* empty */ });
yield return ConstructRow(new string[] { null });
yield return ConstructRow(new string[] { "single" });
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x.ToString()).ToArray());
for (int index = 0; index < 100; index += 25)
{
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x == index ? null : x.ToString()).ToArray());
}
}
/// <summary>
/// Data used for testing with a set of collections, where the data has duplicates.
/// </summary>
/// Format is:
/// 1. Collection
/// 2. internal data
/// <returns>Row of data</returns>
public static IEnumerable<object[]> StringCollection_Duplicates_Data()
{
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (string)null).ToArray());
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x % 10 == 0 ? null : (x % 10).ToString()).ToArray());
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (x % 10).ToString()).ToArray());
}
private static object[] ConstructRow(string[] data)
{
if (data.Contains(ElementNotPresent)) throw new ArgumentException("Do not include \"" + ElementNotPresent + "\" in data.");
StringCollection col = new StringCollection();
col.AddRange(data);
return new object[] { col, data };
}
[Fact]
public static void Constructor_DefaultTest()
{
StringCollection sc = new StringCollection();
Assert.Equal(0, sc.Count);
Assert.False(sc.Contains(null));
Assert.False(sc.Contains(""));
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void AddTest(StringCollection collection, string[] data)
{
StringCollection added = new StringCollection();
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(i, added.Count);
Assert.Throws<ArgumentOutOfRangeException>(() => added[i]);
added.Add(data[i]);
Assert.Equal(data[i], added[i]);
Assert.Equal(i + 1, added.Count);
}
Assert.Equal(collection, added);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Add_ExplicitInterface_Test(StringCollection collection, string[] data)
{
IList added = new StringCollection();
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(i, added.Count);
Assert.Throws<ArgumentOutOfRangeException>(() => added[i]);
added.Add(data[i]);
Assert.Equal(data[i], added[i]);
Assert.Equal(i + 1, added.Count);
}
Assert.Equal(collection, added);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void AddRangeTest(StringCollection collection, string[] data)
{
StringCollection added = new StringCollection();
added.AddRange(data);
Assert.Equal(collection, added);
added.AddRange(new string[] { /*empty*/});
Assert.Equal(collection, added);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void AddRange_NullTest(StringCollection collection, string[] data)
{
AssertExtensions.Throws<ArgumentNullException>("value", () => collection.AddRange(null));
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void ClearTest(StringCollection collection, string[] data)
{
Assert.Equal(data.Length, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void CopyToTest(StringCollection collection, string[] data)
{
string[] full = new string[data.Length];
collection.CopyTo(full, 0);
Assert.Equal(data, full);
string[] large = new string[data.Length * 2];
collection.CopyTo(large, data.Length / 4);
for (int i = 0; i < large.Length; i++)
{
if (i < data.Length / 4 || i >= data.Length + data.Length / 4)
{
Assert.Null(large[i]);
}
else
{
Assert.Equal(data[i - data.Length / 4], large[i]);
}
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void CopyTo_ExplicitInterface_Test(ICollection collection, string[] data)
{
string[] full = new string[data.Length];
collection.CopyTo(full, 0);
Assert.Equal(data, full);
string[] large = new string[data.Length * 2];
collection.CopyTo(large, data.Length / 4);
for (int i = 0; i < large.Length; i++)
{
if (i < data.Length / 4 || i >= data.Length + data.Length / 4)
{
Assert.Null(large[i]);
}
else
{
Assert.Equal(data[i - data.Length / 4], large[i]);
}
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void CopyTo_ArgumentInvalidTest(StringCollection collection, string[] data)
{
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(data, -1));
if (data.Length > 0)
{
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(new string[0], data.Length - 1));
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(new string[data.Length - 1], 0));
}
// As explicit interface implementation
Assert.Throws<ArgumentNullException>(() => ((ICollection)collection).CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)collection).CopyTo(data, -1));
if (data.Length > 0)
{
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => ((ICollection)collection).CopyTo(new string[0], data.Length - 1));
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => ((ICollection)collection).CopyTo(new string[data.Length - 1], 0));
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void CountTest(StringCollection collection, string[] data)
{
Assert.Equal(data.Length, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
collection.Add("one");
Assert.Equal(1, collection.Count);
collection.AddRange(data);
Assert.Equal(1 + data.Length, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void ContainsTest(StringCollection collection, string[] data)
{
Assert.All(data, element => Assert.True(collection.Contains(element)));
Assert.All(data, element => Assert.True(((IList)collection).Contains(element)));
Assert.False(collection.Contains(ElementNotPresent));
Assert.False(((IList)collection).Contains(ElementNotPresent));
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetEnumeratorTest(StringCollection collection, string[] data)
{
bool repeat = true;
StringEnumerator enumerator = collection.GetEnumerator();
Assert.NotNull(enumerator);
while (repeat)
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
foreach (string element in data)
{
Assert.True(enumerator.MoveNext());
Assert.Equal(element, enumerator.Current);
Assert.Equal(element, enumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
enumerator.Reset();
repeat = false;
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetEnumerator_ModifiedCollectionTest(StringCollection collection, string[] data)
{
StringEnumerator enumerator = collection.GetEnumerator();
Assert.NotNull(enumerator);
if (data.Length > 0)
{
Assert.True(enumerator.MoveNext());
string current = enumerator.Current;
Assert.Equal(data[0], current);
collection.RemoveAt(0);
if (data.Length > 1 && data[0] != data[1])
{
Assert.NotEqual(current, collection[0]);
}
Assert.Equal(current, enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
}
else
{
collection.Add("newValue");
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetSetTest(StringCollection collection, string[] data)
{
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(data[i], collection[i]);
}
for (int i = 0; i < data.Length / 2; i++)
{
string temp = collection[i];
collection[i] = collection[data.Length - i - 1];
collection[data.Length - i - 1] = temp;
}
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(data[data.Length - i - 1], collection[i]);
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetSet_ExplicitInterface_Test(IList collection, string[] data)
{
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(data[i], collection[i]);
}
for (int i = 0; i < data.Length / 2; i++)
{
object temp = collection[i];
if (temp != null)
{
Assert.IsType<string>(temp);
}
collection[i] = collection[data.Length - i - 1];
collection[data.Length - i - 1] = temp;
}
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(data[data.Length - i - 1], collection[i]);
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetSet_ArgumentInvalidTest(StringCollection collection, string[] data)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = ElementNotPresent);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = null);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = ElementNotPresent);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = null);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length]);
// As explicitly implementing the interface
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = ElementNotPresent);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = null);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = ElementNotPresent);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = null);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length]);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void IndexOfTest(StringCollection collection, string[] data)
{
Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element)));
Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element)));
Assert.Equal(-1, collection.IndexOf(ElementNotPresent));
Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent));
}
[Theory]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void IndexOf_DuplicateTest(StringCollection collection, string[] data)
{
// Only the index of the first element will be returned.
data = data.Distinct().ToArray();
Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element)));
Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element)));
Assert.Equal(-1, collection.IndexOf(ElementNotPresent));
Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent));
}
[Theory]
[MemberData(nameof(Insert_Data))]
public static void InsertTest(StringCollection collection, string[] data, string element, int location)
{
collection.Insert(location, element);
Assert.Equal(data.Length + 1, collection.Count);
if (element == ElementNotPresent)
{
Assert.Equal(location, collection.IndexOf(ElementNotPresent));
}
for (int i = 0; i < data.Length + 1; i++)
{
if (i < location)
{
Assert.Equal(data[i], collection[i]);
}
else if (i == location)
{
Assert.Equal(element, collection[i]);
}
else
{
Assert.Equal(data[i - 1], collection[i]);
}
}
}
[Theory]
[MemberData(nameof(Insert_Data))]
public static void Insert_ExplicitInterface_Test(IList collection, string[] data, string element, int location)
{
collection.Insert(location, element);
Assert.Equal(data.Length + 1, collection.Count);
if (element == ElementNotPresent)
{
Assert.Equal(location, collection.IndexOf(ElementNotPresent));
}
for (int i = 0; i < data.Length + 1; i++)
{
if (i < location)
{
Assert.Equal(data[i], collection[i]);
}
else if (i == location)
{
Assert.Equal(element, collection[i]);
}
else
{
Assert.Equal(data[i - 1], collection[i]);
}
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Insert_ArgumentInvalidTest(StringCollection collection, string[] data)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, ElementNotPresent));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(data.Length + 1, ElementNotPresent));
// And as explicit interface implementation
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(-1, ElementNotPresent));
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(data.Length + 1, ElementNotPresent));
}
[Fact]
public static void IsFixedSizeTest()
{
Assert.False(((IList)new StringCollection()).IsFixedSize);
}
[Fact]
public static void IsReadOnlyTest()
{
Assert.False(new StringCollection().IsReadOnly);
Assert.False(((IList)new StringCollection()).IsReadOnly);
}
[Fact]
public static void IsSynchronizedTest()
{
Assert.False(new StringCollection().IsSynchronized);
Assert.False(((IList)new StringCollection()).IsSynchronized);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
public static void RemoveTest(StringCollection collection, string[] data)
{
Assert.All(data, element =>
{
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
collection.Remove(element);
Assert.False(collection.Contains(element));
Assert.False(((IList)collection).Contains(element));
});
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
public static void Remove_IListTest(StringCollection collection, string[] data)
{
Assert.All(data, element =>
{
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
((IList)collection).Remove(element);
Assert.False(collection.Contains(element));
Assert.False(((IList)collection).Contains(element));
});
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Remove_NotPresentTest(StringCollection collection, string[] data)
{
collection.Remove(ElementNotPresent);
Assert.Equal(data.Length, collection.Count);
((IList)collection).Remove(ElementNotPresent);
Assert.Equal(data.Length, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Remove_DuplicateTest(StringCollection collection, string[] data)
{
// Only the first element will be removed.
string[] first = data.Distinct().ToArray();
Assert.All(first, element =>
{
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
collection.Remove(element);
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
});
Assert.Equal(data.Length - first.Length, collection.Count);
for (int i = first.Length; i < data.Length; i++)
{
string element = data[i];
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
collection.Remove(element);
bool stillPresent = i < data.Length - first.Length;
Assert.Equal(stillPresent, collection.Contains(element));
Assert.Equal(stillPresent, ((IList)collection).Contains(element));
}
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(RemoveAt_Data))]
public static void RemoveAtTest(StringCollection collection, string[] data, int location)
{
collection.RemoveAt(location);
Assert.Equal(data.Length - 1, collection.Count);
for (int i = 0; i < data.Length - 1; i++)
{
if (i < location)
{
Assert.Equal(data[i], collection[i]);
}
else if (i >= location)
{
Assert.Equal(data[i + 1], collection[i]);
}
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void RemoveAt_ArgumentInvalidTest(StringCollection collection, string[] data)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(data.Length));
}
[Theory]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Remove_Duplicate_IListTest(StringCollection collection, string[] data)
{
// Only the first element will be removed.
string[] first = data.Distinct().ToArray();
Assert.All(first, element =>
{
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
((IList)collection).Remove(element);
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
});
Assert.Equal(data.Length - first.Length, collection.Count);
for (int i = first.Length; i < data.Length; i++)
{
string element = data[i];
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
((IList)collection).Remove(element);
bool stillPresent = i < data.Length - first.Length;
Assert.Equal(stillPresent, collection.Contains(element));
Assert.Equal(stillPresent, ((IList)collection).Contains(element));
}
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void SyncRootTest(StringCollection collection, string[] data)
{
object syncRoot = collection.SyncRoot;
Assert.NotNull(syncRoot);
Assert.IsType<ArrayList>(syncRoot);
Assert.Same(syncRoot, collection.SyncRoot);
Assert.NotSame(syncRoot, new StringCollection().SyncRoot);
StringCollection other = new StringCollection();
other.AddRange(data);
Assert.NotSame(syncRoot, other.SyncRoot);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: StringWriter
**
** <OWNER>[....]</OWNER>
**
** Purpose: For writing text to a string
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Text;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security.Permissions;
#if FEATURE_ASYNC_IO
using System.Threading.Tasks;
#endif
namespace System.IO {
// This class implements a text writer that writes to a string buffer and allows
// the resulting sequence of characters to be presented as a string.
//
[Serializable]
[ComVisible(true)]
public class StringWriter : TextWriter
{
private static volatile UnicodeEncoding m_encoding=null;
private StringBuilder _sb;
private bool _isOpen;
// Constructs a new StringWriter. A new StringBuilder is automatically
// created and associated with the new StringWriter.
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public StringWriter()
: this(new StringBuilder(), CultureInfo.CurrentCulture)
{
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public StringWriter(IFormatProvider formatProvider)
: this(new StringBuilder(), formatProvider) {
}
// Constructs a new StringWriter that writes to the given StringBuilder.
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public StringWriter(StringBuilder sb) : this(sb, CultureInfo.CurrentCulture) {
}
public StringWriter(StringBuilder sb, IFormatProvider formatProvider) : base(formatProvider) {
if (sb==null)
throw new ArgumentNullException("sb", Environment.GetResourceString("ArgumentNull_Buffer"));
Contract.EndContractBlock();
_sb = sb;
_isOpen = true;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override void Close()
{
Dispose(true);
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
protected override void Dispose(bool disposing)
{
// Do not destroy _sb, so that we can extract this after we are
// done writing (similar to MemoryStream's GetBuffer & ToArray methods)
_isOpen = false;
base.Dispose(disposing);
}
public override Encoding Encoding {
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
get {
if (m_encoding==null) {
m_encoding = new UnicodeEncoding(false, false);
}
return m_encoding;
}
}
// Returns the underlying StringBuilder. This is either the StringBuilder
// that was passed to the constructor, or the StringBuilder that was
// automatically created.
//
public virtual StringBuilder GetStringBuilder() {
return _sb;
}
// Writes a character to the underlying string buffer.
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override void Write(char value) {
if (!_isOpen)
__Error.WriterClosed();
_sb.Append(value);
}
// Writes a range of a character array to the underlying string buffer.
// This method will write count characters of data into this
// StringWriter from the buffer character array starting at position
// index.
//
public override void Write(char[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen)
__Error.WriterClosed();
_sb.Append(buffer, index, count);
}
// Writes a string to the underlying string buffer. If the given string is
// null, nothing is written.
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override void Write(String value) {
if (!_isOpen)
__Error.WriterClosed();
if (value != null) _sb.Append(value);
}
#if FEATURE_ASYNC_IO
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
Write(value);
return Task.CompletedTask;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(String value)
{
Write(value);
return Task.CompletedTask;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
Write(buffer, index, count);
return Task.CompletedTask;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
WriteLine(value);
return Task.CompletedTask;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
WriteLine(value);
return Task.CompletedTask;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
WriteLine(buffer, index, count);
return Task.CompletedTask;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task FlushAsync()
{
return Task.CompletedTask;
}
#endregion
#endif //FEATURE_ASYNC_IO
// Returns a string containing the characters written to this TextWriter
// so far.
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override String ToString() {
return _sb.ToString();
}
}
}
| |
using System.Collections;
using System;
using System.Globalization;
namespace io {
public class IoNumber : IoObject
{
public override string name { get { return "Number"; } }
public object value
{
get
{
if (isInteger)
{
return longValue;
}
else
{
return doubleValue;
}
}
}
public int accuracy = 0;
public double doubleValue;
public bool isInteger = true;
public int longValue;
public new static IoNumber createProto(IoState state)
{
IoNumber number = new IoNumber();
return number.proto(state) as IoNumber;
}
public override IoObject proto(IoState state)
{
IoNumber pro = new IoNumber();
pro.state = state;
pro.createSlots();
pro.createProtos();
pro.doubleValue = 0;
pro.longValue = 0;
pro.isInteger = true;
state.registerProtoWithFunc(name, new IoStateProto(pro.name, pro, new IoStateProtoFunc(pro.proto)));
pro.protos.Add(state.protoWithInitFunc("Object"));
IoCFunction[] methodTable = new IoCFunction[] {
new IoCFunction("asNumber", new IoMethodFunc(IoNumber.slotAsNumber)),
new IoCFunction("+", new IoMethodFunc(IoNumber.slotAdd)),
new IoCFunction("-", new IoMethodFunc(IoNumber.slotSubstract)),
new IoCFunction("*", new IoMethodFunc(IoNumber.slotMultiply)),
new IoCFunction("/", new IoMethodFunc(IoNumber.slotDivide)),
new IoCFunction("log10", new IoMethodFunc(IoNumber.slotLog10)),
new IoCFunction("log2", new IoMethodFunc(IoNumber.slotLog2)),
new IoCFunction("log", new IoMethodFunc(IoNumber.slotLog)),
new IoCFunction("pow", new IoMethodFunc(IoNumber.slotPow)),
new IoCFunction("pi", new IoMethodFunc(IoNumber.slotPi)),
new IoCFunction("e", new IoMethodFunc(IoNumber.slotE)),
new IoCFunction("minPositive", new IoMethodFunc(IoNumber.slotMinPositive)),
new IoCFunction("exp", new IoMethodFunc(IoNumber.slotExp)),
new IoCFunction("round", new IoMethodFunc(IoNumber.slotRound)),
// new IoCFunction("asString", new IoMethodFunc(this.asString))
};
pro.addTaglessMethodTable(state, methodTable);
return pro;
}
public static IoNumber newWithDouble(IoState state, double n)
{
IoNumber fab = new IoNumber();
IoNumber num = state.protoWithInitFunc(fab.name) as IoNumber;
num = num.clone(state) as IoNumber;
num.isInteger = false;
num.doubleValue = n;
if (Double.Equals(n, 0) ||
(!Double.IsInfinity(n) && !Double.IsNaN(n) &&
!n.ToString(CultureInfo.InvariantCulture).Contains(".") &&
!n.ToString(CultureInfo.InvariantCulture).Contains("E") &&
!n.ToString(CultureInfo.InvariantCulture).Contains("e")
)
)
{
try
{
num.longValue = Convert.ToInt32(n);
num.isInteger = true;
}
catch (OverflowException oe)
{
}
}
return num;
}
public override int GetHashCode()
{
return Convert.ToInt32(uniqueIdCounter);
}
public override string ToString()
{
return isInteger ? longValue.ToString(CultureInfo.InvariantCulture)
: doubleValue.ToString("G",CultureInfo.InvariantCulture);
}
public override int compare(IoObject v)
{
IoNumber o = this as IoNumber;
if (v is IoNumber)
{
if (Convert.ToDouble((v as IoNumber).value) == Convert.ToDouble(o.value))
{
return 0;
}
double d = (v as IoNumber).isInteger ? (v as IoNumber).longValue : (v as IoNumber).doubleValue;
double thisValue = o.isInteger ? o.longValue : o.doubleValue;
return thisValue < d ? -1 : 1;
}
return base.compare(v);
}
public long asLong()
{
return Convert.ToInt64(value);
}
public int asInt()
{
return Convert.ToInt32(value);
}
public float asFloat()
{
return Convert.ToSingle(value);
}
public double asDouble()
{
return Convert.ToDouble(value);
}
public override void print()
{
Console.Write("{0}", this.ToString());
}
public static IoObject slotAsNumber(IoObject target, IoObject locals, IoObject message)
{
return target;
}
public static IoObject slotAdd(IoObject target, IoObject locals, IoObject message)
{
IoNumber other = (message as IoMessage).localsNumberArgAt(locals, 0);
IoNumber self = target as IoNumber;
if (other == null) return self;
return IoNumber.newWithDouble(target.state,
(self.isInteger ? self.longValue : self.doubleValue) +
(other.isInteger ? other.longValue : other.doubleValue)
);
}
public static IoObject slotSubstract(IoObject target, IoObject locals, IoObject message)
{
IoNumber other = (message as IoMessage).localsNumberArgAt(locals, 0);
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
(self.isInteger ? self.longValue : self.doubleValue) -
(other.isInteger ? other.longValue : other.doubleValue)
);
}
public static IoObject slotMultiply(IoObject target, IoObject locals, IoObject message)
{
IoNumber other = (message as IoMessage).localsNumberArgAt(locals, 0);
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
(self.isInteger ? self.longValue : self.doubleValue) *
(other.isInteger ? other.longValue : other.doubleValue)
);
}
public static IoObject slotDivide(IoObject target, IoObject locals, IoObject message)
{
IoNumber other = (message as IoMessage).localsNumberArgAt(locals, 0);
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
(self.isInteger ? self.longValue : self.doubleValue) /
(other.isInteger ? other.longValue : other.doubleValue)
);
}
public static IoObject slotLog10(IoObject target, IoObject locals, IoObject message)
{
// IoNumber other = (message as IoMessage).localsNumberArgAt(locals, 0);
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
Math.Log10(self.isInteger ? self.longValue : self.doubleValue)
);
}
// setSlot("A", 32.45 + (20*(5836 log10)) + (20*(8.5 log10)))
// !link-budget 22 0 13 126.3606841787141377 8 0
public static IoObject slotLog2(IoObject target, IoObject locals, IoObject message)
{
// IoNumber other = (message as IoMessage).localsNumberArgAt(locals, 0);
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
Math.Log(self.isInteger ? self.longValue : self.doubleValue, 2)
);
}
public static IoObject slotPi(IoObject target, IoObject locals, IoObject message)
{
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state, Math.PI);
}
public static IoObject slotMinPositive(IoObject target, IoObject locals, IoObject message)
{
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state, Double.Epsilon);
}
public static IoObject slotE(IoObject target, IoObject locals, IoObject message)
{
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state, Math.E);
}
public static IoObject slotLog(IoObject target, IoObject locals, IoObject message)
{
IoNumber other = (message as IoMessage).localsNumberArgAt(locals, 0);
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
Math.Log(self.isInteger ? self.longValue : self.doubleValue,
other.isInteger ? other.longValue : other.doubleValue)
);
}
public static IoObject slotPow(IoObject target, IoObject locals, IoObject message)
{
IoNumber other = (message as IoMessage).localsNumberArgAt(locals, 0);
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
Math.Pow(self.isInteger ? self.longValue : self.doubleValue,
other.isInteger ? other.longValue : other.doubleValue)
);
}
public static IoObject slotExp(IoObject target, IoObject locals, IoObject message)
{
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
Math.Exp(self.isInteger ? self.longValue : self.doubleValue)
);
}
public static IoObject slotRound(IoObject target, IoObject locals, IoObject message)
{
IoNumber self = target as IoNumber;
return IoNumber.newWithDouble(target.state,
Math.Round(self.isInteger ? self.longValue : self.doubleValue)
);
}
}
}
| |
//
// CookieCollection.cs
// Copied from System.Net.CookieCollection.cs
//
// Authors:
// Lawrence Pit (loz@cable.a2000.nl)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Sebastien Pouliot (sebastien@ximian.com)
// sta (sta.blockhead@gmail.com)
//
// Copyright (c) 2004,2009 Novell, Inc (http://www.novell.com)
// Copyright (c) 2012-2013 sta.blockhead (sta.blockhead@gmail.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;
using System.Collections.Generic;
using System.Globalization;
namespace Reactor.Net
{
public class CookieCollection : ICollection, IEnumerable
{
// not 100% identical to MS implementation
sealed class CookieCollectionComparer : IComparer<Cookie>
{
public int Compare(Cookie x, Cookie y)
{
if (x == null || y == null)
{
return 0;
}
var ydomain = y.Domain.Length - (y.Domain[0] == '.' ? 1 : 0);
var xdomain = x.Domain.Length - (x.Domain[0] == '.' ? 1 : 0);
int result = ydomain - xdomain;
return result == 0 ? y.Path.Length - x.Path.Length : result;
}
}
static CookieCollectionComparer Comparer = new CookieCollectionComparer();
private List<Cookie> list = new List<Cookie>();
internal IList<Cookie> List
{
get { return list; }
}
// ICollection
public int Count
{
get { return list.Count; }
}
public bool IsSynchronized
{
get { return false; }
}
public Object SyncRoot
{
get { return this; }
}
public void CopyTo(Array array, int index)
{
(list as IList).CopyTo(array, index);
}
public void CopyTo(Cookie[] array, int index)
{
list.CopyTo(array, index);
}
// IEnumerable
public IEnumerator GetEnumerator()
{
return list.GetEnumerator();
}
// This
// LAMESPEC: So how is one supposed to create a writable CookieCollection
// instance?? We simply ignore this property, as this collection is always
// writable.
public bool IsReadOnly
{
get { return true; }
}
public void Add(Cookie cookie)
{
if (cookie == null)
{
throw new ArgumentNullException("cookie");
}
int pos = SearchCookie(cookie);
if (pos == -1)
{
list.Add(cookie);
}
else
{
list[pos] = cookie;
}
}
internal void Sort()
{
if (list.Count > 0)
{
list.Sort(Comparer);
}
}
int SearchCookie(Cookie cookie)
{
string name = cookie.Name;
string domain = cookie.Domain;
string path = cookie.Path;
for (int i = list.Count - 1; i >= 0; i--)
{
Cookie c = list[i];
if (c.Version != cookie.Version)
{
continue;
}
if (0 != String.Compare(domain, c.Domain, true, CultureInfo.InvariantCulture))
{
continue;
}
if (0 != String.Compare(name, c.Name, true, CultureInfo.InvariantCulture))
{
continue;
}
if (0 != String.Compare(path, c.Path, true, CultureInfo.InvariantCulture))
{
continue;
}
return i;
}
return -1;
}
public void Add(CookieCollection cookies)
{
if (cookies == null)
{
throw new ArgumentNullException("cookies");
}
foreach (Cookie c in cookies)
{
Add(c);
}
}
public Cookie this[int index]
{
get
{
if (index < 0 || index >= list.Count)
{
throw new ArgumentOutOfRangeException("index");
}
return list[index];
}
}
public Cookie this[string name]
{
get
{
foreach (Cookie c in list)
{
if (0 == String.Compare(c.Name, name, true, CultureInfo.InvariantCulture))
{
return c;
}
}
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Diagnostics.Tests
{
public partial class ProcessTests : ProcessTestBase
{
private class FinalizingProcess : Process
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingProcess();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestBasePriorityOnWindows()
{
CreateDefaultProcess();
ProcessPriorityClass originalPriority = _process.PriorityClass;
var expected = PlatformDetection.IsWindowsNanoServer ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Normal; // For some reason we're BelowNormal initially on Nano
Assert.Equal(expected, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestExitTime()
{
// ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so
// we subtract ms from the begin time to account for it.
DateTime timeBeforeProcessStart = DateTime.UtcNow.AddMilliseconds(-25);
Process p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart,
$@"TestExitTime is incorrect. " +
$@"TimeBeforeStart {timeBeforeProcessStart} Ticks={timeBeforeProcessStart.Ticks}, " +
$@"ExitTime={p.ExitTime}, Ticks={p.ExitTime.Ticks}, " +
$@"ExitTimeUniversal {p.ExitTime.ToUniversalTime()} Ticks={p.ExitTime.ToUniversalTime().Ticks}, " +
$@"NowUniversal {DateTime.Now.ToUniversalTime()} Ticks={DateTime.Now.Ticks}");
}
[Fact]
public void StartTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StartTime);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestId()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunnerName).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestHasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void HasExited_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HasExited);
}
[Fact]
public void Kill_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Kill());
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestMachineName()
{
CreateDefaultProcess();
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact]
public void MachineName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MachineName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestMainModuleOnNonOSX()
{
Process p = Process.GetCurrentProcess();
Assert.True(p.Modules.Count > 0);
Assert.Equal(HostRunnerName, p.MainModule.ModuleName);
Assert.EndsWith(HostRunnerName, p.MainModule.FileName);
Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", HostRunnerName), p.MainModule.ToString());
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestMaxWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MaxWorkingSet is not supported on OSX.
public void MaxWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MaxWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MaxValueWorkingSet_GetSetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet);
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet = (IntPtr)1);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestMinWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MinWorkingSet is not supported on OSX.
public void MinWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MinWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MinWorkingSet_GetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MinWorkingSet);
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr baseAddr = pModule.BaseAddress;
IntPtr entryAddr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestNonpagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void NonpagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void PagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void PagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPeakPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void PeakPagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPeakVirtualMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void PeakVirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPeakWorkingSet64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void PeakWorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPrivateMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void PrivateMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestVirtualMemorySize64()
{
CreateDefaultProcess();
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void VirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestWorkingSet64()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
Assert.True(_process.WorkingSet64 >= 0);
return;
}
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void WorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WorkingSet64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestProcessorTime()
{
CreateDefaultProcess();
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact]
public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.UserProcessorTime);
}
[Fact]
public void PriviledgedProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivilegedProcessorTime);
}
[Fact]
public void TotalProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.TotalProcessorTime);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestProcessStartTime()
{
TimeSpan allowedWindow = TimeSpan.FromSeconds(3);
DateTime testStartTime = DateTime.UtcNow;
using (var remote = RemoteInvoke(() => { Console.Write(Process.GetCurrentProcess().StartTime.ToUniversalTime()); return SuccessExitCode; },
new RemoteInvokeOptions { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } }))
{
Assert.Equal(remote.Process.StartTime, remote.Process.StartTime);
DateTime remoteStartTime = DateTime.Parse(remote.Process.StandardOutput.ReadToEnd());
DateTime curTime = DateTime.UtcNow;
Assert.InRange(remoteStartTime, testStartTime - allowedWindow, curTime + allowedWindow);
}
}
[Fact]
public void ExitTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ExitTime);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
CreateDefaultProcess();
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPriorityBoostEnabled()
{
CreateDefaultProcess();
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // PriorityBoostEnabled is a no-op on Unix.
public void PriorityBoostEnabled_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled);
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled = true);
}
[Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPriorityClassWindows()
{
CreateDefaultProcess();
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Theory]
[InlineData((ProcessPriorityClass)0)]
[InlineData(ProcessPriorityClass.Normal | ProcessPriorityClass.Idle)]
public void TestInvalidPriorityClass(ProcessPriorityClass priorityClass)
{
var process = new Process();
Assert.Throws<InvalidEnumArgumentException>(() => process.PriorityClass = priorityClass);
}
[Fact]
public void PriorityClass_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityClass);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestProcessName()
{
CreateDefaultProcess();
// Processes are not hosted by dotnet in the full .NET Framework.
string expected = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : HostRunner;
Assert.Equal(Path.GetFileNameWithoutExtension(_process.ProcessName), Path.GetFileNameWithoutExtension(expected), StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void ProcessName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ProcessName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestSafeHandle()
{
CreateDefaultProcess();
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void SafeHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SafeHandle);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestSessionId()
{
CreateDefaultProcess();
uint sessionId;
#if TargetsWindows
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
#else
sessionId = (uint)Interop.getsid(_process.Id);
#endif
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void SessionId_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId =
#if TargetsWindows
Interop.GetCurrentProcessId();
#else
Interop.getpid();
#endif
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestGetProcessById()
{
CreateDefaultProcess();
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void GetProcesseses_NullMachineName_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcesses(null));
}
[Fact]
public void GetProcesses_EmptyMachineName_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcesses(""));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void GetProcessesByName_ProcessName_ReturnsExpected()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(".", process.MachineName));
}
public static IEnumerable<object[]> MachineName_TestData()
{
string currentProcessName = Process.GetCurrentProcess().MachineName;
yield return new object[] { currentProcessName };
yield return new object[] { "." };
yield return new object[] { Dns.GetHostName() };
}
public static IEnumerable<object[]> MachineName_Remote_TestData()
{
yield return new object[] { Guid.NewGuid().ToString("N") };
yield return new object[] { "\\" + Guid.NewGuid().ToString("N") };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
[MemberData(nameof(MachineName_TestData))]
public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName, machineName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(machineName, process.MachineName));
}
[MemberData(nameof(MachineName_Remote_TestData))]
[PlatformSpecific(TestPlatforms.Windows)] // Accessing processes on remote machines is only supported on Windows.
public void GetProcessesByName_RemoteMachineNameWindows_ReturnsExpected(string machineName)
{
try
{
GetProcessesByName_ProcessNameMachineName_ReturnsExpected(machineName);
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void GetProcessesByName_NoSuchProcess_ReturnsEmpty()
{
string processName = Guid.NewGuid().ToString("N");
Assert.Empty(Process.GetProcessesByName(processName));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcessesByName(currentProcess.ProcessName, null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcessesByName(currentProcess.ProcessName, ""));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix
[ActiveIssue("https://github.com/dotnet/corefx/issues/18212", TargetFrameworkMonikers.UapAot)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestProcessOnRemoteMachineWindows()
{
Process currentProccess = Process.GetCurrentProcess();
void TestRemoteProccess(Process remoteProcess)
{
Assert.Equal(currentProccess.Id, remoteProcess.Id);
Assert.Equal(currentProccess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProccess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
try
{
TestRemoteProccess(Process.GetProcessById(currentProccess.Id, "127.0.0.1"));
TestRemoteProccess(Process.GetProcessesByName(currentProccess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProccess.Id).Single());
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void StartInfo_GetFileName_ReturnsExpected()
{
Process process = CreateProcessLong();
process.Start();
// Processes are not hosted by dotnet in the full .NET Framework.
string expectedFileName = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : HostRunner;
Assert.Equal(expectedFileName, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void StartInfo_SetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = CreateProcessLong();
process.Start();
// .NET Core fixes a bug where Process.StartInfo for a unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
var startInfo = new ProcessStartInfo();
process.StartInfo = startInfo;
Assert.Equal(startInfo, process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo = new ProcessStartInfo());
}
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetGet_ReturnsExpected()
{
var process = new Process() { StartInfo = new ProcessStartInfo(TestConsoleApp) };
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
[Fact]
public void StartInfo_SetNull_ThrowsArgumentNullException()
{
var process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
[Fact]
public void StartInfo_GetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = Process.GetCurrentProcess();
// .NET Core fixes a bug where Process.StartInfo for an unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo);
}
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
[InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")]
[InlineData(@"\ \\ \\\", @"\,\\,\\\")]
[InlineData(@"a\\\""b c d", @"a\""b,c,d")]
[InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")]
[InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")]
[InlineData(@"a b c""def", @"a,b,cdef")]
[InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")]
[InlineData("\"\" b \"\"", ",b,")]
[InlineData("\"\"\"\" b c", "\",b,c")]
[InlineData("c\"\"\"\" b \"\"\\", "c\",b,\\")]
[InlineData("\"\"c \"\"b\"\" d\"\\", "c,b,d\\")]
[InlineData("\"\"a\"\" b d", "a,b,d")]
[InlineData("b d \"\"a\"\" ", "b,d,a")]
[InlineData("\\\"\\\"a\\\"\\\" b d", "\"\"a\"\",b,d")]
[InlineData("b d \\\"\\\"a\\\"\\\"", "b,d,\"\"a\"\"")]
public void TestArgumentParsing(string inputArguments, string expectedArgv)
{
var options = new RemoteInvokeOptions
{
Start = true,
StartInfo = new ProcessStartInfo { RedirectStandardOutput = true }
};
using (RemoteInvokeHandle handle = RemoteInvokeRaw((Func<string, string, string, int>)ConcatThreeArguments, inputArguments, options))
{
Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd());
}
}
[Fact]
public void StandardInput_GetNotRedirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StandardInput);
}
private static int ConcatThreeArguments(string one, string two, string three)
{
Console.Write(string.Join(",", one, two, three));
return SuccessExitCode;
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
[Fact]
public void CanBeFinalized()
{
FinalizingProcess.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingProcess.WasFinalized);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestStartWithMissingFile(bool fullPath)
{
string path = Guid.NewGuid().ToString("N");
if (fullPath)
{
path = Path.GetFullPath(path);
Assert.True(Path.IsPathRooted(path));
}
else
{
Assert.False(Path.IsPathRooted(path));
}
Assert.False(File.Exists(path));
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[Fact]
public void Start_NullStartInfo_ThrowsArgumentNullExceptionException()
{
AssertExtensions.Throws<ArgumentNullException>("startInfo", () => Process.Start((ProcessStartInfo)null));
}
[Fact]
public void Start_EmptyFileName_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardOutputEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardOutput = false,
StandardOutputEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardErrorEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardError = false,
StandardErrorEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_Disposed_ThrowsObjectDisposedException()
{
var process = new Process();
process.StartInfo.FileName = "Nothing";
process.Dispose();
Assert.Throws<ObjectDisposedException>(() => process.Start());
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
public void TestHandleCount()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.HandleCount > 0);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Expected process HandleCounts differs on OSX
public void TestHandleCount_OSX()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.Equal(0, p.HandleCount);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Handle count change is not reliable, but seems less robust on NETFX")]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void HandleCountChanges()
{
RemoteInvoke(() =>
{
Process p = Process.GetCurrentProcess();
int handleCount = p.HandleCount;
using (var fs1 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs2 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs3 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
{
p.Refresh();
int secondHandleCount = p.HandleCount;
Assert.True(handleCount < secondHandleCount);
handleCount = secondHandleCount;
}
p.Refresh();
int thirdHandleCount = p.HandleCount;
Assert.True(thirdHandleCount < handleCount);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void HandleCount_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HandleCount);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_NoWindow_ReturnsEmptyHandle()
{
CreateDefaultProcess();
Assert.Equal(IntPtr.Zero, _process.MainWindowHandle);
Assert.Equal(_process.MainWindowHandle, _process.MainWindowHandle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void MainWindowTitle_NoWindow_ReturnsEmpty()
{
CreateDefaultProcess();
Assert.Empty(_process.MainWindowTitle);
Assert.Same(_process.MainWindowTitle, _process.MainWindowTitle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowTitle is a no-op and always returns string.Empty on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void MainWindowTitle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowTitle);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void CloseMainWindow_NoWindow_ReturnsFalse()
{
CreateDefaultProcess();
Assert.False(_process.CloseMainWindow());
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // CloseMainWindow is a no-op and always returns false on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "CloseMainWindow returns false on UAP")]
public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.CloseMainWindow());
}
[PlatformSpecific(TestPlatforms.Windows)] // Needs to get the process Id from OS
[Fact]
public void TestRespondingWindows()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Responding always returns true on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void Responding_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Responding);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestNonpagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void NonpagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPeakPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakPagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPeakVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakVirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPeakWorkingSet()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
public void PeakWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestPrivateMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PrivateMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
Assert.Equal(unchecked((int)_process.VirtualMemorySize64), _process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void VirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void TestWorkingSet()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
#pragma warning disable 0618
Assert.True(_process.WorkingSet >= 0);
#pragma warning restore 0618
return;
}
#pragma warning disable 0618
Assert.True(_process.WorkingSet > 0);
#pragma warning restore 0618
}
[Fact]
public void WorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.WorkingSet);
#pragma warning restore 0618
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartInvalidNamesTest()
{
Assert.Throws<InvalidOperationException>(() => Process.Start(null, "userName", new SecureString(), "thisDomain"));
Assert.Throws<InvalidOperationException>(() => Process.Start(string.Empty, "userName", new SecureString(), "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start("exe", string.Empty, new SecureString(), "thisDomain"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void Process_StartWithInvalidUserNamePassword()
{
SecureString password = AsSecureString("Value");
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), "userName", password, "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), Environment.UserName, password, Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void Process_StartTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = "thisDomain";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, userName, password, domain); // This writes junk to the Console but with this overload, we can't prevent that.
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
Assert.True(p.WaitForExit(WaitInMS));
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not supported on UAP")]
public void Process_StartWithArgumentsTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = Environment.UserDomainName;
string arguments = "-xml testResults.xml";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, arguments, userName, password, domain);
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(arguments, p.StartInfo.Arguments);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
p.Kill();
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithDuplicatePassword()
{
var startInfo = new ProcessStartInfo()
{
FileName = "exe",
UserName = "dummyUser",
PasswordInClearText = "Value",
Password = AsSecureString("Value"),
UseShellExecute = false
};
var process = new Process() { StartInfo = startInfo };
AssertExtensions.Throws<ArgumentException>(null, () => process.Start());
}
private string GetCurrentProcessName()
{
return $"{Process.GetCurrentProcess().ProcessName}.exe";
}
private SecureString AsSecureString(string str)
{
SecureString secureString = new SecureString();
foreach (var ch in str)
{
secureString.AppendChar(ch);
}
return secureString;
}
}
}
| |
// 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!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedTargetInstancesClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListTargetInstancesRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
AggregatedListTargetInstancesRequest request = new AggregatedListTargetInstancesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, TargetInstancesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetInstanceAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListTargetInstancesRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
AggregatedListTargetInstancesRequest request = new AggregatedListTargetInstancesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, TargetInstancesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetInstanceAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, TargetInstancesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetInstanceAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, TargetInstancesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetInstanceAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteTargetInstanceRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
DeleteTargetInstanceRequest request = new DeleteTargetInstanceRequest
{
Zone = "",
RequestId = "",
Project = "",
TargetInstance = "",
};
// Make the request
lro::Operation<Operation, Operation> response = targetInstancesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetInstancesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteTargetInstanceRequest, CallSettings)
// Additional: DeleteAsync(DeleteTargetInstanceRequest, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
DeleteTargetInstanceRequest request = new DeleteTargetInstanceRequest
{
Zone = "",
RequestId = "",
Project = "",
TargetInstance = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await targetInstancesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetInstancesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, string, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
string zone = "";
string targetInstance = "";
// Make the request
lro::Operation<Operation, Operation> response = targetInstancesClient.Delete(project, zone, targetInstance);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetInstancesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, string, CallSettings)
// Additional: DeleteAsync(string, string, string, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string zone = "";
string targetInstance = "";
// Make the request
lro::Operation<Operation, Operation> response = await targetInstancesClient.DeleteAsync(project, zone, targetInstance);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetInstancesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetTargetInstanceRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
GetTargetInstanceRequest request = new GetTargetInstanceRequest
{
Zone = "",
Project = "",
TargetInstance = "",
};
// Make the request
TargetInstance response = targetInstancesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetTargetInstanceRequest, CallSettings)
// Additional: GetAsync(GetTargetInstanceRequest, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
GetTargetInstanceRequest request = new GetTargetInstanceRequest
{
Zone = "",
Project = "",
TargetInstance = "",
};
// Make the request
TargetInstance response = await targetInstancesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, string, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
string zone = "";
string targetInstance = "";
// Make the request
TargetInstance response = targetInstancesClient.Get(project, zone, targetInstance);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, string, CallSettings)
// Additional: GetAsync(string, string, string, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string zone = "";
string targetInstance = "";
// Make the request
TargetInstance response = await targetInstancesClient.GetAsync(project, zone, targetInstance);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertTargetInstanceRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
InsertTargetInstanceRequest request = new InsertTargetInstanceRequest
{
Zone = "",
RequestId = "",
Project = "",
TargetInstanceResource = new TargetInstance(),
};
// Make the request
lro::Operation<Operation, Operation> response = targetInstancesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetInstancesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertTargetInstanceRequest, CallSettings)
// Additional: InsertAsync(InsertTargetInstanceRequest, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
InsertTargetInstanceRequest request = new InsertTargetInstanceRequest
{
Zone = "",
RequestId = "",
Project = "",
TargetInstanceResource = new TargetInstance(),
};
// Make the request
lro::Operation<Operation, Operation> response = await targetInstancesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetInstancesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, string, TargetInstance, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
string zone = "";
TargetInstance targetInstanceResource = new TargetInstance();
// Make the request
lro::Operation<Operation, Operation> response = targetInstancesClient.Insert(project, zone, targetInstanceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetInstancesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, string, TargetInstance, CallSettings)
// Additional: InsertAsync(string, string, TargetInstance, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string zone = "";
TargetInstance targetInstanceResource = new TargetInstance();
// Make the request
lro::Operation<Operation, Operation> response = await targetInstancesClient.InsertAsync(project, zone, targetInstanceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetInstancesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListTargetInstancesRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
ListTargetInstancesRequest request = new ListTargetInstancesRequest
{
Zone = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<TargetInstanceList, TargetInstance> response = targetInstancesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TargetInstance item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetInstanceList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetInstance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetInstance> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetInstance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListTargetInstancesRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
ListTargetInstancesRequest request = new ListTargetInstancesRequest
{
Zone = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<TargetInstanceList, TargetInstance> response = targetInstancesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TargetInstance item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetInstanceList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetInstance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetInstance> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetInstance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, string, int?, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
string zone = "";
// Make the request
PagedEnumerable<TargetInstanceList, TargetInstance> response = targetInstancesClient.List(project, zone);
// Iterate over all response items, lazily performing RPCs as required
foreach (TargetInstance item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetInstanceList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetInstance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetInstance> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetInstance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, string, int?, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string zone = "";
// Make the request
PagedAsyncEnumerable<TargetInstanceList, TargetInstance> response = targetInstancesClient.ListAsync(project, zone);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TargetInstance item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetInstanceList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetInstance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetInstance> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetInstance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Editor;
using Microsoft.Internal.VisualStudio.Shell;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.NavigationBar
{
internal class NavigationBarClient :
IVsDropdownBarClient,
IVsDropdownBarClient3,
IVsDropdownBarClientEx,
IVsCoTaskMemFreeMyStrings,
INavigationBarPresenter,
IVsCodeWindowEvents
{
private readonly IVsDropdownBarManager _manager;
private readonly IVsCodeWindow _codeWindow;
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly IComEventSink _codeWindowEventsSink;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IntPtr _imageList;
private readonly IVsImageService2 _imageService;
private readonly Dictionary<IVsTextView, ITextView> _trackedTextViews = new Dictionary<IVsTextView, ITextView>();
private IVsDropdownBar _dropdownBar;
private IList<NavigationBarProjectItem> _projectItems;
private IList<NavigationBarItem> _currentTypeItems;
public NavigationBarClient(
IVsDropdownBarManager manager,
IVsCodeWindow codeWindow,
IServiceProvider serviceProvider,
VisualStudioWorkspaceImpl workspace)
{
_manager = manager;
_codeWindow = codeWindow;
_workspace = workspace;
_imageService = (IVsImageService2)serviceProvider.GetService(typeof(SVsImageService));
_projectItems = SpecializedCollections.EmptyList<NavigationBarProjectItem>();
_currentTypeItems = SpecializedCollections.EmptyList<NavigationBarItem>();
var vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;
if (vsShell != null)
{
object varImageList;
int hresult = vsShell.GetProperty((int)__VSSPROPID.VSSPROPID_ObjectMgrTypesImgList, out varImageList);
if (ErrorHandler.Succeeded(hresult) && varImageList != null)
{
_imageList = (IntPtr)(int)varImageList;
}
}
_codeWindowEventsSink = ComEventSink.Advise<IVsCodeWindowEvents>(codeWindow, this);
_editorAdaptersFactoryService = serviceProvider.GetMefService<IVsEditorAdaptersFactoryService>();
IVsTextView pTextView;
codeWindow.GetPrimaryView(out pTextView);
StartTrackingView(pTextView);
pTextView = null;
codeWindow.GetSecondaryView(out pTextView);
StartTrackingView(pTextView);
}
private void StartTrackingView(IVsTextView pTextView)
{
if (pTextView != null)
{
var wpfTextView = _editorAdaptersFactoryService.GetWpfTextView(pTextView);
if (wpfTextView != null)
{
_trackedTextViews.Add(pTextView, wpfTextView);
wpfTextView.Caret.PositionChanged += OnCaretPositionChanged;
wpfTextView.GotAggregateFocus += OnViewGotAggregateFocus;
}
}
}
private NavigationBarItem GetCurrentTypeItem()
{
int currentTypeIndex;
_dropdownBar.GetCurrentSelection(1, out currentTypeIndex);
return currentTypeIndex >= 0
? _currentTypeItems[currentTypeIndex]
: null;
}
private NavigationBarItem GetItem(int combo, int index)
{
switch (combo)
{
case 0:
return _projectItems[index];
case 1:
return _currentTypeItems[index];
case 2:
return GetCurrentTypeItem().ChildItems[index];
default:
throw new ArgumentException();
}
}
int IVsDropdownBarClient.GetComboAttributes(int iCombo, out uint pcEntries, out uint puEntryType, out IntPtr phImageList)
{
puEntryType = (uint)(DROPDOWNENTRYTYPE.ENTRY_TEXT | DROPDOWNENTRYTYPE.ENTRY_ATTR | DROPDOWNENTRYTYPE.ENTRY_IMAGE);
phImageList = _imageList;
switch (iCombo)
{
case 0:
pcEntries = (uint)_projectItems.Count;
break;
case 1:
pcEntries = (uint)_currentTypeItems.Count;
break;
case 2:
var currentTypeItem = GetCurrentTypeItem();
pcEntries = currentTypeItem != null
? (uint)currentTypeItem.ChildItems.Count
: 0;
break;
default:
pcEntries = 0;
return VSConstants.E_INVALIDARG;
}
return VSConstants.S_OK;
}
int IVsDropdownBarClient.GetComboTipText(int iCombo, out string pbstrText)
{
int selectionIndex;
var selectedItemPreviewText = string.Empty;
if (_dropdownBar.GetCurrentSelection(iCombo, out selectionIndex) == VSConstants.S_OK && selectionIndex >= 0)
{
selectedItemPreviewText = GetItem(iCombo, selectionIndex).Text;
}
switch (iCombo)
{
case 0:
var keybindingString = KeyBindingHelper.GetGlobalKeyBinding(VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.MoveToDropdownBar);
if (!string.IsNullOrWhiteSpace(keybindingString))
{
pbstrText = string.Format(ServicesVSResources.Project_colon_0_1_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to, selectedItemPreviewText, keybindingString);
}
else
{
pbstrText = string.Format(ServicesVSResources.Project_colon_0_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to, selectedItemPreviewText);
}
return VSConstants.S_OK;
case 1:
case 2:
pbstrText = string.Format(ServicesVSResources._0_Use_the_dropdown_to_view_and_navigate_to_other_items_in_this_file, selectedItemPreviewText);
return VSConstants.S_OK;
default:
pbstrText = null;
return VSConstants.E_INVALIDARG;
}
}
int IVsDropdownBarClient.GetEntryAttributes(int iCombo, int iIndex, out uint pAttr)
{
DROPDOWNFONTATTR attributes = DROPDOWNFONTATTR.FONTATTR_PLAIN;
var item = GetItem(iCombo, iIndex);
if (item.Grayed)
{
attributes |= DROPDOWNFONTATTR.FONTATTR_GRAY;
}
if (item.Bolded)
{
attributes |= DROPDOWNFONTATTR.FONTATTR_BOLD;
}
pAttr = (uint)attributes;
return VSConstants.S_OK;
}
int IVsDropdownBarClient.GetEntryImage(int iCombo, int iIndex, out int piImageIndex)
{
var item = GetItem(iCombo, iIndex);
piImageIndex = item.Glyph.GetGlyphIndex();
return VSConstants.S_OK;
}
int IVsDropdownBarClient.GetEntryText(int iCombo, int iIndex, out string ppszText)
{
ppszText = GetItem(iCombo, iIndex).Text;
return VSConstants.S_OK;
}
int IVsDropdownBarClient.OnComboGetFocus(int iCombo)
{
DropDownFocused?.Invoke(this, EventArgs.Empty);
return VSConstants.S_OK;
}
int IVsDropdownBarClient.OnItemChosen(int iCombo, int iIndex)
{
int selection;
// If we chose an item for the type drop-down, then refresh the member dropdown
if (iCombo == (int)NavigationBarDropdownKind.Type)
{
_dropdownBar.GetCurrentSelection((int)NavigationBarDropdownKind.Member, out selection);
_dropdownBar.RefreshCombo((int)NavigationBarDropdownKind.Member, selection);
}
_dropdownBar.GetCurrentSelection(iCombo, out selection);
if (selection >= 0)
{
var item = GetItem(iCombo, selection);
ItemSelected?.Invoke(this, new NavigationBarItemSelectedEventArgs(item));
}
return VSConstants.S_OK;
}
int IVsDropdownBarClient.OnItemSelected(int iCombo, int iIndex)
{
return VSConstants.S_OK;
}
int IVsDropdownBarClient.SetDropdownBar(IVsDropdownBar pDropdownBar)
{
_dropdownBar = pDropdownBar;
return VSConstants.S_OK;
}
int IVsDropdownBarClient3.GetComboWidth(int iCombo, out int piWidthPercent)
{
piWidthPercent = 100;
return VSConstants.S_OK;
}
int IVsDropdownBarClient3.GetAutomationProperties(int iCombo, out string pbstrName, out string pbstrId)
{
switch (iCombo)
{
case 0:
pbstrName = NavigationBarAutomationStrings.ProjectDropdownName;
pbstrId = NavigationBarAutomationStrings.ProjectDropdownId;
return VSConstants.S_OK;
case 1:
pbstrName = NavigationBarAutomationStrings.TypeDropdownName;
pbstrId = NavigationBarAutomationStrings.TypeDropdownId;
return VSConstants.S_OK;
case 2:
pbstrName = NavigationBarAutomationStrings.MemberDropdownName;
pbstrId = NavigationBarAutomationStrings.MemberDropdownId;
return VSConstants.S_OK;
default:
pbstrName = null;
pbstrId = null;
return VSConstants.E_INVALIDARG;
}
}
int IVsDropdownBarClient3.GetEntryImage(int iCombo, int iIndex, out int piImageIndex, out IntPtr phImageList)
{
var item = GetItem(iCombo, iIndex);
// If this is a project item, try to get the actual proper image from the VSHierarchy it
// represents. That way the icon will always look right no matter which type of project
// it is. For example, if phone/Windows projects have different icons, then this can
// ensure we get the right icon, and not just a hardcoded C#/VB icon.
if (item is NavigationBarProjectItem)
{
var projectItem = (NavigationBarProjectItem)item;
if (_workspace.TryGetImageListAndIndex(_imageService, projectItem.DocumentId.ProjectId, out phImageList, out piImageIndex))
{
return VSConstants.S_OK;
}
}
piImageIndex = GetItem(iCombo, iIndex).Glyph.GetGlyphIndex();
phImageList = _imageList;
return VSConstants.S_OK;
}
int IVsDropdownBarClientEx.GetEntryIndent(int iCombo, int iIndex, out uint pIndent)
{
pIndent = (uint)GetItem(iCombo, iIndex).Indent;
return VSConstants.S_OK;
}
void INavigationBarPresenter.Disconnect()
{
_manager.RemoveDropdownBar();
_codeWindowEventsSink.Unadvise();
foreach (var view in _trackedTextViews.Values)
{
view.Caret.PositionChanged -= OnCaretPositionChanged;
view.GotAggregateFocus -= OnViewGotAggregateFocus;
}
_trackedTextViews.Clear();
}
void INavigationBarPresenter.PresentItems(
IList<NavigationBarProjectItem> projects,
NavigationBarProjectItem selectedProject,
IList<NavigationBarItem> types,
NavigationBarItem selectedType,
NavigationBarItem selectedMember)
{
_projectItems = projects;
_currentTypeItems = types;
// It's possible we're presenting items before the dropdown bar has been initialized.
if (_dropdownBar == null)
{
return;
}
var projectIndex = selectedProject != null ? _projectItems.IndexOf(selectedProject) : -1;
var typeIndex = selectedType != null ? _currentTypeItems.IndexOf(selectedType) : -1;
var memberIndex = selectedType != null && selectedMember != null ? selectedType.ChildItems.IndexOf(selectedMember) : -1;
_dropdownBar.RefreshCombo((int)NavigationBarDropdownKind.Project, projectIndex);
_dropdownBar.RefreshCombo((int)NavigationBarDropdownKind.Type, typeIndex);
_dropdownBar.RefreshCombo((int)NavigationBarDropdownKind.Member, memberIndex);
}
public event EventHandler DropDownFocused;
public event EventHandler<NavigationBarItemSelectedEventArgs> ItemSelected;
public event EventHandler<EventArgs> ViewFocused;
public event EventHandler<CaretPositionChangedEventArgs> CaretMoved;
int IVsCodeWindowEvents.OnCloseView(IVsTextView pView)
{
ITextView view;
if (_trackedTextViews.TryGetValue(pView, out view))
{
view.Caret.PositionChanged -= OnCaretPositionChanged;
view.GotAggregateFocus -= OnViewGotAggregateFocus;
_trackedTextViews.Remove(pView);
}
return VSConstants.S_OK;
}
int IVsCodeWindowEvents.OnNewView(IVsTextView pView)
{
if (!_trackedTextViews.ContainsKey(pView))
{
var wpfTextView = _editorAdaptersFactoryService.GetWpfTextView(pView);
wpfTextView.Caret.PositionChanged += OnCaretPositionChanged;
wpfTextView.GotAggregateFocus += OnViewGotAggregateFocus;
_trackedTextViews.Add(pView, wpfTextView);
}
return VSConstants.S_OK;
}
private void OnCaretPositionChanged(object sender, CaretPositionChangedEventArgs e)
{
CaretMoved?.Invoke(this, e);
}
private void OnViewGotAggregateFocus(object sender, EventArgs e)
{
ViewFocused?.Invoke(this, e);
}
ITextView INavigationBarPresenter.TryGetCurrentView()
{
IVsTextView lastActiveView;
_codeWindow.GetLastActiveView(out lastActiveView);
return _editorAdaptersFactoryService.GetWpfTextView(lastActiveView);
}
}
}
| |
using System;
using System.Collections;
using System.Reflection;
namespace jGrid.Helpers
{
#region Class StringEnum
/// <summary>
/// Helper class for working with 'extended' enums using <see cref="StringValueAttribute"/> attributes.
/// http://www.codeproject.com/KB/cs/stringenum.aspx
/// </summary>
public class StringEnum
{
#region Instance implementation
private Type _enumType;
private static Hashtable _stringValues = new Hashtable();
/// <summary>
/// Creates a new <see cref="StringEnum"/> instance.
/// </summary>
/// <param name="enumType">Enum type.</param>
public StringEnum(Type enumType)
{
if (!enumType.IsEnum)
throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", enumType.ToString()));
_enumType = enumType;
}
/// <summary>
/// Gets the string value associated with the given enum value.
/// </summary>
/// <param name="valueName">Name of the enum value.</param>
/// <returns>String Value</returns>
public string GetStringValue(string valueName)
{
Enum enumType;
string stringValue = null;
try
{
enumType = (Enum) Enum.Parse(_enumType, valueName);
stringValue = GetStringValue(enumType);
}
catch (Exception) { }//Swallow!
return stringValue;
}
/// <summary>
/// Gets the string values associated with the enum.
/// </summary>
/// <returns>String value array</returns>
public Array GetStringValues()
{
ArrayList values = new ArrayList();
//Look for our string value associated with fields in this enum
foreach (FieldInfo fi in _enumType.GetFields())
{
//Check for our custom attribute
StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs.Length > 0)
values.Add(attrs[0].Value);
}
return values.ToArray();
}
/// <summary>
/// Gets the values as a 'bindable' list datasource.
/// </summary>
/// <returns>IList for data binding</returns>
public IList GetListValues()
{
Type underlyingType = Enum.GetUnderlyingType(_enumType);
ArrayList values = new ArrayList();
//Look for our string value associated with fields in this enum
foreach (FieldInfo fi in _enumType.GetFields())
{
//Check for our custom attribute
StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs.Length > 0)
values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));
}
return values;
}
/// <summary>
/// Return the existence of the given string value within the enum.
/// </summary>
/// <param name="stringValue">String value.</param>
/// <returns>Existence of the string value</returns>
public bool IsStringDefined(string stringValue)
{
return Parse(_enumType, stringValue) != null;
}
/// <summary>
/// Return the existence of the given string value within the enum.
/// </summary>
/// <param name="stringValue">String value.</param>
/// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
/// <returns>Existence of the string value</returns>
public bool IsStringDefined(string stringValue, bool ignoreCase)
{
return Parse(_enumType, stringValue, ignoreCase) != null;
}
/// <summary>
/// Gets the underlying enum type for this instance.
/// </summary>
/// <value></value>
public Type EnumType
{
get { return _enumType; }
}
#endregion
#region Static implementation
/// <summary>
/// Gets a string value for a particular enum value.
/// </summary>
/// <param name="value">Value.</param>
/// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns>
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
if (_stringValues.ContainsKey(value))
output = (_stringValues[value] as StringValueAttribute).Value;
else
{
//Look for our 'StringValueAttribute' in the field's custom attributes
FieldInfo fi = type.GetField(value.ToString());
StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs.Length > 0)
{
_stringValues.Add(value, attrs[0]);
output = attrs[0].Value;
}
}
return output;
}
/// <summary>
/// Parses the supplied enum and string value to find an associated enum value (case sensitive).
/// </summary>
/// <param name="type">Type.</param>
/// <param name="stringValue">String value.</param>
/// <returns>Enum value associated with the string value, or null if not found.</returns>
public static object Parse(Type type, string stringValue)
{
return Parse(type, stringValue, false);
}
/// <summary>
/// Parses the supplied enum and string value to find an associated enum value.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="stringValue">String value.</param>
/// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
/// <returns>Enum value associated with the string value, or null if not found.</returns>
public static object Parse(Type type, string stringValue, bool ignoreCase)
{
object output = null;
string enumStringValue = null;
if (!type.IsEnum)
throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", type.ToString()));
//Look for our string value associated with fields in this enum
foreach (FieldInfo fi in type.GetFields())
{
//Check for our custom attribute
StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs.Length > 0)
enumStringValue = attrs[0].Value;
//Check for equality then select actual enum value.
if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
{
output = Enum.Parse(type, fi.Name);
break;
}
}
return output;
}
/// <summary>
/// Return the existence of the given string value within the enum.
/// </summary>
/// <param name="stringValue">String value.</param>
/// <param name="enumType">Type of enum</param>
/// <returns>Existence of the string value</returns>
public static bool IsStringDefined(Type enumType, string stringValue)
{
return Parse(enumType, stringValue) != null;
}
/// <summary>
/// Return the existence of the given string value within the enum.
/// </summary>
/// <param name="stringValue">String value.</param>
/// <param name="enumType">Type of enum</param>
/// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
/// <returns>Existence of the string value</returns>
public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)
{
return Parse(enumType, stringValue, ignoreCase) != null;
}
#endregion
}
#endregion
#region Class StringValueAttribute
/// <summary>
/// Simple attribute class for storing String Values
/// </summary>
public class StringValueAttribute : Attribute
{
private string _value;
/// <summary>
/// Creates a new <see cref="StringValueAttribute"/> instance.
/// </summary>
/// <param name="value">Value.</param>
public StringValueAttribute(string value)
{
_value = value;
}
/// <summary>
/// Gets the value.
/// </summary>
/// <value></value>
public string Value
{
get { return _value; }
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
//
// Visual Basic .NET Parser
//
// Copyright (C) 2005, Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
// MERCHANTIBILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
namespace VBConverter.CodeParser.Error
{
/// <summary>
/// A syntax error.
/// </summary>
public sealed class SyntaxError
{
static string[] ErrorMessages = null;
private readonly SyntaxErrorType _Type;
private readonly Span _Span;
/// <summary>
/// The type of the syntax error.
/// </summary>
public SyntaxErrorType Type {
get { return _Type; }
}
/// <summary>
/// The location of the syntax error.
/// </summary>
public Span Span {
get { return _Span; }
}
/// <summary>
/// Constructs a new syntax error.
/// </summary>
/// <param name="type">The type of the syntax error.</param>
/// <param name="span">The location of the syntax error.</param>
public SyntaxError(SyntaxErrorType type, Span span)
{
Debug.Assert(System.Enum.IsDefined(typeof(SyntaxErrorType), type));
_Type = type;
_Span = span;
}
public override string ToString()
{
int typeValue = (int)this.Type;
string description = GetErrorMessage(this.Type);
string message = string.Format("error {0} {1}: {2}", typeValue, Span.ToString(), description);
return message;
}
static SyntaxError()
{
BuildErrorMessages();
}
static public string GetErrorMessage(SyntaxErrorType type)
{
int index = (int)type;
string message = "Unknown error.";
if (index <= ErrorMessages.GetUpperBound(0))
message = ErrorMessages[index];
return message;
}
static private void BuildErrorMessages()
{
string[] Strings = new string[] {
"",
"Invalid escaped identifier.",
"Invalid identifier.",
"Cannot put a type character on a keyword.",
"Invalid character.",
"Invalid character literal.",
"Invalid string literal.",
"Invalid date literal.",
"Invalid floating point literal.",
"Invalid integer literal.",
"Invalid decimal literal.",
"Syntax error.",
"Expected ','.",
"Expected '('.",
"Expected ')'.",
"Expected '='.",
"Expected 'As'.",
"Expected '}'.",
"Expected '.'.",
"Expected '-'.",
"Expected 'Is'.",
"Expected '>'.",
"Type expected.",
"Expected identifier.",
"Invalid use of keyword.",
"Bounds can be specified only for the top-level array when initializing an array of arrays.",
"Array bounds cannot appear in type specifiers.",
"Expected expression.",
"Comma, ')', or a valid expression continuation expected.",
"Expected named argument.",
"MyBase must be followed by a '.'.",
"MyClass must be followed by a '.'.",
"Exit must be followed by Do, For, While, Select, Sub, Function, Property or Try.",
"Expected 'Next'.",
"Expected 'Resume' or 'GoTo'.",
"Expected 'Error'.",
"Type character does not match declared data type String.",
"Comma, '}', or a valid expression continuation expected.",
"Expected one of 'Dim', 'Const', 'Public', 'Private', 'Protected', 'Friend', 'Shadows', 'ReadOnly' or 'Shared'.",
"End of statement expected.",
"'Do' must end with a matching 'Loop'.",
"'While' must end with a matching 'End While'.",
"'Select' must end with a matching 'End Select'.",
"'SyncLock' must end with a matching 'End SyncLock'.",
"'With' must end with a matching 'End With'.",
"'If' must end with a matching 'End If'.",
"'Try' must end with a matching 'End Try'.",
"'Sub' must end with a matching 'End Sub'.",
"'Function' must end with a matching 'End Function'.",
"'Property' must end with a matching 'End Property'.",
"'Get' must end with a matching 'End Get'.",
"'Set' must end with a matching 'End Set'.",
"'Class' must end with a matching 'End Class'.",
"'Structure' must end with a matching 'End Structure'.",
"'Module' must end with a matching 'End Module'.",
"'Interface' must end with a matching 'End Interface'.",
"'Enum' must end with a matching 'End Enum'.",
"'Namespace' must end with a matching 'End Namespace'.",
"'Loop' cannot have a condition if matching 'Do' has one.",
"'Loop' must be preceded by a matching 'Do'.",
"'Next' must be preceded by a matching 'For' or 'For Each'.",
"'End While' must be preceded by a matching 'While'.",
"'End Select' must be preceded by a matching 'Select'.",
"'End SyncLock' must be preceded by a matching 'SyncLock'.",
"'End If' must be preceded by a matching 'If'.",
"'End Try' must be preceded by a matching 'Try'.",
"'End With' must be preceded by a matching 'With'.",
"'Catch' cannot appear outside a 'Try' statement.",
"'Finally' cannot appear outside a 'Try' statement.",
"'Catch' cannot appear after 'Finally' within a 'Try' statement.",
"'Finally' can only appear once in a 'Try' statement.",
"'Case' must be preceded by a matching 'Select'.",
"'Case' cannot appear after 'Case Else' within a 'Select' statement.",
"'Case Else' can only appear once in a 'Select' statement.",
"'Case Else' must be preceded by a matching 'Select'.",
"'End Sub' must be preceded by a matching 'Sub'.",
"'End Function' must be preceded by a matching 'Function'.",
"'End Property' must be preceded by a matching 'Property'.",
"'End Get' must be preceded by a matching 'Get'.",
"'End Set' must be preceded by a matching 'Set'.",
"'End Class' must be preceded by a matching 'Class'.",
"'End Structure' must be preceded by a matching 'Structure'.",
"'End Module' must be preceded by a matching 'Module'.",
"'End Interface' must be preceded by a matching 'Interface'.",
"'End Enum' must be preceded by a matching 'Enum'.",
"'End Namespace' must be preceded by a matching 'Namespace'.",
"Statements and labels are not valid between 'Select Case' and first 'Case'.",
"'ElseIf' cannot appear after 'Else' within an 'If' statement.",
"'ElseIf' must be preceded by a matching 'If'.",
"'Else' can only appear once in an 'If' statement.",
"'Else' must be preceded by a matching 'If'.",
"Statement cannot end a block outside of a line 'If' statement.",
"Attribute of this type is not allowed here.",
"Modifier cannot be specified twice.",
"Modifier is not valid on this declaration type.",
"Can only specify one of 'Dim', 'Static' or 'Const'.",
"Events cannot have a return type.",
"Comma or ')' expected.",
"Method declaration statements must be the first statement on a logical line.",
"First statement of a method body cannot be on the same line as the method declaration.",
"'End Sub' must be the first statement on a line.",
"'End Function' must be the first statement on a line.",
"'End Get' must be the first statement on a line.",
"'End Set' must be the first statement on a line.",
"'Sub' or 'Function' expected.",
"String constant expected.",
"'Lib' expected.",
"Declaration cannot appear within a Property declaration.",
"Declaration cannot appear within a Class declaration.",
"Declaration cannot appear within a Structure declaration.",
"Declaration cannot appear within a Module declaration.",
"Declaration cannot appear within an Interface declaration.",
"Declaration cannot appear within an Enum declaration.",
"Declaration cannot appear within a Namespace declaration.",
"Specifiers and attributes are not valid on this statement.",
"Specifiers and attributes are not valid on a Namespace declaration.",
"Specifiers and attributes are not valid on an Imports declaration.",
"Specifiers and attributes are not valid on an Option declaration.",
"Inherits' can only specify one class.",
"'Inherits' statements must precede all declarations.",
"'Implements' statements must follow any 'Inherits' statement and precede all declarations in a class.",
"Enum must contain at least one member.",
"'Option Explicit' can be followed only by 'On' or 'Off'.",
"'Option Strict' can be followed only by 'On' or 'Off'.",
"'Option Compare' must be followed by 'Text' or 'Binary'.",
"'Option' must be followed by 'Compare', 'Explicit', or 'Strict'.",
"'Option' statements must precede any declarations or 'Imports' statements.",
"'Imports' statements must precede any declarations.",
"Assembly or Module attribute statements must precede any declarations in a file.",
"'End' statement not valid.",
"Expected relational operator.",
"'If', 'ElseIf', 'Else', 'End If', or 'Const' expected.",
"Expected integer literal.",
"'#ExternalSource' statements cannot be nested.",
"'ExternalSource', 'Region' or 'If' expected.",
"'#End ExternalSource' must be preceded by a matching '#ExternalSource'.",
"'#ExternalSource' must end with a matching '#End ExternalSource'.",
"'#End Region' must be preceded by a matching '#Region'.",
"'#Region' must end with a matching '#End Region'.",
"'#Region' and '#End Region' statements are not valid within method bodies.",
"Conversions to and from 'String' cannot occur in a conditional compilation expression.",
"Conversion is not valid in a conditional compilation expression.",
"Expression is not valid in a conditional compilation expression.",
"Operator is not valid for these types in a conditional compilation expression.",
"'#If' must end with a matching '#End If'.",
"'#End If' must be preceded by a matching '#If'.",
"'#ElseIf' cannot appear after '#Else' within an '#If' statement.",
"'#ElseIf' must be preceded by a matching '#If'.",
"'#Else' can only appear once in an '#If' statement.",
"'#Else' must be preceded by a matching '#If'.",
"'Global' not allowed in this context; identifier expected.",
"Modules cannot be generic.",
"Expected 'Of'.",
"Operator declaration must be one of: +, -, *, \\, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.",
"'Operator' must end with a matching 'End Operator'.",
"'End Operator' must be preceded by a matching 'Operator'.",
"'End Operator' must be the first statement on a line.",
"Properties cannot be generic.",
"Constructors cannot be generic.",
"Operators cannot be generic.",
"Global must be followed by a '.'.",
"Continue must be followed by Do, For, or While.",
"'Using' must end with a matching 'End Using'.",
"Custom 'Event' must end with a matching 'End Event'.",
"'AddHandler' must end with a matching 'End AddHandler'.",
"'RemoveHandler' must end with a matching 'End RemoveHandler'.",
"'RaiseEvent' must end with a matching 'End RaiseEvent'.",
"'End Using' must be preceded by a matching 'Using'.",
"'End Event' must be preceded by a matching custom 'Event'.",
"'End AddHandler' must be preceded by a matching 'AddHandler'.",
"'End RemoveHandler' must be preceded by a matching 'RemoveHandler'.",
"'End RaiseEvent' must be preceded by a matching 'RaiseEvent'.",
"'End AddHandler' must be the first statement on a line.",
"'End RemoveHandler' must be the first statement on a line.",
"'End RaiseEvent' must be the first statement on a line.",
"Expected: Get or Let or Set.",
"Argument required for Property Let or Property Set",
"Statement invalid inside Type Block",
"Expected: 0 or 1",
"Only comments may appear End Sub, End Function, or End Property"
};
ErrorMessages = Strings;
}
}
}
| |
//
// WidgetBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt;
using System.Collections.Generic;
using System.Linq;
using Xwt.Drawing;
namespace Xwt.GtkBackend
{
public partial class WidgetBackend: IWidgetBackend, IGtkWidgetBackend
{
Gtk.Widget widget;
Widget frontend;
Gtk.EventBox eventBox;
IWidgetEventSink eventSink;
WidgetEvent enabledEvents;
bool destroyed;
SizeConstraint currentWidthConstraint = SizeConstraint.Unconstrained;
SizeConstraint currentHeightConstraint = SizeConstraint.Unconstrained;
bool minSizeSet;
class DragDropData
{
public TransferDataSource CurrentDragData;
public Gdk.DragAction DestDragAction;
public Gdk.DragAction SourceDragAction;
public int DragDataRequests;
public TransferDataStore DragData;
public bool DragDataForMotion;
public Gtk.TargetEntry[] ValidDropTypes;
public Point LastDragPosition;
}
DragDropData dragDropInfo;
const WidgetEvent dragDropEvents = WidgetEvent.DragDropCheck | WidgetEvent.DragDrop | WidgetEvent.DragOver | WidgetEvent.DragOverCheck;
void IBackend.InitializeBackend (object frontend, ApplicationContext context)
{
this.frontend = (Widget) frontend;
ApplicationContext = context;
}
void IWidgetBackend.Initialize (IWidgetEventSink sink)
{
eventSink = sink;
Initialize ();
}
public virtual void Initialize ()
{
}
public IWidgetEventSink EventSink {
get { return eventSink; }
}
public Widget Frontend {
get { return frontend; }
}
public ApplicationContext ApplicationContext {
get;
private set;
}
public object NativeWidget {
get {
return RootWidget;
}
}
public Gtk.Widget Widget {
get { return widget; }
set {
if (widget != null) {
value.Visible = widget.Visible;
GtkEngine.ReplaceChild (widget, value);
}
widget = value;
}
}
public Gtk.Widget RootWidget {
get {
return eventBox ?? (Gtk.Widget) Widget;
}
}
public virtual bool Visible {
get { return Widget.Visible; }
set {
Widget.Visible = value;
if (eventBox != null)
eventBox.Visible = value;
}
}
void RunWhenRealized (Action a)
{
if (Widget.IsRealized)
a ();
else {
EventHandler h = null;
h = delegate {
a ();
};
EventsRootWidget.Realized += h;
}
}
public virtual bool Sensitive {
get { return Widget.Sensitive; }
set {
Widget.Sensitive = value;
if (eventBox != null)
eventBox.Sensitive = value;
}
}
public bool CanGetFocus {
get { return Widget.CanFocus; }
set { Widget.CanFocus = value; }
}
public bool HasFocus {
get { return Widget.IsFocus; }
}
public virtual void SetFocus ()
{
Widget.IsFocus = true;
// SetFocus (Widget);
}
void SetFocus (Gtk.Widget w)
{
if (w.Parent != null)
SetFocus (w.Parent);
w.GrabFocus ();
w.IsFocus = true;
w.HasFocus = true;
}
public string TooltipText {
get {
return Widget.TooltipText;
}
set {
Widget.TooltipText = value;
}
}
static Dictionary<CursorType,Gdk.Cursor> gtkCursors = new Dictionary<CursorType, Gdk.Cursor> ();
Gdk.Cursor gdkCursor;
internal CursorType CurrentCursor { get; private set; }
public void SetCursor (CursorType cursor)
{
AllocEventBox ();
CurrentCursor = cursor;
Gdk.Cursor gc;
if (!gtkCursors.TryGetValue (cursor, out gc)) {
Gdk.CursorType ctype;
if (cursor == CursorType.Arrow)
ctype = Gdk.CursorType.LeftPtr;
else if (cursor == CursorType.Crosshair)
ctype = Gdk.CursorType.Crosshair;
else if (cursor == CursorType.Hand)
ctype = Gdk.CursorType.Hand1;
else if (cursor == CursorType.IBeam)
ctype = Gdk.CursorType.Xterm;
else if (cursor == CursorType.ResizeDown)
ctype = Gdk.CursorType.BottomSide;
else if (cursor == CursorType.ResizeUp)
ctype = Gdk.CursorType.TopSide;
else if (cursor == CursorType.ResizeLeft)
ctype = Gdk.CursorType.LeftSide;
else if (cursor == CursorType.ResizeRight)
ctype = Gdk.CursorType.RightSide;
else if (cursor == CursorType.ResizeLeftRight)
ctype = Gdk.CursorType.SbHDoubleArrow;
else if (cursor == CursorType.ResizeUpDown)
ctype = Gdk.CursorType.SbVDoubleArrow;
else if (cursor == CursorType.Move)
ctype = Gdk.CursorType.Fleur;
else if (cursor == CursorType.Wait)
ctype = Gdk.CursorType.Watch;
else if (cursor == CursorType.Help)
ctype = Gdk.CursorType.QuestionArrow;
else if (cursor == CursorType.Invisible)
ctype = (Gdk.CursorType)(-2); // Gdk.CursorType.None, since Gtk 2.16
else
ctype = Gdk.CursorType.Arrow;
gtkCursors [cursor] = gc = new Gdk.Cursor (ctype);
}
gdkCursor = gc;
// subscribe mouse entered/leaved events, when widget gets/is realized
RunWhenRealized(SubscribeCursorEnterLeaveEvent);
if (immediateCursorChange) // if realized and mouse inside set immediatly
EventsRootWidget.GdkWindow.Cursor = gdkCursor;
}
bool cursorEnterLeaveSubscribed, immediateCursorChange;
void SubscribeCursorEnterLeaveEvent ()
{
if (!cursorEnterLeaveSubscribed) {
cursorEnterLeaveSubscribed = true; // subscribe only once
EventsRootWidget.AddEvents ((int)Gdk.EventMask.EnterNotifyMask);
EventsRootWidget.AddEvents ((int)Gdk.EventMask.LeaveNotifyMask);
EventsRootWidget.EnterNotifyEvent += (o, args) => {
immediateCursorChange = true;
if (gdkCursor != null) ((Gtk.Widget)o).GdkWindow.Cursor = gdkCursor;
};
EventsRootWidget.LeaveNotifyEvent += (o, args) => {
immediateCursorChange = false;
((Gtk.Widget)o).GdkWindow.Cursor = null;
};
}
}
~WidgetBackend ()
{
Dispose (false);
}
public void Dispose ()
{
GC.SuppressFinalize (this);
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (Widget != null && disposing && Widget.Parent == null && !destroyed) {
MarkDestroyed (Frontend);
Widget.Destroy ();
}
if (IMContext != null)
IMContext.Dispose ();
}
void MarkDestroyed (Widget w)
{
var bk = (WidgetBackend) Toolkit.GetBackend (w);
bk.destroyed = true;
foreach (var c in w.Surface.Children)
MarkDestroyed (c);
}
public Size Size {
get {
return new Size (Widget.Allocation.Width, Widget.Allocation.Height);
}
}
public void SetSizeConstraints (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
{
currentWidthConstraint = widthConstraint;
currentHeightConstraint = heightConstraint;
}
DragDropData DragDropInfo {
get {
if (dragDropInfo == null)
dragDropInfo = new DragDropData ();
return dragDropInfo;
}
}
public Point ConvertToScreenCoordinates (Point widgetCoordinates)
{
if (Widget.ParentWindow == null)
return Point.Zero;
int x, y;
Widget.ParentWindow.GetOrigin (out x, out y);
var a = Widget.Allocation;
x += a.X;
y += a.Y;
return new Point (x + widgetCoordinates.X, y + widgetCoordinates.Y);
}
Pango.FontDescription customFont;
public virtual object Font {
get {
return customFont ?? Widget.Style.FontDescription;
}
set {
var fd = (Pango.FontDescription) value;
customFont = fd;
Widget.ModifyFont (fd);
}
}
Color? customBackgroundColor;
public virtual Color BackgroundColor {
get {
return customBackgroundColor.HasValue ? customBackgroundColor.Value : Widget.Style.Background (Gtk.StateType.Normal).ToXwtValue ();
}
set {
customBackgroundColor = value;
AllocEventBox (visibleWindow: true);
OnSetBackgroundColor (value);
}
}
public virtual bool UsingCustomBackgroundColor {
get { return customBackgroundColor.HasValue; }
}
Gtk.Widget IGtkWidgetBackend.Widget {
get { return RootWidget; }
}
protected virtual Gtk.Widget EventsRootWidget {
get { return eventBox ?? Widget; }
}
bool needsEventBox = true; // require event box by default
protected virtual bool NeedsEventBox {
get { return needsEventBox; }
set { needsEventBox = value; }
}
public static Gtk.Widget GetWidget (IWidgetBackend w)
{
return w != null ? ((IGtkWidgetBackend)w).Widget : null;
}
public virtual void UpdateChildPlacement (IWidgetBackend childBackend)
{
SetChildPlacement (childBackend);
}
public static Gtk.Widget GetWidgetWithPlacement (IWidgetBackend childBackend)
{
var backend = (WidgetBackend)childBackend;
var child = backend.RootWidget;
var wrapper = child.Parent as WidgetPlacementWrapper;
if (wrapper != null)
return wrapper;
if (!NeedsAlignmentWrapper (backend.Frontend))
return child;
wrapper = new WidgetPlacementWrapper ();
wrapper.UpdatePlacement (backend.Frontend);
wrapper.Show ();
wrapper.Add (child);
return wrapper;
}
public static void RemoveChildPlacement (Gtk.Widget w)
{
if (w == null)
return;
if (w is WidgetPlacementWrapper) {
var wp = (WidgetPlacementWrapper)w;
wp.Remove (wp.Child);
}
}
static bool NeedsAlignmentWrapper (Widget fw)
{
return fw.HorizontalPlacement != WidgetPlacement.Fill || fw.VerticalPlacement != WidgetPlacement.Fill || fw.Margin.VerticalSpacing != 0 || fw.Margin.HorizontalSpacing != 0;
}
public static void SetChildPlacement (IWidgetBackend childBackend)
{
var backend = (WidgetBackend)childBackend;
var child = backend.RootWidget;
var wrapper = child.Parent as WidgetPlacementWrapper;
var fw = backend.Frontend;
if (!NeedsAlignmentWrapper (fw)) {
if (wrapper != null) {
wrapper.Remove (child);
GtkEngine.ReplaceChild (wrapper, child);
}
return;
}
if (wrapper == null) {
wrapper = new WidgetPlacementWrapper ();
wrapper.Show ();
GtkEngine.ReplaceChild (child, wrapper);
wrapper.Add (child);
}
wrapper.UpdatePlacement (fw);
}
public virtual void UpdateLayout ()
{
Widget.QueueResize ();
if (!Widget.IsRealized) {
// This is a workaround to a GTK bug. When a widget is inside a ScrolledWindow, sometimes the QueueResize call on
// the widget is ignored if the widget is not realized.
var p = Widget.Parent;
while (p != null && !(p is Gtk.ScrolledWindow))
p = p.Parent;
if (p != null)
p.QueueResize ();
}
}
protected void AllocEventBox (bool visibleWindow = false)
{
// Wraps the widget with an event box. Required for some
// widgets such as Label which doesn't have its own gdk window
if (!NeedsEventBox) return;
if (eventBox == null && !EventsRootWidget.GetHasWindow()) {
if (EventsRootWidget is Gtk.EventBox) {
((Gtk.EventBox)EventsRootWidget).VisibleWindow = true;
return;
}
eventBox = new Gtk.EventBox ();
eventBox.Visible = Widget.Visible;
eventBox.Sensitive = Widget.Sensitive;
eventBox.VisibleWindow = visibleWindow;
GtkEngine.ReplaceChild (Widget, eventBox);
eventBox.Add (Widget);
}
}
public virtual void EnableEvent (object eventId)
{
if (eventId is WidgetEvent) {
WidgetEvent ev = (WidgetEvent) eventId;
switch (ev) {
case WidgetEvent.DragLeave:
AllocEventBox ();
EventsRootWidget.DragLeave += HandleWidgetDragLeave;
break;
case WidgetEvent.DragStarted:
AllocEventBox ();
EventsRootWidget.DragBegin += HandleWidgetDragBegin;
break;
case WidgetEvent.KeyPressed:
Widget.KeyPressEvent += HandleKeyPressEvent;
break;
case WidgetEvent.KeyReleased:
Widget.KeyReleaseEvent += HandleKeyReleaseEvent;
break;
case WidgetEvent.GotFocus:
EventsRootWidget.AddEvents ((int)Gdk.EventMask.FocusChangeMask);
Widget.FocusGrabbed += HandleWidgetFocusInEvent;
break;
case WidgetEvent.LostFocus:
EventsRootWidget.AddEvents ((int)Gdk.EventMask.FocusChangeMask);
Widget.FocusOutEvent += HandleWidgetFocusOutEvent;
break;
case WidgetEvent.MouseEntered:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.EnterNotifyMask);
EventsRootWidget.EnterNotifyEvent += HandleEnterNotifyEvent;
break;
case WidgetEvent.MouseExited:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.LeaveNotifyMask);
EventsRootWidget.LeaveNotifyEvent += HandleLeaveNotifyEvent;
break;
case WidgetEvent.ButtonPressed:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.ButtonPressMask);
EventsRootWidget.ButtonPressEvent += HandleButtonPressEvent;
break;
case WidgetEvent.ButtonReleased:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.ButtonReleaseMask);
EventsRootWidget.ButtonReleaseEvent += HandleButtonReleaseEvent;
break;
case WidgetEvent.MouseMoved:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.PointerMotionMask);
EventsRootWidget.MotionNotifyEvent += HandleMotionNotifyEvent;
break;
case WidgetEvent.BoundsChanged:
Widget.SizeAllocated += HandleWidgetBoundsChanged;
break;
case WidgetEvent.MouseScrolled:
AllocEventBox();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.ScrollMask);
Widget.ScrollEvent += HandleScrollEvent;
break;
case WidgetEvent.TextInput:
if (EditableWidget != null) {
EditableWidget.TextInserted += HandleTextInserted;
} else {
RunWhenRealized (delegate {
if (IMContext == null) {
IMContext = new Gtk.IMMulticontext ();
IMContext.ClientWindow = EventsRootWidget.GdkWindow;
IMContext.Commit += HandleImCommitEvent;
}
});
Widget.KeyPressEvent += HandleTextInputKeyPressEvent;
Widget.KeyReleaseEvent += HandleTextInputKeyReleaseEvent;
}
break;
}
if ((ev & dragDropEvents) != 0 && (enabledEvents & dragDropEvents) == 0) {
// Enabling a drag&drop event for the first time
AllocEventBox ();
EventsRootWidget.DragDrop += HandleWidgetDragDrop;
EventsRootWidget.DragMotion += HandleWidgetDragMotion;
EventsRootWidget.DragDataReceived += HandleWidgetDragDataReceived;
}
if ((ev & WidgetEvent.PreferredSizeCheck) != 0) {
EnableSizeCheckEvents ();
}
enabledEvents |= ev;
}
}
public virtual void DisableEvent (object eventId)
{
if (eventId is WidgetEvent) {
WidgetEvent ev = (WidgetEvent) eventId;
switch (ev) {
case WidgetEvent.DragLeave:
EventsRootWidget.DragLeave -= HandleWidgetDragLeave;
break;
case WidgetEvent.DragStarted:
EventsRootWidget.DragBegin -= HandleWidgetDragBegin;
break;
case WidgetEvent.KeyPressed:
Widget.KeyPressEvent -= HandleKeyPressEvent;
break;
case WidgetEvent.KeyReleased:
Widget.KeyReleaseEvent -= HandleKeyReleaseEvent;
break;
case WidgetEvent.GotFocus:
Widget.FocusInEvent -= HandleWidgetFocusInEvent;
break;
case WidgetEvent.LostFocus:
Widget.FocusOutEvent -= HandleWidgetFocusOutEvent;
break;
case WidgetEvent.MouseEntered:
EventsRootWidget.EnterNotifyEvent -= HandleEnterNotifyEvent;
break;
case WidgetEvent.MouseExited:
EventsRootWidget.LeaveNotifyEvent -= HandleLeaveNotifyEvent;
break;
case WidgetEvent.ButtonPressed:
if (!EventsRootWidget.IsRealized)
EventsRootWidget.Events &= ~Gdk.EventMask.ButtonPressMask;
EventsRootWidget.ButtonPressEvent -= HandleButtonPressEvent;
break;
case WidgetEvent.ButtonReleased:
if (!EventsRootWidget.IsRealized)
EventsRootWidget.Events &= Gdk.EventMask.ButtonReleaseMask;
EventsRootWidget.ButtonReleaseEvent -= HandleButtonReleaseEvent;
break;
case WidgetEvent.MouseMoved:
if (!EventsRootWidget.IsRealized)
EventsRootWidget.Events &= Gdk.EventMask.PointerMotionMask;
EventsRootWidget.MotionNotifyEvent -= HandleMotionNotifyEvent;
break;
case WidgetEvent.BoundsChanged:
Widget.SizeAllocated -= HandleWidgetBoundsChanged;
break;
case WidgetEvent.MouseScrolled:
if (!EventsRootWidget.IsRealized)
EventsRootWidget.Events &= ~Gdk.EventMask.ScrollMask;
Widget.ScrollEvent -= HandleScrollEvent;
break;
case WidgetEvent.TextInput:
if (EditableWidget != null) {
EditableWidget.TextInserted -= HandleTextInserted;
} else {
if (IMContext != null)
IMContext.Commit -= HandleImCommitEvent;
Widget.KeyPressEvent -= HandleTextInputKeyPressEvent;
Widget.KeyReleaseEvent -= HandleTextInputKeyReleaseEvent;
}
break;
}
enabledEvents &= ~ev;
if ((ev & dragDropEvents) != 0 && (enabledEvents & dragDropEvents) == 0) {
// All drag&drop events have been disabled
EventsRootWidget.DragDrop -= HandleWidgetDragDrop;
EventsRootWidget.DragMotion -= HandleWidgetDragMotion;
EventsRootWidget.DragDataReceived -= HandleWidgetDragDataReceived;
}
if ((ev & WidgetEvent.PreferredSizeCheck) != 0) {
DisableSizeCheckEvents ();
}
if ((ev & WidgetEvent.GotFocus) == 0 && (enabledEvents & WidgetEvent.LostFocus) == 0 && !EventsRootWidget.IsRealized) {
EventsRootWidget.Events &= ~Gdk.EventMask.FocusChangeMask;
}
}
}
Gdk.Rectangle lastAllocation;
void HandleWidgetBoundsChanged (object o, Gtk.SizeAllocatedArgs args)
{
if (Widget.Allocation != lastAllocation) {
lastAllocation = Widget.Allocation;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnBoundsChanged ();
});
}
}
[GLib.ConnectBefore]
void HandleKeyReleaseEvent (object o, Gtk.KeyReleaseEventArgs args)
{
KeyEventArgs kargs = GetKeyReleaseEventArgs (args);
if (kargs == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnKeyReleased (kargs);
});
if (kargs.Handled)
args.RetVal = true;
}
protected virtual KeyEventArgs GetKeyReleaseEventArgs (Gtk.KeyReleaseEventArgs args)
{
Key k = (Key)args.Event.KeyValue;
ModifierKeys m = ModifierKeys.None;
if ((args.Event.State & Gdk.ModifierType.ShiftMask) != 0)
m |= ModifierKeys.Shift;
if ((args.Event.State & Gdk.ModifierType.ControlMask) != 0)
m |= ModifierKeys.Control;
if ((args.Event.State & Gdk.ModifierType.Mod1Mask) != 0)
m |= ModifierKeys.Alt;
return new KeyEventArgs (k, (int)args.Event.KeyValue, m, false, (long)args.Event.Time);
}
[GLib.ConnectBefore]
void HandleKeyPressEvent (object o, Gtk.KeyPressEventArgs args)
{
KeyEventArgs kargs = GetKeyPressEventArgs (args);
if (kargs == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnKeyPressed (kargs);
});
if (kargs.Handled)
args.RetVal = true;
}
protected virtual KeyEventArgs GetKeyPressEventArgs (Gtk.KeyPressEventArgs args)
{
Key k = (Key)args.Event.KeyValue;
ModifierKeys m = args.Event.State.ToXwtValue ();
return new KeyEventArgs (k, (int)args.Event.KeyValue, m, false, (long)args.Event.Time);
}
protected Gtk.IMContext IMContext { get; set; }
[GLib.ConnectBefore]
void HandleTextInserted (object o, Gtk.TextInsertedArgs args)
{
if (String.IsNullOrEmpty (args.GetText ()))
return;
var pargs = new TextInputEventArgs (args.GetText ());
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnTextInput (pargs);
});
if (pargs.Handled)
((GLib.Object)o).StopSignal ("insert-text");
}
[GLib.ConnectBefore]
void HandleTextInputKeyReleaseEvent (object o, Gtk.KeyReleaseEventArgs args)
{
if (IMContext != null)
IMContext.FilterKeypress (args.Event);
}
[GLib.ConnectBefore]
void HandleTextInputKeyPressEvent (object o, Gtk.KeyPressEventArgs args)
{
if (IMContext != null)
IMContext.FilterKeypress (args.Event);
// new lines are not triggered by im, handle them here
if (args.Event.Key == Gdk.Key.Return ||
args.Event.Key == Gdk.Key.ISO_Enter ||
args.Event.Key == Gdk.Key.KP_Enter) {
var pargs = new TextInputEventArgs (Environment.NewLine);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnTextInput (pargs);
});
}
}
[GLib.ConnectBefore]
void HandleImCommitEvent (object o, Gtk.CommitArgs args)
{
if (String.IsNullOrEmpty (args.Str))
return;
var pargs = new TextInputEventArgs (args.Str);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnTextInput (pargs);
});
if (pargs.Handled)
args.RetVal = true;
}
[GLib.ConnectBefore]
void HandleScrollEvent(object o, Gtk.ScrollEventArgs args)
{
var a = GetScrollEventArgs (args);
if (a == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnMouseScrolled(a);
});
if (a.Handled)
args.RetVal = true;
}
protected virtual MouseScrolledEventArgs GetScrollEventArgs (Gtk.ScrollEventArgs args)
{
var direction = args.Event.Direction.ToXwtValue ();
return new MouseScrolledEventArgs ((long) args.Event.Time, args.Event.X, args.Event.Y, direction);
}
void HandleWidgetFocusOutEvent (object o, Gtk.FocusOutEventArgs args)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnLostFocus ();
});
}
void HandleWidgetFocusInEvent (object o, EventArgs args)
{
if (!CanGetFocus)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnGotFocus ();
});
}
void HandleLeaveNotifyEvent (object o, Gtk.LeaveNotifyEventArgs args)
{
if (args.Event.Detail == Gdk.NotifyType.Inferior)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnMouseExited ();
});
}
void HandleEnterNotifyEvent (object o, Gtk.EnterNotifyEventArgs args)
{
if (args.Event.Detail == Gdk.NotifyType.Inferior)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnMouseEntered ();
});
}
void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args)
{
var a = GetMouseMovedEventArgs (args);
if (a == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnMouseMoved (a);
});
if (a.Handled)
args.RetVal = true;
}
protected virtual MouseMovedEventArgs GetMouseMovedEventArgs (Gtk.MotionNotifyEventArgs args)
{
var pointer_coords = Widget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y);
return new MouseMovedEventArgs ((long) args.Event.Time, pointer_coords.X, pointer_coords.Y);
}
void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args)
{
var a = GetButtonReleaseEventArgs (args);
if (a == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnButtonReleased (a);
});
if (a.Handled)
args.RetVal = true;
}
protected virtual ButtonEventArgs GetButtonReleaseEventArgs (Gtk.ButtonReleaseEventArgs args)
{
var a = new ButtonEventArgs ();
var pointer_coords = Widget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y);
a.X = pointer_coords.X;
a.Y = pointer_coords.Y;
a.Button = (PointerButton) args.Event.Button;
return a;
}
[GLib.ConnectBeforeAttribute]
void HandleButtonPressEvent (object o, Gtk.ButtonPressEventArgs args)
{
var a = GetButtonPressEventArgs (args);
if (a == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnButtonPressed (a);
});
if (a.Handled)
args.RetVal = true;
}
protected virtual ButtonEventArgs GetButtonPressEventArgs (Gtk.ButtonPressEventArgs args)
{
var a = new ButtonEventArgs ();
var pointer_coords = Widget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y);
a.X = pointer_coords.X;
a.Y = pointer_coords.Y;
a.Button = (PointerButton) args.Event.Button;
if (args.Event.Type == Gdk.EventType.TwoButtonPress)
a.MultiplePress = 2;
else if (args.Event.Type == Gdk.EventType.ThreeButtonPress)
a.MultiplePress = 3;
else
a.MultiplePress = 1;
return a;
}
[GLib.ConnectBefore]
void HandleWidgetDragMotion (object o, Gtk.DragMotionArgs args)
{
args.RetVal = DoDragMotion (args.Context, args.X, args.Y, args.Time);
}
internal bool DoDragMotion (Gdk.DragContext context, int x, int y, uint time)
{
DragDropInfo.LastDragPosition = new Point (x, y);
DragDropAction ac;
if ((enabledEvents & WidgetEvent.DragOverCheck) == 0) {
if ((enabledEvents & WidgetEvent.DragOver) != 0)
ac = DragDropAction.Default;
else
ac = ConvertDragAction (DragDropInfo.DestDragAction);
}
else {
// This is a workaround to what seems to be a mac gtk bug.
// Suggested action is set to all when no control key is pressed
var cact = ConvertDragAction (context.Actions);
if (cact == DragDropAction.All)
cact = DragDropAction.Move;
var target = Gtk.Drag.DestFindTarget (EventsRootWidget, context, null);
var targetTypes = Util.GetDragTypes (new Gdk.Atom[] { target });
DragOverCheckEventArgs da = new DragOverCheckEventArgs (new Point (x, y), targetTypes, cact);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnDragOverCheck (da);
});
ac = da.AllowedAction;
if ((enabledEvents & WidgetEvent.DragOver) == 0 && ac == DragDropAction.Default)
ac = DragDropAction.None;
}
if (ac == DragDropAction.None) {
OnSetDragStatus (context, x, y, time, (Gdk.DragAction)0);
return true;
}
else if (ac == DragDropAction.Default) {
// Undefined, we need more data
QueryDragData (context, time, true);
return true;
}
else {
// Gtk.Drag.Highlight (Widget);
OnSetDragStatus (context, x, y, time, ConvertDragAction (ac));
return true;
}
}
[GLib.ConnectBefore]
void HandleWidgetDragDrop (object o, Gtk.DragDropArgs args)
{
args.RetVal = DoDragDrop (args.Context, args.X, args.Y, args.Time);
}
internal bool DoDragDrop (Gdk.DragContext context, int x, int y, uint time)
{
DragDropInfo.LastDragPosition = new Point (x, y);
var cda = ConvertDragAction (context.GetSelectedAction());
DragDropResult res;
if ((enabledEvents & WidgetEvent.DragDropCheck) == 0) {
if ((enabledEvents & WidgetEvent.DragDrop) != 0)
res = DragDropResult.None;
else
res = DragDropResult.Canceled;
}
else {
DragCheckEventArgs da = new DragCheckEventArgs (new Point (x, y), Util.GetDragTypes (context.ListTargets ()), cda);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnDragDropCheck (da);
});
res = da.Result;
if ((enabledEvents & WidgetEvent.DragDrop) == 0 && res == DragDropResult.None)
res = DragDropResult.Canceled;
}
if (res == DragDropResult.Canceled) {
Gtk.Drag.Finish (context, false, false, time);
return true;
}
else if (res == DragDropResult.Success) {
Gtk.Drag.Finish (context, true, cda == DragDropAction.Move, time);
return true;
}
else {
// Undefined, we need more data
QueryDragData (context, time, false);
return true;
}
}
void HandleWidgetDragLeave (object o, Gtk.DragLeaveArgs args)
{
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnDragLeave (EventArgs.Empty);
});
}
void QueryDragData (Gdk.DragContext ctx, uint time, bool isMotionEvent)
{
DragDropInfo.DragDataForMotion = isMotionEvent;
DragDropInfo.DragData = new TransferDataStore ();
DragDropInfo.DragDataRequests = DragDropInfo.ValidDropTypes.Length;
foreach (var t in DragDropInfo.ValidDropTypes) {
var at = Gdk.Atom.Intern (t.Target, true);
Gtk.Drag.GetData (EventsRootWidget, ctx, at, time);
}
}
void HandleWidgetDragDataReceived (object o, Gtk.DragDataReceivedArgs args)
{
args.RetVal = DoDragDataReceived (args.Context, args.X, args.Y, args.SelectionData, args.Info, args.Time);
}
internal bool DoDragDataReceived (Gdk.DragContext context, int x, int y, Gtk.SelectionData selectionData, uint info, uint time)
{
if (DragDropInfo.DragDataRequests == 0) {
// Got the data without requesting it. Create the datastore here
DragDropInfo.DragData = new TransferDataStore ();
DragDropInfo.LastDragPosition = new Point (x, y);
DragDropInfo.DragDataRequests = 1;
}
DragDropInfo.DragDataRequests--;
// If multiple drag/drop data types are supported, we need to iterate through them all and
// append the data. If one of the supported data types is not found, there's no need to
// bail out. We must raise the event
Util.GetSelectionData (ApplicationContext, selectionData, DragDropInfo.DragData);
if (DragDropInfo.DragDataRequests == 0) {
if (DragDropInfo.DragDataForMotion) {
// If no specific action is set, it means that no key has been pressed.
// In that case, use Move or Copy or Link as default (when allowed, in this order).
var cact = ConvertDragAction (context.Actions);
if (cact != DragDropAction.Copy && cact != DragDropAction.Move && cact != DragDropAction.Link) {
if (cact.HasFlag (DragDropAction.Move))
cact = DragDropAction.Move;
else if (cact.HasFlag (DragDropAction.Copy))
cact = DragDropAction.Copy;
else if (cact.HasFlag (DragDropAction.Link))
cact = DragDropAction.Link;
else
cact = DragDropAction.None;
}
DragOverEventArgs da = new DragOverEventArgs (DragDropInfo.LastDragPosition, DragDropInfo.DragData, cact);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnDragOver (da);
});
OnSetDragStatus (context, (int)DragDropInfo.LastDragPosition.X, (int)DragDropInfo.LastDragPosition.Y, time, ConvertDragAction (da.AllowedAction));
return true;
}
else {
// Use Context.Action here since that's the action selected in DragOver
var cda = ConvertDragAction (context.GetSelectedAction());
DragEventArgs da = new DragEventArgs (DragDropInfo.LastDragPosition, DragDropInfo.DragData, cda);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnDragDrop (da);
});
Gtk.Drag.Finish (context, da.Success, cda == DragDropAction.Move, time);
return true;
}
} else
return false;
}
protected virtual void OnSetDragStatus (Gdk.DragContext context, int x, int y, uint time, Gdk.DragAction action)
{
Gdk.Drag.Status (context, action, time);
}
void HandleWidgetDragBegin (object o, Gtk.DragBeginArgs args)
{
// If SetDragSource has not been called, ignore the event
if (DragDropInfo.SourceDragAction == default (Gdk.DragAction))
return;
DragStartData sdata = null;
ApplicationContext.InvokeUserCode (delegate {
sdata = EventSink.OnDragStarted ();
});
if (sdata == null)
return;
DragDropInfo.CurrentDragData = sdata.Data;
if (sdata.ImageBackend != null) {
var gi = (GtkImage)sdata.ImageBackend;
var img = gi.ToPixbuf (ApplicationContext, Widget);
Gtk.Drag.SetIconPixbuf (args.Context, img, (int)sdata.HotX, (int)sdata.HotY);
}
HandleDragBegin (null, args);
}
class IconInitializer
{
public Gdk.Pixbuf Image;
public double HotX, HotY;
public Gtk.Widget Widget;
public static void Init (Gtk.Widget w, Gdk.Pixbuf image, double hotX, double hotY)
{
IconInitializer ii = new WidgetBackend.IconInitializer ();
ii.Image = image;
ii.HotX = hotX;
ii.HotY = hotY;
ii.Widget = w;
w.DragBegin += ii.Begin;
}
void Begin (object o, Gtk.DragBeginArgs args)
{
Gtk.Drag.SetIconPixbuf (args.Context, Image, (int)HotX, (int)HotY);
Widget.DragBegin -= Begin;
}
}
public void DragStart (DragStartData sdata)
{
AllocEventBox ();
Gdk.DragAction action = ConvertDragAction (sdata.DragAction);
DragDropInfo.CurrentDragData = sdata.Data;
EventsRootWidget.DragBegin += HandleDragBegin;
if (sdata.ImageBackend != null) {
var img = ((GtkImage)sdata.ImageBackend).ToPixbuf (ApplicationContext, Widget);
IconInitializer.Init (EventsRootWidget, img, sdata.HotX, sdata.HotY);
}
Gtk.Drag.Begin (EventsRootWidget, Util.BuildTargetTable (sdata.Data.DataTypes), action, 1, Gtk.Global.CurrentEvent ?? new Gdk.Event (IntPtr.Zero));
}
void HandleDragBegin (object o, Gtk.DragBeginArgs args)
{
EventsRootWidget.DragEnd += HandleWidgetDragEnd;
EventsRootWidget.DragFailed += HandleDragFailed;
EventsRootWidget.DragDataDelete += HandleDragDataDelete;
EventsRootWidget.DragDataGet += HandleWidgetDragDataGet;
}
void HandleWidgetDragDataGet (object o, Gtk.DragDataGetArgs args)
{
Util.SetDragData (DragDropInfo.CurrentDragData, args);
}
void HandleDragFailed (object o, Gtk.DragFailedArgs args)
{
Console.WriteLine ("FAILED");
}
void HandleDragDataDelete (object o, Gtk.DragDataDeleteArgs args)
{
DoDragaDataDelete ();
}
internal void DoDragaDataDelete ()
{
FinishDrag (true);
}
void HandleWidgetDragEnd (object o, Gtk.DragEndArgs args)
{
FinishDrag (false);
}
void FinishDrag (bool delete)
{
EventsRootWidget.DragEnd -= HandleWidgetDragEnd;
EventsRootWidget.DragDataGet -= HandleWidgetDragDataGet;
EventsRootWidget.DragFailed -= HandleDragFailed;
EventsRootWidget.DragDataDelete -= HandleDragDataDelete;
EventsRootWidget.DragBegin -= HandleDragBegin; // This event is subscribed only when manualy starting a drag
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnDragFinished (new DragFinishedEventArgs (delete));
});
}
public void SetDragTarget (TransferDataType[] types, DragDropAction dragAction)
{
DragDropInfo.DestDragAction = ConvertDragAction (dragAction);
var table = Util.BuildTargetTable (types);
DragDropInfo.ValidDropTypes = (Gtk.TargetEntry[]) table;
OnSetDragTarget (DragDropInfo.ValidDropTypes, DragDropInfo.DestDragAction);
}
protected virtual void OnSetDragTarget (Gtk.TargetEntry[] table, Gdk.DragAction actions)
{
AllocEventBox ();
Gtk.Drag.DestSet (EventsRootWidget, Gtk.DestDefaults.Highlight, table, actions);
}
public void SetDragSource (TransferDataType[] types, DragDropAction dragAction)
{
AllocEventBox ();
DragDropInfo.SourceDragAction = ConvertDragAction (dragAction);
var table = Util.BuildTargetTable (types);
OnSetDragSource (Gdk.ModifierType.Button1Mask, (Gtk.TargetEntry[]) table, DragDropInfo.SourceDragAction);
}
protected virtual void OnSetDragSource (Gdk.ModifierType modifierType, Gtk.TargetEntry[] table, Gdk.DragAction actions)
{
Gtk.Drag.SourceSet (EventsRootWidget, modifierType, table, actions);
}
Gdk.DragAction ConvertDragAction (DragDropAction dragAction)
{
Gdk.DragAction action = (Gdk.DragAction)0;
if ((dragAction & DragDropAction.Copy) != 0)
action |= Gdk.DragAction.Copy;
if ((dragAction & DragDropAction.Move) != 0)
action |= Gdk.DragAction.Move;
if ((dragAction & DragDropAction.Link) != 0)
action |= Gdk.DragAction.Link;
return action;
}
DragDropAction ConvertDragAction (Gdk.DragAction dragAction)
{
DragDropAction action = (DragDropAction)0;
if ((dragAction & Gdk.DragAction.Copy) != 0)
action |= DragDropAction.Copy;
if ((dragAction & Gdk.DragAction.Move) != 0)
action |= DragDropAction.Move;
if ((dragAction & Gdk.DragAction.Link) != 0)
action |= DragDropAction.Link;
return action;
}
}
public interface IGtkWidgetBackend
{
Gtk.Widget Widget { get; }
}
class WidgetPlacementWrapper: Gtk.Alignment, IConstraintProvider
{
public WidgetPlacementWrapper (): base (0, 0, 1, 1)
{
}
public void UpdatePlacement (Xwt.Widget widget)
{
LeftPadding = (uint)widget.MarginLeft;
RightPadding = (uint)widget.MarginRight;
TopPadding = (uint)widget.MarginTop;
BottomPadding = (uint)widget.MarginBottom;
Xalign = (float) widget.HorizontalPlacement.GetValue ();
Yalign = (float) widget.VerticalPlacement.GetValue ();
Xscale = (widget.HorizontalPlacement == WidgetPlacement.Fill) ? 1 : 0;
Yscale = (widget.VerticalPlacement == WidgetPlacement.Fill) ? 1 : 0;
}
#region IConstraintProvider implementation
public void GetConstraints (Gtk.Widget target, out SizeConstraint width, out SizeConstraint height)
{
if (Parent is IConstraintProvider)
((IConstraintProvider)Parent).GetConstraints (this, out width, out height);
else
width = height = SizeConstraint.Unconstrained;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Drawing;
using Android.Graphics;
using Android.Content.PM;
using Android.Hardware;
using System.Threading.Tasks;
using System.Threading;
namespace ZXing.Mobile
{
// based on https://github.com/xamarin/monodroid-samples/blob/master/ApiDemo/Graphics/CameraPreview.cs
public class ZXingSurfaceView : SurfaceView, ISurfaceHolderCallback, Android.Hardware.Camera.IPreviewCallback, Android.Hardware.Camera.IAutoFocusCallback
{
private const int MIN_FRAME_WIDTH = 240;
private const int MIN_FRAME_HEIGHT = 240;
private const int MAX_FRAME_WIDTH = 600;
private const int MAX_FRAME_HEIGHT = 400;
CancellationTokenSource tokenSource;
ISurfaceHolder surface_holder;
Android.Hardware.Camera camera;
MobileBarcodeScanningOptions options;
Action<ZXing.Result> callback;
Activity activity;
bool isAnalyzing = false;
bool wasScanned = false;
bool isTorchOn = false;
static ManualResetEventSlim _cameraLockEvent = new ManualResetEventSlim(true);
public ZXingSurfaceView (Activity activity)
: base (activity)
{
this.activity = activity;
Init ();
}
protected ZXingSurfaceView(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
Init ();
}
void Init ()
{
CheckPermissions ();
this.surface_holder = Holder;
this.surface_holder.AddCallback (this);
this.surface_holder.SetType (SurfaceType.PushBuffers);
this.tokenSource = new System.Threading.CancellationTokenSource();
}
void CheckPermissions()
{
var perf = PerformanceCounter.Start ();
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Checking Camera Permissions...");
if (!PlatformChecks.HasCameraPermission (this.Context))
{
var msg = "ZXing.Net.Mobile requires permission to use the Camera (" + Android.Manifest.Permission.Camera + "), but was not found in your AndroidManifest.xml file.";
Android.Util.Log.Error ("ZXing.Net.Mobile", msg);
throw new UnauthorizedAccessException (msg);
}
PerformanceCounter.Stop (perf, "CheckPermissions took {0}ms");
}
public void SurfaceCreated (ISurfaceHolder holder)
{
}
public void SurfaceChanged (ISurfaceHolder holder, Format format, int w, int h)
{
if (camera == null)
return;
var perf = PerformanceCounter.Start ();
var parameters = camera.GetParameters ();
parameters.PreviewFormat = ImageFormatType.Nv21;
var availableResolutions = new List<CameraResolution> ();
foreach (var sps in parameters.SupportedPreviewSizes) {
availableResolutions.Add (new CameraResolution {
Width = sps.Width,
Height = sps.Height
});
}
// Try and get a desired resolution from the options selector
var resolution = options.GetResolution (availableResolutions);
// If the user did not specify a resolution, let's try and find a suitable one
if (resolution == null) {
// Loop through all supported sizes
foreach (var sps in parameters.SupportedPreviewSizes) {
// Find one that's >= 640x360 but <= 1000x1000
// This will likely pick the *smallest* size in that range, which should be fine
if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000) {
resolution = new CameraResolution {
Width = sps.Width,
Height = sps.Height
};
break;
}
}
}
// Google Glass requires this fix to display the camera output correctly
if (Build.Model.Contains ("Glass")) {
resolution = new CameraResolution {
Width = 640,
Height = 360
};
// Glass requires 30fps
parameters.SetPreviewFpsRange (30000, 30000);
}
// Hopefully a resolution was selected at some point
if (resolution != null) {
Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Selected Resolution: " + resolution.Width + "x" + resolution.Height);
parameters.SetPreviewSize (resolution.Width, resolution.Height);
}
camera.SetParameters (parameters);
SetCameraDisplayOrientation (this.activity);
camera.SetPreviewDisplay (holder);
camera.StartPreview ();
//cameraResolution = new Size(parameters.PreviewSize.Width, parameters.PreviewSize.Height);
PerformanceCounter.Stop (perf, "SurfaceChanged took {0}ms");
AutoFocus();
}
public void SurfaceDestroyed (ISurfaceHolder holder)
{
ShutdownCamera ();
}
public byte[] rotateCounterClockwise(byte[] data, int width, int height)
{
var rotatedData = new byte[data.Length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
return rotatedData;
}
private byte[] rotateYUV420Degree90(byte[] data, int imageWidth, int imageHeight)
{
byte [] yuv = new byte[imageWidth*imageHeight*3/2];
// Rotate the Y luma
int i = 0;
for(int x = 0;x < imageWidth;x++)
{
for(int y = imageHeight-1;y >= 0;y--)
{
yuv[i] = data[y*imageWidth+x];
i++;
}
}
// Rotate the U and V color components
i = imageWidth*imageHeight*3/2-1;
for(int x = imageWidth-1;x > 0;x=x-2)
{
for(int y = 0;y < imageHeight/2;y++)
{
yuv[i] = data[(imageWidth*imageHeight)+(y*imageWidth)+x];
i--;
yuv[i] = data[(imageWidth*imageHeight)+(y*imageWidth)+(x-1)];
i--;
}
}
return yuv;
}
DateTime lastPreviewAnalysis = DateTime.UtcNow;
BarcodeReader barcodeReader = null;
Task processingTask;
public void OnPreviewFrame (byte [] bytes, Android.Hardware.Camera camera)
{
if (!isAnalyzing)
return;
//Check and see if we're still processing a previous frame
if (processingTask != null && !processingTask.IsCompleted)
return;
if ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames)
return;
// Delay a minimum between scans
if (wasScanned && ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenContinuousScans))
return;
wasScanned = false;
var cameraParameters = camera.GetParameters();
var width = cameraParameters.PreviewSize.Width;
var height = cameraParameters.PreviewSize.Height;
//var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null);
lastPreviewAnalysis = DateTime.UtcNow;
processingTask = Task.Factory.StartNew (() =>
{
try
{
if (barcodeReader == null)
{
barcodeReader = new BarcodeReader (null, null, null, (p, w, h, f) =>
new PlanarYUVLuminanceSource (p, w, h, 0, 0, w, h, false));
//new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false))
if (this.options.TryHarder.HasValue)
barcodeReader.Options.TryHarder = this.options.TryHarder.Value;
if (this.options.PureBarcode.HasValue)
barcodeReader.Options.PureBarcode = this.options.PureBarcode.Value;
if (!string.IsNullOrEmpty (this.options.CharacterSet))
barcodeReader.Options.CharacterSet = this.options.CharacterSet;
if (this.options.TryInverted.HasValue)
barcodeReader.TryInverted = this.options.TryInverted.Value;
if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0)
{
barcodeReader.Options.PossibleFormats = new List<BarcodeFormat> ();
foreach (var pf in this.options.PossibleFormats)
barcodeReader.Options.PossibleFormats.Add (pf);
}
}
bool rotate = false;
int newWidth = width;
int newHeight = height;
var cDegrees = getCameraDisplayOrientation(this.activity);
if (cDegrees == 90 || cDegrees == 270)
{
rotate = true;
newWidth = height;
newHeight = width;
}
if (rotate)
bytes = rotateYUV420Degree90(bytes, width, height);//rotateCounterClockwise(bytes, width, height);
var result = barcodeReader.Decode (bytes, newWidth, newHeight, RGBLuminanceSource.BitmapFormat.Unknown);
if (result == null || string.IsNullOrEmpty (result.Text))
return;
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Barcode Found: " + result.Text);
var img = new YuvImage(bytes, cameraParameters.PreviewFormat, newWidth, newHeight, null);
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
bool didIt = img.CompressToJpeg(new Rect(0,0,newWidth, newHeight), 75, outStream);
outStream.Seek(0, System.IO.SeekOrigin.Begin);
Bitmap newBM = BitmapFactory.DecodeStream(outStream);
result.CaptureImage = newBM;
wasScanned = true;
callback (result);
}
catch (ReaderException)
{
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "No barcode Found");
// ignore this exception; it happens every time there is a failed scan
}
catch (Exception)
{
// TODO: this one is unexpected.. log or otherwise handle it
throw;
}
});
}
public void OnAutoFocus (bool success, Android.Hardware.Camera camera)
{
Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "AutoFocused");
/*
Task.Factory.StartNew(() =>
{
int slept = 0;
while (!tokenSource.IsCancellationRequested && slept < 2000)
{
System.Threading.Thread.Sleep(100);
slept += 100;
}
if (!tokenSource.IsCancellationRequested)
AutoFocus();
});
*/
}
public override bool OnTouchEvent (MotionEvent e)
{
var r = base.OnTouchEvent(e);
AutoFocus();
return r;
}
public void AutoFocus()
{
if (camera != null)
{
if (!tokenSource.IsCancellationRequested)
{
Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "AutoFocus Requested");
try {
camera.AutoFocus(this);
} catch (Exception ex) {
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "AutoFocus Failed: {0}", ex);
}
}
}
}
//int cameraDegrees = 0;
int getCameraDisplayOrientation(Activity context)
{
var degrees = 0;
var display = context.WindowManager.DefaultDisplay;
var rotation = display.Rotation;
var displayMetrics = new Android.Util.DisplayMetrics ();
display.GetMetrics (displayMetrics);
int width = displayMetrics.WidthPixels;
int height = displayMetrics.HeightPixels;
if((rotation == SurfaceOrientation.Rotation0 || rotation == SurfaceOrientation.Rotation180) && height > width ||
(rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270) && width > height)
{
switch(rotation)
{
case SurfaceOrientation.Rotation0:
degrees = 90;
break;
case SurfaceOrientation.Rotation90:
degrees = 0;
break;
case SurfaceOrientation.Rotation180:
degrees = 270;
break;
case SurfaceOrientation.Rotation270:
degrees = 180;
break;
}
}
//Natural orientation is landscape or square
else
{
switch(rotation)
{
case SurfaceOrientation.Rotation0:
degrees = 0;
break;
case SurfaceOrientation.Rotation90:
degrees = 270;
break;
case SurfaceOrientation.Rotation180:
degrees = 180;
break;
case SurfaceOrientation.Rotation270:
degrees = 90;
break;
}
}
return degrees;
}
public void SetCameraDisplayOrientation(Activity context)
{
var degrees = getCameraDisplayOrientation (context);
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Changing Camera Orientation to: " + degrees);
//cameraDegrees = degrees;
try { camera.SetDisplayOrientation (degrees); }
catch (Exception ex) {
Android.Util.Log.Error (MobileBarcodeScanner.TAG, ex.ToString ());
}
}
public void ShutdownCamera ()
{
tokenSource.Cancel();
if (camera == null)
return;
var theCamera = camera;
camera = null;
// make this asyncronous so that we can return from the view straight away instead of waiting for the camera to release.
Task.Factory.StartNew(() => {
try {
theCamera.SetPreviewCallback(null);
theCamera.StopPreview();
theCamera.Release();
} catch (Exception e) {
Android.Util.Log.Error(MobileBarcodeScanner.TAG, e.ToString());
} finally {
ReleaseExclusiveAccess();
}
});
}
private void drawResultPoints(Bitmap barcode, ZXing.Result rawResult)
{
var points = rawResult.ResultPoints;
if (points != null && points.Length > 0)
{
var canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.Color = Android.Graphics.Color.White;
paint.StrokeWidth = 3.0f;
paint.SetStyle(Paint.Style.Stroke);
var border = new RectF(2, 2, barcode.Width - 2, barcode.Height - 2);
canvas.DrawRect(border, paint);
paint.Color = Android.Graphics.Color.Purple;
if (points.Length == 2)
{
paint.StrokeWidth = 4.0f;
drawLine(canvas, paint, points[0], points[1]);
}
else if (points.Length == 4 &&
(rawResult.BarcodeFormat == BarcodeFormat.UPC_A ||
rawResult.BarcodeFormat == BarcodeFormat.EAN_13))
{
// Hacky special case -- draw two lines, for the barcode and metadata
drawLine(canvas, paint, points[0], points[1]);
drawLine(canvas, paint, points[2], points[3]);
}
else
{
paint.StrokeWidth = 10.0f;
foreach (ResultPoint point in points)
canvas.DrawPoint(point.X, point.Y, paint);
}
}
}
private void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b)
{
canvas.DrawLine(a.X, a.Y, b.X, b.Y, paint);
}
public Size FindBestPreviewSize(Android.Hardware.Camera.Parameters p, Size screenRes)
{
var max = p.SupportedPreviewSizes.Count;
var s = p.SupportedPreviewSizes[max - 1];
return new Size(s.Width, s.Height);
}
private void GetExclusiveAccess()
{
Console.WriteLine ("Getting Camera Exclusive access");
var result = _cameraLockEvent.Wait(TimeSpan.FromSeconds(10));
if (!result)
throw new Exception("Couldn't get exclusive access to the camera");
_cameraLockEvent.Reset();
Console.WriteLine ("Got Camera Exclusive access");
}
private void ReleaseExclusiveAccess()
{
// release the camera exclusive access allowing it to be used again.
Console.WriteLine ("Releasing Exclusive access to camera");
_cameraLockEvent.Set();
}
public void StartScanning (MobileBarcodeScanningOptions options, Action<Result> callback)
{
this.callback = callback;
this.options = options;
lastPreviewAnalysis = DateTime.UtcNow.AddMilliseconds(options.InitialDelayBeforeAnalyzingFrames);
isAnalyzing = true;
Console.WriteLine ("StartScanning");
CheckPermissions ();
var perf = PerformanceCounter.Start ();
GetExclusiveAccess();
try
{
var version = Build.VERSION.SdkInt;
if (version >= BuildVersionCodes.Gingerbread)
{
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Checking Number of cameras...");
var numCameras = Android.Hardware.Camera.NumberOfCameras;
var camInfo = new Android.Hardware.Camera.CameraInfo();
var found = false;
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Found " + numCameras + " cameras...");
var whichCamera = CameraFacing.Back;
if (options.UseFrontCameraIfAvailable.HasValue && options.UseFrontCameraIfAvailable.Value)
whichCamera = CameraFacing.Front;
for (int i = 0; i < numCameras; i++)
{
Android.Hardware.Camera.GetCameraInfo(i, camInfo);
if (camInfo.Facing == whichCamera)
{
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Found " + whichCamera + " Camera, opening...");
camera = Android.Hardware.Camera.Open(i);
found = true;
break;
}
}
if (!found)
{
Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Finding " + whichCamera + " camera failed, opening camera 0...");
camera = Android.Hardware.Camera.Open(0);
}
}
else
{
camera = Android.Hardware.Camera.Open();
}
if (camera == null)
Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Camera is null :(");
camera.SetPreviewCallback (this);
} catch (Exception ex) {
ShutdownCamera ();
Console.WriteLine("Setup Error: " + ex);
}
PerformanceCounter.Stop (perf, "SurfaceCreated took {0}ms");
}
public void StartScanning (Action<Result> callback)
{
StartScanning (new MobileBarcodeScanningOptions (), callback);
}
public void StopScanning ()
{
isAnalyzing = false;
ShutdownCamera ();
}
public void PauseAnalysis ()
{
isAnalyzing = false;
}
public void ResumeAnalysis ()
{
isAnalyzing = true;
}
public void SetTorch (bool on)
{
if (!this.Context.PackageManager.HasSystemFeature(PackageManager.FeatureCameraFlash))
{
Android.Util.Log.Info(MobileBarcodeScanner.TAG, "Flash not supported on this device");
return;
}
if (!PlatformChecks.HasFlashlightPermission (this.Context))
{
var msg = "ZXing.Net.Mobile requires permission to use the Flash (" + Android.Manifest.Permission.Flashlight + "), but was not found in your AndroidManifest.xml file.";
Android.Util.Log.Error (MobileBarcodeScanner.TAG, msg);
throw new UnauthorizedAccessException (msg);
}
if (camera == null)
{
Android.Util.Log.Info(MobileBarcodeScanner.TAG, "NULL Camera");
return;
}
var p = camera.GetParameters();
var supportedFlashModes = p.SupportedFlashModes;
if (supportedFlashModes == null)
supportedFlashModes = new List<string>();
var flashMode= string.Empty;
if (on)
{
if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeTorch))
flashMode = Android.Hardware.Camera.Parameters.FlashModeTorch;
else if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeOn))
flashMode = Android.Hardware.Camera.Parameters.FlashModeOn;
isTorchOn = true;
}
else
{
if ( supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeOff))
flashMode = Android.Hardware.Camera.Parameters.FlashModeOff;
isTorchOn = false;
}
if (!string.IsNullOrEmpty(flashMode))
{
p.FlashMode = flashMode;
camera.SetParameters(p);
}
}
public void ToggleTorch ()
{
SetTorch (!isTorchOn);
}
public MobileBarcodeScanningOptions ScanningOptions {
get { return options; }
}
public bool IsTorchOn {
get { return isTorchOn; }
}
public bool IsAnalyzing {
get { return isAnalyzing; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
/*
* Clas for various methods and utility constants.
*/
class M {
internal const int SSLv20 = 0x0200;
internal const int SSLv30 = 0x0300;
internal const int TLSv10 = 0x0301;
internal const int TLSv11 = 0x0302;
internal const int TLSv12 = 0x0303;
internal const int CHANGE_CIPHER_SPEC = 20;
internal const int ALERT = 21;
internal const int HANDSHAKE = 22;
internal const int APPLICATION = 23;
internal const int HELLO_REQUEST = 0;
internal const int CLIENT_HELLO = 1;
internal const int SERVER_HELLO = 2;
internal const int CERTIFICATE = 11;
internal const int SERVER_KEY_EXCHANGE = 12;
internal const int CERTIFICATE_REQUEST = 13;
internal const int SERVER_HELLO_DONE = 14;
internal const int CERTIFICATE_VERIFY = 15;
internal const int CLIENT_KEY_EXCHANGE = 16;
internal const int FINISHED = 20;
internal const int TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF;
internal const int TLS_FALLBACK_SCSV = 0x5600;
/* From RFC 5246 */
internal const int EXT_SIGNATURE_ALGORITHMS = 0x000D;
/* From RFC 6066 */
internal const int EXT_SERVER_NAME = 0x0000;
internal const int EXT_MAX_FRAGMENT_LENGTH = 0x0001;
internal const int EXT_CLIENT_CERTIFICATE_URL = 0x0002;
internal const int EXT_TRUSTED_CA_KEYS = 0x0003;
internal const int EXT_TRUNCATED_HMAC = 0x0004;
internal const int EXT_STATUS_REQUEST = 0x0005;
/* From RFC 4492 */
internal const int EXT_SUPPORTED_CURVES = 0x000A;
internal const int EXT_SUPPORTED_EC_POINTS = 0x000B;
/* From RFC 5746 */
internal const int EXT_RENEGOTIATION_INFO = 0xFF01;
/* From RFC 7366 */
internal const int EXT_ENCRYPT_THEN_MAC = 0x0016;
internal static void Enc16be(int val, byte[] buf, int off)
{
buf[off] = (byte)(val >> 8);
buf[off + 1] = (byte)val;
}
internal static void Enc24be(int val, byte[] buf, int off)
{
buf[off] = (byte)(val >> 16);
buf[off + 1] = (byte)(val >> 8);
buf[off + 2] = (byte)val;
}
internal static void Enc32be(int val, byte[] buf, int off)
{
buf[off] = (byte)(val >> 24);
buf[off + 1] = (byte)(val >> 16);
buf[off + 2] = (byte)(val >> 8);
buf[off + 3] = (byte)val;
}
internal static int Dec16be(byte[] buf, int off)
{
return ((int)buf[off] << 8)
| (int)buf[off + 1];
}
internal static int Dec24be(byte[] buf, int off)
{
return ((int)buf[off] << 16)
| ((int)buf[off + 1] << 8)
| (int)buf[off + 2];
}
internal static uint Dec32be(byte[] buf, int off)
{
return ((uint)buf[off] << 24)
| ((uint)buf[off + 1] << 16)
| ((uint)buf[off + 2] << 8)
| (uint)buf[off + 3];
}
internal static void ReadFully(Stream s, byte[] buf)
{
ReadFully(s, buf, 0, buf.Length);
}
internal static void ReadFully(Stream s, byte[] buf, int off, int len)
{
while (len > 0) {
int rlen = s.Read(buf, off, len);
if (rlen <= 0) {
throw new EndOfStreamException();
}
off += rlen;
len -= rlen;
}
}
static byte[] SKIPBUF = new byte[8192];
internal static void Skip(Stream s, int len)
{
while (len > 0) {
int rlen = Math.Min(len, SKIPBUF.Length);
ReadFully(s, SKIPBUF, 0, rlen);
len -= rlen;
}
}
static readonly DateTime Jan1st1970 =
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal static long CurrentTimeMillis()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
/*
* Compute the SHA-1 hash of some bytes, returning the hash
* value in hexadecimal (lowercase).
*/
internal static string DoSHA1(byte[] buf)
{
return DoSHA1(buf, 0, buf.Length);
}
internal static string DoSHA1(byte[] buf, int off, int len)
{
byte[] hv = new SHA1Managed().ComputeHash(buf, off, len);
StringBuilder sb = new StringBuilder();
foreach (byte b in hv) {
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
/*
* Hash a whole chain of certificates. This is the SHA-1 hash
* of the concatenation of the provided buffers. The hash value
* is returned in lowercase hexadecimal.
*/
internal static string DoSHA1(byte[][] chain)
{
SHA1Managed sh = new SHA1Managed();
foreach (byte[] ec in chain) {
sh.TransformBlock(ec, 0, ec.Length, null, 0);
}
sh.TransformFinalBlock(new byte[0], 0, 0);
StringBuilder sb = new StringBuilder();
foreach (byte b in sh.Hash) {
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
/*
* Hash several values together. This makes an unambiguous
* concatenation.
*/
internal static string DoSHA1Values(params object[] values)
{
MemoryStream ms = new MemoryStream();
foreach (object obj in values) {
byte[] data;
if (obj == null) {
data = new byte[1];
data[0] = 0x00;
} else if (obj is int) {
data = new byte[5];
data[0] = 0x01;
Enc32be((int)obj, data, 1);
} else if (obj is byte[]) {
byte[] buf = (byte[])obj;
data = new byte[5 + buf.Length];
data[0] = 0x01;
Enc32be(buf.Length, data, 1);
Array.Copy(buf, 0, data, 5, buf.Length);
} else {
throw new ArgumentException(
"Unsupported object type: "
+ obj.GetType().FullName);
}
ms.Write(data, 0, data.Length);
}
return DoSHA1(ms.ToArray());
}
internal static int Read1(Stream s)
{
int x = s.ReadByte();
if (x < 0) {
throw new IOException();
}
return x;
}
internal static int Read2(Stream s)
{
int x = Read1(s);
return (x << 8) | Read1(s);
}
internal static int Read3(Stream s)
{
int x = Read1(s);
x = (x << 8) | Read1(s);
return (x << 8) | Read1(s);
}
internal static void Write1(Stream s, int x)
{
s.WriteByte((byte)x);
}
internal static void Write2(Stream s, int x)
{
s.WriteByte((byte)(x >> 8));
s.WriteByte((byte)x);
}
internal static void Write3(Stream s, int x)
{
s.WriteByte((byte)(x >> 16));
s.WriteByte((byte)(x >> 8));
s.WriteByte((byte)x);
}
internal static void Write4(Stream s, int x)
{
s.WriteByte((byte)(x >> 24));
s.WriteByte((byte)(x >> 16));
s.WriteByte((byte)(x >> 8));
s.WriteByte((byte)x);
}
internal static void Write4(Stream s, uint x)
{
Write4(s, (int)x);
}
internal static void WriteExtension(Stream s, int extType, byte[] val)
{
if (val.Length > 0xFFFF) {
throw new ArgumentException("Oversized extension");
}
Write2(s, extType);
Write2(s, val.Length);
s.Write(val, 0, val.Length);
}
static RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
static byte[] rngBuf = new byte[256];
internal static void Rand(byte[] buf)
{
RNG.GetBytes(buf);
}
internal static void Rand(byte[] buf, int off, int len)
{
if (len == 0) {
return;
}
if (off == 0 && len == buf.Length) {
RNG.GetBytes(buf);
return;
}
while (len > 0) {
RNG.GetBytes(rngBuf);
int clen = Math.Min(len, rngBuf.Length);
Array.Copy(rngBuf, 0, buf, off, clen);
off += clen;
len -= clen;
}
}
internal static string VersionString(int v)
{
if (v == 0x0200) {
return "SSLv2";
} else if (v == 0x0300) {
return "SSLv3";
} else if ((v >> 8) == 0x03) {
return "TLSv1." + ((v & 0xFF) - 1);
} else {
return string.Format(
"UNKNOWN_VERSION:0x{0:X4}", v);
}
}
internal static bool Equals(int[] t1, int[] t2)
{
if (t1 == t2) {
return true;
}
if (t1 == null || t2 == null) {
return false;
}
int n = t1.Length;
if (t2.Length != n) {
return false;
}
for (int i = 0; i < n; i ++) {
if (t1[i] != t2[i]) {
return false;
}
}
return true;
}
internal static void Reverse<T>(T[] tab)
{
if (tab == null || tab.Length <= 1) {
return;
}
int n = tab.Length;
for (int i = 0; i < (n >> 1); i ++) {
T x = tab[i];
tab[i] = tab[n - 1 - i];
tab[n - 1 - i] = x;
}
}
const string B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz0123456789+/";
static string ToBase64(byte[] buf, int off, int len)
{
char[] tc = new char[((len + 2) / 3) << 2];
for (int i = 0, j = 0; i < len; i += 3) {
if ((i + 3) <= len) {
int x = Dec24be(buf, off + i);
tc[j ++] = B64[x >> 18];
tc[j ++] = B64[(x >> 12) & 0x3F];
tc[j ++] = B64[(x >> 6) & 0x3F];
tc[j ++] = B64[x & 0x3F];
} else if ((i + 2) == len) {
int x = Dec16be(buf, off + i);
tc[j ++] = B64[x >> 10];
tc[j ++] = B64[(x >> 4) & 0x3F];
tc[j ++] = B64[(x << 2) & 0x3F];
tc[j ++] = '=';
} else if ((i + 1) == len) {
int x = buf[off + i];
tc[j ++] = B64[(x >> 2) & 0x3F];
tc[j ++] = B64[(x << 4) & 0x3F];
tc[j ++] = '=';
tc[j ++] = '=';
}
}
return new string(tc);
}
internal static void WritePEM(TextWriter w, string objType, byte[] buf)
{
w.WriteLine("-----BEGIN {0}-----", objType.ToUpperInvariant());
int n = buf.Length;
for (int i = 0; i < n; i += 57) {
int len = Math.Min(57, n - i);
w.WriteLine(ToBase64(buf, i, len));
}
w.WriteLine("-----END {0}-----", objType.ToUpperInvariant());
}
internal static string ToPEM(string objType, byte[] buf)
{
return ToPEM(objType, buf, "\n");
}
internal static string ToPEM(string objType, byte[] buf, string nl)
{
StringWriter w = new StringWriter();
w.NewLine = nl;
WritePEM(w, objType, buf);
return w.ToString();
}
/*
* Compute bit length for an integer (unsigned big-endian).
* Bit length is the smallest integer k such that the integer
* value is less than 2^k.
*/
internal static int BitLength(byte[] v)
{
for (int k = 0; k < v.Length; k ++) {
int b = v[k];
if (b != 0) {
int bitLen = (v.Length - k) << 3;
while (b < 0x80) {
b <<= 1;
bitLen --;
}
return bitLen;
}
}
return 0;
}
/*
* Compute "adjusted" bit length for an integer (unsigned
* big-endian). The adjusted bit length is the integer k
* such that 2^k is closest to the integer value (if the
* integer is x = 3*2^m, then the adjusted bit length is
* m+2, not m+1).
*/
internal static int AdjustedBitLength(byte[] v)
{
for (int k = 0; k < v.Length; k ++) {
int b = v[k];
if (b == 0) {
continue;
}
int bitLen = (v.Length - k) << 3;
if (b == 1) {
if ((k + 1) == v.Length) {
return 0;
}
bitLen -= 7;
if (v[k + 1] < 0x80) {
bitLen --;
}
} else {
while (b < 0x80) {
b <<= 1;
bitLen --;
}
if (b < 0xC0) {
bitLen --;
}
}
return bitLen;
}
return 0;
}
internal static V[] ToValueArray<K, V>(IDictionary<K, V> s)
{
V[] vv = new V[s.Count];
int k = 0;
foreach (V v in s.Values) {
vv[k ++] = v;
}
return vv;
}
}
| |
// <copyright file="EventFiringWebDriver.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.Drawing;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Support.Events
{
/// <summary>
/// A wrapper around an arbitrary WebDriver instance which supports registering for
/// events, e.g. for logging purposes.
/// </summary>
public class EventFiringWebDriver : IWebDriver, IJavaScriptExecutor, ITakesScreenshot, IWrapsDriver
{
private IWebDriver driver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringWebDriver"/> class.
/// </summary>
/// <param name="parentDriver">The driver to register events for.</param>
public EventFiringWebDriver(IWebDriver parentDriver)
{
this.driver = parentDriver;
}
/// <summary>
/// Fires before the driver begins navigation.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> Navigating;
/// <summary>
/// Fires after the driver completes navigation
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> Navigated;
/// <summary>
/// Fires before the driver begins navigation back one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatingBack;
/// <summary>
/// Fires after the driver completes navigation back one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatedBack;
/// <summary>
/// Fires before the driver begins navigation forward one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatingForward;
/// <summary>
/// Fires after the driver completes navigation forward one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatedForward;
/// <summary>
/// Fires before the driver clicks on an element.
/// </summary>
public event EventHandler<WebElementEventArgs> ElementClicking;
/// <summary>
/// Fires after the driver has clicked on an element.
/// </summary>
public event EventHandler<WebElementEventArgs> ElementClicked;
/// <summary>
/// Fires before the driver changes the value of an element via Clear(), SendKeys() or Toggle().
/// </summary>
public event EventHandler<WebElementValueEventArgs> ElementValueChanging;
/// <summary>
/// Fires after the driver has changed the value of an element via Clear(), SendKeys() or Toggle().
/// </summary>
public event EventHandler<WebElementValueEventArgs> ElementValueChanged;
/// <summary>
/// Fires before the driver starts to find an element.
/// </summary>
public event EventHandler<FindElementEventArgs> FindingElement;
/// <summary>
/// Fires after the driver completes finding an element.
/// </summary>
public event EventHandler<FindElementEventArgs> FindElementCompleted;
/// <summary>
/// Fires before a script is executed.
/// </summary>
public event EventHandler<WebDriverScriptEventArgs> ScriptExecuting;
/// <summary>
/// Fires after a script is executed.
/// </summary>
public event EventHandler<WebDriverScriptEventArgs> ScriptExecuted;
/// <summary>
/// Fires when an exception is thrown.
/// </summary>
public event EventHandler<WebDriverExceptionEventArgs> ExceptionThrown;
/// <summary>
/// Gets the <see cref="IWebDriver"/> wrapped by this EventsFiringWebDriver instance.
/// </summary>
public IWebDriver WrappedDriver
{
get { return this.driver; }
}
/// <summary>
/// Gets or sets the URL the browser is currently displaying.
/// </summary>
/// <remarks>
/// Setting the <see cref="Url"/> property will load a new web page in the current browser window.
/// This is done using an HTTP GET operation, and the method will block until the
/// load is complete. This will follow redirects issued either by the server or
/// as a meta-redirect from within the returned HTML. Should a meta-redirect "rest"
/// for any duration of time, it is best to wait until this timeout is over, since
/// should the underlying page change while your test is executing the results of
/// future calls against this interface will be against the freshly loaded page.
/// </remarks>
/// <seealso cref="INavigation.GoToUrl(string)"/>
/// <seealso cref="INavigation.GoToUrl(System.Uri)"/>
public string Url
{
get
{
string url = string.Empty;
try
{
url = this.driver.Url;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return url;
}
set
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.driver, value);
this.OnNavigating(e);
this.driver.Url = value;
this.OnNavigated(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
}
/// <summary>
/// Gets the title of the current browser window.
/// </summary>
public string Title
{
get
{
string title = string.Empty;
try
{
title = this.driver.Title;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return title;
}
}
/// <summary>
/// Gets the source of the page last loaded by the browser.
/// </summary>
/// <remarks>
/// If the page has been modified after loading (for example, by JavaScript)
/// there is no guarantee that the returned text is that of the modified page.
/// Please consult the documentation of the particular driver being used to
/// determine whether the returned text reflects the current state of the page
/// or the text last sent by the web server. The page source returned is a
/// representation of the underlying DOM: do not expect it to be formatted
/// or escaped in the same way as the response sent from the web server.
/// </remarks>
public string PageSource
{
get
{
string source = string.Empty;
try
{
source = this.driver.PageSource;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return source;
}
}
/// <summary>
/// Gets the current window handle, which is an opaque handle to this
/// window that uniquely identifies it within this driver instance.
/// </summary>
public string CurrentWindowHandle
{
get
{
string handle = string.Empty;
try
{
handle = this.driver.CurrentWindowHandle;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return handle;
}
}
/// <summary>
/// Gets the window handles of open browser windows.
/// </summary>
public ReadOnlyCollection<string> WindowHandles
{
get
{
ReadOnlyCollection<string> handles = null;
try
{
handles = this.driver.WindowHandles;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return handles;
}
}
/// <summary>
/// Close the current window, quitting the browser if it is the last window currently open.
/// </summary>
public void Close()
{
try
{
this.driver.Close();
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
/// <summary>
/// Quits this driver, closing every associated window.
/// </summary>
public void Quit()
{
try
{
this.driver.Quit();
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
/// <summary>
/// Instructs the driver to change its settings.
/// </summary>
/// <returns>An <see cref="IOptions"/> object allowing the user to change
/// the settings of the driver.</returns>
public IOptions Manage()
{
return new EventFiringOptions(this);
}
/// <summary>
/// Instructs the driver to navigate the browser to another location.
/// </summary>
/// <returns>An <see cref="INavigation"/> object allowing the user to access
/// the browser's history and to navigate to a given URL.</returns>
public INavigation Navigate()
{
return new EventFiringNavigation(this);
}
/// <summary>
/// Instructs the driver to send future commands to a different frame or window.
/// </summary>
/// <returns>An <see cref="ITargetLocator"/> object which can be used to select
/// a frame or window.</returns>
public ITargetLocator SwitchTo()
{
return new EventFiringTargetLocator(this);
}
/// <summary>
/// Find the first <see cref="IWebElement"/> using the given method.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
/// <exception cref="NoSuchElementException">If no element matches the criteria.</exception>
public IWebElement FindElement(By by)
{
IWebElement wrappedElement = null;
try
{
FindElementEventArgs e = new FindElementEventArgs(this.driver, by);
this.OnFindingElement(e);
IWebElement element = this.driver.FindElement(by);
this.OnFindElementCompleted(e);
wrappedElement = this.WrapElement(element);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return wrappedElement;
}
/// <summary>
/// Find all <see cref="IWebElement">IWebElements</see> within the current context
/// using the given mechanism.
/// </summary>
/// <param name="by">The locating mechanism to use.</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 ReadOnlyCollection<IWebElement> FindElements(By by)
{
List<IWebElement> wrappedElementList = new List<IWebElement>();
try
{
FindElementEventArgs e = new FindElementEventArgs(this.driver, by);
this.OnFindingElement(e);
ReadOnlyCollection<IWebElement> elements = this.driver.FindElements(by);
this.OnFindElementCompleted(e);
foreach (IWebElement element in elements)
{
IWebElement wrappedElement = this.WrapElement(element);
wrappedElementList.Add(wrappedElement);
}
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return wrappedElementList.AsReadOnly();
}
/// <summary>
/// Frees all managed and unmanaged resources used by this instance.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Executes JavaScript in the context of the currently selected frame or window.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
/// <remarks>
/// <para>
/// The <see cref="ExecuteScript"/>method executes JavaScript in the context of
/// the currently selected frame or window. This means that "document" will refer
/// to the current document. If the script has a return value, then the following
/// steps will be taken:
/// </para>
/// <para>
/// <list type="bullet">
/// <item><description>For an HTML element, this method returns a <see cref="IWebElement"/></description></item>
/// <item><description>For a number, a <see cref="long"/> is returned</description></item>
/// <item><description>For a boolean, a <see cref="bool"/> is returned</description></item>
/// <item><description>For all other cases a <see cref="string"/> is returned.</description></item>
/// <item><description>For an array,we check the first element, and attempt to return a
/// <see cref="List{T}"/> of that type, following the rules above. Nested lists are not
/// supported.</description></item>
/// <item><description>If the value is null or there is no return value,
/// <see langword="null"/> is returned.</description></item>
/// </list>
/// </para>
/// <para>
/// Arguments must be a number (which will be converted to a <see cref="long"/>),
/// a <see cref="bool"/>, a <see cref="string"/> or a <see cref="IWebElement"/>.
/// An exception will be thrown if the arguments do not meet these criteria.
/// The arguments will be made available to the JavaScript via the "arguments" magic
/// variable, as if the function were called via "Function.apply"
/// </para>
/// </remarks>
public object ExecuteScript(string script, params object[] args)
{
IJavaScriptExecutor javascriptDriver = this.driver as IJavaScriptExecutor;
if (javascriptDriver == null)
{
throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
object scriptResult = null;
try
{
object[] unwrappedArgs = UnwrapElementArguments(args);
WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.driver, script);
this.OnScriptExecuting(e);
scriptResult = javascriptDriver.ExecuteScript(script, unwrappedArgs);
this.OnScriptExecuted(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return scriptResult;
}
/// <summary>
/// Executes JavaScript asynchronously in the context of the currently selected frame or window.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
public object ExecuteAsyncScript(string script, params object[] args)
{
object scriptResult = null;
IJavaScriptExecutor javascriptDriver = this.driver as IJavaScriptExecutor;
if (javascriptDriver == null)
{
throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
try
{
object[] unwrappedArgs = UnwrapElementArguments(args);
WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.driver, script);
this.OnScriptExecuting(e);
scriptResult = javascriptDriver.ExecuteAsyncScript(script, unwrappedArgs);
this.OnScriptExecuted(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return scriptResult;
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
ITakesScreenshot screenshotDriver = this.driver as ITakesScreenshot;
if (this.driver == null)
{
throw new NotSupportedException("Underlying driver instance does not support taking screenshots");
}
Screenshot screen = null;
screen = screenshotDriver.GetScreenshot();
return screen;
}
/// <summary>
/// Frees all managed and, optionally, unmanaged resources used by this instance.
/// </summary>
/// <param name="disposing"><see langword="true"/> to dispose of only managed resources;
/// <see langword="false"/> to dispose of managed and unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.driver.Dispose();
}
}
/// <summary>
/// Raises the <see cref="Navigating"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigating(WebDriverNavigationEventArgs e)
{
if (this.Navigating != null)
{
this.Navigating(this, e);
}
}
/// <summary>
/// Raises the <see cref="Navigated"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigated(WebDriverNavigationEventArgs e)
{
if (this.Navigated != null)
{
this.Navigated(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatingBack"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatingBack(WebDriverNavigationEventArgs e)
{
if (this.NavigatingBack != null)
{
this.NavigatingBack(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatedBack"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatedBack(WebDriverNavigationEventArgs e)
{
if (this.NavigatedBack != null)
{
this.NavigatedBack(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatingForward"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatingForward(WebDriverNavigationEventArgs e)
{
if (this.NavigatingForward != null)
{
this.NavigatingForward(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatedForward"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatedForward(WebDriverNavigationEventArgs e)
{
if (this.NavigatedForward != null)
{
this.NavigatedForward(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementClicking"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
protected virtual void OnElementClicking(WebElementEventArgs e)
{
if (this.ElementClicking != null)
{
this.ElementClicking(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementClicked"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
protected virtual void OnElementClicked(WebElementEventArgs e)
{
if (this.ElementClicked != null)
{
this.ElementClicked(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementValueChanging"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementValueEventArgs"/> that contains the event data.</param>
protected virtual void OnElementValueChanging(WebElementValueEventArgs e)
{
if (this.ElementValueChanging != null)
{
this.ElementValueChanging(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementValueChanged"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementValueEventArgs"/> that contains the event data.</param>
protected virtual void OnElementValueChanged(WebElementValueEventArgs e)
{
if (this.ElementValueChanged != null)
{
this.ElementValueChanged(this, e);
}
}
/// <summary>
/// Raises the <see cref="FindingElement"/> event.
/// </summary>
/// <param name="e">A <see cref="FindElementEventArgs"/> that contains the event data.</param>
protected virtual void OnFindingElement(FindElementEventArgs e)
{
if (this.FindingElement != null)
{
this.FindingElement(this, e);
}
}
/// <summary>
/// Raises the <see cref="FindElementCompleted"/> event.
/// </summary>
/// <param name="e">A <see cref="FindElementEventArgs"/> that contains the event data.</param>
protected virtual void OnFindElementCompleted(FindElementEventArgs e)
{
if (this.FindElementCompleted != null)
{
this.FindElementCompleted(this, e);
}
}
/// <summary>
/// Raises the <see cref="ScriptExecuting"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverScriptEventArgs"/> that contains the event data.</param>
protected virtual void OnScriptExecuting(WebDriverScriptEventArgs e)
{
if (this.ScriptExecuting != null)
{
this.ScriptExecuting(this, e);
}
}
/// <summary>
/// Raises the <see cref="ScriptExecuted"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverScriptEventArgs"/> that contains the event data.</param>
protected virtual void OnScriptExecuted(WebDriverScriptEventArgs e)
{
if (this.ScriptExecuted != null)
{
this.ScriptExecuted(this, e);
}
}
/// <summary>
/// Raises the <see cref="ExceptionThrown"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverExceptionEventArgs"/> that contains the event data.</param>
protected virtual void OnException(WebDriverExceptionEventArgs e)
{
if (this.ExceptionThrown != null)
{
this.ExceptionThrown(this, e);
}
}
private static object[] UnwrapElementArguments(object[] args)
{
// Walk the args: the various drivers expect unwrapped versions of the elements
List<object> unwrappedArgs = new List<object>();
foreach (object arg in args)
{
IWrapsElement eventElementArg = arg as IWrapsElement;
if (eventElementArg != null)
{
unwrappedArgs.Add(eventElementArg.WrappedElement);
}
else
{
unwrappedArgs.Add(arg);
}
}
return unwrappedArgs.ToArray();
}
private IWebElement WrapElement(IWebElement underlyingElement)
{
IWebElement wrappedElement = new EventFiringWebElement(this, underlyingElement);
return wrappedElement;
}
/// <summary>
/// Provides a mechanism for Navigating with the driver.
/// </summary>
private class EventFiringNavigation : INavigation
{
private EventFiringWebDriver parentDriver;
private INavigation wrappedNavigation;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringNavigation"/> class
/// </summary>
/// <param name="driver">Driver in use</param>
public EventFiringNavigation(EventFiringWebDriver driver)
{
this.parentDriver = driver;
this.wrappedNavigation = this.parentDriver.WrappedDriver.Navigate();
}
/// <summary>
/// Move the browser back
/// </summary>
public void Back()
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
this.parentDriver.OnNavigatingBack(e);
this.wrappedNavigation.Back();
this.parentDriver.OnNavigatedBack(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Move the browser forward
/// </summary>
public void Forward()
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
this.parentDriver.OnNavigatingForward(e);
this.wrappedNavigation.Forward();
this.parentDriver.OnNavigatedForward(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Navigate to a url for your test
/// </summary>
/// <param name="url">String of where you want the browser to go to</param>
public void GoToUrl(string url)
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver, url);
this.parentDriver.OnNavigating(e);
this.wrappedNavigation.GoToUrl(url);
this.parentDriver.OnNavigated(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Navigate to a url for your test
/// </summary>
/// <param name="url">Uri object of where you want the browser to go to</param>
public void GoToUrl(Uri url)
{
if (url == null)
{
throw new ArgumentNullException("url", "url cannot be null");
}
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver, url.ToString());
this.parentDriver.OnNavigating(e);
this.wrappedNavigation.GoToUrl(url);
this.parentDriver.OnNavigated(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Refresh the browser
/// </summary>
public void Refresh()
{
try
{
this.wrappedNavigation.Refresh();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
}
/// <summary>
/// Provides a mechanism for setting options needed for the driver during the test.
/// </summary>
private class EventFiringOptions : IOptions
{
private IOptions wrappedOptions;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringOptions"/> class
/// </summary>
/// <param name="driver">Instance of the driver currently in use</param>
public EventFiringOptions(EventFiringWebDriver driver)
{
this.wrappedOptions = driver.WrappedDriver.Manage();
}
/// <summary>
/// Gets an object allowing the user to manipulate cookies on the page.
/// </summary>
public ICookieJar Cookies
{
get { return this.wrappedOptions.Cookies; }
}
/// <summary>
/// Gets an object allowing the user to manipulate the currently-focused browser window.
/// </summary>
/// <remarks>"Currently-focused" is defined as the browser window having the window handle
/// returned when IWebDriver.CurrentWindowHandle is called.</remarks>
public IWindow Window
{
get { return this.wrappedOptions.Window; }
}
public ILogs Logs
{
get { return this.wrappedOptions.Logs; }
}
/// <summary>
/// Provides access to the timeouts defined for this driver.
/// </summary>
/// <returns>An object implementing the <see cref="ITimeouts"/> interface.</returns>
public ITimeouts Timeouts()
{
return new EventFiringTimeouts(this.wrappedOptions);
}
}
/// <summary>
/// Provides a mechanism for finding elements on the page with locators.
/// </summary>
private class EventFiringTargetLocator : ITargetLocator
{
private ITargetLocator wrappedLocator;
private EventFiringWebDriver parentDriver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringTargetLocator"/> class
/// </summary>
/// <param name="driver">The driver that is currently in use</param>
public EventFiringTargetLocator(EventFiringWebDriver driver)
{
this.parentDriver = driver;
this.wrappedLocator = this.parentDriver.WrappedDriver.SwitchTo();
}
/// <summary>
/// Move to a different frame using its index
/// </summary>
/// <param name="frameIndex">The index of the </param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Frame(int frameIndex)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Frame(frameIndex);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Move to different frame using its name
/// </summary>
/// <param name="frameName">name of the frame</param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Frame(string frameName)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Frame(frameName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Move to a frame element.
/// </summary>
/// <param name="frameElement">a previously found FRAME or IFRAME element.</param>
/// <returns>A WebDriver instance that is currently in use.</returns>
public IWebDriver Frame(IWebElement frameElement)
{
IWebDriver driver = null;
try
{
IWrapsElement wrapper = frameElement as IWrapsElement;
driver = this.wrappedLocator.Frame(wrapper.WrappedElement);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Select the parent frame of the currently selected frame.
/// </summary>
/// <returns>An <see cref="IWebDriver"/> instance focused on the specified frame.</returns>
public IWebDriver ParentFrame()
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.ParentFrame();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Change to the Window by passing in the name
/// </summary>
/// <param name="windowName">name of the window that you wish to move to</param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Window(string windowName)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Window(windowName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Creates a new browser window and switches the focus for future commands
/// of this driver to the new window.
/// </summary>
/// <param name="typeHint">The type of new browser window to be created.
/// The created window is not guaranteed to be of the requested type; if
/// the driver does not support the requested type, a new browser window
/// will be created of whatever type the driver does support.</param>
/// <returns>An <see cref="IWebDriver"/> instance focused on the new browser.</returns>
public IWebDriver NewWindow(WindowType typeHint)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.NewWindow(typeHint);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Change the active frame to the default
/// </summary>
/// <returns>Element of the default</returns>
public IWebDriver DefaultContent()
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.DefaultContent();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Finds the active element on the page and returns it
/// </summary>
/// <returns>Element that is active</returns>
public IWebElement ActiveElement()
{
IWebElement element = null;
try
{
element = this.wrappedLocator.ActiveElement();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return element;
}
/// <summary>
/// Switches to the currently active modal dialog for this particular driver instance.
/// </summary>
/// <returns>A handle to the dialog.</returns>
public IAlert Alert()
{
IAlert alert = null;
try
{
alert = this.wrappedLocator.Alert();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return alert;
}
}
/// <summary>
/// Defines the interface through which the user can define timeouts.
/// </summary>
private class EventFiringTimeouts : ITimeouts
{
private ITimeouts wrappedTimeouts;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringTimeouts"/> class
/// </summary>
/// <param name="options">The <see cref="IOptions"/> object to wrap.</param>
public EventFiringTimeouts(IOptions options)
{
this.wrappedTimeouts = options.Timeouts();
}
/// <summary>
/// Gets or sets the implicit wait timeout, which is the amount of time the
/// driver should wait when searching for an element if it is not immediately
/// present.
/// </summary>
/// <remarks>
/// When searching for a single element, the driver should poll the page
/// until the element has been found, or this timeout expires before throwing
/// a <see cref="NoSuchElementException"/>. When searching for multiple elements,
/// the driver should poll the page until at least one element has been found
/// or this timeout has expired.
/// <para>
/// Increasing the implicit wait timeout should be used judiciously as it
/// will have an adverse effect on test run time, especially when used with
/// slower location strategies like XPath.
/// </para>
/// </remarks>
public TimeSpan ImplicitWait
{
get { return this.wrappedTimeouts.ImplicitWait; }
set { this.wrappedTimeouts.ImplicitWait = value; }
}
/// <summary>
/// Gets or sets the asynchronous script timeout, which is the amount
/// of time the driver should wait when executing JavaScript asynchronously.
/// This timeout only affects the <see cref="IJavaScriptExecutor.ExecuteAsyncScript(string, object[])"/>
/// method.
/// </summary>
public TimeSpan AsynchronousJavaScript
{
get { return this.wrappedTimeouts.AsynchronousJavaScript; }
set { this.wrappedTimeouts.AsynchronousJavaScript = value; }
}
/// <summary>
/// Gets or sets the page load timeout, which is the amount of time the driver
/// should wait for a page to load when setting the <see cref="IWebDriver.Url"/>
/// property.
/// </summary>
public TimeSpan PageLoad
{
get { return this.wrappedTimeouts.PageLoad; }
set { this.wrappedTimeouts.PageLoad = value; }
}
}
/// <summary>
/// EventFiringWebElement allows you to have access to specific items that are found on the page
/// </summary>
private class EventFiringWebElement : IWebElement, IWrapsElement
{
private IWebElement underlyingElement;
private EventFiringWebDriver parentDriver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringWebElement"/> class.
/// </summary>
/// <param name="driver">The <see cref="EventFiringWebDriver"/> instance hosting this element.</param>
/// <param name="element">The <see cref="IWebElement"/> to wrap for event firing.</param>
public EventFiringWebElement(EventFiringWebDriver driver, IWebElement element)
{
this.underlyingElement = element;
this.parentDriver = driver;
}
/// <summary>
/// Gets the underlying wrapped <see cref="IWebElement"/>.
/// </summary>
public IWebElement WrappedElement
{
get { return this.underlyingElement; }
}
/// <summary>
/// Gets the DOM Tag of element
/// </summary>
public string TagName
{
get
{
string tagName = string.Empty;
try
{
tagName = this.underlyingElement.TagName;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return tagName;
}
}
/// <summary>
/// Gets the text from the element
/// </summary>
public string Text
{
get
{
string text = string.Empty;
try
{
text = this.underlyingElement.Text;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return text;
}
}
/// <summary>
/// Gets a value indicating whether an element is currently enabled
/// </summary>
public bool Enabled
{
get
{
bool enabled = false;
try
{
enabled = this.underlyingElement.Enabled;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return enabled;
}
}
/// <summary>
/// Gets a value indicating whether this element is selected or not. This operation only applies to input elements such as checkboxes, options in a select and radio buttons.
/// </summary>
public bool Selected
{
get
{
bool selected = false;
try
{
selected = this.underlyingElement.Selected;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return selected;
}
}
/// <summary>
/// Gets the Location of an element and returns a Point object
/// </summary>
public Point Location
{
get
{
Point location = default(Point);
try
{
location = this.underlyingElement.Location;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return location;
}
}
/// <summary>
/// Gets the <see cref="Size"/> of the element on the page
/// </summary>
public Size Size
{
get
{
Size size = default(Size);
try
{
size = this.underlyingElement.Size;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return size;
}
}
/// <summary>
/// Gets a value indicating whether the element is currently being displayed
/// </summary>
public bool Displayed
{
get
{
bool displayed = false;
try
{
displayed = this.underlyingElement.Displayed;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return displayed;
}
}
/// <summary>
/// Gets the underlying EventFiringWebDriver for this element.
/// </summary>
protected EventFiringWebDriver ParentDriver
{
get { return this.parentDriver; }
}
/// <summary>
/// Method to clear the text out of an Input element
/// </summary>
public void Clear()
{
try
{
WebElementValueEventArgs e = new WebElementValueEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, null);
this.parentDriver.OnElementValueChanging(e);
this.underlyingElement.Clear();
this.parentDriver.OnElementValueChanged(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Method for sending native key strokes to the browser
/// </summary>
/// <param name="text">String containing what you would like to type onto the screen</param>
public void SendKeys(string text)
{
try
{
WebElementValueEventArgs e = new WebElementValueEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, text);
this.parentDriver.OnElementValueChanging(e);
this.underlyingElement.SendKeys(text);
this.parentDriver.OnElementValueChanged(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// If this current element is a form, or an element within a form, then this will be submitted to the remote server.
/// If this causes the current page to change, then this method will block until the new page is loaded.
/// </summary>
public void Submit()
{
try
{
this.underlyingElement.Submit();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Click this element. If this causes a new page to load, this method will block until
/// the page has loaded. At this point, you should discard all references to this element
/// and any further operations performed on this element will have undefined behavior unless
/// you know that the element and the page will still be present. If this element is not
/// clickable, then this operation is a no-op since it's pretty common for someone to
/// accidentally miss the target when clicking in Real Life
/// </summary>
public void Click()
{
try
{
WebElementEventArgs e = new WebElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement);
this.parentDriver.OnElementClicking(e);
this.underlyingElement.Click();
this.parentDriver.OnElementClicked(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// If this current element is a form, or an element within a form, then this will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded.
/// </summary>
/// <param name="attributeName">Attribute you wish to get details of</param>
/// <returns>The attribute's current value or null if the value is not set.</returns>
public string GetAttribute(string attributeName)
{
string attribute = string.Empty;
try
{
attribute = this.underlyingElement.GetAttribute(attributeName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return attribute;
}
/// <summary>
/// Gets the value of a JavaScript property of this element.
/// </summary>
/// <param name="propertyName">The name JavaScript the JavaScript property to get the value of.</param>
/// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the
/// value is not set or the property does not exist.</returns>
public string GetProperty(string propertyName)
{
string elementProperty = string.Empty;
try
{
elementProperty = this.underlyingElement.GetProperty(propertyName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return elementProperty;
}
/// <summary>
/// Method to return the value of a CSS Property
/// </summary>
/// <param name="propertyName">CSS property key</param>
/// <returns>string value of the CSS property</returns>
public string GetCssValue(string propertyName)
{
string cssValue = string.Empty;
try
{
cssValue = this.underlyingElement.GetCssValue(propertyName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return cssValue;
}
/// <summary>
/// Finds the first element in the page that matches the <see cref="By"/> object
/// </summary>
/// <param name="by">By mechanism to find the element</param>
/// <returns>IWebElement object so that you can interaction that object</returns>
public IWebElement FindElement(By by)
{
IWebElement wrappedElement = null;
try
{
FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, by);
this.parentDriver.OnFindingElement(e);
IWebElement element = this.underlyingElement.FindElement(by);
this.parentDriver.OnFindElementCompleted(e);
wrappedElement = this.parentDriver.WrapElement(element);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return wrappedElement;
}
/// <summary>
/// Finds the elements on the page by using the <see cref="By"/> object and returns a ReadOnlyCollection of the Elements on the page
/// </summary>
/// <param name="by">By mechanism to find the element</param>
/// <returns>ReadOnlyCollection of IWebElement</returns>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
List<IWebElement> wrappedElementList = new List<IWebElement>();
try
{
FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, by);
this.parentDriver.OnFindingElement(e);
ReadOnlyCollection<IWebElement> elements = this.underlyingElement.FindElements(by);
this.parentDriver.OnFindElementCompleted(e);
foreach (IWebElement element in elements)
{
IWebElement wrappedElement = this.parentDriver.WrapElement(element);
wrappedElementList.Add(wrappedElement);
}
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return wrappedElementList.AsReadOnly();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System.Net
{
// More sophisticated password cache that stores multiple
// name-password pairs and associates these with host/realm.
public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable
{
private readonly Dictionary<CredentialKey, NetworkCredential> _cache = new Dictionary<CredentialKey, NetworkCredential>();
private readonly Dictionary<CredentialHostKey, NetworkCredential> _cacheForHosts = new Dictionary<CredentialHostKey, NetworkCredential>();
internal int _version;
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.CredentialCache'/> class.
/// </para>
/// </devdoc>
public CredentialCache()
{
}
/// <devdoc>
/// <para>
/// Adds a <see cref='System.Net.NetworkCredential'/> instance to the credential cache.
/// </para>
/// </devdoc>
public void Add(Uri uriPrefix, string authenticationType, NetworkCredential credential)
{
// Parameter validation
if (uriPrefix == null)
{
throw new ArgumentNullException(nameof(uriPrefix));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
++_version;
CredentialKey key = new CredentialKey(uriPrefix, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
}
_cache.Add(key, credential);
}
public void Add(string host, int port, string authenticationType, NetworkCredential credential)
{
// Parameter validation
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (host.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host"));
}
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
++_version;
CredentialHostKey key = new CredentialHostKey(host, port, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
}
_cacheForHosts.Add(key, credential);
}
/// <devdoc>
/// <para>
/// Removes a <see cref='System.Net.NetworkCredential'/> instance from the credential cache.
/// </para>
/// </devdoc>
public void Remove(Uri uriPrefix, string authenticationType)
{
if (uriPrefix == null || authenticationType == null)
{
// These couldn't possibly have been inserted into
// the cache because of the test in Add().
return;
}
++_version;
CredentialKey key = new CredentialKey(uriPrefix, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
}
_cache.Remove(key);
}
public void Remove(string host, int port, string authenticationType)
{
if (host == null || authenticationType == null)
{
// These couldn't possibly have been inserted into
// the cache because of the test in Add().
return;
}
if (port < 0)
{
return;
}
++_version;
CredentialHostKey key = new CredentialHostKey(host, port, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
}
_cacheForHosts.Remove(key);
}
/// <devdoc>
/// <para>
/// Returns the <see cref='System.Net.NetworkCredential'/>
/// instance associated with the supplied Uri and
/// authentication type.
/// </para>
/// </devdoc>
public NetworkCredential GetCredential(Uri uriPrefix, string authenticationType)
{
if (uriPrefix == null)
{
throw new ArgumentNullException(nameof(uriPrefix));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authenticationType + "\")");
}
int longestMatchPrefix = -1;
NetworkCredential mostSpecificMatch = null;
// Enumerate through every credential in the cache
foreach (KeyValuePair<CredentialKey, NetworkCredential> pair in _cache)
{
CredentialKey key = pair.Key;
// Determine if this credential is applicable to the current Uri/AuthType
if (key.Match(uriPrefix, authenticationType))
{
int prefixLen = key.UriPrefixLength;
// Check if the match is better than the current-most-specific match
if (prefixLen > longestMatchPrefix)
{
// Yes: update the information about currently preferred match
longestMatchPrefix = prefixLen;
mostSpecificMatch = pair.Value;
}
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch == null) ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")"));
}
return mostSpecificMatch;
}
public NetworkCredential GetCredential(string host, int port, string authenticationType)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (host.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host"));
}
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() + "\", authenticationType=\"" + authenticationType + "\")");
}
NetworkCredential match = null;
// Enumerate through every credential in the cache
foreach (KeyValuePair<CredentialHostKey, NetworkCredential> pair in _cacheForHosts)
{
CredentialHostKey key = pair.Key;
// Determine if this credential is applicable to the current Uri/AuthType
if (key.Match(host, port, authenticationType))
{
match = pair.Value;
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential returning " + ((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")"));
}
return match;
}
public IEnumerator GetEnumerator()
{
return new CredentialEnumerator(this, _cache, _cacheForHosts, _version);
}
/// <devdoc>
/// <para>
/// Gets the default system credentials from the <see cref='System.Net.CredentialCache'/>.
/// </para>
/// </devdoc>
public static ICredentials DefaultCredentials
{
get
{
return SystemNetworkCredential.s_defaultCredential;
}
}
public static NetworkCredential DefaultNetworkCredentials
{
get
{
return SystemNetworkCredential.s_defaultCredential;
}
}
private class CredentialEnumerator : IEnumerator
{
private CredentialCache _cache;
private ICredentials[] _array;
private int _index = -1;
private int _version;
internal CredentialEnumerator(CredentialCache cache, Dictionary<CredentialKey, NetworkCredential> table, Dictionary<CredentialHostKey, NetworkCredential> hostTable, int version)
{
_cache = cache;
_array = new ICredentials[table.Count + hostTable.Count];
((ICollection)table.Values).CopyTo(_array, 0);
((ICollection)hostTable.Values).CopyTo(_array, table.Count);
_version = version;
}
object IEnumerator.Current
{
get
{
if (_index < 0 || _index >= _array.Length)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_version != _cache._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
return _array[_index];
}
}
bool IEnumerator.MoveNext()
{
if (_version != _cache._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (++_index < _array.Length)
{
return true;
}
_index = _array.Length;
return false;
}
void IEnumerator.Reset()
{
_index = -1;
}
}
}
// Abstraction for credentials in password-based
// authentication schemes (basic, digest, NTLM, Kerberos).
//
// Note that this is not applicable to public-key based
// systems such as SSL client authentication.
//
// "Password" here may be the clear text password or it
// could be a one-way hash that is sufficient to
// authenticate, as in HTTP/1.1 digest.
internal class SystemNetworkCredential : NetworkCredential
{
internal static readonly SystemNetworkCredential s_defaultCredential = new SystemNetworkCredential();
// We want reference equality to work. Making this private is a good way to guarantee that.
private SystemNetworkCredential() :
base(string.Empty, string.Empty, string.Empty)
{
}
}
internal class CredentialHostKey : IEquatable<CredentialHostKey>
{
public readonly string Host;
public readonly string AuthenticationType;
public readonly int Port;
internal CredentialHostKey(string host, int port, string authenticationType)
{
Host = host;
Port = port;
AuthenticationType = authenticationType;
}
internal bool Match(string host, int port, string authenticationType)
{
if (host == null || authenticationType == null)
{
return false;
}
// If the protocols don't match, this credential is not applicable for the given Uri.
if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) ||
!string.Equals(Host, host, StringComparison.OrdinalIgnoreCase) ||
port != Port)
{
return false;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Match(" + Host.ToString() + ":" + Port.ToString() + " & " + host.ToString() + ":" + port.ToString() + ")");
}
return true;
}
private int _hashCode = 0;
private bool _computedHashCode = false;
public override int GetHashCode()
{
if (!_computedHashCode)
{
// Compute HashCode on demand
_hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + Host.ToUpperInvariant().GetHashCode() + Port.GetHashCode();
_computedHashCode = true;
}
return _hashCode;
}
public bool Equals(CredentialHostKey other)
{
if (other == null)
{
return false;
}
bool equals =
string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase) &&
Port == other.Port;
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString());
}
return equals;
}
public override bool Equals(object comparand)
{
return Equals(comparand as CredentialHostKey);
}
public override string ToString()
{
return "[" + Host.Length.ToString(NumberFormatInfo.InvariantInfo) + "]:" + Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + LoggingHash.ObjectToString(AuthenticationType);
}
}
internal class CredentialKey : IEquatable<CredentialKey>
{
public readonly Uri UriPrefix;
public readonly int UriPrefixLength = -1;
public readonly string AuthenticationType;
private int _hashCode = 0;
private bool _computedHashCode = false;
internal CredentialKey(Uri uriPrefix, string authenticationType)
{
UriPrefix = uriPrefix;
UriPrefixLength = UriPrefix.ToString().Length;
AuthenticationType = authenticationType;
}
internal bool Match(Uri uri, string authenticationType)
{
if (uri == null || authenticationType == null)
{
return false;
}
// If the protocols don't match, this credential is not applicable for the given Uri.
if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")");
}
return IsPrefix(uri, UriPrefix);
}
// IsPrefix (Uri)
//
// Determines whether <prefixUri> is a prefix of this URI. A prefix
// match is defined as:
//
// scheme match
// + host match
// + port match, if any
// + <prefix> path is a prefix of <URI> path, if any
//
// Returns:
// True if <prefixUri> is a prefix of this URI
internal bool IsPrefix(Uri uri, Uri prefixUri)
{
if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port)
{
return false;
}
int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/');
if (prefixLen > uri.AbsolutePath.LastIndexOf('/'))
{
return false;
}
return String.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase) == 0;
}
public override int GetHashCode()
{
if (!_computedHashCode)
{
// Compute HashCode on demand
_hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + UriPrefixLength + UriPrefix.GetHashCode();
_computedHashCode = true;
}
return _hashCode;
}
public bool Equals(CredentialKey other)
{
if (other == null)
{
return false;
}
bool equals =
string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
UriPrefix.Equals(other.UriPrefix);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString());
}
return equals;
}
public override bool Equals(object comparand)
{
return Equals(comparand as CredentialKey);
}
public override string ToString()
{
return "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + LoggingHash.ObjectToString(UriPrefix) + ":" + LoggingHash.ObjectToString(AuthenticationType);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Attributes for debugger
**
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System.Diagnostics
{
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
public DebuggerStepThroughAttribute() { }
}
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerHiddenAttribute : Attribute
{
public DebuggerHiddenAttribute() { }
}
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)]
public sealed class DebuggerNonUserCodeAttribute : Attribute
{
public DebuggerNonUserCodeAttribute() { }
}
// Attribute class used by the compiler to mark modules.
// If present, then debugging information for everything in the
// assembly was generated by the compiler, and will be preserved
// by the Runtime so that the debugger can provide full functionality
// in the case of JIT attach. If not present, then the compiler may
// or may not have included debugging information, and the Runtime
// won't preserve the debugging info, which will make debugging after
// a JIT attach difficult.
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module, AllowMultiple = false)]
public sealed class DebuggableAttribute : Attribute
{
[Flags]
public enum DebuggingModes
{
None = 0x0,
Default = 0x1,
DisableOptimizations = 0x100,
IgnoreSymbolStoreSequencePoints = 0x2,
EnableEditAndContinue = 0x4
}
private DebuggingModes m_debuggingModes;
public DebuggableAttribute(bool isJITTrackingEnabled,
bool isJITOptimizerDisabled)
{
m_debuggingModes = 0;
if (isJITTrackingEnabled)
{
m_debuggingModes |= DebuggingModes.Default;
}
if (isJITOptimizerDisabled)
{
m_debuggingModes |= DebuggingModes.DisableOptimizations;
}
}
public DebuggableAttribute(DebuggingModes modes)
{
m_debuggingModes = modes;
}
public bool IsJITTrackingEnabled
{
get { return ((m_debuggingModes & DebuggingModes.Default) != 0); }
}
public bool IsJITOptimizerDisabled
{
get { return ((m_debuggingModes & DebuggingModes.DisableOptimizations) != 0); }
}
public DebuggingModes DebuggingFlags
{
get { return m_debuggingModes; }
}
}
// DebuggerBrowsableState states are defined as follows:
// Never never show this element
// Expanded expansion of the class is done, so that all visible internal members are shown
// Collapsed expansion of the class is not performed. Internal visible members are hidden
// RootHidden The target element itself should not be shown, but should instead be
// automatically expanded to have its members displayed.
// Default value is collapsed
// Please also change the code which validates DebuggerBrowsableState variable (in this file)
// if you change this enum.
public enum DebuggerBrowsableState
{
Never = 0,
//Expanded is not supported in this release
//Expanded = 1,
Collapsed = 2,
RootHidden = 3
}
// the one currently supported with the csee.dat
// (mcee.dat, autoexp.dat) file.
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class DebuggerBrowsableAttribute : Attribute
{
private DebuggerBrowsableState state;
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
if (state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
throw new ArgumentOutOfRangeException(nameof(state));
Contract.EndContractBlock();
this.state = state;
}
public DebuggerBrowsableState State
{
get { return state; }
}
}
// DebuggerTypeProxyAttribute
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class DebuggerTypeProxyAttribute : Attribute
{
private string typeName;
private string targetName;
private Type target;
public DebuggerTypeProxyAttribute(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
typeName = type.AssemblyQualifiedName;
}
public DebuggerTypeProxyAttribute(string typeName)
{
this.typeName = typeName;
}
public string ProxyTypeName
{
get { return typeName; }
}
public Type Target
{
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
// This attribute is used to control what is displayed for the given class or field
// in the data windows in the debugger. The single argument to this attribute is
// the string that will be displayed in the value column for instances of the type.
// This string can include text between { and } which can be either a field,
// property or method (as will be documented in mscorlib). In the C# case,
// a general expression will be allowed which only has implicit access to the this pointer
// for the current instance of the target type. The expression will be limited,
// however: there is no access to aliases, locals, or pointers.
// In addition, attributes on properties referenced in the expression are not processed.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class DebuggerDisplayAttribute : Attribute
{
private string name;
private string value;
private string type;
private string targetName;
private Type target;
public DebuggerDisplayAttribute(string value)
{
if (value == null)
{
this.value = "";
}
else
{
this.value = value;
}
name = "";
type = "";
}
public string Value
{
get { return value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public Type Target
{
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.IO {
// ABOUT:
// Helps with path normalization; support allocating on the stack or heap
//
// PathHelper can't stackalloc the array for obvious reasons; you must pass
// in an array of chars allocated on the stack.
//
// USAGE:
// Suppose you need to represent a char array of length len. Then this is the
// suggested way to instantiate PathHelper:
// ***************************************************************************
// PathHelper pathHelper;
// if (charArrayLength less than stack alloc threshold == Path.MaxPath)
// char* arrayPtr = stackalloc char[Path.MaxPath];
// pathHelper = new PathHelper(arrayPtr);
// else
// pathHelper = new PathHelper(capacity, maxPath);
// ***************************************************************************
//
// note in the StringBuilder ctor:
// - maxPath may be greater than Path.MaxPath (for isolated storage)
// - capacity may be greater than maxPath. This is even used for non-isolated
// storage scenarios where we want to temporarily allow strings greater
// than Path.MaxPath if they can be normalized down to Path.MaxPath. This
// can happen if the path contains escape characters "..".
//
unsafe internal struct PathHelper { // should not be serialized
// maximum size, max be greater than max path if contains escape sequence
private int m_capacity;
// current length (next character position)
private int m_length;
// max path, may be less than capacity
private int m_maxPath;
// ptr to stack alloc'd array of chars
[SecurityCritical]
private char* m_arrayPtr;
// StringBuilder
private StringBuilder m_sb;
// whether to operate on stack alloc'd or heap alloc'd array
private bool useStackAlloc;
// Whether to skip calls to Win32Native.GetLongPathName becasue we tried before and failed:
private bool doNotTryExpandShortFileName;
// Instantiates a PathHelper with a stack alloc'd array of chars
[System.Security.SecurityCritical]
internal PathHelper(char* charArrayPtr, int length) {
Contract.Requires(charArrayPtr != null);
// force callers to be aware of this
Contract.Requires(length == Path.MaxPath);
this.m_length = 0;
this.m_sb = null;
this.m_arrayPtr = charArrayPtr;
this.m_capacity = length;
this.m_maxPath = Path.MaxPath;
useStackAlloc = true;
doNotTryExpandShortFileName = false;
}
// Instantiates a PathHelper with a heap alloc'd array of ints. Will create a StringBuilder
[System.Security.SecurityCritical]
internal PathHelper(int capacity, int maxPath)
{
this.m_length = 0;
this.m_arrayPtr = null;
this.useStackAlloc = false;
this.m_sb = new StringBuilder(capacity);
this.m_capacity = capacity;
this.m_maxPath = maxPath;
doNotTryExpandShortFileName = false;
}
internal int Length {
get {
if (useStackAlloc) {
return m_length;
}
else {
return m_sb.Length;
}
}
set {
if (useStackAlloc) {
m_length = value;
}
else {
m_sb.Length = value;
}
}
}
internal int Capacity {
get {
return m_capacity;
}
}
internal char this[int index] {
[System.Security.SecurityCritical]
get {
Contract.Requires(index >= 0 && index < Length);
if (useStackAlloc) {
return m_arrayPtr[index];
}
else {
return m_sb[index];
}
}
[System.Security.SecurityCritical]
set {
Contract.Requires(index >= 0 && index < Length);
if (useStackAlloc) {
m_arrayPtr[index] = value;
}
else {
m_sb[index] = value;
}
}
}
[System.Security.SecurityCritical]
internal unsafe void Append(char value) {
if (Length + 1 >= m_capacity)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
if (useStackAlloc) {
m_arrayPtr[Length] = value;
m_length++;
}
else {
m_sb.Append(value);
}
}
[System.Security.SecurityCritical]
internal unsafe int GetFullPathName() {
if (useStackAlloc) {
char* finalBuffer = stackalloc char[Path.MaxPath + 1];
int result = Win32Native.GetFullPathName(m_arrayPtr, Path.MaxPath + 1, finalBuffer, IntPtr.Zero);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (result > Path.MaxPath) {
char* tempBuffer = stackalloc char[result];
finalBuffer = tempBuffer;
result = Win32Native.GetFullPathName(m_arrayPtr, result, finalBuffer, IntPtr.Zero);
}
// Full path is genuinely long
if (result >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
Contract.Assert(result < Path.MaxPath, "did we accidently remove a PathTooLongException check?");
if (result == 0 && m_arrayPtr[0] != '\0') {
__Error.WinIOError();
}
else if (result < Path.MaxPath) {
// Null terminate explicitly (may be only needed for some cases such as empty strings)
// GetFullPathName return length doesn't account for null terminating char...
finalBuffer[result] = '\0'; // Safe to write directly as result is < Path.MaxPath
}
// We have expanded the paths and GetLongPathName may or may not behave differently from before.
// We need to call it again to see:
doNotTryExpandShortFileName = false;
String.wstrcpy(m_arrayPtr, finalBuffer, result);
// Doesn't account for null terminating char. Think of this as the last
// valid index into the buffer but not the length of the buffer
Length = result;
return result;
}
else {
StringBuilder finalBuffer = new StringBuilder(m_capacity + 1);
int result = Win32Native.GetFullPathName(m_sb.ToString(), m_capacity + 1, finalBuffer, IntPtr.Zero);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (result > m_maxPath) {
finalBuffer.Length = result;
result = Win32Native.GetFullPathName(m_sb.ToString(), result, finalBuffer, IntPtr.Zero);
}
// Fullpath is genuinely long
if (result >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
Contract.Assert(result < m_maxPath, "did we accidentally remove a PathTooLongException check?");
if (result == 0 && m_sb[0] != '\0') {
if (Length >= m_maxPath) {
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
__Error.WinIOError();
}
// We have expanded the paths and GetLongPathName may or may not behave differently from before.
// We need to call it again to see:
doNotTryExpandShortFileName = false;
m_sb = finalBuffer;
return result;
}
}
[System.Security.SecurityCritical]
internal unsafe bool TryExpandShortFileName() {
if (doNotTryExpandShortFileName)
return false;
if (useStackAlloc) {
NullTerminate();
char* buffer = UnsafeGetArrayPtr();
char* shortFileNameBuffer = stackalloc char[Path.MaxPath + 1];
int r = Win32Native.GetLongPathName(buffer, shortFileNameBuffer, Path.MaxPath);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (r >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
if (r == 0) {
// Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a
// path like \\.\PHYSICALDEVICE0 - some device driver doesn't
// support GetLongPathName on that string. This behavior is
// by design, according to the Core File Services team.
// We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs
// intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\
// We do not need to call GetLongPathName if we know it will fail becasue the path does not exist:
int lastErr = Marshal.GetLastWin32Error();
if (lastErr == Win32Native.ERROR_FILE_NOT_FOUND || lastErr == Win32Native.ERROR_PATH_NOT_FOUND)
doNotTryExpandShortFileName = true;
return false;
}
// Safe to copy as we have already done Path.MaxPath bound checking
String.wstrcpy(buffer, shortFileNameBuffer, r);
Length = r;
// We should explicitly null terminate as in some cases the long version of the path
// might actually be shorter than what we started with because of Win32's normalization
// Safe to write directly as bufferLength is guaranteed to be < Path.MaxPath
NullTerminate();
return true;
}
else {
StringBuilder sb = GetStringBuilder();
String origName = sb.ToString();
String tempName = origName;
bool addedPrefix = false;
if (tempName.Length > Path.MaxPath) {
tempName = Path.AddLongPathPrefix(tempName);
addedPrefix = true;
}
sb.Capacity = m_capacity;
sb.Length = 0;
int r = Win32Native.GetLongPathName(tempName, sb, m_capacity);
if (r == 0) {
// Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a
// path like \\.\PHYSICALDEVICE0 - some device driver doesn't
// support GetLongPathName on that string. This behavior is
// by design, according to the Core File Services team.
// We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs
// intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\
// We do not need to call GetLongPathName if we know it will fail becasue the path does not exist:
int lastErr = Marshal.GetLastWin32Error();
if (Win32Native.ERROR_FILE_NOT_FOUND == lastErr || Win32Native.ERROR_PATH_NOT_FOUND == lastErr)
doNotTryExpandShortFileName = true;
sb.Length = 0;
sb.Append(origName);
return false;
}
if (addedPrefix)
r -= 4;
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (r >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
sb = Path.RemoveLongPathPrefix(sb);
Length = sb.Length;
return true;
}
}
[System.Security.SecurityCritical]
internal unsafe void Fixup(int lenSavedName, int lastSlash) {
if (useStackAlloc) {
char* savedName = stackalloc char[lenSavedName];
String.wstrcpy(savedName, m_arrayPtr + lastSlash + 1, lenSavedName);
Length = lastSlash;
NullTerminate();
doNotTryExpandShortFileName = false;
bool r = TryExpandShortFileName();
// Clean up changes made to the newBuffer.
Append(Path.DirectorySeparatorChar);
if (Length + lenSavedName >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
String.wstrcpy(m_arrayPtr + Length, savedName, lenSavedName);
Length = Length + lenSavedName;
}
else {
String savedName = m_sb.ToString(lastSlash + 1, lenSavedName);
Length = lastSlash;
doNotTryExpandShortFileName = false;
bool r = TryExpandShortFileName();
// Clean up changes made to the newBuffer.
Append(Path.DirectorySeparatorChar);
if (Length + lenSavedName >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
m_sb.Append(savedName);
}
}
[System.Security.SecurityCritical]
internal unsafe bool OrdinalStartsWith(String compareTo, bool ignoreCase) {
if (Length < compareTo.Length)
return false;
if (useStackAlloc) {
NullTerminate();
if (ignoreCase) {
String s = new String(m_arrayPtr, 0, compareTo.Length);
return compareTo.Equals(s, StringComparison.OrdinalIgnoreCase);
}
else {
for (int i = 0; i < compareTo.Length; i++) {
if (m_arrayPtr[i] != compareTo[i]) {
return false;
}
}
return true;
}
}
else {
if (ignoreCase) {
return m_sb.ToString().StartsWith(compareTo, StringComparison.OrdinalIgnoreCase);
}
else {
return m_sb.ToString().StartsWith(compareTo, StringComparison.Ordinal);
}
}
}
[System.Security.SecurityCritical]
private unsafe bool OrdinalEqualsStackAlloc(String compareTo)
{
Contract.Requires(useStackAlloc, "Currently no efficient implementation for StringBuilder.OrdinalEquals(String)");
if (Length != compareTo.Length) {
return false;
}
for (int i = 0; i < compareTo.Length; i++) {
if (m_arrayPtr[i] != compareTo[i]) {
return false;
}
}
return true;
}
[System.Security.SecuritySafeCritical]
public override String ToString() {
if (useStackAlloc) {
return new String(m_arrayPtr, 0, Length);
}
else {
return m_sb.ToString();
}
}
[System.Security.SecuritySafeCritical]
internal String ToStringOrExisting(String existingString)
{
if (useStackAlloc) {
return OrdinalEqualsStackAlloc(existingString) ?
existingString :
new String(m_arrayPtr, 0, Length);
}
else {
string newString = m_sb.ToString(); // currently no good StringBuilder.OrdinalEquals(string)
return String.Equals(newString, existingString, StringComparison.Ordinal) ?
existingString :
newString;
}
}
[System.Security.SecurityCritical]
private unsafe char* UnsafeGetArrayPtr() {
Contract.Requires(useStackAlloc, "This should never be called for PathHelpers wrapping a StringBuilder");
return m_arrayPtr;
}
private StringBuilder GetStringBuilder() {
Contract.Requires(!useStackAlloc, "This should never be called for PathHelpers that wrap a stackalloc'd buffer");
return m_sb;
}
[System.Security.SecurityCritical]
private unsafe void NullTerminate() {
Contract.Requires(useStackAlloc, "This should never be called for PathHelpers wrapping a StringBuilder");
m_arrayPtr[m_length] = '\0';
}
}
}
| |
using UnityEngine;
using System.Collections;
namespace DGX.Mecanics
{
public class LevierForce : MonoBehaviour
{
private enum eState
{
knThrowing = 0,
knPulling,
knReleased,
knReadyToFill,
knReadyToShot
};
public float Teta;
public float InitSpeed;
public float PullingSpeed;
public float acceleration;
public Transform ProjectilePrefab;
public float CatapulteForce;
public float AngularForce;
public bool AutoLauch;
public float TimeCycle;
private Transform projectile = null;
private Transform levier;
private eState mState = eState.knReleased;
private float mAngle=0;
private float mCurrentSpeed = 0;
private float m_nTimer;
private bool LPressing = false;
#region callback
// Use this for initialization
protected void Start () {
m_nTimer = 0;
levier = transform.FindChild("levier");
StartReleased();
}
// Update is called once per frame
protected void Update () {
if(AutoLauch)
{
m_nTimer += Time.deltaTime;
if( m_nTimer >= TimeCycle )
{
NextState();
m_nTimer = 0;
}
}
switch(mState)
{
case eState.knReadyToShot:
case eState.knReadyToFill:
case eState.knReleased:
if(!LPressing && Input.GetKey(KeyCode.L))
{
LPressing = true;
NextState();
}
else if(LPressing && !Input.GetKey(KeyCode.L))
{
LPressing = false;
}
break;
case eState.knPulling:
if(mAngle- PullingSpeed > 0)
{
mAngle -= PullingSpeed;
RotateLevier(-PullingSpeed);
}
else
{
StopPulling();
}
break;
case eState.knThrowing:
mCurrentSpeed += acceleration;
if(mAngle+mCurrentSpeed < Teta)
{
mAngle += mCurrentSpeed;
RotateLevier(mCurrentSpeed);
}
else
{
StopThrowing();
}
break;
}
}
#endregion
#region catapulte
private void RotateLevier(float fAngle)
{
levier.transform.Rotate(fAngle,0,0);
}
public void NextState()
{
switch(mState)
{
case eState.knReadyToShot:
StartThrowing();
break;
case eState.knReadyToFill:
projectile = (Transform)Instantiate(ProjectilePrefab,GameObject.Find("SpawnPoint_fill").transform.position, Quaternion.identity);
if(projectile)
{
projectile.transform.parent = levier;
}
StartReadyToShot();
break;
case eState.knReleased:
StartPulling();
break;
}
}
#endregion
#region State
private void StartReadyToShot()
{
mState = eState.knReadyToShot;
}
private void StartThrowing()
{
mState = eState.knThrowing;
mCurrentSpeed = InitSpeed;
mAngle = 0;
}
private void StartReadyToFill()
{
mState = eState.knReadyToFill;
}
private void StartPulling()
{
mState = eState.knPulling;
}
private void StartReleased()
{
mAngle = Teta;
mState = eState.knReleased;
}
private void StopPulling()
{
RotateLevier(-mAngle);
mAngle = 0;
StartReadyToFill();
}
private void StopThrowing()
{
float x,y,z;
x = transform.rotation.eulerAngles.x;
y = transform.rotation.eulerAngles.y;
z = transform.rotation.eulerAngles.z;
float kForward = ProjectilePrefab.GetComponent<Rigidbody>().mass*CatapulteForce;
if(projectile)
Destroy(projectile.gameObject);
projectile = (Transform)Instantiate(ProjectilePrefab,GameObject.Find("SpawnPoint_throw").transform.position, Quaternion.identity);
projectile.GetComponent<Rigidbody>().AddForce( transform.forward*kForward);
projectile.GetComponent<Rigidbody>().AddForce( transform.up*AngularForce);
RotateLevier(-(mAngle - Teta));
StartReleased();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing {
using System.Runtime.Serialization.Formatters;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
using System.Threading;
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter"]/*' />
/// <devdoc>
/// ColorConverter is a class that can be used to convert
/// colors from one data type to another. Access this
/// class through the TypeDescriptor.
/// </devdoc>
public class ColorConverter : TypeConverter {
private static string ColorConstantsLock = "colorConstants";
private static Hashtable colorConstants;
private static string SystemColorConstantsLock = "systemColorConstants";
private static Hashtable systemColorConstants;
private static string ValuesLock = "values";
private static StandardValuesCollection values;
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ColorConverter"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ColorConverter() {
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.Colors"]/*' />
/// <devdoc>
/// Hashtable of color / value pairs (color name is key)
/// for standard colors.
/// </devdoc>
private static Hashtable Colors {
get {
if (colorConstants == null) {
lock(ColorConstantsLock) {
if (colorConstants == null) {
Hashtable tempHash = new Hashtable(StringComparer.OrdinalIgnoreCase);
FillConstants(tempHash, typeof(Color));
colorConstants = tempHash;
}
}
}
return colorConstants;
}
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.SystemColors"]/*' />
/// <devdoc>
/// Hashtable of color / value pairs (color name is key)
/// for system colors.
/// </devdoc>
private static Hashtable SystemColors {
get {
if (systemColorConstants == null) {
lock (SystemColorConstantsLock) {
if (systemColorConstants == null) {
Hashtable tempHash = new Hashtable(StringComparer.OrdinalIgnoreCase);
FillConstants(tempHash, typeof(System.Drawing.SystemColors));
systemColorConstants = tempHash;
}
}
}
return systemColorConstants;
}
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.CanConvertFrom"]/*' />
/// <devdoc>
/// Determines if this converter can convert an object in the given source
/// type to the native type of the converter.
/// </devdoc>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.CanConvertTo"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.</para>
/// </devdoc>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (destinationType == typeof(InstanceDescriptor)) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
internal static object GetNamedColor(string name) {
object color = null;
// First, check to see if this is a standard name.
//
color = Colors[name];
if (color != null) {
return color;
}
// Ok, how about a system color?
//
color = SystemColors[name];
return color;
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ConvertFrom"]/*' />
/// <devdoc>
/// Converts the given object to the converter's native type.
/// </devdoc>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
string strValue = value as string;
if (strValue != null) {
object obj = null;
string text = strValue.Trim();
if (text.Length == 0) {
obj = Color.Empty;
}
else {
// First, check to see if this is a standard name.
//
obj = GetNamedColor(text);
if (obj == null) {
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
char sep = culture.TextInfo.ListSeparator[0];
bool tryMappingToKnownColor = true;
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
// If the value is a 6 digit hex number only, then
// we want to treat the Alpha as 255, not 0
//
if (text.IndexOf(sep) == -1) {
// text can be '' (empty quoted string)
if (text.Length >= 2 && (text[0] == '\'' || text[0] == '"') && text[0] == text[text.Length -1]) {
// In quotes means a named value
string colorName = text.Substring(1, text.Length - 2);
obj = Color.FromName(colorName);
tryMappingToKnownColor = false;
}
else if ((text.Length == 7 && text[0] == '#') ||
(text.Length == 8 && (text.StartsWith("0x") || text.StartsWith("0X"))) ||
(text.Length == 8 && (text.StartsWith("&h") || text.StartsWith("&H")))) {
// Note: ConvertFromString will raise exception if value cannot be converted.
obj = Color.FromArgb(unchecked((int)(0xFF000000 | (uint)(int)intConverter.ConvertFromString(context, culture, text))));
}
}
// Nope. Parse the RGBA from the text.
//
if (obj == null) {
string[] tokens = text.Split(new char[] {sep});
int[] values = new int[tokens.Length];
for (int i = 0; i < values.Length; i++) {
values[i] = unchecked((int)intConverter.ConvertFromString(context, culture, tokens[i]));
}
// We should now have a number of parsed integer values.
// We support 1, 3, or 4 arguments:
//
// 1 -- full ARGB encoded
// 3 -- RGB
// 4 -- ARGB
//
switch (values.Length) {
case 1:
obj = Color.FromArgb(values[0]);
break;
case 3:
obj = Color.FromArgb(values[0], values[1], values[2]);
break;
case 4:
obj = Color.FromArgb(values[0], values[1], values[2], values[3]);
break;
}
tryMappingToKnownColor = true;
}
if ((obj != null) && tryMappingToKnownColor) {
// Now check to see if this color matches one of our known colors.
// If it does, then substitute it. We can only do this for "Colors"
// because system colors morph with user settings.
//
int targetARGB = ((Color)obj).ToArgb();
foreach (Color c in Colors.Values) {
if (c.ToArgb() == targetARGB) {
obj = c;
break;
}
}
}
}
if (obj == null) {
throw new ArgumentException(SR.Format(SR.InvalidColor, text));
}
}
return obj;
}
return base.ConvertFrom(context, culture, value);
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ConvertTo"]/*' />
/// <devdoc>
/// Converts the given object to another type. The most common types to convert
/// are to and from a string object. The default implementation will make a call
/// to ToString on the object if the object is valid and if the destination
/// type is string. If this cannot convert to the desitnation type, this will
/// throw a NotSupportedException.
/// </devdoc>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw new ArgumentNullException(nameof(destinationType));
}
if ( value is Color ){
if (destinationType == typeof(string)) {
Color c = (Color)value;
if (c == Color.Empty) {
return string.Empty;
}
else {
// If this is a known color, then Color can provide its own
// name. Otherwise, we fabricate an ARGB value for it.
//
if (c.IsKnownColor) {
return c.Name;
}
else if (c.IsNamedColor) {
return "'" + c.Name + "'";
}
else {
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
string[] args;
int nArg = 0;
if (c.A < 255) {
args = new string[4];
args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.A);
}
else {
args = new string[3];
}
// Note: ConvertToString will raise exception if value cannot be converted.
args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.R);
args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.G);
args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.B);
// Now slam all of these together with the fantastic Join
// method.
//
return string.Join(sep, args);
}
}
}
if (destinationType == typeof(InstanceDescriptor)) {
MemberInfo member = null;
object[] args = null;
Color c = (Color)value;
if (c.IsEmpty) {
member = typeof(Color).GetField("Empty");
}
else if (c.IsSystemColor) {
member = typeof(SystemColors).GetProperty(c.Name);
}
else if (c.IsKnownColor) {
member = typeof(Color).GetProperty(c.Name);
}
else if (c.A != 255) {
member = typeof(Color).GetMethod("FromArgb", new Type[] {typeof(int), typeof(int), typeof(int), typeof(int)});
args = new object[] {c.A, c.R, c.G, c.B};
}
else if (c.IsNamedColor) {
member = typeof(Color).GetMethod("FromName", new Type[] {typeof(string)});
args = new object[] {c.Name};
}
else {
member = typeof(Color).GetMethod("FromArgb", new Type[] {typeof(int), typeof(int), typeof(int)});
args = new object[] {c.R, c.G, c.B};
}
Debug.Assert(member != null, "Could not convert color to member. Did someone change method name / signature and not update Colorconverter?");
if (member != null) {
return new InstanceDescriptor(member, args);
}
else {
return null;
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.FillConstants"]/*' />
/// <devdoc>
/// Fills the given hashtable with field name / value pairs. It walks all public static
/// properties of enumType that have a property type of Color.
/// </devdoc>
private static void FillConstants(Hashtable hash, Type enumType) {
MethodAttributes attrs = MethodAttributes.Public | MethodAttributes.Static;
PropertyInfo[] props = enumType.GetProperties();
for (int i = 0; i < props.Length; i++) {
PropertyInfo prop = props[i];
if (prop.PropertyType == typeof(Color)) {
MethodInfo method = prop.GetGetMethod();
if (method != null && (method.Attributes & attrs) == attrs) {
object[] tempIndex = null;
hash[prop.Name] = prop.GetValue(null, tempIndex);
}
}
}
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.GetStandardValues"]/*' />
/// <devdoc>
/// Retrieves a collection containing a set of standard values
/// for the data type this validator is designed for. This
/// will return null if the data type does not support a
/// standard set of values.
/// </devdoc>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
if (values == null) {
lock (ValuesLock) {
if (values == null) {
// We must take the value from each hashtable and combine them.
//
ArrayList arrayValues = new ArrayList();
arrayValues.AddRange(Colors.Values);
arrayValues.AddRange(SystemColors.Values);
// Now, we have a couple of colors that have the same names but
// are identical values. Look for these and remove them. Too
// bad this is n^2.
//
int count = arrayValues.Count;
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (arrayValues[i].Equals(arrayValues[j])) {
// Remove this item!
//
arrayValues.RemoveAt(j);
count--;
j--;
}
}
}
// Sort the array.
//
arrayValues.Sort(0, arrayValues.Count, new ColorComparer());
values = new StandardValuesCollection(arrayValues.ToArray());
}
}
}
return values;
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.GetStandardValuesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports a standard set of values
/// that can be picked from a list.
/// </devdoc>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
/// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ColorComparer"]/*' />
/// <devdoc>
/// IComparer for color values. This takes color values but compares their
/// names.
/// </devdoc>
private class ColorComparer : IComparer {
public int Compare(object left, object right) {
Color cLeft = (Color)left;
Color cRight = (Color)right;
return string.Compare(cLeft.Name, cRight.Name, false, CultureInfo.InvariantCulture);
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Web page type: Image gallery page.
/// </summary>
public class ImageGallery_Core : TypeCore, ICollectionPage
{
public ImageGallery_Core()
{
this._TypeId = 135;
this._Id = "ImageGallery";
this._Schema_Org_Url = "http://schema.org/ImageGallery";
string label = "";
GetLabel(out label, "ImageGallery", typeof(ImageGallery_Core));
this._Label = label;
this._Ancestors = new int[]{266,78,293,64};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{64};
this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,38,117,133,169,208};
}
/// <summary>
/// The subject matter of the content.
/// </summary>
private About_Core about;
public About_Core About
{
get
{
return about;
}
set
{
about = value;
SetPropertyInstance(about);
}
}
/// <summary>
/// Specifies the Person that is legally accountable for the CreativeWork.
/// </summary>
private AccountablePerson_Core accountablePerson;
public AccountablePerson_Core AccountablePerson
{
get
{
return accountablePerson;
}
set
{
accountablePerson = value;
SetPropertyInstance(accountablePerson);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A secondary title of the CreativeWork.
/// </summary>
private AlternativeHeadline_Core alternativeHeadline;
public AlternativeHeadline_Core AlternativeHeadline
{
get
{
return alternativeHeadline;
}
set
{
alternativeHeadline = value;
SetPropertyInstance(alternativeHeadline);
}
}
/// <summary>
/// The media objects that encode this creative work. This property is a synonym for encodings.
/// </summary>
private AssociatedMedia_Core associatedMedia;
public AssociatedMedia_Core AssociatedMedia
{
get
{
return associatedMedia;
}
set
{
associatedMedia = value;
SetPropertyInstance(associatedMedia);
}
}
/// <summary>
/// An embedded audio object.
/// </summary>
private Audio_Core audio;
public Audio_Core Audio
{
get
{
return audio;
}
set
{
audio = value;
SetPropertyInstance(audio);
}
}
/// <summary>
/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.
/// </summary>
private Author_Core author;
public Author_Core Author
{
get
{
return author;
}
set
{
author = value;
SetPropertyInstance(author);
}
}
/// <summary>
/// Awards won by this person or for this creative work.
/// </summary>
private Awards_Core awards;
public Awards_Core Awards
{
get
{
return awards;
}
set
{
awards = value;
SetPropertyInstance(awards);
}
}
/// <summary>
/// A set of links that can help a user understand and navigate a website hierarchy.
/// </summary>
private Breadcrumb_Core breadcrumb;
public Breadcrumb_Core Breadcrumb
{
get
{
return breadcrumb;
}
set
{
breadcrumb = value;
SetPropertyInstance(breadcrumb);
}
}
/// <summary>
/// Comments, typically from users, on this CreativeWork.
/// </summary>
private Comment_Core comment;
public Comment_Core Comment
{
get
{
return comment;
}
set
{
comment = value;
SetPropertyInstance(comment);
}
}
/// <summary>
/// The location of the content.
/// </summary>
private ContentLocation_Core contentLocation;
public ContentLocation_Core ContentLocation
{
get
{
return contentLocation;
}
set
{
contentLocation = value;
SetPropertyInstance(contentLocation);
}
}
/// <summary>
/// Official rating of a piece of content\u2014for example,'MPAA PG-13'.
/// </summary>
private ContentRating_Core contentRating;
public ContentRating_Core ContentRating
{
get
{
return contentRating;
}
set
{
contentRating = value;
SetPropertyInstance(contentRating);
}
}
/// <summary>
/// A secondary contributor to the CreativeWork.
/// </summary>
private Contributor_Core contributor;
public Contributor_Core Contributor
{
get
{
return contributor;
}
set
{
contributor = value;
SetPropertyInstance(contributor);
}
}
/// <summary>
/// The party holding the legal copyright to the CreativeWork.
/// </summary>
private CopyrightHolder_Core copyrightHolder;
public CopyrightHolder_Core CopyrightHolder
{
get
{
return copyrightHolder;
}
set
{
copyrightHolder = value;
SetPropertyInstance(copyrightHolder);
}
}
/// <summary>
/// The year during which the claimed copyright for the CreativeWork was first asserted.
/// </summary>
private CopyrightYear_Core copyrightYear;
public CopyrightYear_Core CopyrightYear
{
get
{
return copyrightYear;
}
set
{
copyrightYear = value;
SetPropertyInstance(copyrightYear);
}
}
/// <summary>
/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
/// </summary>
private Creator_Core creator;
public Creator_Core Creator
{
get
{
return creator;
}
set
{
creator = value;
SetPropertyInstance(creator);
}
}
/// <summary>
/// The date on which the CreativeWork was created.
/// </summary>
private DateCreated_Core dateCreated;
public DateCreated_Core DateCreated
{
get
{
return dateCreated;
}
set
{
dateCreated = value;
SetPropertyInstance(dateCreated);
}
}
/// <summary>
/// The date on which the CreativeWork was most recently modified.
/// </summary>
private DateModified_Core dateModified;
public DateModified_Core DateModified
{
get
{
return dateModified;
}
set
{
dateModified = value;
SetPropertyInstance(dateModified);
}
}
/// <summary>
/// Date of first broadcast/publication.
/// </summary>
private DatePublished_Core datePublished;
public DatePublished_Core DatePublished
{
get
{
return datePublished;
}
set
{
datePublished = value;
SetPropertyInstance(datePublished);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// A link to the page containing the comments of the CreativeWork.
/// </summary>
private DiscussionURL_Core discussionURL;
public DiscussionURL_Core DiscussionURL
{
get
{
return discussionURL;
}
set
{
discussionURL = value;
SetPropertyInstance(discussionURL);
}
}
/// <summary>
/// Specifies the Person who edited the CreativeWork.
/// </summary>
private Editor_Core editor;
public Editor_Core Editor
{
get
{
return editor;
}
set
{
editor = value;
SetPropertyInstance(editor);
}
}
/// <summary>
/// The media objects that encode this creative work
/// </summary>
private Encodings_Core encodings;
public Encodings_Core Encodings
{
get
{
return encodings;
}
set
{
encodings = value;
SetPropertyInstance(encodings);
}
}
/// <summary>
/// Genre of the creative work
/// </summary>
private Genre_Core genre;
public Genre_Core Genre
{
get
{
return genre;
}
set
{
genre = value;
SetPropertyInstance(genre);
}
}
/// <summary>
/// Headline of the article
/// </summary>
private Headline_Core headline;
public Headline_Core Headline
{
get
{
return headline;
}
set
{
headline = value;
SetPropertyInstance(headline);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a>
/// </summary>
private InLanguage_Core inLanguage;
public InLanguage_Core InLanguage
{
get
{
return inLanguage;
}
set
{
inLanguage = value;
SetPropertyInstance(inLanguage);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// Indicates whether this content is family friendly.
/// </summary>
private IsFamilyFriendly_Core isFamilyFriendly;
public IsFamilyFriendly_Core IsFamilyFriendly
{
get
{
return isFamilyFriendly;
}
set
{
isFamilyFriendly = value;
SetPropertyInstance(isFamilyFriendly);
}
}
/// <summary>
/// Indicates the collection or gallery to which the item belongs.
/// </summary>
private IsPartOf_Core isPartOf;
public IsPartOf_Core IsPartOf
{
get
{
return isPartOf;
}
set
{
isPartOf = value;
SetPropertyInstance(isPartOf);
}
}
/// <summary>
/// The keywords/tags used to describe this content.
/// </summary>
private Keywords_Core keywords;
public Keywords_Core Keywords
{
get
{
return keywords;
}
set
{
keywords = value;
SetPropertyInstance(keywords);
}
}
/// <summary>
/// Indicates if this web page element is the main subject of the page.
/// </summary>
private MainContentOfPage_Core mainContentOfPage;
public MainContentOfPage_Core MainContentOfPage
{
get
{
return mainContentOfPage;
}
set
{
mainContentOfPage = value;
SetPropertyInstance(mainContentOfPage);
}
}
/// <summary>
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
/// </summary>
private Mentions_Core mentions;
public Mentions_Core Mentions
{
get
{
return mentions;
}
set
{
mentions = value;
SetPropertyInstance(mentions);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// Indicates the main image on the page
/// </summary>
private PrimaryImageOfPage_Core primaryImageOfPage;
public PrimaryImageOfPage_Core PrimaryImageOfPage
{
get
{
return primaryImageOfPage;
}
set
{
primaryImageOfPage = value;
SetPropertyInstance(primaryImageOfPage);
}
}
/// <summary>
/// Specifies the Person or Organization that distributed the CreativeWork.
/// </summary>
private Provider_Core provider;
public Provider_Core Provider
{
get
{
return provider;
}
set
{
provider = value;
SetPropertyInstance(provider);
}
}
/// <summary>
/// The publisher of the creative work.
/// </summary>
private Publisher_Core publisher;
public Publisher_Core Publisher
{
get
{
return publisher;
}
set
{
publisher = value;
SetPropertyInstance(publisher);
}
}
/// <summary>
/// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
/// </summary>
private PublishingPrinciples_Core publishingPrinciples;
public PublishingPrinciples_Core PublishingPrinciples
{
get
{
return publishingPrinciples;
}
set
{
publishingPrinciples = value;
SetPropertyInstance(publishingPrinciples);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The most significant URLs on the page. Typically, these are the non-navigation links that are clicked on the most
/// </summary>
private SignificantLinks_Core significantLinks;
public SignificantLinks_Core SignificantLinks
{
get
{
return significantLinks;
}
set
{
significantLinks = value;
SetPropertyInstance(significantLinks);
}
}
/// <summary>
/// The Organization on whose behalf the creator was working.
/// </summary>
private SourceOrganization_Core sourceOrganization;
public SourceOrganization_Core SourceOrganization
{
get
{
return sourceOrganization;
}
set
{
sourceOrganization = value;
SetPropertyInstance(sourceOrganization);
}
}
/// <summary>
/// A thumbnail image relevant to the Thing.
/// </summary>
private ThumbnailURL_Core thumbnailURL;
public ThumbnailURL_Core ThumbnailURL
{
get
{
return thumbnailURL;
}
set
{
thumbnailURL = value;
SetPropertyInstance(thumbnailURL);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
/// <summary>
/// The version of the CreativeWork embodied by a specified resource.
/// </summary>
private Version_Core version;
public Version_Core Version
{
get
{
return version;
}
set
{
version = value;
SetPropertyInstance(version);
}
}
/// <summary>
/// An embedded video object.
/// </summary>
private Video_Core video;
public Video_Core Video
{
get
{
return video;
}
set
{
video = value;
SetPropertyInstance(video);
}
}
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.POSPlugin
{
public class POSPrim : PhysicsActor
{
private Vector3 _position;
private Vector3 _velocity;
private Vector3 _acceleration;
private Vector3 _size;
private Vector3 m_rotationalVelocity = Vector3.Zero;
private Quaternion _orientation;
private bool iscolliding;
public POSPrim()
{
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Prim; }
set { return; }
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsColliding
{
get { return iscolliding; }
set { iscolliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override bool Stopped
{
get { return false; }
}
public override Vector3 Position
{
get { return _position; }
set { _position = value; }
}
public override Vector3 Size
{
get { return _size; }
set { _size = value; }
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void VehicleFlags(int param, bool remove) { }
public override void SetVolumeDetect(int param)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override Vector3 Velocity
{
get { return _velocity; }
set { _velocity = value; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return _orientation; }
set { _orientation = value; }
}
public override Vector3 Acceleration
{
get { return _acceleration; }
set { _acceleration = value; }
}
public override bool Kinematic
{
get { return true; }
set { }
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override void SetMomentum(Vector3 momentum)
{
}
public override bool Flying
{
get { return false; }
set { }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public override bool Selected
{
set { return; }
}
public override void CrossingFailure()
{
}
public override Vector3 PIDTarget
{
set { return; }
}
public override bool PIDActive
{
set { return; }
}
public override float PIDTau
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override bool PIDHoverActive
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override Quaternion APIDTarget
{
set { return; }
}
public override bool APIDActive
{
set { return; }
}
public override float APIDStrength
{
set { return; }
}
public override float APIDDamping
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Xml;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Security.Cryptography.Xml
{
public class Reference
{
internal const string DefaultDigestMethod = SignedXml.XmlDsigSHA256Url;
private string _id;
private string _uri;
private string _type;
private TransformChain _transformChain;
private string _digestMethod;
private byte[] _digestValue;
private HashAlgorithm _hashAlgorithm;
private object _refTarget;
private ReferenceTargetType _refTargetType;
private XmlElement _cachedXml;
private SignedXml _signedXml = null;
internal CanonicalXmlNodeList _namespaces = null;
//
// public constructors
//
public Reference()
{
_transformChain = new TransformChain();
_refTarget = null;
_refTargetType = ReferenceTargetType.UriReference;
_cachedXml = null;
_digestMethod = DefaultDigestMethod;
}
public Reference(Stream stream)
{
_transformChain = new TransformChain();
_refTarget = stream;
_refTargetType = ReferenceTargetType.Stream;
_cachedXml = null;
_digestMethod = DefaultDigestMethod;
}
public Reference(string uri)
{
_transformChain = new TransformChain();
_refTarget = uri;
_uri = uri;
_refTargetType = ReferenceTargetType.UriReference;
_cachedXml = null;
_digestMethod = DefaultDigestMethod;
}
internal Reference(XmlElement element)
{
_transformChain = new TransformChain();
_refTarget = element;
_refTargetType = ReferenceTargetType.XmlElement;
_cachedXml = null;
_digestMethod = DefaultDigestMethod;
}
//
// public properties
//
public string Id
{
get { return _id; }
set { _id = value; }
}
public string Uri
{
get { return _uri; }
set
{
_uri = value;
_cachedXml = null;
}
}
public string Type
{
get { return _type; }
set
{
_type = value;
_cachedXml = null;
}
}
public string DigestMethod
{
get { return _digestMethod; }
set
{
_digestMethod = value;
_cachedXml = null;
}
}
public byte[] DigestValue
{
get { return _digestValue; }
set
{
_digestValue = value;
_cachedXml = null;
}
}
public TransformChain TransformChain
{
get
{
if (_transformChain == null)
_transformChain = new TransformChain();
return _transformChain;
}
set
{
_transformChain = value;
_cachedXml = null;
}
}
internal bool CacheValid
{
get
{
return (_cachedXml != null);
}
}
internal SignedXml SignedXml
{
get { return _signedXml; }
set { _signedXml = value; }
}
internal ReferenceTargetType ReferenceTargetType
{
get
{
return _refTargetType;
}
}
//
// public methods
//
public XmlElement GetXml()
{
if (CacheValid) return (_cachedXml);
XmlDocument document = new XmlDocument();
document.PreserveWhitespace = true;
return GetXml(document);
}
internal XmlElement GetXml(XmlDocument document)
{
// Create the Reference
XmlElement referenceElement = document.CreateElement("Reference", SignedXml.XmlDsigNamespaceUrl);
if (!string.IsNullOrEmpty(_id))
referenceElement.SetAttribute("Id", _id);
if (_uri != null)
referenceElement.SetAttribute("URI", _uri);
if (!string.IsNullOrEmpty(_type))
referenceElement.SetAttribute("Type", _type);
// Add the transforms to the Reference
if (TransformChain.Count != 0)
referenceElement.AppendChild(TransformChain.GetXml(document, SignedXml.XmlDsigNamespaceUrl));
// Add the DigestMethod
if (string.IsNullOrEmpty(_digestMethod))
throw new CryptographicException(SR.Cryptography_Xml_DigestMethodRequired);
XmlElement digestMethodElement = document.CreateElement("DigestMethod", SignedXml.XmlDsigNamespaceUrl);
digestMethodElement.SetAttribute("Algorithm", _digestMethod);
referenceElement.AppendChild(digestMethodElement);
if (DigestValue == null)
{
if (_hashAlgorithm.Hash == null)
throw new CryptographicException(SR.Cryptography_Xml_DigestValueRequired);
DigestValue = _hashAlgorithm.Hash;
}
XmlElement digestValueElement = document.CreateElement("DigestValue", SignedXml.XmlDsigNamespaceUrl);
digestValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(_digestValue)));
referenceElement.AppendChild(digestValueElement);
return referenceElement;
}
public void LoadXml(XmlElement value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl);
_uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
_type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);
if (!Utils.VerifyAttributes(value, new string[] { "Id", "URI", "Type" }))
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference");
XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
// Transforms
bool hasTransforms = false;
TransformChain = new TransformChain();
XmlNodeList transformsNodes = value.SelectNodes("ds:Transforms", nsm);
if (transformsNodes != null && transformsNodes.Count != 0)
{
if (transformsNodes.Count > 1)
{
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
}
hasTransforms = true;
XmlElement transformsElement = transformsNodes[0] as XmlElement;
if (!Utils.VerifyAttributes(transformsElement, (string[])null))
{
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
}
XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm);
if (transformNodes != null)
{
if (transformNodes.Count != transformsElement.SelectNodes("*").Count)
{
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
}
if (transformNodes.Count > Utils.MaxTransformsPerReference)
{
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms");
}
foreach (XmlNode transformNode in transformNodes)
{
XmlElement transformElement = transformNode as XmlElement;
string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
if (algorithm == null || !Utils.VerifyAttributes(transformElement, "Algorithm"))
{
throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform);
}
Transform transform = CryptoHelpers.CreateFromName<Transform>(algorithm);
if (transform == null)
{
throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform);
}
AddTransform(transform);
// let the transform read the children of the transformElement for data
transform.LoadInnerXml(transformElement.ChildNodes);
// Hack! this is done to get around the lack of here() function support in XPath
if (transform is XmlDsigEnvelopedSignatureTransform)
{
// Walk back to the Signature tag. Find the nearest signature ancestor
// Signature-->SignedInfo-->Reference-->Transforms-->Transform
XmlNode signatureTag = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm);
XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm);
if (signatureList != null)
{
int position = 0;
foreach (XmlNode node in signatureList)
{
position++;
if (node == signatureTag)
{
((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position;
break;
}
}
}
}
}
}
}
// DigestMethod
XmlNodeList digestMethodNodes = value.SelectNodes("ds:DigestMethod", nsm);
if (digestMethodNodes == null || digestMethodNodes.Count == 0 || digestMethodNodes.Count > 1)
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod");
XmlElement digestMethodElement = digestMethodNodes[0] as XmlElement;
_digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
if (_digestMethod == null || !Utils.VerifyAttributes(digestMethodElement, "Algorithm"))
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod");
// DigestValue
XmlNodeList digestValueNodes = value.SelectNodes("ds:DigestValue", nsm);
if (digestValueNodes == null || digestValueNodes.Count == 0 || digestValueNodes.Count > 1)
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue");
XmlElement digestValueElement = digestValueNodes[0] as XmlElement;
_digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText));
if (!Utils.VerifyAttributes(digestValueElement, (string[])null))
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue");
// Verify that there aren't any extra nodes that aren't allowed
int expectedChildNodeCount = hasTransforms ? 3 : 2;
if (value.SelectNodes("*").Count != expectedChildNodeCount)
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference");
// cache the Xml
_cachedXml = value;
}
public void AddTransform(Transform transform)
{
if (transform == null)
throw new ArgumentNullException(nameof(transform));
transform.Reference = this;
TransformChain.Add(transform);
}
internal void UpdateHashValue(XmlDocument document, CanonicalXmlNodeList refList)
{
DigestValue = CalculateHashValue(document, refList);
}
// What we want to do is pump the input throug the TransformChain and then
// hash the output of the chain document is the document context for resolving relative references
internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList)
{
// refList is a list of elements that might be targets of references
// Now's the time to create our hashing algorithm
_hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(_digestMethod);
if (_hashAlgorithm == null)
throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed);
// Let's go get the target.
string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI);
Stream hashInputStream = null;
WebResponse response = null;
Stream inputStream = null;
XmlResolver resolver = null;
byte[] hashval = null;
try
{
switch (_refTargetType)
{
case ReferenceTargetType.Stream:
// This is the easiest case. We already have a stream, so just pump it through the TransformChain
resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
hashInputStream = TransformChain.TransformToOctetStream((Stream)_refTarget, resolver, baseUri);
break;
case ReferenceTargetType.UriReference:
// Second-easiest case -- dereference the URI & pump through the TransformChain
// handle the special cases where the URI is null (meaning whole doc)
// or the URI is just a fragment (meaning a reference to an embedded Object)
if (_uri == null)
{
// We need to create a DocumentNavigator out of the XmlElement
resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
// In the case of a Uri-less reference, we will simply pass null to the transform chain.
// The first transform in the chain is expected to know how to retrieve the data to hash.
hashInputStream = TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri);
}
else if (_uri.Length == 0)
{
// This is the self-referential case. First, check that we have a document context.
// The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process
if (document == null)
throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri));
// Normalize the containing document
resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri));
hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
}
else if (_uri[0] == '#')
{
// If we get here, then we are constructing a Reference to an embedded DataObject
// referenced by an Id = attribute. Go find the relevant object
bool discardComments = true;
string idref = Utils.GetIdFromLocalUri(_uri, out discardComments);
if (idref == "xpointer(/)")
{
// This is a self referencial case
if (document == null)
throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri));
// We should not discard comments here!!!
resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri);
break;
}
XmlElement elem = SignedXml.GetIdElement(document, idref);
if (elem != null)
_namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement);
if (elem == null)
{
// Go throw the referenced items passed in
if (refList != null)
{
foreach (XmlNode node in refList)
{
XmlElement tempElem = node as XmlElement;
if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl))
&& (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref)))
{
elem = tempElem;
if (_signedXml._context != null)
_namespaces = Utils.GetPropagatedAttributes(_signedXml._context);
break;
}
}
}
}
if (elem == null)
throw new CryptographicException(SR.Cryptography_Xml_InvalidReference);
XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri);
// Add the propagated attributes
Utils.AddNamespaces(normDocument.DocumentElement, _namespaces);
resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
if (discardComments)
{
// We should discard comments before going into the transform chain
XmlDocument docWithNoComments = Utils.DiscardComments(normDocument);
hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
}
else
{
// This is an XPointer reference, do not discard comments!!!
hashInputStream = TransformChain.TransformToOctetStream(normDocument, resolver, baseUri);
}
}
else
{
throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri);
}
break;
case ReferenceTargetType.XmlElement:
// We need to create a DocumentNavigator out of the XmlElement
resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)_refTarget, resolver, baseUri), resolver, baseUri);
break;
default:
throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri);
}
// Compute the new hash value
hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream);
hashval = _hashAlgorithm.ComputeHash(hashInputStream);
}
finally
{
if (hashInputStream != null)
hashInputStream.Close();
if (response != null)
response.Close();
if (inputStream != null)
inputStream.Close();
}
return hashval;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using Android.Support.V4.View;
using Android.Views;
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
public abstract class VisualElementRenderer<TElement> : FormsViewGroup, IVisualElementRenderer, AView.IOnTouchListener, AView.IOnClickListener, IEffectControlProvider where TElement : VisualElement
{
readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers = new List<EventHandler<VisualElementChangedEventArgs>>();
readonly Lazy<GestureDetector> _gestureDetector;
readonly PanGestureHandler _panGestureHandler;
readonly PinchGestureHandler _pinchGestureHandler;
readonly TapGestureHandler _tapGestureHandler;
NotifyCollectionChangedEventHandler _collectionChangeHandler;
VisualElementRendererFlags _flags = VisualElementRendererFlags.AutoPackage | VisualElementRendererFlags.AutoTrack;
InnerGestureListener _gestureListener;
VisualElementPackager _packager;
PropertyChangedEventHandler _propertyChangeHandler;
Lazy<ScaleGestureDetector> _scaleDetector;
protected VisualElementRenderer() : base(Forms.Context)
{
_tapGestureHandler = new TapGestureHandler(() => View);
_panGestureHandler = new PanGestureHandler(() => View, Context.FromPixels);
_pinchGestureHandler = new PinchGestureHandler(() => View);
_gestureDetector =
new Lazy<GestureDetector>(
() =>
new GestureDetector(
_gestureListener =
new InnerGestureListener(_tapGestureHandler.OnTap, _tapGestureHandler.TapGestureRecognizers, _panGestureHandler.OnPan, _panGestureHandler.OnPanStarted, _panGestureHandler.OnPanComplete)));
_scaleDetector =
new Lazy<ScaleGestureDetector>(
() => new ScaleGestureDetector(Context, new InnerScaleListener(_pinchGestureHandler.OnPinch, _pinchGestureHandler.OnPinchStarted, _pinchGestureHandler.OnPinchEnded), Handler));
}
public TElement Element { get; private set; }
protected bool AutoPackage
{
get { return (_flags & VisualElementRendererFlags.AutoPackage) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoPackage;
else
_flags &= ~VisualElementRendererFlags.AutoPackage;
}
}
protected bool AutoTrack
{
get { return (_flags & VisualElementRendererFlags.AutoTrack) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoTrack;
else
_flags &= ~VisualElementRendererFlags.AutoTrack;
}
}
View View
{
get { return Element as View; }
}
void IEffectControlProvider.RegisterEffect(Effect effect)
{
var platformEffect = effect as PlatformEffect;
if (platformEffect != null)
OnRegisterEffect(platformEffect);
}
void IOnClickListener.OnClick(AView v)
{
_tapGestureHandler.OnSingleClick();
}
bool IOnTouchListener.OnTouch(AView v, MotionEvent e)
{
var handled = false;
if (_pinchGestureHandler.IsPinchSupported)
{
if (!_scaleDetector.IsValueCreated)
ScaleGestureDetectorCompat.SetQuickScaleEnabled(_scaleDetector.Value, true);
handled = _scaleDetector.Value.OnTouchEvent(e);
}
return _gestureDetector.Value.OnTouchEvent(e) || handled;
}
VisualElement IVisualElementRenderer.Element
{
get { return Element; }
}
event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged
{
add { _elementChangedHandlers.Add(value); }
remove { _elementChangedHandlers.Remove(value); }
}
public virtual SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
{
Measure(widthConstraint, heightConstraint);
return new SizeRequest(new Size(MeasuredWidth, MeasuredHeight), MinimumSize());
}
void IVisualElementRenderer.SetElement(VisualElement element)
{
if (!(element is TElement))
throw new ArgumentException("element is not of type " + typeof(TElement), "element");
SetElement((TElement)element);
}
public VisualElementTracker Tracker { get; private set; }
public void UpdateLayout()
{
Performance.Start();
if (Tracker != null)
Tracker.UpdateLayout();
Performance.Stop();
}
public ViewGroup ViewGroup
{
get { return this; }
}
public event EventHandler<ElementChangedEventArgs<TElement>> ElementChanged;
public void SetElement(TElement element)
{
if (element == null)
throw new ArgumentNullException("element");
TElement oldElement = Element;
Element = element;
Performance.Start();
if (oldElement != null)
{
oldElement.PropertyChanged -= _propertyChangeHandler;
UnsubscribeGestureRecognizers(oldElement);
}
// element may be allowed to be passed as null in the future
if (element != null)
{
Color currentColor = oldElement != null ? oldElement.BackgroundColor : Color.Default;
if (element.BackgroundColor != currentColor)
UpdateBackgroundColor();
}
if (_propertyChangeHandler == null)
_propertyChangeHandler = OnElementPropertyChanged;
element.PropertyChanged += _propertyChangeHandler;
SubscribeGestureRecognizers(element);
if (oldElement == null)
{
SetOnClickListener(this);
SetOnTouchListener(this);
SoundEffectsEnabled = false;
}
InputTransparent = Element.InputTransparent;
// must be updated AFTER SetOnClickListener is called
// SetOnClickListener implicitly calls Clickable = true
UpdateGestureRecognizers(true);
OnElementChanged(new ElementChangedEventArgs<TElement>(oldElement, element));
if (AutoPackage && _packager == null)
SetPackager(new VisualElementPackager(this));
if (AutoTrack && Tracker == null)
SetTracker(new VisualElementTracker(this));
if (element != null)
SendVisualElementInitialized(element, this);
var controller = (IElementController)oldElement;
if (controller != null && controller.EffectControlProvider == this)
controller.EffectControlProvider = null;
controller = element;
if (controller != null)
controller.EffectControlProvider = this;
if (element != null && !string.IsNullOrEmpty(element.AutomationId))
SetAutomationId(element.AutomationId);
Performance.Stop();
}
/// <summary>
/// Determines whether the native control is disposed of when this renderer is disposed
/// Can be overridden in deriving classes
/// </summary>
protected virtual bool ManageNativeControlLifetime => true;
protected override void Dispose(bool disposing)
{
if ((_flags & VisualElementRendererFlags.Disposed) != 0)
return;
_flags |= VisualElementRendererFlags.Disposed;
if (disposing)
{
if (Tracker != null)
{
Tracker.Dispose();
Tracker = null;
}
if (_packager != null)
{
_packager.Dispose();
_packager = null;
}
if (_scaleDetector != null && _scaleDetector.IsValueCreated)
{
_scaleDetector.Value.Dispose();
_scaleDetector = null;
}
if (_gestureListener != null)
{
_gestureListener.Dispose();
_gestureListener = null;
}
if (ManageNativeControlLifetime)
{
int count = ChildCount;
for (var i = 0; i < count; i++)
{
AView child = GetChildAt(i);
child.Dispose();
}
}
RemoveAllViews();
if (Element != null)
{
Element.PropertyChanged -= _propertyChangeHandler;
UnsubscribeGestureRecognizers(Element);
if (Platform.GetRenderer(Element) == this)
Platform.SetRenderer(Element, null);
Element = null;
}
}
base.Dispose(disposing);
}
protected virtual Size MinimumSize()
{
return new Size();
}
protected virtual void OnElementChanged(ElementChangedEventArgs<TElement> e)
{
var args = new VisualElementChangedEventArgs(e.OldElement, e.NewElement);
for (var i = 0; i < _elementChangedHandlers.Count; i++)
_elementChangedHandlers[i](this, args);
EventHandler<ElementChangedEventArgs<TElement>> changed = ElementChanged;
if (changed != null)
changed(this, e);
}
protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackgroundColor();
else if (e.PropertyName == VisualElement.InputTransparentProperty.PropertyName)
InputTransparent = Element.InputTransparent;
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
if (Element == null)
return;
ReadOnlyCollection<Element> children = Element.LogicalChildren;
for (var i = 0; i < children.Count; i++)
{
var visualElement = children[i] as VisualElement;
if (visualElement == null)
continue;
IVisualElementRenderer renderer = Platform.GetRenderer(visualElement);
renderer?.UpdateLayout();
}
}
protected virtual void OnRegisterEffect(PlatformEffect effect)
{
effect.Container = this;
}
protected virtual void SetAutomationId(string id)
{
ContentDescription = id;
}
protected void SetPackager(VisualElementPackager packager)
{
_packager = packager;
packager.Load();
}
protected void SetTracker(VisualElementTracker tracker)
{
Tracker = tracker;
}
protected virtual void UpdateBackgroundColor()
{
SetBackgroundColor(Element.BackgroundColor.ToAndroid());
}
internal virtual void SendVisualElementInitialized(VisualElement element, AView nativeView)
{
element.SendViewInitialized(nativeView);
}
void HandleGestureRecognizerCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
UpdateGestureRecognizers();
}
void SubscribeGestureRecognizers(VisualElement element)
{
var view = element as View;
if (view == null)
return;
if (_collectionChangeHandler == null)
_collectionChangeHandler = HandleGestureRecognizerCollectionChanged;
var observableCollection = (ObservableCollection<IGestureRecognizer>)view.GestureRecognizers;
observableCollection.CollectionChanged += _collectionChangeHandler;
}
void UnsubscribeGestureRecognizers(VisualElement element)
{
var view = element as View;
if (view == null || _collectionChangeHandler == null)
return;
var observableCollection = (ObservableCollection<IGestureRecognizer>)view.GestureRecognizers;
observableCollection.CollectionChanged -= _collectionChangeHandler;
}
void UpdateClickable(bool force = false)
{
var view = Element as View;
if (view == null)
return;
bool newValue = view.ShouldBeMadeClickable();
if (force || newValue)
Clickable = newValue;
}
void UpdateGestureRecognizers(bool forceClick = false)
{
if (View == null)
return;
UpdateClickable(forceClick);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Security;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// A base class for the trace cmdlets that allow you to specify
/// which trace listeners to add to a TraceSource.
/// </summary>
public class TraceListenerCommandBase : TraceCommandBase
{
#region Parameters
/// <summary>
/// The TraceSource parameter determines which TraceSource categories the
/// operation will take place on.
/// </summary>
internal string[] NameInternal { get; set; } = new string[0];
/// <summary>
/// The flags to be set on the TraceSource.
/// </summary>
/// <value></value>
internal PSTraceSourceOptions OptionsInternal
{
get { return _options; }
set
{
_options = value;
optionsSpecified = true;
}
}
private PSTraceSourceOptions _options = PSTraceSourceOptions.All;
/// <summary>
/// True if the Options parameter has been set, or false otherwise.
/// </summary>
internal bool optionsSpecified;
/// <summary>
/// The parameter which determines the options for output from the trace listeners.
/// </summary>
internal TraceOptions ListenerOptionsInternal
{
get { return _traceOptions; }
set
{
traceOptionsSpecified = true;
_traceOptions = value;
}
}
private TraceOptions _traceOptions = TraceOptions.None;
/// <summary>
/// True if the TraceOptions parameter was specified, or false otherwise.
/// </summary>
internal bool traceOptionsSpecified;
/// <summary>
/// Adds the file trace listener using the specified file.
/// </summary>
/// <value></value>
internal string FileListener { get; set; }
/// <summary>
/// Property that sets force parameter. This will clear the
/// read-only attribute on an existing file if present.
/// </summary>
/// <remarks>
/// Note that we do not attempt to reset the read-only attribute.
/// </remarks>
public bool ForceWrite { get; set; }
/// <summary>
/// If this parameter is specified the Debugger trace listener will be added.
/// </summary>
/// <value></value>
internal bool DebuggerListener { get; set; }
/// <summary>
/// If this parameter is specified the Msh Host trace listener will be added.
/// </summary>
/// <value></value>
internal SwitchParameter PSHostListener
{
get { return _host; }
set { _host = value; }
}
private bool _host = false;
#endregion Parameters
internal Collection<PSTraceSource> ConfigureTraceSource(
string[] sourceNames,
bool preConfigure,
out Collection<PSTraceSource> preconfiguredSources)
{
preconfiguredSources = new Collection<PSTraceSource>();
// Find the matching and unmatched trace sources.
Collection<string> notMatched = null;
Collection<PSTraceSource> matchingSources = GetMatchingTraceSource(sourceNames, false, out notMatched);
if (preConfigure)
{
// Set the flags if they were specified
if (optionsSpecified)
{
SetFlags(matchingSources);
}
AddTraceListenersToSources(matchingSources);
SetTraceListenerOptions(matchingSources);
}
// Now try to preset options for sources which have not yet been
// constructed.
foreach (string notMatchedName in notMatched)
{
if (string.IsNullOrEmpty(notMatchedName))
{
continue;
}
if (WildcardPattern.ContainsWildcardCharacters(notMatchedName))
{
continue;
}
PSTraceSource newTraceSource =
PSTraceSource.GetNewTraceSource(
notMatchedName,
string.Empty,
true);
preconfiguredSources.Add(newTraceSource);
}
// Preconfigure any trace sources that were not already present
if (preconfiguredSources.Count > 0)
{
if (preConfigure)
{
// Set the flags if they were specified
if (optionsSpecified)
{
SetFlags(preconfiguredSources);
}
AddTraceListenersToSources(preconfiguredSources);
SetTraceListenerOptions(preconfiguredSources);
}
// Add the sources to the preconfigured table so that they are found
// when the trace source finally gets created by the system.
foreach (PSTraceSource sourceToPreconfigure in preconfiguredSources)
{
if (!PSTraceSource.PreConfiguredTraceSource.ContainsKey(sourceToPreconfigure.Name))
{
PSTraceSource.PreConfiguredTraceSource.Add(sourceToPreconfigure.Name, sourceToPreconfigure);
}
}
}
return matchingSources;
}
#region AddTraceListeners
/// <summary>
/// Adds the console, debugger, file, or host listener if requested.
/// </summary>
internal void AddTraceListenersToSources(Collection<PSTraceSource> matchingSources)
{
if (DebuggerListener)
{
if (_defaultListener == null)
{
_defaultListener =
new DefaultTraceListener();
// Note, this is not meant to be localized.
_defaultListener.Name = "Debug";
}
AddListenerToSources(matchingSources, _defaultListener);
}
if (PSHostListener)
{
if (_hostListener == null)
{
((MshCommandRuntime)this.CommandRuntime).DebugPreference = ActionPreference.Continue;
_hostListener = new PSHostTraceListener(this);
// Note, this is not meant to be localized.
_hostListener.Name = "Host";
}
AddListenerToSources(matchingSources, _hostListener);
}
if (FileListener != null)
{
if (_fileListeners == null)
{
_fileListeners = new Collection<TextWriterTraceListener>();
FileStreams = new Collection<FileStream>();
Exception error = null;
try
{
Collection<string> resolvedPaths = new Collection<string>();
try
{
// Resolve the file path
ProviderInfo provider = null;
resolvedPaths = this.SessionState.Path.GetResolvedProviderPathFromPSPath(FileListener, out provider);
// We can only export aliases to the file system
if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
{
throw
new PSNotSupportedException(
StringUtil.Format(TraceCommandStrings.TraceFileOnly,
FileListener,
provider.FullName));
}
}
catch (ItemNotFoundException)
{
// Since the file wasn't found, just make a provider-qualified path out if it
// and use that.
PSDriveInfo driveInfo = null;
ProviderInfo provider = null;
string path =
this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(
FileListener,
new CmdletProviderContext(this.Context),
out provider,
out driveInfo);
// We can only export aliases to the file system
if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
{
throw
new PSNotSupportedException(
StringUtil.Format(TraceCommandStrings.TraceFileOnly,
FileListener,
provider.FullName));
}
resolvedPaths.Add(path);
}
if (resolvedPaths.Count > 1)
{
throw
new PSNotSupportedException(StringUtil.Format(TraceCommandStrings.TraceSingleFileOnly, FileListener));
}
string resolvedPath = resolvedPaths[0];
Exception fileOpenError = null;
try
{
if (ForceWrite && System.IO.File.Exists(resolvedPath))
{
// remove readonly attributes on the file
System.IO.FileInfo fInfo = new System.IO.FileInfo(resolvedPath);
if (fInfo != null)
{
// Save some disk write time by checking whether file is readonly..
if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make sure the file is not read only
fInfo.Attributes &= ~(FileAttributes.ReadOnly);
}
}
}
// Trace commands always append..So there is no need to set overwrite with force..
FileStream fileStream = new FileStream(resolvedPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
FileStreams.Add(fileStream);
// Open the file stream
TextWriterTraceListener fileListener =
new TextWriterTraceListener(fileStream, resolvedPath);
fileListener.Name = FileListener;
_fileListeners.Add(fileListener);
}
catch (IOException ioException)
{
fileOpenError = ioException;
}
catch (SecurityException securityException)
{
fileOpenError = securityException;
}
catch (UnauthorizedAccessException unauthorized)
{
fileOpenError = unauthorized;
}
if (fileOpenError != null)
{
ErrorRecord errorRecord =
new ErrorRecord(
fileOpenError,
"FileListenerPathResolutionFailed",
ErrorCategory.OpenError,
resolvedPath);
WriteError(errorRecord);
}
}
catch (ProviderNotFoundException providerNotFound)
{
error = providerNotFound;
}
catch (System.Management.Automation.DriveNotFoundException driveNotFound)
{
error = driveNotFound;
}
catch (NotSupportedException notSupported)
{
error = notSupported;
}
if (error != null)
{
ErrorRecord errorRecord =
new ErrorRecord(
error,
"FileListenerPathResolutionFailed",
ErrorCategory.InvalidArgument,
FileListener);
WriteError(errorRecord);
}
}
foreach (TraceListener listener in _fileListeners)
{
AddListenerToSources(matchingSources, listener);
}
}
}
private DefaultTraceListener _defaultListener;
private PSHostTraceListener _hostListener;
private Collection<TextWriterTraceListener> _fileListeners;
/// <summary>
/// The file streams that were open by this command.
/// </summary>
internal Collection<FileStream> FileStreams { get; private set; }
private static void AddListenerToSources(Collection<PSTraceSource> matchingSources, TraceListener listener)
{
// Now add the listener to all the sources
foreach (PSTraceSource source in matchingSources)
{
source.Listeners.Add(listener);
}
}
#endregion AddTraceListeners
#region RemoveTraceListeners
/// <summary>
/// Removes the tracelisteners from the specified trace sources.
/// </summary>
internal static void RemoveListenersByName(
Collection<PSTraceSource> matchingSources,
string[] listenerNames,
bool fileListenersOnly)
{
Collection<WildcardPattern> listenerMatcher =
SessionStateUtilities.CreateWildcardsFromStrings(
listenerNames,
WildcardOptions.IgnoreCase);
// Loop through all the matching sources and remove the matching listeners
foreach (PSTraceSource source in matchingSources)
{
// Get the indexes of the listeners that need to be removed.
// This is done because we cannot remove the listeners while
// we are enumerating them.
for (int index = source.Listeners.Count - 1; index >= 0; --index)
{
TraceListener listenerToRemove = source.Listeners[index];
if (fileListenersOnly && !(listenerToRemove is TextWriterTraceListener))
{
// Since we only want to remove file listeners, skip any that
// aren't file listeners
continue;
}
// Now match the names
if (SessionStateUtilities.MatchesAnyWildcardPattern(
listenerToRemove.Name,
listenerMatcher,
true))
{
listenerToRemove.Flush();
listenerToRemove.Dispose();
source.Listeners.RemoveAt(index);
}
}
}
}
#endregion RemoveTraceListeners
#region SetTraceListenerOptions
/// <summary>
/// Sets the trace listener options based on the ListenerOptions parameter.
/// </summary>
internal void SetTraceListenerOptions(Collection<PSTraceSource> matchingSources)
{
// Set the trace options if they were specified
if (traceOptionsSpecified)
{
foreach (PSTraceSource source in matchingSources)
{
foreach (TraceListener listener in source.Listeners)
{
listener.TraceOutputOptions = this.ListenerOptionsInternal;
}
}
}
}
#endregion SetTraceListenerOptions
#region SetFlags
/// <summary>
/// Sets the flags for all the specified TraceSources.
/// </summary>
internal void SetFlags(Collection<PSTraceSource> matchingSources)
{
foreach (PSTraceSource structuredSource in matchingSources)
{
structuredSource.Options = this.OptionsInternal;
}
}
#endregion SetFlags
#region TurnOnTracing
/// <summary>
/// Turns on tracing for the TraceSources, flags, and listeners defined by the parameters.
/// </summary>
internal void TurnOnTracing(Collection<PSTraceSource> matchingSources, bool preConfigured)
{
foreach (PSTraceSource source in matchingSources)
{
// Store the current state of the TraceSource
if (!_storedTraceSourceState.ContainsKey(source))
{
// Copy the listeners into a different collection
Collection<TraceListener> listenerCollection = new Collection<TraceListener>();
foreach (TraceListener listener in source.Listeners)
{
listenerCollection.Add(listener);
}
if (preConfigured)
{
// If the source is a preconfigured source, then the default options
// and listeners should be stored as the existing state.
_storedTraceSourceState[source] =
new KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>>(
PSTraceSourceOptions.None,
new Collection<TraceListener>());
}
else
{
_storedTraceSourceState[source] =
new KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>>(
source.Options,
listenerCollection);
}
}
// Now set the new flags
source.Options = this.OptionsInternal;
}
// Now turn on the listeners
AddTraceListenersToSources(matchingSources);
SetTraceListenerOptions(matchingSources);
}
#endregion TurnOnTracing
#region ResetTracing
/// <summary>
/// Resets tracing to the previous level for the TraceSources defined by the parameters.
/// Note, TurnOnTracing must be called before calling ResetTracing or else all
/// TraceSources will be turned off.
/// </summary>
internal void ResetTracing(Collection<PSTraceSource> matchingSources)
{
foreach (PSTraceSource source in matchingSources)
{
// First flush all the existing trace listeners
foreach (TraceListener listener in source.Listeners)
{
listener.Flush();
}
if (_storedTraceSourceState.ContainsKey(source))
{
// Restore the TraceSource to its original state
KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>> storedState =
_storedTraceSourceState[source];
source.Listeners.Clear();
foreach (TraceListener listener in storedState.Value)
{
source.Listeners.Add(listener);
}
source.Options = storedState.Key;
}
else
{
// Since we don't have any stored state for this TraceSource,
// just turn it off.
source.Listeners.Clear();
source.Options = PSTraceSourceOptions.None;
}
}
}
#endregion ResetTracing
#region stored state
/// <summary>
/// Clears the store TraceSource state.
/// </summary>
protected void ClearStoredState()
{
// First close all listeners
foreach (KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>> pair in _storedTraceSourceState.Values)
{
foreach (TraceListener listener in pair.Value)
{
listener.Flush();
listener.Dispose();
}
}
_storedTraceSourceState.Clear();
}
private Dictionary<PSTraceSource, KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>>> _storedTraceSourceState =
new Dictionary<PSTraceSource, KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>>>();
#endregion stored state
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
namespace Hydra.Framework.Conversions
{
//
// **********************************************************************
/// <summary>
/// Utility methods to work with files.
/// </summary>
// **********************************************************************
//
public class ConvertFile
{
#region Delegates
//
// **********************************************************************
/// <summary>
/// Delegate to handle file exception.
/// </summary>
/// <param name="fileName">file name</param>
/// <param name="e">exception</param>
// **********************************************************************
//
public delegate void DxFileExceptionHandler(string fileName, Exception e);
#endregion
#region WIN32 SHGetFileInfo Import
//
// **********************************************************************
/// <summary>
/// SHs the get file info.
/// </summary>
/// <param name="pszPath">The PSZ path.</param>
/// <param name="dwFileAttributes">The dw file attributes.</param>
/// <param name="psfi">The psfi.</param>
/// <param name="cbfileInfo">The cbfile info.</param>
/// <param name="uFlags">The u flags.</param>
/// <returns></returns>
// **********************************************************************
//
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int SHGetFileInfo(
string pszPath,
int dwFileAttributes,
out SHFILEINFO psfi,
uint cbfileInfo,
SHGFI uFlags);
private const int MAX_PATH = 260;
private const int MAX_TYPE = 80;
private struct SHFILEINFO
{
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="SHFILEINFO"/> struct.
/// </summary>
/// <param name="b">if set to <c>true</c> [b].</param>
// **********************************************************************
//
public SHFILEINFO(bool b)
{
hIcon = IntPtr.Zero;
iIcon = 0;
dwAttributes = 0;
szDisplayName = "";
szTypeName = "";
}
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_TYPE)]
public string szTypeName;
};
[Flags]
enum SHGFI : int
{
//
// **********************************************************************
/// <summary>get icon</summary>
// **********************************************************************
//
Icon = 0x000000100,
//
// **********************************************************************
/// <summary>get display name</summary>
// **********************************************************************
//
DisplayName = 0x000000200,
//
// **********************************************************************
/// <summary>get type name</summary>
// **********************************************************************
//
TypeName = 0x000000400,
//
// **********************************************************************
/// <summary>get attributes</summary>
// **********************************************************************
//
Attributes = 0x000000800,
//
// **********************************************************************
/// <summary>get icon location</summary>
// **********************************************************************
//
IconLocation = 0x000001000,
//
// **********************************************************************
/// <summary>return exe type</summary>
// **********************************************************************
//
ExeType = 0x000002000,
//
// **********************************************************************
/// <summary>get system icon index</summary>
// **********************************************************************
//
SysIconIndex = 0x000004000,
//
// **********************************************************************
/// <summary>put a link overlay on icon</summary>
// **********************************************************************
//
LinkOverlay = 0x000008000,
//
// **********************************************************************
/// <summary>show icon in selected state</summary>
// **********************************************************************
//
Selected = 0x000010000,
//
// **********************************************************************
/// <summary>get only specified attributes</summary>
// **********************************************************************
//
Attr_Specified = 0x000020000,
//
// **********************************************************************
/// <summary>get large icon</summary>
// **********************************************************************
//
LargeIcon = 0x000000000,
//
// **********************************************************************
/// <summary>get small icon</summary>
// **********************************************************************
//
SmallIcon = 0x000000001,
//
// **********************************************************************
/// <summary>get open icon</summary>
// **********************************************************************
//
OpenIcon = 0x000000002,
//
// **********************************************************************
/// <summary>get shell size icon</summary>
// **********************************************************************
//
ShellIconize = 0x000000004,
//
// **********************************************************************
/// <summary>pszPath is a pidl</summary>
// **********************************************************************
//
PIDL = 0x000000008,
//
// **********************************************************************
/// <summary>use passed dwFileAttribute</summary>
// **********************************************************************
//
UseFileAttributes = 0x000000010,
//
// **********************************************************************
/// <summary>apply the appropriate overlays</summary>
// **********************************************************************
//
AddOverlays = 0x000000020,
//
// **********************************************************************
/// <summary>Get the index of the overlay in the upper 8 bits of the iIcon</summary>
// **********************************************************************
//
OverlayIndex = 0x000000040,
}
#endregion
#region Member Variables
//
// **********************************************************************
/// <summary>
/// Extension Icons
/// </summary>
// **********************************************************************
//
static Dictionary<string, Icon> m_ExtensionIcons = new Dictionary<string, Icon>(StringComparer.OrdinalIgnoreCase);
#endregion
#region Static Methods
//
// **********************************************************************
/// <summary>
/// Checks if file available for writing.
/// Returns write exception or null if file is available for writing.
/// </summary>
/// <param name="fileName">name of file to check</param>
/// <returns>
/// file write exception or null if file is available for writing
/// </returns>
// **********************************************************************
//
static public Exception GetWriteException(string fileName)
{
try
{
if (File.Exists(fileName))
{
using (File.OpenWrite(fileName))
{
}
}
else
{
using (File.Create(fileName))
{
}
File.Delete(fileName);
}
return null;
}
catch (Exception e)
{
return e;
}
}
//
// **********************************************************************
/// <summary>
/// Checks if file available for writing.
/// </summary>
/// <param name="fileName">name of file to check</param>
/// <returns>
/// true if file can be written or false otherwise
/// </returns>
// **********************************************************************
//
static public bool IsAvailableToWrite(string fileName)
{
return GetWriteException(fileName) == null;
}
//
// **********************************************************************
/// <summary>
/// Check if given file is available to write.
/// If write exception occurred, executes exception handler.
/// </summary>
/// <param name="fileName">file to check</param>
/// <param name="exceptionHandler">exception handler to execute on write error</param>
// **********************************************************************
//
static public void TryToWrite(string fileName, DxFileExceptionHandler exceptionHandler)
{
Exception e = GetWriteException(fileName);
if (e != null)
{
if (exceptionHandler != null)
{
exceptionHandler(fileName, e);
}
else
{
throw e;
}
}
}
//
// **********************************************************************
/// <summary>
/// Creates temporary file in temporary folder.
/// </summary>
/// <returns>created file name</returns>
// **********************************************************************
//
static public string CreateTempFile()
{
return Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
}
//
// **********************************************************************
/// <summary>
/// Deletes a file without raising an exception.
/// </summary>
/// <param name="fileName">file to delete</param>
/// <returns>true if file was deleted indeed</returns>
// **********************************************************************
//
static public bool SilentDelete(string fileName)
{
if (ConvertUtils.NotEmpty(fileName))
{
try
{
File.Delete(fileName);
return true;
}
catch
{
return false;
}
}
return false;
}
//
// **********************************************************************
/// <summary>
/// Sets file attributes for all files in specified path, including all
/// subfolders.
/// </summary>
/// <param name="path">target path</param>
/// <param name="fileMask">target file mask to set attributes</param>
/// <param name="fileAttr">attributes to set</param>
// **********************************************************************
//
static public void SetAttrRecurrent(string path, string fileMask, FileAttributes fileAttr)
{
string[] files = Directory.GetFiles(path, fileMask);
foreach (string fileName in files)
File.SetAttributes(fileName, fileAttr);
string[] dirs = Directory.GetDirectories(path, fileMask);
foreach (string dirName in dirs)
SetAttrRecurrent(dirName, fileMask, fileAttr);
}
//
// **********************************************************************
/// <summary>
/// Loads file from embedded resources.
/// </summary>
/// <param name="fileName">name of the file</param>
/// <param name="type">type to get assembly and namespace</param>
/// <returns>file contents</returns>
// **********************************************************************
//
static public string LoadContentFromResource(string fileName, Type type)
{
Stream stream = type.Assembly.GetManifestResourceStream(type.Namespace + "." + fileName);
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
Decoder decoder = Encoding.ASCII.GetDecoder();
char[] chars = new char[decoder.GetCharCount(bytes, 0, bytes.Length)];
decoder.GetChars(bytes, 0, bytes.Length, chars, 0);
string s = new string(chars);
return s;
}
//
// **********************************************************************
/// <summary>
/// Returns associated icon for the file.
/// </summary>
/// <param name="fileName">file name</param>
/// <param name="large">true to return large icon</param>
/// <returns>associated icon</returns>
// **********************************************************************
//
static private Icon GetAssociatedIcon(string fileName, bool large)
{
SHFILEINFO info = new SHFILEINFO(true);
int cbFileInfo = Marshal.SizeOf(info);
SHGFI flags = (large) ? SHGFI.Icon | SHGFI.LargeIcon | SHGFI.UseFileAttributes : SHGFI.Icon | SHGFI.SmallIcon | SHGFI.UseFileAttributes;
SHGetFileInfo(fileName, 256, out info, (uint)cbFileInfo, flags);
return (Icon)Icon.FromHandle(info.hIcon);
}
//
// **********************************************************************
/// <summary>
/// Returns content type for the given file.
/// Content type is determined by the file extension.
/// </summary>
/// <param name="fileName">file name to return content type for</param>
/// <returns>content type string</returns>
// **********************************************************************
//
static public string GetFileContentType(string fileName)
{
if (ConvertUtils.IsEmpty(fileName))
return null;
string extension = Path.GetExtension(fileName);
if (ConvertUtils.IsEmpty(extension))
return null;
if (!extension.StartsWith("."))
extension = "." + extension;
RegistryKey extKey = Registry.ClassesRoot.OpenSubKey(extension);
if (extKey != null)
{
string contentType = ConvertUtils.ToString(extKey.GetValue("Content Type"));
extKey.Close();
return contentType;
}
return null;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Routing;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Plugins;
using Nop.Plugin.Payments.PayPalDirect.Controllers;
using Nop.Plugin.Payments.PayPalDirect.PayPalSvc;
using Nop.Services.Configuration;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Services.Payments;
namespace Nop.Plugin.Payments.PayPalDirect
{
/// <summary>
/// PayPalDirect payment processor
/// </summary>
public class PayPalDirectPaymentProcessor : BasePlugin, IPaymentMethod
{
#region Fields
private readonly PayPalDirectPaymentSettings _paypalDirectPaymentSettings;
private readonly ISettingService _settingService;
private readonly ICurrencyService _currencyService;
private readonly ICustomerService _customerService;
private readonly CurrencySettings _currencySettings;
private readonly IWebHelper _webHelper;
private readonly IOrderTotalCalculationService _orderTotalCalculationService;
#endregion
#region Ctor
public PayPalDirectPaymentProcessor(PayPalDirectPaymentSettings paypalDirectPaymentSettings,
ISettingService settingService,
ICurrencyService currencyService, ICustomerService customerService,
CurrencySettings currencySettings, IWebHelper webHelper,
IOrderTotalCalculationService orderTotalCalculationService)
{
this._paypalDirectPaymentSettings = paypalDirectPaymentSettings;
this._settingService = settingService;
this._currencyService = currencyService;
this._customerService = customerService;
this._currencySettings = currencySettings;
this._webHelper = webHelper;
this._orderTotalCalculationService = orderTotalCalculationService;
}
#endregion
#region Utilities
/// <summary>
/// Gets Paypal URL
/// </summary>
/// <returns></returns>
private string GetPaypalUrl()
{
return _paypalDirectPaymentSettings.UseSandbox ? "https://www.sandbox.paypal.com/us/cgi-bin/webscr" :
"https://www.paypal.com/us/cgi-bin/webscr";
}
/// <summary>
/// Get Paypal country code
/// </summary>
/// <param name="country">Country</param>
/// <returns>Paypal country code</returns>
protected CountryCodeType GetPaypalCountryCodeType(Country country)
{
CountryCodeType payerCountry = CountryCodeType.US;
try
{
payerCountry = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.TwoLetterIsoCode);
}
catch
{
}
return payerCountry;
}
/// <summary>
/// Get Paypal credit card type
/// </summary>
/// <param name="creditCardType">Credit card type</param>
/// <returns>Paypal credit card type</returns>
protected CreditCardTypeType GetPaypalCreditCardType(string creditCardType)
{
var creditCardTypeType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), creditCardType);
return creditCardTypeType;
//if (creditCardType.ToLower() == "visa")
// return CreditCardTypeType.Visa;
//if (creditCardType.ToLower() == "mastercard")
// return CreditCardTypeType.MasterCard;
//if (creditCardType.ToLower() == "americanexpress")
// return CreditCardTypeType.Amex;
//if (creditCardType.ToLower() == "discover")
// return CreditCardTypeType.Discover;
//throw new NopException("Unknown credit card type");
}
protected string GetApiVersion()
{
return "63";
}
protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
{
var result = new ProcessPaymentResult();
var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
if (customer == null)
throw new Exception("Customer cannot be loaded");
var req = new DoDirectPaymentReq();
req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
req.DoDirectPaymentRequest.Version = GetApiVersion();
var details = new DoDirectPaymentRequestDetailsType();
req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
if (authorizeOnly)
details.PaymentAction = PaymentActionCodeType.Authorization;
else
details.PaymentAction = PaymentActionCodeType.Sale;
//credit card
details.CreditCard = new CreditCardDetailsType();
details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
details.CreditCard.ExpMonthSpecified = true;
details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
details.CreditCard.ExpYearSpecified = true;
details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
details.CreditCard.CardOwner = new PayerInfoType();
details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country);
details.CreditCard.CreditCardTypeSpecified = true;
//billing address
details.CreditCard.CardOwner.Address = new AddressType();
details.CreditCard.CardOwner.Address.CountrySpecified = true;
details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
if (customer.BillingAddress.StateProvince != null)
details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
else
details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(customer.BillingAddress.Country);
details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
details.CreditCard.CardOwner.PayerName = new PersonNameType();
details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;
//order totals
var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
details.PaymentDetails = new PaymentDetailsType();
details.PaymentDetails.OrderTotal = new BasicAmountType();
details.PaymentDetails.OrderTotal.Value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
details.PaymentDetails.Custom = processPaymentRequest.OrderGuid.ToString();
details.PaymentDetails.ButtonSource = "nopCommerceCart";
//pass product names and totals to PayPal
//if (_paypalDirectPaymentSettings.PassProductNamesAndTotals)
//{
// //individual items
//var cart = customer.ShoppingCartItems
// .Where(x=>x.ShoppingCartType == ShoppingCartType.ShoppingCart)
// .LimitPerStore(processPaymentRequest.StoreId)
// .ToList();
// var cartItems = new PaymentDetailsItemType[cart.Count];
// for (int i = 0; i < cart.Count; i++)
// {
// var sc = cart[i];
// decimal taxRate = decimal.Zero;
// var customer = processPaymentRequest.Customer;
// decimal scUnitPrice = _priceCalculationService.GetUnitPrice(sc, true);
// decimal scSubTotal = _priceCalculationService.GetSubTotal(sc, true);
// decimal scUnitPriceInclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, true, customer, out taxRate);
// decimal scUnitPriceExclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, false, customer, out taxRate);
// //decimal scSubTotalInclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, true, customer, out taxRate);
// //decimal scSubTotalExclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, false, customer, out taxRate);
// cartItems[i] = new PaymentDetailsItemType()
// {
// Name = sc.ProductVariant.FullProductName,
// Number = sc.ProductVariant.Id.ToString(),
// Quantity = sc.Quantity.ToString(),
// Amount = new BasicAmountType()
// {
// currencyID = payPalCurrency,
// Value = scUnitPriceExclTax.ToString("N", new CultureInfo("en-us")),
// },
// Tax = new BasicAmountType()
// {
// currencyID = payPalCurrency,
// Value = (scUnitPriceInclTax - scUnitPriceExclTax).ToString("N", new CultureInfo("en-us")),
// },
// };
// };
// details.PaymentDetails.PaymentDetailsItem = cartItems;
// //other totals (undone)
// details.PaymentDetails.ItemTotal = null;
// details.PaymentDetails.ShippingTotal = null;
// details.PaymentDetails.TaxTotal = null;
// details.PaymentDetails.HandlingTotal = null;
//}
//shipping
if (customer.ShippingAddress != null)
{
if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
{
var shippingAddress = new AddressType();
shippingAddress.Name = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
shippingAddress.Street1 = customer.ShippingAddress.Address1;
shippingAddress.CityName = customer.ShippingAddress.City;
shippingAddress.StateOrProvince = customer.ShippingAddress.StateProvince.Abbreviation;
shippingAddress.PostalCode = customer.ShippingAddress.ZipPostalCode;
shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
shippingAddress.CountrySpecified = true;
details.PaymentDetails.ShipToAddress = shippingAddress;
}
}
//send request
using (var service2 = new PayPalAPIAASoapBinding())
{
if (!_paypalDirectPaymentSettings.UseSandbox)
service2.Url = "https://api-3t.paypal.com/2.0/";
else
service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";
service2.RequesterCredentials = new CustomSecurityHeaderType();
service2.RequesterCredentials.Credentials = new UserIdPasswordType();
service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
service2.RequesterCredentials.Credentials.Subject = "";
DoDirectPaymentResponseType response = service2.DoDirectPayment(req);
string error = "";
bool success = PaypalHelper.CheckSuccess(response, out error);
if (success)
{
result.AvsResult = response.AVSCode;
result.AuthorizationTransactionCode = response.CVV2Code;
if (authorizeOnly)
{
result.AuthorizationTransactionId = response.TransactionID;
result.AuthorizationTransactionResult = response.Ack.ToString();
result.NewPaymentStatus = PaymentStatus.Authorized;
}
else
{
result.CaptureTransactionId = response.TransactionID;
result.CaptureTransactionResult = response.Ack.ToString();
result.NewPaymentStatus = PaymentStatus.Paid;
}
}
else
{
result.AddError(error);
}
}
return result;
}
/// <summary>
/// Verifies IPN
/// </summary>
/// <param name="formString">Form string</param>
/// <param name="values">Values</param>
/// <returns>Result</returns>
public bool VerifyIPN(string formString, out Dictionary<string, string> values)
{
var req = (HttpWebRequest)WebRequest.Create(GetPaypalUrl());
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string formContent = string.Format("{0}&cmd=_notify-validate", formString);
req.ContentLength = formContent.Length;
using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
{
sw.Write(formContent);
}
string response = null;
using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = HttpUtility.UrlDecode(sr.ReadToEnd());
}
bool success = response.Trim().Equals("VERIFIED", StringComparison.OrdinalIgnoreCase);
values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (string l in formString.Split('&'))
{
string line = l.Trim();
int equalPox = line.IndexOf('=');
if (equalPox >= 0)
values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
}
return success;
}
#endregion
#region Methods
/// <summary>
/// Process a payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
if (_paypalDirectPaymentSettings.TransactMode == TransactMode.Authorize)
{
return AuthorizeOrSale(processPaymentRequest, true);
}
else
{
return AuthorizeOrSale(processPaymentRequest, false);
}
}
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
}
/// <summary>
/// Gets additional handling fee
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>Additional handling fee</returns>
public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
{
var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart,
_paypalDirectPaymentSettings.AdditionalFee, _paypalDirectPaymentSettings.AdditionalFeePercentage);
return result;
}
/// <summary>
/// Captures payment
/// </summary>
/// <param name="capturePaymentRequest">Capture payment request</param>
/// <returns>Capture payment result</returns>
public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
{
var result = new CapturePaymentResult();
string authorizationId = capturePaymentRequest.Order.AuthorizationTransactionId;
var req = new DoCaptureReq();
req.DoCaptureRequest = new DoCaptureRequestType();
req.DoCaptureRequest.Version = GetApiVersion();
req.DoCaptureRequest.AuthorizationID = authorizationId;
req.DoCaptureRequest.Amount = new BasicAmountType();
req.DoCaptureRequest.Amount.Value = Math.Round(capturePaymentRequest.Order.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
req.DoCaptureRequest.Amount.currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
req.DoCaptureRequest.CompleteType = CompleteCodeType.Complete;
using (var service2 = new PayPalAPIAASoapBinding())
{
if (!_paypalDirectPaymentSettings.UseSandbox)
service2.Url = "https://api-3t.paypal.com/2.0/";
else
service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";
service2.RequesterCredentials = new CustomSecurityHeaderType();
service2.RequesterCredentials.Credentials = new UserIdPasswordType();
service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
service2.RequesterCredentials.Credentials.Subject = "";
DoCaptureResponseType response = service2.DoCapture(req);
string error = "";
bool success = PaypalHelper.CheckSuccess(response, out error);
if (success)
{
result.NewPaymentStatus = PaymentStatus.Paid;
result.CaptureTransactionId = response.DoCaptureResponseDetails.PaymentInfo.TransactionID;
result.CaptureTransactionResult = response.Ack.ToString();
}
else
{
result.AddError(error);
}
}
return result;
}
/// <summary>
/// Refunds a payment
/// </summary>
/// <param name="refundPaymentRequest">Request</param>
/// <returns>Result</returns>
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
{
var result = new RefundPaymentResult();
string transactionId = refundPaymentRequest.Order.CaptureTransactionId;
var req = new RefundTransactionReq();
req.RefundTransactionRequest = new RefundTransactionRequestType();
//NOTE: Specify amount in partial refund
req.RefundTransactionRequest.RefundType = RefundType.Full;
req.RefundTransactionRequest.RefundTypeSpecified = true;
req.RefundTransactionRequest.Version = GetApiVersion();
req.RefundTransactionRequest.TransactionID = transactionId;
using (var service1 = new PayPalAPISoapBinding())
{
if (!_paypalDirectPaymentSettings.UseSandbox)
service1.Url = "https://api-3t.paypal.com/2.0/";
else
service1.Url = "https://api-3t.sandbox.paypal.com/2.0/";
service1.RequesterCredentials = new CustomSecurityHeaderType();
service1.RequesterCredentials.Credentials = new UserIdPasswordType();
service1.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
service1.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
service1.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
service1.RequesterCredentials.Credentials.Subject = "";
RefundTransactionResponseType response = service1.RefundTransaction(req);
string error = string.Empty;
bool Success = PaypalHelper.CheckSuccess(response, out error);
if (Success)
{
result.NewPaymentStatus = PaymentStatus.Refunded;
//cancelPaymentResult.RefundTransactionID = response.RefundTransactionID;
}
else
{
result.AddError(error);
}
}
return result;
}
/// <summary>
/// Voids a payment
/// </summary>
/// <param name="voidPaymentRequest">Request</param>
/// <returns>Result</returns>
public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
{
var result = new VoidPaymentResult();
string transactionId = voidPaymentRequest.Order.AuthorizationTransactionId;
if (String.IsNullOrEmpty(transactionId))
transactionId = voidPaymentRequest.Order.CaptureTransactionId;
var req = new DoVoidReq();
req.DoVoidRequest = new DoVoidRequestType();
req.DoVoidRequest.Version = GetApiVersion();
req.DoVoidRequest.AuthorizationID = transactionId;
using (var service2 = new PayPalAPIAASoapBinding())
{
if (!_paypalDirectPaymentSettings.UseSandbox)
service2.Url = "https://api-3t.paypal.com/2.0/";
else
service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";
service2.RequesterCredentials = new CustomSecurityHeaderType();
service2.RequesterCredentials.Credentials = new UserIdPasswordType();
service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
service2.RequesterCredentials.Credentials.Subject = "";
DoVoidResponseType response = service2.DoVoid(req);
string error = "";
bool success = PaypalHelper.CheckSuccess(response, out error);
if (success)
{
result.NewPaymentStatus = PaymentStatus.Voided;
//result.VoidTransactionID = response.RefundTransactionID;
}
else
{
result.AddError(error);
}
}
return result;
}
/// <summary>
/// Process recurring payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
var req = new CreateRecurringPaymentsProfileReq();
req.CreateRecurringPaymentsProfileRequest = new CreateRecurringPaymentsProfileRequestType();
req.CreateRecurringPaymentsProfileRequest.Version = GetApiVersion();
var details = new CreateRecurringPaymentsProfileRequestDetailsType();
req.CreateRecurringPaymentsProfileRequest.CreateRecurringPaymentsProfileRequestDetails = details;
details.CreditCard = new CreditCardDetailsType();
details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
details.CreditCard.ExpMonthSpecified = true;
details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
details.CreditCard.ExpYearSpecified = true;
details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
details.CreditCard.CardOwner = new PayerInfoType();
details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country);
details.CreditCard.CreditCardTypeSpecified = true;
details.CreditCard.CardOwner.Address = new AddressType();
details.CreditCard.CardOwner.Address.CountrySpecified = true;
details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
if (customer.BillingAddress.StateProvince != null)
details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
else
details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(customer.BillingAddress.Country);
details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
details.CreditCard.CardOwner.PayerName = new PersonNameType();
details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;
//start date
details.RecurringPaymentsProfileDetails = new RecurringPaymentsProfileDetailsType();
details.RecurringPaymentsProfileDetails.BillingStartDate = DateTime.UtcNow;
details.RecurringPaymentsProfileDetails.ProfileReference = processPaymentRequest.OrderGuid.ToString();
//schedule
details.ScheduleDetails = new ScheduleDetailsType();
details.ScheduleDetails.Description = "Recurring payment";
details.ScheduleDetails.PaymentPeriod = new BillingPeriodDetailsType();
details.ScheduleDetails.PaymentPeriod.Amount = new BasicAmountType();
details.ScheduleDetails.PaymentPeriod.Amount.Value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
details.ScheduleDetails.PaymentPeriod.Amount.currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
details.ScheduleDetails.PaymentPeriod.BillingFrequency = processPaymentRequest.RecurringCycleLength;
switch (processPaymentRequest.RecurringCyclePeriod)
{
case RecurringProductCyclePeriod.Days:
details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Day;
break;
case RecurringProductCyclePeriod.Weeks:
details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Week;
break;
case RecurringProductCyclePeriod.Months:
details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Month;
break;
case RecurringProductCyclePeriod.Years:
details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Year;
break;
default:
throw new NopException("Not supported cycle period");
}
details.ScheduleDetails.PaymentPeriod.TotalBillingCycles = processPaymentRequest.RecurringTotalCycles;
details.ScheduleDetails.PaymentPeriod.TotalBillingCyclesSpecified = true;
using (var service2 = new PayPalAPIAASoapBinding())
{
if (!_paypalDirectPaymentSettings.UseSandbox)
service2.Url = "https://api-3t.paypal.com/2.0/";
else
service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";
service2.RequesterCredentials = new CustomSecurityHeaderType();
service2.RequesterCredentials.Credentials = new UserIdPasswordType();
service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
service2.RequesterCredentials.Credentials.Subject = "";
CreateRecurringPaymentsProfileResponseType response = service2.CreateRecurringPaymentsProfile(req);
string error = "";
bool success = PaypalHelper.CheckSuccess(response, out error);
if (success)
{
result.NewPaymentStatus = PaymentStatus.Pending;
if (response.CreateRecurringPaymentsProfileResponseDetails != null)
{
result.SubscriptionTransactionId = response.CreateRecurringPaymentsProfileResponseDetails.ProfileID;
}
}
else
{
result.AddError(error);
}
}
return result;
}
/// <summary>
/// Cancels a recurring payment
/// </summary>
/// <param name="cancelPaymentRequest">Request</param>
/// <returns>Result</returns>
public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
{
var result = new CancelRecurringPaymentResult();
var order = cancelPaymentRequest.Order;
var req = new ManageRecurringPaymentsProfileStatusReq();
req.ManageRecurringPaymentsProfileStatusRequest = new ManageRecurringPaymentsProfileStatusRequestType();
req.ManageRecurringPaymentsProfileStatusRequest.Version = GetApiVersion();
var details = new ManageRecurringPaymentsProfileStatusRequestDetailsType();
req.ManageRecurringPaymentsProfileStatusRequest.ManageRecurringPaymentsProfileStatusRequestDetails = details;
details.Action = StatusChangeActionType.Cancel;
//Recurring payments profile ID returned in the CreateRecurringPaymentsProfile response
details.ProfileID = order.SubscriptionTransactionId;
using (var service2 = new PayPalAPIAASoapBinding())
{
if (!_paypalDirectPaymentSettings.UseSandbox)
service2.Url = "https://api-3t.paypal.com/2.0/";
else
service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";
service2.RequesterCredentials = new CustomSecurityHeaderType();
service2.RequesterCredentials.Credentials = new UserIdPasswordType();
service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
service2.RequesterCredentials.Credentials.Subject = "";
var response = service2.ManageRecurringPaymentsProfileStatus(req);
string error = "";
if (!PaypalHelper.CheckSuccess(response, out error))
{
result.AddError(error);
}
}
return result;
}
/// <summary>
/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
/// </summary>
/// <param name="order">Order</param>
/// <returns>Result</returns>
public bool CanRePostProcessPayment(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
//it's not a redirection payment method. So we always return false
return false;
}
/// <summary>
/// Gets a route for provider configuration
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "Configure";
controllerName = "PaymentPayPalDirect";
routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.PayPalDirect.Controllers" }, { "area", null } };
}
/// <summary>
/// Gets a route for payment info
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "PaymentInfo";
controllerName = "PaymentPayPalDirect";
routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.PayPalDirect.Controllers" }, { "area", null } };
}
public Type GetControllerType()
{
return typeof(PaymentPayPalDirectController);
}
public override void Install()
{
//settings
var settings = new PayPalDirectPaymentSettings()
{
TransactMode = TransactMode.Authorize,
UseSandbox = true,
};
_settingService.SaveSetting(settings);
//locales
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.UseSandbox", "Use Sandbox");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.UseSandbox.Hint", "Check to enable Sandbox (testing environment).");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.TransactMode", "Transaction mode");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.TransactMode.Hint", "Specify transaction mode.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.ApiAccountName", "API Account Name");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.ApiAccountName.Hint", "Specify API account name.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.ApiAccountPassword", "API Account Password");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.ApiAccountPassword.Hint", "Specify API account password.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.Signature", "Signature");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.Signature.Hint", "Specify signature.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.AdditionalFee", "Additional fee");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.AdditionalFee.Hint", "Enter additional fee to charge your customers.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.AdditionalFeePercentage", "Additional fee. Use percentage");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used.");
base.Install();
}
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<PayPalDirectPaymentSettings>();
//locales
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.UseSandbox");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.UseSandbox.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.TransactMode");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.TransactMode.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.ApiAccountName");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.ApiAccountName.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.ApiAccountPassword");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.ApiAccountPassword.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.Signature");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.Signature.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.AdditionalFee");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.AdditionalFee.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.AdditionalFeePercentage");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalDirect.Fields.AdditionalFeePercentage.Hint");
base.Uninstall();
}
#endregion
#region Properies
/// <summary>
/// Gets a value indicating whether capture is supported
/// </summary>
public bool SupportCapture
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether partial refund is supported
/// </summary>
public bool SupportPartiallyRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether refund is supported
/// </summary>
public bool SupportRefund
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether void is supported
/// </summary>
public bool SupportVoid
{
get
{
return true;
}
}
/// <summary>
/// Gets a recurring payment type of payment method
/// </summary>
public RecurringPaymentType RecurringPaymentType
{
get
{
return RecurringPaymentType.Automatic;
}
}
/// <summary>
/// Gets a payment method type
/// </summary>
public PaymentMethodType PaymentMethodType
{
get
{
return PaymentMethodType.Standard;
}
}
/// <summary>
/// Gets a value indicating whether we should display a payment information page for this plugin
/// </summary>
public bool SkipPaymentInfo
{
get
{
return false;
}
}
#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.Diagnostics;
using System.Threading.Tasks;
namespace System.Xml
{
internal partial class ReadContentAsBinaryHelper
{
// Internal methods
internal async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
switch (_state)
{
case State.None:
if (!_reader.CanReadContentAs())
{
throw _reader.CreateReadContentAsException(nameof(ReadContentAsBase64));
}
if (!await InitAsync().ConfigureAwait(false))
{
return 0;
}
break;
case State.InReadContent:
// if we have a correct decoder, go read
if (_decoder == _base64Decoder)
{
// read more binary data
return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
break;
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
Debug.Assert(_state == State.InReadContent);
// setup base64 decoder
InitBase64Decoder();
// read more binary data
return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
internal async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
switch (_state)
{
case State.None:
if (!_reader.CanReadContentAs())
{
throw _reader.CreateReadContentAsException(nameof(ReadContentAsBinHex));
}
if (!await InitAsync().ConfigureAwait(false))
{
return 0;
}
break;
case State.InReadContent:
// if we have a correct decoder, go read
if (_decoder == _binHexDecoder)
{
// read more binary data
return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
break;
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
Debug.Assert(_state == State.InReadContent);
// setup binhex decoder
InitBinHexDecoder();
// read more binary data
return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
internal async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
switch (_state)
{
case State.None:
if (_reader.NodeType != XmlNodeType.Element)
{
throw _reader.CreateReadElementContentAsException(nameof(ReadElementContentAsBase64));
}
if (!await InitOnElementAsync().ConfigureAwait(false))
{
return 0;
}
break;
case State.InReadContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
case State.InReadElementContent:
// if we have a correct decoder, go read
if (_decoder == _base64Decoder)
{
// read more binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
break;
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
Debug.Assert(_state == State.InReadElementContent);
// setup base64 decoder
InitBase64Decoder();
// read more binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
internal async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
switch (_state)
{
case State.None:
if (_reader.NodeType != XmlNodeType.Element)
{
throw _reader.CreateReadElementContentAsException(nameof(ReadElementContentAsBinHex));
}
if (!await InitOnElementAsync().ConfigureAwait(false))
{
return 0;
}
break;
case State.InReadContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
case State.InReadElementContent:
// if we have a correct decoder, go read
if (_decoder == _binHexDecoder)
{
// read more binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
break;
default:
Debug.Fail($"Unexpected state {_state}");
return 0;
}
Debug.Assert(_state == State.InReadElementContent);
// setup binhex decoder
InitBinHexDecoder();
// read more binary data
return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
}
internal async Task FinishAsync()
{
if (_state != State.None)
{
while (await MoveToNextContentNodeAsync(true).ConfigureAwait(false))
;
if (_state == State.InReadElementContent)
{
if (_reader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo);
}
// move off the EndElement
await _reader.ReadAsync().ConfigureAwait(false);
}
}
Reset();
}
// Private methods
private async Task<bool> InitAsync()
{
// make sure we are on a content node
if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false))
{
return false;
}
_state = State.InReadContent;
_isEnd = false;
return true;
}
private async Task<bool> InitOnElementAsync()
{
Debug.Assert(_reader.NodeType == XmlNodeType.Element);
bool isEmpty = _reader.IsEmptyElement;
// move to content or off the empty element
await _reader.ReadAsync().ConfigureAwait(false);
if (isEmpty)
{
return false;
}
// make sure we are on a content node
if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false))
{
if (_reader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo);
}
// move off end element
await _reader.ReadAsync().ConfigureAwait(false);
return false;
}
_state = State.InReadElementContent;
_isEnd = false;
return true;
}
private async Task<int> ReadContentAsBinaryAsync(byte[] buffer, int index, int count)
{
Debug.Assert(_decoder != null);
if (_isEnd)
{
Reset();
return 0;
}
_decoder.SetNextOutputBuffer(buffer, index, count);
for (;;)
{
// use streaming ReadValueChunk if the reader supports it
if (_canReadValueChunk)
{
for (;;)
{
if (_valueOffset < _valueChunkLength)
{
int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset);
_valueOffset += decodedCharsCount;
}
if (_decoder.IsFull)
{
return _decoder.DecodedCount;
}
Debug.Assert(_valueOffset == _valueChunkLength);
if ((_valueChunkLength = await _reader.ReadValueChunkAsync(_valueChunk, 0, ChunkSize).ConfigureAwait(false)) == 0)
{
break;
}
_valueOffset = 0;
}
}
else
{
// read what is reader.Value
string value = await _reader.GetValueAsync().ConfigureAwait(false);
int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset);
_valueOffset += decodedCharsCount;
if (_decoder.IsFull)
{
return _decoder.DecodedCount;
}
}
_valueOffset = 0;
// move to next textual node in the element content; throw on sub elements
if (!await MoveToNextContentNodeAsync(true).ConfigureAwait(false))
{
_isEnd = true;
return _decoder.DecodedCount;
}
}
}
private async Task<int> ReadElementContentAsBinaryAsync(byte[] buffer, int index, int count)
{
if (count == 0)
{
return 0;
}
// read binary
int decoded = await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false);
if (decoded > 0)
{
return decoded;
}
// if 0 bytes returned check if we are on a closing EndElement, throw exception if not
if (_reader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo);
}
// move off the EndElement
await _reader.ReadAsync().ConfigureAwait(false);
_state = State.None;
return 0;
}
private async Task<bool> MoveToNextContentNodeAsync(bool moveIfOnContentNode)
{
do
{
switch (_reader.NodeType)
{
case XmlNodeType.Attribute:
return !moveIfOnContentNode;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
if (!moveIfOnContentNode)
{
return true;
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.EndEntity:
// skip comments, pis and end entity nodes
break;
case XmlNodeType.EntityReference:
if (_reader.CanResolveEntity)
{
_reader.ResolveEntity();
break;
}
goto default;
default:
return false;
}
moveIfOnContentNode = false;
} while (await _reader.ReadAsync().ConfigureAwait(false));
return false;
}
}
}
| |
// 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 System.ComponentModel.Composition;
using System.Windows.Media;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
// TODO: Localization - How to localize the different classification names
namespace Microsoft.PythonTools.Repl {
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveBlackFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - Black";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveBlackFormatDefinition() {
DisplayName = Strings.PythonInteractive_Black;
ForegroundColor = Colors.Black;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveDarkRedFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - DarkRed";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveDarkRedFormatDefinition() {
DisplayName = Strings.PythonInteractive_DarkRed;
ForegroundColor = Color.FromRgb(0x7f, 0, 0);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveDarkGreenFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - DarkGreen";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveDarkGreenFormatDefinition() {
DisplayName = Strings.PythonInteractive_DarkGreen;
ForegroundColor = Color.FromRgb(0x00, 0x7f, 0);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveDarkYellowFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - DarkYellow";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveDarkYellowFormatDefinition() {
DisplayName = Strings.PythonInteractive_DarkYellow;
ForegroundColor = Color.FromRgb(0x7f, 0x7f, 0);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveDarkBlueFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - DarkBlue";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveDarkBlueFormatDefinition() {
DisplayName = Strings.PythonInteractive_DarkBlue;
ForegroundColor = Color.FromRgb(0x00, 0x00, 0x7f);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveDarkMagentaFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - DarkMagenta";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveDarkMagentaFormatDefinition() {
DisplayName = Strings.PythonInteractive_DarkMagenta;
ForegroundColor = Color.FromRgb(0x7f, 0x00, 0x7f);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveDarkCyanFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - DarkCyan";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveDarkCyanFormatDefinition() {
DisplayName = Strings.PythonInteractive_DarkCyan;
ForegroundColor = Color.FromRgb(0x00, 0x7f, 0x7f);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveGrayFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - Gray";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveGrayFormatDefinition() {
DisplayName = Strings.PythonInteractive_Gray;
ForegroundColor = Color.FromRgb(0xC0, 0xC0, 0xC0);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveDarkGrayFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - DarkGray";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveDarkGrayFormatDefinition() {
DisplayName = Strings.PythonInteractive_DarkGray;
ForegroundColor = Color.FromRgb(0x7f, 0x7f, 0x7f);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveRedFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - Red";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveRedFormatDefinition() {
DisplayName = Strings.PythonInteractive_Red;
ForegroundColor = Color.FromRgb(0xff, 0, 0);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveGreenFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - Green";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveGreenFormatDefinition() {
DisplayName = Strings.PythonInteractive_Green;
ForegroundColor = Color.FromRgb(0x00, 0xff, 0);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveYellowFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - Yellow";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveYellowFormatDefinition() {
DisplayName = Strings.PythonInteractive_Yellow;
ForegroundColor = Color.FromRgb(0xff, 0xff, 0);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
[Order(After = Priority.Default, Before = Priority.High)]
internal class InteractiveBlueFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - Blue";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveBlueFormatDefinition() {
DisplayName = Strings.PythonInteractive_Blue;
ForegroundColor = Color.FromRgb(0x00, 0x00, 0xff);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveMagentaFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - Magenta";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveMagentaFormatDefinition() {
DisplayName = Strings.PythonInteractive_Magenta;
ForegroundColor = Color.FromRgb(0xff, 0x00, 0xff);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveCyanFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - Cyan";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveCyanFormatDefinition() {
DisplayName = Strings.PythonInteractive_Cyan;
ForegroundColor = Color.FromRgb(0x00, 0xff, 0xff);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Name)]
[Name(Name)]
[UserVisible(true)]
internal class InteractiveWhiteFormatDefinition : ClassificationFormatDefinition {
public const string Name = "Python Interactive - White";
[Export]
[Name(Name)]
[BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)]
internal static ClassificationTypeDefinition Definition = null; // Set via MEF
public InteractiveWhiteFormatDefinition() {
DisplayName = Strings.PythonInteractive_White;
ForegroundColor = Color.FromRgb(0xff, 0xff, 0xff);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel.Claims
{
using System;
using System.Xml;
/// <summary>
/// Dictionary of naming elements relevant to Windows Identity Foundation.
/// </summary>
internal sealed class SessionDictionary : XmlDictionary
{
static readonly SessionDictionary instance = new SessionDictionary();
XmlDictionaryString _claim;
XmlDictionaryString _sct;
XmlDictionaryString _issuer;
XmlDictionaryString _originalIssuer;
XmlDictionaryString _issuerRef;
XmlDictionaryString _claimCollection;
XmlDictionaryString _actor;
XmlDictionaryString _claimProperty;
XmlDictionaryString _claimProperties;
XmlDictionaryString _value;
XmlDictionaryString _valueType;
XmlDictionaryString _label;
XmlDictionaryString _claimPropertyName;
XmlDictionaryString _claimPropertyValue;
XmlDictionaryString _type;
XmlDictionaryString _subjectId;
XmlDictionaryString _contextId;
XmlDictionaryString _authenticationType;
XmlDictionaryString _nameClaimType;
XmlDictionaryString _roleClaimType;
XmlDictionaryString _version;
XmlDictionaryString _scVersion;
XmlDictionaryString _emptyString;
XmlDictionaryString _nullValue;
XmlDictionaryString _key;
XmlDictionaryString _effectiveTime;
XmlDictionaryString _expiryTime;
XmlDictionaryString _keyGeneration;
XmlDictionaryString _keyEffectiveTime;
XmlDictionaryString _keyExpiryTime;
XmlDictionaryString _sessionId;
XmlDictionaryString _id;
XmlDictionaryString _validFrom;
XmlDictionaryString _validTo;
XmlDictionaryString _sesionToken;
XmlDictionaryString _sesionTokenCookie;
XmlDictionaryString _bootStrapToken;
XmlDictionaryString _context;
XmlDictionaryString _claimsPrincipal;
XmlDictionaryString _windowsPrincipal;
XmlDictionaryString _windowsIdentity;
XmlDictionaryString _identity;
XmlDictionaryString _identities;
XmlDictionaryString _windowsLogonName;
XmlDictionaryString _persistentTrue;
XmlDictionaryString _sctAuthorizationPolicy;
XmlDictionaryString _right;
XmlDictionaryString _endpointId;
XmlDictionaryString _windowsSidClaim;
XmlDictionaryString _denyOnlySidClaim;
XmlDictionaryString _x500DistinguishedNameClaim;
XmlDictionaryString _x509ThumbprintClaim;
XmlDictionaryString _nameClaim;
XmlDictionaryString _dnsClaim;
XmlDictionaryString _rsaClaim;
XmlDictionaryString _mailAddressClaim;
XmlDictionaryString _systemClaim;
XmlDictionaryString _hashClaim;
XmlDictionaryString _spnClaim;
XmlDictionaryString _upnClaim;
XmlDictionaryString _urlClaim;
XmlDictionaryString _sid;
XmlDictionaryString _referenceModeTrue;
private SessionDictionary()
{
_claim = Add("Claim");
_sct = Add("SecurityContextToken");
_version = Add("Version");
_scVersion = Add("SecureConversationVersion");
_issuer = Add("Issuer");
_originalIssuer = Add("OriginalIssuer");
_issuerRef = Add("IssuerRef");
_claimCollection = Add("ClaimCollection");
_actor = Add("Actor");
_claimProperty = Add("ClaimProperty");
_claimProperties = Add("ClaimProperties");
_value = Add("Value");
_valueType = Add("ValueType");
_label = Add("Label");
_type = Add("Type");
_subjectId = Add("subjectID");
_claimPropertyName = Add("ClaimPropertyName");
_claimPropertyValue = Add("ClaimPropertyValue");
_authenticationType = Add("AuthenticationType");
_nameClaimType = Add("NameClaimType");
_roleClaimType = Add("RoleClaimType");
_nullValue = Add("Null");
_emptyString = Add(String.Empty);
_key = Add("Key");
_effectiveTime = Add("EffectiveTime");
_expiryTime = Add("ExpiryTime");
_keyGeneration = Add("KeyGeneration");
_keyEffectiveTime = Add("KeyEffectiveTime");
_keyExpiryTime = Add("KeyExpiryTime");
_sessionId = Add("SessionId");
_id = Add("Id");
_validFrom = Add("ValidFrom");
_validTo = Add("ValidTo");
_contextId = Add("ContextId");
_sesionToken = Add("SessionToken");
_sesionTokenCookie = Add("SessionTokenCookie");
_bootStrapToken = Add("BootStrapToken");
_context = Add("Context");
_claimsPrincipal = Add("ClaimsPrincipal");
_windowsPrincipal = Add("WindowsPrincipal");
_windowsIdentity = Add("WindowIdentity");
_identity = Add("Identity");
_identities = Add("Identities");
_windowsLogonName = Add("WindowsLogonName");
_persistentTrue = Add("PersistentTrue");
_sctAuthorizationPolicy = Add("SctAuthorizationPolicy");
_right = Add("Right");
_endpointId = Add("EndpointId");
_windowsSidClaim = Add("WindowsSidClaim");
_denyOnlySidClaim = Add("DenyOnlySidClaim");
_x500DistinguishedNameClaim = Add("X500DistinguishedNameClaim");
_x509ThumbprintClaim = Add("X509ThumbprintClaim");
_nameClaim = Add("NameClaim");
_dnsClaim = Add("DnsClaim");
_rsaClaim = Add("RsaClaim");
_mailAddressClaim = Add("MailAddressClaim");
_systemClaim = Add("SystemClaim");
_hashClaim = Add("HashClaim");
_spnClaim = Add("SpnClaim");
_upnClaim = Add("UpnClaim");
_urlClaim = Add("UrlClaim");
_sid = Add("Sid");
_referenceModeTrue = Add("ReferenceModeTrue");
}
#pragma warning disable 1591
public static SessionDictionary Instance
{
get { return instance; }
}
public XmlDictionaryString PersistentTrue
{
get { return _persistentTrue; }
}
public XmlDictionaryString WindowsLogonName
{
get { return _windowsLogonName; }
}
public XmlDictionaryString ClaimsPrincipal
{
get { return _claimsPrincipal; }
}
public XmlDictionaryString WindowsPrincipal
{
get { return _windowsPrincipal; }
}
public XmlDictionaryString WindowsIdentity
{
get { return _windowsIdentity; }
}
public XmlDictionaryString Identity
{
get { return _identity; }
}
public XmlDictionaryString Identities
{
get { return _identities; }
}
public XmlDictionaryString SessionId
{
get { return _sessionId; }
}
public XmlDictionaryString ReferenceModeTrue
{
get { return _referenceModeTrue; }
}
public XmlDictionaryString ValidFrom
{
get { return _validFrom; }
}
public XmlDictionaryString ValidTo
{
get { return _validTo; }
}
public XmlDictionaryString EffectiveTime
{
get { return _effectiveTime; }
}
public XmlDictionaryString ExpiryTime
{
get { return _expiryTime; }
}
public XmlDictionaryString KeyEffectiveTime
{
get { return _keyEffectiveTime; }
}
public XmlDictionaryString KeyExpiryTime
{
get { return _keyExpiryTime; }
}
public XmlDictionaryString Claim
{
get { return _claim; }
}
public XmlDictionaryString Issuer
{
get { return _issuer; }
}
public XmlDictionaryString OriginalIssuer
{
get { return _originalIssuer; }
}
public XmlDictionaryString IssuerRef
{
get { return _issuerRef; }
}
public XmlDictionaryString ClaimCollection
{
get { return _claimCollection; }
}
public XmlDictionaryString Actor
{
get { return _actor; }
}
public XmlDictionaryString ClaimProperties
{
get { return _claimProperties; }
}
public XmlDictionaryString ClaimProperty
{
get { return _claimProperty; }
}
public XmlDictionaryString Value
{
get { return _value; }
}
public XmlDictionaryString ValueType
{
get { return _valueType; }
}
public XmlDictionaryString Label
{
get { return _label; }
}
public XmlDictionaryString Type
{
get { return _type; }
}
public XmlDictionaryString SubjectId
{
get { return _subjectId; }
}
public XmlDictionaryString ClaimPropertyName
{
get { return _claimPropertyName; }
}
public XmlDictionaryString ClaimPropertyValue
{
get { return _claimPropertyValue; }
}
public XmlDictionaryString AuthenticationType
{
get { return _authenticationType; }
}
public XmlDictionaryString NameClaimType
{
get { return _nameClaimType; }
}
public XmlDictionaryString RoleClaimType
{
get { return _roleClaimType; }
}
public XmlDictionaryString NullValue
{
get { return _nullValue; }
}
public XmlDictionaryString SecurityContextToken
{
get { return _sct; }
}
public XmlDictionaryString Version
{
get { return _version; }
}
public XmlDictionaryString SecureConversationVersion
{
get { return _scVersion; }
}
public XmlDictionaryString EmptyString
{
get { return _emptyString; }
}
public XmlDictionaryString Key
{
get { return _key; }
}
public XmlDictionaryString KeyGeneration
{
get { return _keyGeneration; }
}
public XmlDictionaryString Id
{
get { return _id; }
}
public XmlDictionaryString ContextId
{
get { return _contextId; }
}
public XmlDictionaryString SessionToken
{
get { return _sesionToken; }
}
public XmlDictionaryString SessionTokenCookie
{
get { return _sesionTokenCookie; }
}
public XmlDictionaryString BootstrapToken
{
get { return _bootStrapToken; }
}
public XmlDictionaryString Context
{
get { return _context; }
}
public XmlDictionaryString SctAuthorizationPolicy
{
get { return _sctAuthorizationPolicy; }
}
public XmlDictionaryString Right
{
get { return _right; }
}
public XmlDictionaryString EndpointId
{
get { return _endpointId; }
}
public XmlDictionaryString WindowsSidClaim
{
get { return _windowsSidClaim; }
}
public XmlDictionaryString DenyOnlySidClaim
{
get { return _denyOnlySidClaim; }
}
public XmlDictionaryString X500DistinguishedNameClaim
{
get { return _x500DistinguishedNameClaim; }
}
public XmlDictionaryString X509ThumbprintClaim
{
get { return _x509ThumbprintClaim; }
}
public XmlDictionaryString NameClaim
{
get { return _nameClaim; }
}
public XmlDictionaryString DnsClaim
{
get { return _dnsClaim; }
}
public XmlDictionaryString RsaClaim
{
get { return _rsaClaim; }
}
public XmlDictionaryString MailAddressClaim
{
get { return _mailAddressClaim; }
}
public XmlDictionaryString SystemClaim
{
get { return _systemClaim; }
}
public XmlDictionaryString HashClaim
{
get { return _hashClaim; }
}
public XmlDictionaryString SpnClaim
{
get { return _spnClaim; }
}
public XmlDictionaryString UpnClaim
{
get { return _upnClaim; }
}
public XmlDictionaryString UrlClaim
{
get { return _urlClaim; }
}
public XmlDictionaryString Sid
{
get { return _sid; }
}
#pragma warning restore 1591
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BroadcastScalarToVector128Single()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__BroadcastScalarToVector128Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__BroadcastScalarToVector128Single testClass)
{
var result = Avx2.BroadcastScalarToVector128(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__BroadcastScalarToVector128Single testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar1;
private Vector128<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__BroadcastScalarToVector128Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleUnaryOpTest__BroadcastScalarToVector128Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.BroadcastScalarToVector128(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.BroadcastScalarToVector128(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.BroadcastScalarToVector128(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.BroadcastScalarToVector128(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse.LoadVector128((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var result = Avx2.BroadcastScalarToVector128(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Single();
var result = Avx2.BroadcastScalarToVector128(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Single();
fixed (Vector128<Single>* pFld1 = &test._fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.BroadcastScalarToVector128(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = Avx2.BroadcastScalarToVector128(
Sse.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.BroadcastScalarToVector128(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.BroadcastScalarToVector128(
Sse.LoadVector128((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector128)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.Caching.SqlServer
{
/// <summary>
/// Distributed cache implementation using Microsoft SQL Server database.
/// </summary>
public class SqlServerCache : IDistributedCache
{
private static readonly TimeSpan MinimumExpiredItemsDeletionInterval = TimeSpan.FromMinutes(5);
private static readonly TimeSpan DefaultExpiredItemsDeletionInterval = TimeSpan.FromMinutes(30);
private readonly IDatabaseOperations _dbOperations;
private readonly ISystemClock _systemClock;
private readonly TimeSpan _expiredItemsDeletionInterval;
private DateTimeOffset _lastExpirationScan;
private readonly Action _deleteExpiredCachedItemsDelegate;
private readonly TimeSpan _defaultSlidingExpiration;
private readonly Object _mutex = new Object();
/// <summary>
/// Initializes a new instance of <see cref="SqlServerCache"/>.
/// </summary>
/// <param name="options">The configuration options.</param>
public SqlServerCache(IOptions<SqlServerCacheOptions> options)
{
var cacheOptions = options.Value;
if (string.IsNullOrEmpty(cacheOptions.ConnectionString))
{
throw new ArgumentException(
$"{nameof(SqlServerCacheOptions.ConnectionString)} cannot be empty or null.");
}
if (string.IsNullOrEmpty(cacheOptions.SchemaName))
{
throw new ArgumentException(
$"{nameof(SqlServerCacheOptions.SchemaName)} cannot be empty or null.");
}
if (string.IsNullOrEmpty(cacheOptions.TableName))
{
throw new ArgumentException(
$"{nameof(SqlServerCacheOptions.TableName)} cannot be empty or null.");
}
if (cacheOptions.ExpiredItemsDeletionInterval.HasValue &&
cacheOptions.ExpiredItemsDeletionInterval.Value < MinimumExpiredItemsDeletionInterval)
{
throw new ArgumentException(
$"{nameof(SqlServerCacheOptions.ExpiredItemsDeletionInterval)} cannot be less than the minimum " +
$"value of {MinimumExpiredItemsDeletionInterval.TotalMinutes} minutes.");
}
if (cacheOptions.DefaultSlidingExpiration <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(
nameof(cacheOptions.DefaultSlidingExpiration),
cacheOptions.DefaultSlidingExpiration,
"The sliding expiration value must be positive.");
}
_systemClock = cacheOptions.SystemClock ?? new SystemClock();
_expiredItemsDeletionInterval =
cacheOptions.ExpiredItemsDeletionInterval ?? DefaultExpiredItemsDeletionInterval;
_deleteExpiredCachedItemsDelegate = DeleteExpiredCacheItems;
_defaultSlidingExpiration = cacheOptions.DefaultSlidingExpiration;
// SqlClient library on Mono doesn't have support for DateTimeOffset and also
// it doesn't have support for apis like GetFieldValue, GetFieldValueAsync etc.
// So we detect the platform to perform things differently for Mono vs. non-Mono platforms.
if (PlatformHelper.IsMono)
{
_dbOperations = new MonoDatabaseOperations(
cacheOptions.ConnectionString,
cacheOptions.SchemaName,
cacheOptions.TableName,
_systemClock);
}
else
{
_dbOperations = new DatabaseOperations(
cacheOptions.ConnectionString,
cacheOptions.SchemaName,
cacheOptions.TableName,
_systemClock);
}
}
/// <inheritdoc />
public byte[] Get(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var value = _dbOperations.GetCacheItem(key);
ScanForExpiredItemsIfRequired();
return value;
}
/// <inheritdoc />
public async Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
var value = await _dbOperations.GetCacheItemAsync(key, token).ConfigureAwait(false);
ScanForExpiredItemsIfRequired();
return value;
}
/// <inheritdoc />
public void Refresh(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
_dbOperations.RefreshCacheItem(key);
ScanForExpiredItemsIfRequired();
}
/// <inheritdoc />
public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
await _dbOperations.RefreshCacheItemAsync(key, token).ConfigureAwait(false);
ScanForExpiredItemsIfRequired();
}
/// <inheritdoc />
public void Remove(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
_dbOperations.DeleteCacheItem(key);
ScanForExpiredItemsIfRequired();
}
/// <inheritdoc />
public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
await _dbOperations.DeleteCacheItemAsync(key, token).ConfigureAwait(false);
ScanForExpiredItemsIfRequired();
}
/// <inheritdoc />
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
GetOptions(ref options);
_dbOperations.SetCacheItem(key, value, options);
ScanForExpiredItemsIfRequired();
}
/// <inheritdoc />
public async Task SetAsync(
string key,
byte[] value,
DistributedCacheEntryOptions options,
CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
token.ThrowIfCancellationRequested();
GetOptions(ref options);
await _dbOperations.SetCacheItemAsync(key, value, options, token).ConfigureAwait(false);
ScanForExpiredItemsIfRequired();
}
// Called by multiple actions to see how long it's been since we last checked for expired items.
// If sufficient time has elapsed then a scan is initiated on a background task.
private void ScanForExpiredItemsIfRequired()
{
lock(_mutex)
{
var utcNow = _systemClock.UtcNow;
if ((utcNow - _lastExpirationScan) > _expiredItemsDeletionInterval)
{
_lastExpirationScan = utcNow;
Task.Run(_deleteExpiredCachedItemsDelegate);
}
}
}
private void DeleteExpiredCacheItems()
{
_dbOperations.DeleteExpiredCacheItems();
}
private void GetOptions(ref DistributedCacheEntryOptions options)
{
if (!options.AbsoluteExpiration.HasValue
&& !options.AbsoluteExpirationRelativeToNow.HasValue
&& !options.SlidingExpiration.HasValue)
{
options = new DistributedCacheEntryOptions()
{
SlidingExpiration = _defaultSlidingExpiration
};
}
}
}
}
| |
//*******************************************************
//
// Delphi DataSnap Framework
//
// Copyright(c) 1995-2011 Embarcadero Technologies, Inc.
//
//*******************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using Newtonsoft.Json.Linq;
using System.Windows.Threading;
namespace Embarcadero.Datasnap.WindowsPhone7
{
/*! \mainpage Windows Phone 7 DataSnap Connector
*
* \section intro_sec Introduction
*
* Windows Phone 7 DataSnap Connector is a framework that allows to connect
* to a Datasnap REST server.
*
*
*/
/**
* Allows you to manage and make REST requests based on the protocol, the target
* host , the context and other features. Supports authentication and
* authorization.
*
* Use the properties and methods of DSRESTConnection to: <br>
* - Set the general parameters of a connection as
* target host and port, context, protocol , URL path etc... <br>
* - Setting Username and Password for authentication
* and authorization. <br>
* - Execute a REST request from a {@link DSRESTCommand}
* . <br>
* - Rebuild and save the parameters contained in the
* response.
*
*/
public class DSRESTConnection
{
/**
* This method returns the URL encoded string starting from the input string
* URL. The characters encoding is UTF-8.
* @param value the URL string to encode
* @return the URL string encoded
*/
private string encodeURIComponent(string value)
{
return URLUTF8Encoder.encode(value);
}
/** This method returns the URL encoded string starting from the input
* DSRESTParameter
*
* @param parameter
* the DSRESTParameter to encode
* @return the DSRESTParameter encoded
*/
private String encodeURIComponent(DSRESTParameter parameter)
{
return encodeURIComponent(parameter.getValue().ToString());
}
/**
* Clone the current connection. The session is not cloned, so the cloned
* connection will not have the same session as its parent.
*
* @return the new DSRESTConnection
*/
public DSRESTConnection Clone()
{
return Clone(false);
}
/**
* Clone the current connection. The session is optionally included in the clone.
*
* @param includeSession true to include session information in the new connection, false to exclude it.
*
* @return the new DSRESTConnection
*/
public DSRESTConnection Clone(bool includeSession)
{
DSRESTConnection connection = new DSRESTConnection();
connection.setHost(this.getHost());
connection.setPort(this.getPort());
connection.setProtocol(this.getProtocol());
connection.setUserName(this.getUserName());
connection.setPassword(this.getPassword());
connection.setUrlPath(this.getUrlPath());
connection.setConnectionTimeout(this.getConnectionTimeout());
if (includeSession)
{
connection.setSessionID(this.getSessionID());
connection.SessionIDExpires = this.SessionIDExpires;
}
return connection;
}
protected Uri uri = null;
private int Port = 0;
private String UrlPath = "";
private String Host = "";
private String Protocol = "";
private String Context = "";
private String UserName = "";
private String Password = "";
private int ConnectionTimeout = 0;
public SynchronizationContext syncContext = null;
private String SessionID;
private long SessionIDExpires;
public void setBaseURI(Uri uri)
{
this.uri = uri;
}
public DSRESTConnection()
: base()
{
CloseSession();
syncContext = SynchronizationContext.Current;
}
/**
* This method close the active session
*/
public void CloseSession()
{
SessionID = null;
SessionIDExpires = -1;
}
public DSRESTConnection(Uri uri)
: base()
{
setBaseURI(uri);
syncContext = SynchronizationContext.Current;
}
/**
* Creates a brand new command that belong to this connection.
*
* @return a new DSRESTCommand
*/
/**
* This method create a new DSRESTCommand
*
* @return a new DSRESTCommand
*/
public DSRESTCommand CreateCommand()
{
return new DSRESTCommand(this);
}
/**
* Collects all the informations contained in this object like the target
* host, the protocol; the more information contained in
* {@link DSRESTCommand} input parameter as the type of request, the method
* to call then to return the url to run
*
*
* @param the
* specific DSRESTCommand
* @return a requested url
*/
private String BuildRequestURL(DSRESTCommand command)
{
String LPathPrefix = getUrlPath();
int LPort = getPort();
String LHost = getHost();
String LMethodName = command.getText();
String LProtocol = getProtocol();
if (LProtocol.Equals(""))
LProtocol = "http";
if (LHost.Equals(""))
LHost = "localhost";
if (!LPathPrefix.Equals(""))
LPathPrefix = "/" + LPathPrefix;
String LPortString = "";
if (LPort > 0)
LPortString = ":" + Convert.ToInt32(LPort);
if (command.getRequestType() == DSHTTPRequestType.GET
|| command.getRequestType() == DSHTTPRequestType.DELETE)
{
LMethodName = LMethodName.Substring(0, LMethodName.IndexOf(".")) + "/" + LMethodName.Substring(LMethodName.IndexOf(".") + 1);
LMethodName = LMethodName.Replace("\"", "");
}
else
{
LMethodName = LMethodName.Substring(0, LMethodName.IndexOf(".")) + "/%22" + LMethodName.Substring(LMethodName.IndexOf(".") + 1) + "%22";
LMethodName = LMethodName.Replace("\"", "%22");
}
String LContext = getContext();
if (LContext.Equals(""))
LContext = "datasnap/";
String LUrl = LProtocol + "://" +
encodeURIComponent(LHost) + LPortString + LPathPrefix + "/" + LContext + "rest/" + LMethodName + "/";
SessionID = getSessionID();
return LUrl;
}
/**
* Execute the request from a specific {@link DSRESTCommand} input, that
* will contain useful information to construct the URL as the type of
* request, the method to execute and the parameters to be passed. This
* information be added to those contained in this object as protocol,
* target host, context... They form the complete request to execute. This
* method is need to pass parameters correctly or under the parameter
* direction, it will be append on the url string or written in the body of
* the request. Upon receipt of the response will have to check the
* correctness of the received parameters and set them in the
* {@link DSRESTCommand}.
*
* @param command the specific {@link DSRESTCommand}
* @param Sender DSAdmin
* @param callback Delegate
* @param EXCallback Delegate
*/
public void execute(DSRESTCommand command, DSAdmin Sender, Delegate callback, Delegate EXCallback = null)
{
TJSONArray _parameters = null;
String URL = BuildRequestURL(command);
LinkedList<DSRESTParameter> ParametersToSend = new LinkedList<DSRESTParameter>();
if (command.getParameters().Count > 0)
foreach (DSRESTParameter parameter in command.getParameters())
{
if (parameter.Direction == DSRESTParamDirection.Input ||
parameter.Direction == DSRESTParamDirection.InputOutput)
ParametersToSend.AddLast(parameter);
}
if (command.getRequestType() == DSHTTPRequestType.GET ||
command.getRequestType() == DSHTTPRequestType.DELETE)
{
foreach (DSRESTParameter parameter in ParametersToSend)
URL += encodeURIComponent(parameter) + '/';
}
else // POST or PUT
{
bool CanAddParamsToUrl = true;
_parameters = new TJSONArray();
foreach (DSRESTParameter parameter in ParametersToSend)
if (CanAddParamsToUrl && isURLParameter(parameter))
URL += encodeURIComponent(parameter) + '/';
else // add the json rapresentation in the body
{
CanAddParamsToUrl = false;
parameter.getValue().appendTo(_parameters);
}
}
HttpWebRequest Client = (HttpWebRequest)WebRequest.Create(URL + "?" + DateTime.Now.Ticks.ToString());
HTTPExecutor _executor = null;
try
{
switch (command.getRequestType())
{
case DSHTTPRequestType.GET:
{
_executor = new HTTPGETExecutor(this, Client, command, Sender, callback, EXCallback);
break;
}
case DSHTTPRequestType.DELETE:
{
_executor = new HTTPDELETEExecutor(this, Client, command, Sender, callback, EXCallback);
break;
}
case DSHTTPRequestType.POST:
{
_executor = new HTTPPOSTExecutor(this, Client, command, Sender, callback, EXCallback, _parameters);
break;
}
case DSHTTPRequestType.PUT:
{
_executor = new HTTPPUTExecutor(this, Client, command, Sender, callback, EXCallback, _parameters);
break;
}
default: { break; }
}
if (_executor != null)
{
try
{
_executor.execute();
}
catch (Exception ex)
{
_executor.stop();
throw new DBXException(ex.Message);
}
}
}
catch (DBXException e)
{
throw new DBXException(e.Message);
}
}
private void setSessionIdentifier(HttpWebResponse response)
{
string STRDSSESSION = "dssession=";
string STRDSSESSIONEXPIRES = "dssessionexpires=";
bool found = false;
foreach (String h in response.Headers.AllKeys)
{
if (h.Equals("Pragma", StringComparison.OrdinalIgnoreCase))
{
string[] parts = response.Headers[h].Split(new char[] { ',' });
foreach (string part in parts)
{
if (part.Contains(STRDSSESSION))
{
SessionID = part.Substring(part.IndexOf(STRDSSESSION) + STRDSSESSION.Length);
found = true;
}
if (part.Contains(STRDSSESSIONEXPIRES))
SessionIDExpires = Convert.ToInt64(part.Substring(part.IndexOf(STRDSSESSIONEXPIRES) + STRDSSESSIONEXPIRES.Length));
}
}
}
if (!found)
CloseSession();
}
private bool isURLParameter(DSRESTParameter parameter)
{
return ((parameter.getDBXType() != DBXDataTypes.JsonValueType)
&& (parameter.getDBXType() != DBXDataTypes.BinaryBlobType) && (parameter
.getDBXType() != DBXDataTypes.TableType));
}
/**
* Throw an exception only if the HTTP ERROR CODE is != 200
*
* @param response
*/
private void throwExceptionIfNeeded(HttpWebResponse response)
{
if (response.StatusCode != HttpStatusCode.OK)
{
JObject json = null;
try
{
string resultStr = null;
using (StreamReader rder = new StreamReader(response.GetResponseStream()))
resultStr = rder.ReadToEnd();
json = new JObject(resultStr);
}
catch (Exception)
{
}
if (json == null)
throw new DBXException(response.StatusDescription);
else
throwExceptionIfNeeded(json);
}
}
/**
* Throw an Exception inspecting the returned json object
*
* @param json
*/
private void throwExceptionIfNeeded(JObject json)
{
if (json.ToString().Contains("error"))
throw new DBXException(json.Value<string>("error"));
if (json.ToString().Contains("SessionExpired"))
{
CloseSession();
throw new DBXException(json.Value<string>("SessionExpired"));
}
}
/**
*
* @return the session id of this connection
*/
public String getSessionID()
{
return SessionID;
}
/**
*
* @return the Session ID expires
*/
public long getSessionExpires()
{
return SessionIDExpires;
}
/**
*
* @return the context of this connection
*/
public String getContext()
{
return Context;
}
/**
* This method returns the protocol used
*
* @return the protocol of this connection
*/
public String getProtocol()
{
return Protocol;
}
/**
* This method returns the target host of connection
*
* @return the target host of connection
*/
public String getHost()
{
return Host;
}
/**
* This method returns the target host port of connection
*
* @return the target host port of this connection
*/
public int getPort()
{
return Port;
}
/**
* This method set the target host port of this connection
*
* @param Port
* the value of the target host port
*/
public void setPort(int Port)
{
this.Port = Port;
}
/**
* This method returns the target url path of this connection
*
* @return the target url path of this connection
*/
public String getUrlPath()
{
return UrlPath;
}
/**
* This method set the url Path of the request
*
* @param urlPath
* the target url path
*/
public void setUrlPath(String urlPath)
{
UrlPath = urlPath;
}
/**
* This method set the target host of this connection
*
* @param host
* the target host
*/
public void setHost(String host)
{
Host = host;
}
/**
* This method set the protocol of the requested connection
*
* @param protocol
* the protocol of this connection
*/
public void setProtocol(String protocol)
{
Protocol = protocol;
}
/**
* This method set the context of this connection
*
* @param context
* the context of this connection
*/
public void setContext(String context)
{
Context = context;
}
protected void setSessionID(String sessionID)
{
SessionID = sessionID;
}
/**
* This method set the Username parameter to use for authentication
*
* @param userName
* the Username to use for authentication
*/
public void setUserName(String userName)
{
UserName = userName;
}
/**
* Returns the username setting that will be used for authentication.
*
* @return the username used
*/
public String getUserName()
{
return UserName;
}
/**
* This method set the password parameter to use for authentication
*
* @param password
* the password to use for authentication
*/
public void setPassword(String password)
{
Password = password;
}
/**
* Returns the password setting that will be used for authentication.
*
* @return the password used
*/
public String getPassword()
{
return Password;
}
/**
* Sets the time in milliseconds before a connection's request times out.
* This property should not be set (should be a number below 1) if this connection will
* be used for a heavyweight callback (DSCallbackChannelManager).
*
* @param connectionTimeout the communicationTimeout to set
*/
public void setConnectionTimeout(int connectionTimeout)
{
ConnectionTimeout = connectionTimeout;
}
/**
* Returns the time in milliseconds before a connection's request times out.
*
* @return the connectionTimeout
*/
public int getConnectionTimeout()
{
return ConnectionTimeout;
}
private abstract class HTTPExecutor
{
protected DSRESTConnection connection;
protected HttpWebRequest Client;
protected DSRESTCommand command;
protected DSAdmin Sender;
protected Delegate callback;
protected Delegate EXCallback;
protected DispatcherTimer _Timer;
protected bool _TimedOut;
protected HTTPExecutor(DSRESTConnection connection, HttpWebRequest Client, DSRESTCommand command, DSAdmin Sender, Delegate callback, Delegate EXCallback)
{
this.connection = connection;
this.Client = Client;
this.command = command;
this.Sender = Sender;
this.callback = callback;
this.EXCallback = EXCallback;
this._TimedOut = false;
this._Timer = null;
//don't enable timeout if the request is for a heavyweight callback. Heavyweight callbacks should be timed out
//with custom code, which uses a call to close the channel with the server when the timeout happens.
if (connection.getConnectionTimeout() > 0 && !isHeavyweightCallbackRequest(Client))
{
connection.syncContext.Send(new SendOrPostCallback(x => initTimer()), null);
}
}
private Boolean isHeavyweightCallbackRequest(HttpWebRequest Client)
{
return Client != null && Client.RequestUri.OriginalString.Contains("/datasnap/rest/DSAdmin/%22ConsumeClientChannel%22/");
}
protected void initTimer()
{
try
{
_Timer = new DispatcherTimer();
_Timer.Interval = new TimeSpan(0, 0, 0, 0, connection.getConnectionTimeout());
_TimedOut = false;
// Set the delegate to be notified of a timeout
_Timer.Tick += delegate
{
_TimedOut = true;
_Timer.Stop();
if (EXCallback != null) connection.syncContext.Send(new SendOrPostCallback(x => EXCallback.DynamicInvoke(new DBXException("Request timed out."))), null);
};
}
catch
{
_Timer = null;
_TimedOut = false;
}
}
public bool isTimedOut()
{
return _TimedOut;
}
public void stop()
{
if (_Timer != null) _Timer.Stop();
}
protected void syncStop()
{
if (_Timer != null) connection.syncContext.Send(new SendOrPostCallback(x => _Timer.Stop()), null);
}
protected void start()
{
if (connection.getConnectionTimeout() > 0 && _Timer != null) _Timer.Start();
}
protected void SetUpHeaders(HttpWebRequest Client)
{
if (Client.Method == "POST" || Client.Method == "PUT")
Client.ContentType = "text/plain;charset=UTF-8";
Client.Accept = "application/JSON";
Client.UserAgent = "Mozilla/3.0 (compatible; Indy Library)";
if (connection.SessionID == null)
SetUpAuthorizationHeader(Client);
else
SetUpSessionHeader(Client);
}
protected void SetUpSessionHeader(HttpWebRequest Client)
{
if (connection.SessionID != null)
Client.Headers["Pragma"] = "dssession=" + connection.SessionID;
}
protected void SetUpAuthorizationHeader(HttpWebRequest Client)
{
if (connection.UserName == null || connection.UserName.Equals(""))
Client.Headers["Authorization"] = "Basic Og=="; // no auth
else
{
String auth = DBXDefaultFormatter.getInstance().Base64Encode(
connection.UserName + ":" + connection.Password);
Client.Headers["Authorization"] = "Basic " + auth; // auth
}
}
protected bool isThereOnlyOneStreamInOutput(List<DSRESTParameter> parameters)
{
if (isOnlyOneParameterInOutput(parameters))
{
foreach (DSRESTParameter param in parameters)
{
if (((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput) || (param.Direction == DSRESTParamDirection.Output))
&& (param.getDBXType() == DBXDataTypes.BinaryBlobType))
{
return true;
} // if
} // for
}
return false;
}
protected bool isOnlyOneParameterInOutput(List<DSRESTParameter> parameters)
{
int Count = 0;
foreach (DSRESTParameter param in parameters)
{
if (((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput) || (param.Direction == DSRESTParamDirection.Output)))
{
Count++;
} // if
} // for
return Count == 1;
}
public abstract void execute();
}
private class HTTPGETExecutor : HTTPExecutor
{
public HTTPGETExecutor(DSRESTConnection connection, HttpWebRequest Client, DSRESTCommand command, DSAdmin Sender, Delegate callback, Delegate EXCallback)
: base(connection, Client, command, Sender, callback, EXCallback)
{
Client.Method = "GET";
SetUpHeaders(Client);
}
public override void execute()
{
Client.BeginGetResponse((IAsyncResult asynchResult) =>
{
HttpWebRequest request = (HttpWebRequest)asynchResult.AsyncState;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.EndGetResponse(asynchResult);
}
catch (WebException e)
{
try
{
Stream s = ((HttpWebResponse)e.Response).GetResponseStream();
TextReader txt = new StreamReader(s);
if (s.Length > 0)
{
connection.throwExceptionIfNeeded(JObject.Parse(txt.ReadToEnd()));
}
else
{
throw new WebException(e.Message);
}
}
catch (Exception ex)
{
if (EXCallback != null) connection.syncContext.Send(new SendOrPostCallback(x => EXCallback.DynamicInvoke(ex)), null);
else connection.syncContext.Send(new SendOrPostCallback(x => Sender.BaseExCal.DynamicInvoke(ex)), null);
return;
}
}
finally
{
syncStop();
}
connection.throwExceptionIfNeeded(response);
connection.setSessionIdentifier(response);
if (!isThereOnlyOneStreamInOutput(command.getParameters()))
{
string resultString = null;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
resultString = rdr.ReadToEnd();
rdr.Close();
}
response.Close();
try
{
JObject obj = JObject.Parse(resultString);
JArray arr = obj.Value<JArray>("result");
int returnParIndex = 0;
foreach (DSRESTParameter param in command.getParameters())
{
if ((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput)
|| (param.Direction == DSRESTParamDirection.Output))
{
DBXJSONTools.JSONtoDBX(arr[returnParIndex],
param.getValue(), param.TypeName);
returnParIndex++;
} // if
} // for
}
catch (DBXException e)
{
throw new DBXException(e.Message);
}
if (!(_TimedOut)) connection.syncContext.Send(new SendOrPostCallback(x => callback.DynamicInvoke()), null);
}
else
{
Stream inputstream = response.GetResponseStream();
byte[] b1 = DBXTools.streamToByteArray(inputstream);
inputstream.Close();
response.Close();
TStream ins = new TStream(b1);
foreach (DSRESTParameter param in command.getParameters())
{
if ((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput)
|| (param.Direction == DSRESTParamDirection.Output))
{
param.getValue().SetAsStream(ins);
if (!(_TimedOut)) connection.syncContext.Send(new SendOrPostCallback(x => callback.DynamicInvoke()), null);
}
}
}
}, Client);
start();
}
}
private class HTTPPOSTExecutor : HTTPExecutor
{
protected TJSONArray _parameters;
public HTTPPOSTExecutor(DSRESTConnection connection, HttpWebRequest Client, DSRESTCommand command, DSAdmin Sender, Delegate callback, Delegate EXCallback, TJSONArray parameters)
: base(connection, Client, command, Sender, callback, EXCallback)
{
this._parameters = parameters;
Client.Method = "POST";
SetUpHeaders(Client);
}
public override void execute()
{
if (_parameters == null)
throw new DBXException(
"Parameters cannot be null in a POST request");
TJSONObject body = new TJSONObject();
body.addPairs("_parameters", _parameters);
Client.BeginGetRequestStream((IAsyncResult asynchronousResult) =>
{
Stream postStream = Client.EndGetRequestStream(asynchronousResult);
byte[] postBytes = Encoding.UTF8.GetBytes(body.ToString());
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
Client.BeginGetResponse((IAsyncResult asynchResult) =>
{
HttpWebRequest request = (HttpWebRequest)asynchResult.AsyncState;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.EndGetResponse(asynchResult);
}
catch (WebException e)
{
try
{
Stream s = ((HttpWebResponse)e.Response).GetResponseStream();
TextReader txt = new StreamReader(s);
if (s.Length > 0)
{
connection.throwExceptionIfNeeded(JObject.Parse(txt.ReadToEnd()));
}
else
{
throw new DBXException(e.Message);
}
}
catch (Exception ex)
{
if (EXCallback != null)
connection.syncContext.Send(new SendOrPostCallback(x => EXCallback.DynamicInvoke(ex)), null);
else
if (Sender.BaseExCal != null)
connection.syncContext.Send(new SendOrPostCallback(x => Sender.BaseExCal.DynamicInvoke(ex)), null);
else
throw ex;
return;
}
}
finally
{
syncStop();
}
connection.setSessionIdentifier(response);
connection.throwExceptionIfNeeded(response);
if (!isThereOnlyOneStreamInOutput(command.getParameters()))
{
string resultString = null;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
resultString = rdr.ReadToEnd();
rdr.Close();
}
response.Close();
try
{
JObject obj = JObject.Parse(resultString);
JArray arr = obj.Value<JArray>("result");
int returnParIndex = 0;
foreach (DSRESTParameter param in command.getParameters())
{
if ((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput)
|| (param.Direction == DSRESTParamDirection.Output))
{
DBXJSONTools.JSONtoDBX(arr[returnParIndex],
param.getValue(), param.TypeName);
returnParIndex++;
} // if
} // for
}
catch (DBXException e)
{
throw new DBXException(e.Message);
}
if (!(_TimedOut)) connection.syncContext.Send(new SendOrPostCallback(x => callback.DynamicInvoke()), null);
}
else
{
Stream inputstream = response.GetResponseStream();
byte[] b1 = DBXTools.streamToByteArray(inputstream);
inputstream.Close();
response.Close();
TStream ins = new TStream(b1);
foreach (DSRESTParameter param in command.getParameters())
{
if ((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput)
|| (param.Direction == DSRESTParamDirection.Output))
{
if (param.TypeName.StartsWith("TDBX") && param.TypeName.EndsWith("Value"))
{
param.getValue().GetAsDBXValue().SetAsStream(ins);
}
else
{
param.getValue().SetAsStream(ins);
}
if (!(_TimedOut)) connection.syncContext.Send(new SendOrPostCallback(x => callback.DynamicInvoke()), null);
}
}
};
}, Client);
}, Client);
start();
}
}
private class HTTPPUTExecutor : HTTPExecutor
{
protected TJSONArray _parameters;
public HTTPPUTExecutor(DSRESTConnection connection, HttpWebRequest Client, DSRESTCommand command, DSAdmin Sender, Delegate callback, Delegate EXCallback, TJSONArray parameters)
: base(connection, Client, command, Sender, callback, EXCallback)
{
this._parameters = parameters;
Client.Method = "PUT";
SetUpHeaders(Client);
}
public override void execute()
{
if (_parameters == null)
throw new DBXException(
"Parameters cannot be null in a PUT request");
TJSONObject body = new TJSONObject();
body.addPairs("_parameters", _parameters);
Client.BeginGetRequestStream((IAsyncResult asynchronousResult) =>
{
Stream postStream = Client.EndGetRequestStream(asynchronousResult);
byte[] postBytes = Encoding.UTF8.GetBytes(body.ToString());
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
Client.BeginGetResponse((IAsyncResult asynchResult) =>
{
HttpWebRequest request = (HttpWebRequest)asynchResult.AsyncState;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.EndGetResponse(asynchResult);
}
catch (WebException e)
{
try
{
Stream s = ((HttpWebResponse)e.Response).GetResponseStream();
TextReader txt = new StreamReader(s);
if (s.Length > 0)
{
connection.throwExceptionIfNeeded(JObject.Parse(txt.ReadToEnd()));
}
else
{
throw new WebException(e.Message);
}
}
catch (Exception ex)
{
if (EXCallback != null) connection.syncContext.Send(new SendOrPostCallback(x => EXCallback.DynamicInvoke(ex)), null);
else connection.syncContext.Send(new SendOrPostCallback(x => Sender.BaseExCal.DynamicInvoke(ex)), null);
return;
}
}
finally
{
syncStop();
}
connection.setSessionIdentifier(response);
connection.throwExceptionIfNeeded(response);
if (!isThereOnlyOneStreamInOutput(command.getParameters()))
{
string resultString = null;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
resultString = rdr.ReadToEnd();
try
{
JObject obj = JObject.Parse(resultString);
JArray arr = obj.Value<JArray>("result");
int returnParIndex = 0;
foreach (DSRESTParameter param in command.getParameters())
{
if ((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput)
|| (param.Direction == DSRESTParamDirection.Output))
{
DBXJSONTools.JSONtoDBX(arr[returnParIndex],
param.getValue(), param.TypeName);
returnParIndex++;
} // if
} // for
}
catch (DBXException e)
{
throw new DBXException(e.Message);
}
if (!(_TimedOut)) connection.syncContext.Send(new SendOrPostCallback(x => callback.DynamicInvoke()), null);
}
else
{
Stream inputstream = response.GetResponseStream();
byte[] b1 = DBXTools.streamToByteArray(inputstream);
TStream ins = new TStream(b1);
foreach (DSRESTParameter param in command.getParameters())
{
if ((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput)
|| (param.Direction == DSRESTParamDirection.Output))
{
if (param.TypeName.StartsWith("TDBX") && param.TypeName.EndsWith("Value"))
{
param.getValue().GetAsDBXValue().SetAsStream(ins);
}
else
{
param.getValue().SetAsStream(ins);
}
if (!(_TimedOut)) connection.syncContext.Send(new SendOrPostCallback(x => callback.DynamicInvoke()), null);
}
}
};
}, Client);
}, Client);
start();
}
}
private class HTTPDELETEExecutor : HTTPExecutor
{
public HTTPDELETEExecutor(DSRESTConnection connection, HttpWebRequest Client, DSRESTCommand command, DSAdmin Sender, Delegate callback, Delegate EXCallback)
: base(connection, Client, command, Sender, callback, EXCallback)
{
Client.Method = "DELETE";
SetUpHeaders(Client);
}
public override void execute()
{
Client.BeginGetResponse((IAsyncResult asynchResult) =>
{
HttpWebRequest request = (HttpWebRequest)asynchResult.AsyncState;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.EndGetResponse(asynchResult);
}
catch (WebException e)
{
try
{
Stream s = ((HttpWebResponse)e.Response).GetResponseStream();
TextReader txt = new StreamReader(s);
if (s.Length > 0)
{
connection.throwExceptionIfNeeded(JObject.Parse(txt.ReadToEnd()));
}
else
{
throw new WebException(e.Message);
}
}
catch (Exception ex)
{
if (EXCallback != null) connection.syncContext.Send(new SendOrPostCallback(x => EXCallback.DynamicInvoke(ex)), null);
else connection.syncContext.Send(new SendOrPostCallback(x => Sender.BaseExCal.DynamicInvoke(ex)), null);
return;
}
}
finally
{
syncStop();
}
connection.throwExceptionIfNeeded(response);
connection.setSessionIdentifier(response);
if (!isThereOnlyOneStreamInOutput(command.getParameters()))
{
string resultString = null;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
resultString = rdr.ReadToEnd();
try
{
JObject obj = JObject.Parse(resultString);
JArray arr = obj.Value<JArray>("result");
int returnParIndex = 0;
foreach (DSRESTParameter param in command.getParameters())
{
if ((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput)
|| (param.Direction == DSRESTParamDirection.Output))
{
DBXJSONTools.JSONtoDBX(arr[returnParIndex],
param.getValue(), param.TypeName);
returnParIndex++;
} // if
} // for
}
catch (DBXException e)
{
throw new DBXException(e.Message);
}
if (!(_TimedOut)) connection.syncContext.Send(new SendOrPostCallback(x => callback.DynamicInvoke()), null);
}
else
{
Stream inputstream = response.GetResponseStream();
byte[] b1 = DBXTools.streamToByteArray(inputstream);
TStream ins = new TStream(b1);
foreach (DSRESTParameter param in command.getParameters())
{
if ((param.Direction == DSRESTParamDirection.ReturnValue)
|| (param.Direction == DSRESTParamDirection.InputOutput)
|| (param.Direction == DSRESTParamDirection.Output))
{
param.getValue().SetAsStream(ins);
if (!(_TimedOut)) connection.syncContext.Send(new SendOrPostCallback(x => callback.DynamicInvoke()), null);
}
}
}
}, Client);
start();
}
}
}
}
| |
// 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.Buffers;
using System.IO;
namespace System.Security.Cryptography
{
public abstract partial class ECDsa : AsymmetricAlgorithm
{
protected ECDsa() { }
public static new ECDsa Create(string algorithm)
{
if (algorithm == null)
{
throw new ArgumentNullException(nameof(algorithm));
}
return CryptoConfig.CreateFromName(algorithm) as ECDsa;
}
/// <summary>
/// When overridden in a derived class, exports the named or explicit ECParameters for an ECCurve.
/// If the curve has a name, the Curve property will contain named curve parameters otherwise it will contain explicit parameters.
/// </summary>
/// <param name="includePrivateParameters">true to include private parameters, otherwise, false.</param>
/// <returns></returns>
public virtual ECParameters ExportParameters(bool includePrivateParameters)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
/// <summary>
/// When overridden in a derived class, exports the explicit ECParameters for an ECCurve.
/// </summary>
/// <param name="includePrivateParameters">true to include private parameters, otherwise, false.</param>
/// <returns></returns>
public virtual ECParameters ExportExplicitParameters(bool includePrivateParameters)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
/// <summary>
/// When overridden in a derived class, imports the specified ECParameters.
/// </summary>
/// <param name="parameters">The curve parameters.</param>
public virtual void ImportParameters(ECParameters parameters)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
/// <summary>
/// When overridden in a derived class, generates a new public/private keypair for the specified curve.
/// </summary>
/// <param name="curve">The curve to use.</param>
public virtual void GenerateKey(ECCurve curve)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
public virtual byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
return SignData(data, 0, data.Length, hashAlgorithm);
}
public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return SignHash(hash);
}
public virtual bool TrySignData(ReadOnlySpan<byte> source, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
}
if (TryHashData(source, destination, hashAlgorithm, out int hashLength) &&
TrySignHash(destination.Slice(0, hashLength), destination, out bytesWritten))
{
return true;
}
bytesWritten = 0;
return false;
}
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
byte[] hash = HashData(data, hashAlgorithm);
return SignHash(hash);
}
public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
return VerifyData(data, 0, data.Length, signature, hashAlgorithm);
}
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return VerifyHash(hash, signature);
}
public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
}
for (int i = 256; ; i = checked(i * 2))
{
int hashLength = 0;
byte[] hash = ArrayPool<byte>.Shared.Rent(i);
try
{
if (TryHashData(data, hash, hashAlgorithm, out hashLength))
{
return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature);
}
}
finally
{
Array.Clear(hash, 0, hashLength);
ArrayPool<byte>.Shared.Return(hash);
}
}
}
public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
byte[] hash = HashData(data, hashAlgorithm);
return VerifyHash(hash, signature);
}
public abstract byte[] SignHash(byte[] hash);
public abstract bool VerifyHash(byte[] hash, byte[] signature);
public override string KeyExchangeAlgorithm => null;
public override string SignatureAlgorithm => "ECDsa";
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
protected virtual bool TryHashData(ReadOnlySpan<byte> source, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
byte[] array = ArrayPool<byte>.Shared.Rent(source.Length);
try
{
source.CopyTo(array);
byte[] hash = HashData(array, 0, source.Length, hashAlgorithm);
if (hash.Length <= destination.Length)
{
new ReadOnlySpan<byte>(hash).CopyTo(destination);
bytesWritten = hash.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
finally
{
Array.Clear(array, 0, source.Length);
ArrayPool<byte>.Shared.Return(array);
}
}
public virtual bool TrySignHash(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten)
{
byte[] result = SignHash(source.ToArray());
if (result.Length <= destination.Length)
{
new ReadOnlySpan<byte>(result).CopyTo(destination);
bytesWritten = result.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) =>
VerifyHash(hash.ToArray(), signature.ToArray());
}
}
| |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System;
using System.Runtime.InteropServices;
/// @cond
namespace Gvr.Internal {
/// Controller Provider that uses the native GVR C API to communicate with controllers
/// via Google VR Services on Android.
class AndroidNativeControllerProvider : IControllerProvider {
#if !UNITY_HAS_GOOGLEVR || (!UNITY_ANDROID && !UNITY_EDITOR)
public void Dispose() { }
#else
// Note: keep structs and function signatures in sync with the C header file (gvr_controller.h).
// GVR controller option flags.
private const int GVR_CONTROLLER_ENABLE_ORIENTATION = 1 << 0;
private const int GVR_CONTROLLER_ENABLE_TOUCH = 1 << 1;
private const int GVR_CONTROLLER_ENABLE_GYRO = 1 << 2;
private const int GVR_CONTROLLER_ENABLE_ACCEL = 1 << 3;
private const int GVR_CONTROLLER_ENABLE_GESTURES = 1 << 4;
private const int GVR_CONTROLLER_ENABLE_POSE_PREDICTION = 1 << 5;
// enum gvr_controller_button:
private const int GVR_CONTROLLER_BUTTON_NONE = 0;
private const int GVR_CONTROLLER_BUTTON_CLICK = 1;
private const int GVR_CONTROLLER_BUTTON_HOME = 2;
private const int GVR_CONTROLLER_BUTTON_APP = 3;
private const int GVR_CONTROLLER_BUTTON_VOLUME_UP = 4;
private const int GVR_CONTROLLER_BUTTON_VOLUME_DOWN = 5;
private const int GVR_CONTROLLER_BUTTON_COUNT = 6;
// enum gvr_controller_connection_state:
private const int GVR_CONTROLLER_DISCONNECTED = 0;
private const int GVR_CONTROLLER_SCANNING = 1;
private const int GVR_CONTROLLER_CONNECTING = 2;
private const int GVR_CONTROLLER_CONNECTED = 3;
// enum gvr_controller_api_status
private const int GVR_CONTROLLER_API_OK = 0;
private const int GVR_CONTROLLER_API_UNSUPPORTED = 1;
private const int GVR_CONTROLLER_API_NOT_AUTHORIZED = 2;
private const int GVR_CONTROLLER_API_UNAVAILABLE = 3;
private const int GVR_CONTROLLER_API_SERVICE_OBSOLETE = 4;
private const int GVR_CONTROLLER_API_CLIENT_OBSOLETE = 5;
private const int GVR_CONTROLLER_API_MALFUNCTION = 6;
[StructLayout(LayoutKind.Sequential)]
private struct gvr_quat {
internal float x;
internal float y;
internal float z;
internal float w;
}
[StructLayout(LayoutKind.Sequential)]
private struct gvr_vec3 {
internal float x;
internal float y;
internal float z;
}
[StructLayout(LayoutKind.Sequential)]
private struct gvr_vec2 {
internal float x;
internal float y;
}
private const string dllName = "gvr";
[DllImport(dllName)]
private static extern int gvr_controller_get_default_options();
[DllImport(dllName)]
private static extern IntPtr gvr_controller_create_and_init_android(
IntPtr jniEnv, IntPtr androidContext, IntPtr classLoader,
int options, IntPtr context);
[DllImport(dllName)]
private static extern void gvr_controller_destroy(ref IntPtr api);
[DllImport(dllName)]
private static extern void gvr_controller_pause(IntPtr api);
[DllImport(dllName)]
private static extern void gvr_controller_resume(IntPtr api);
[DllImport(dllName)]
private static extern IntPtr gvr_controller_state_create();
[DllImport(dllName)]
private static extern void gvr_controller_state_destroy(ref IntPtr state);
[DllImport(dllName)]
private static extern void gvr_controller_state_update(IntPtr api, int flags, IntPtr out_state);
[DllImport(dllName)]
private static extern int gvr_controller_state_get_api_status(IntPtr state);
[DllImport(dllName)]
private static extern int gvr_controller_state_get_connection_state(IntPtr state);
[DllImport(dllName)]
private static extern gvr_quat gvr_controller_state_get_orientation(IntPtr state);
[DllImport(dllName)]
private static extern gvr_vec3 gvr_controller_state_get_gyro(IntPtr state);
[DllImport(dllName)]
private static extern gvr_vec3 gvr_controller_state_get_accel(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_is_touching(IntPtr state);
[DllImport(dllName)]
private static extern gvr_vec2 gvr_controller_state_get_touch_pos(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_touch_down(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_touch_up(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_recentered(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_recentering(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_button_state(IntPtr state, int button);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_button_down(IntPtr state, int button);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_button_up(IntPtr state, int button);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_orientation_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_gyro_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_accel_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_touch_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_button_timestamp(IntPtr state);
[DllImport(dllName)]
private static extern byte gvr_controller_state_get_battery_charging(IntPtr state);
[DllImport(dllName)]
private static extern int gvr_controller_state_get_battery_level(IntPtr state);
[DllImport(dllName)]
private static extern long gvr_controller_state_get_last_battery_timestamp(IntPtr state);
private const string VRCORE_UTILS_CLASS = "com.google.vr.vrcore.base.api.VrCoreUtils";
private IntPtr api;
private AndroidJavaObject androidContext;
private AndroidJavaObject classLoader;
private bool error = false;
private string errorDetails = string.Empty;
private IntPtr statePtr;
private MutablePose3D pose3d = new MutablePose3D();
internal AndroidNativeControllerProvider() {
#if !UNITY_EDITOR
Debug.Log("Initializing Daydream controller API.");
int options = gvr_controller_get_default_options();
options |= GVR_CONTROLLER_ENABLE_ACCEL;
options |= GVR_CONTROLLER_ENABLE_GYRO;
statePtr = gvr_controller_state_create();
// Get a hold of the activity, context and class loader.
AndroidJavaObject activity = GvrActivityHelper.GetActivity();
if (activity == null) {
error = true;
errorDetails = "Failed to get Activity from Unity Player.";
return;
}
androidContext = GvrActivityHelper.GetApplicationContext(activity);
if (androidContext == null) {
error = true;
errorDetails = "Failed to get Android application context from Activity.";
return;
}
classLoader = GetClassLoaderFromActivity(activity);
if (classLoader == null) {
error = true;
errorDetails = "Failed to get class loader from Activity.";
return;
}
// Use IntPtr instead of GetRawObject() so that Unity can shut down gracefully on
// Application.Quit(). Note that GetRawObject() is not pinned by the receiver so it's not
// cleaned up appropriately on shutdown, which is a known bug in Unity.
IntPtr androidContextPtr = AndroidJNI.NewLocalRef(androidContext.GetRawObject());
IntPtr classLoaderPtr = AndroidJNI.NewLocalRef(classLoader.GetRawObject());
Debug.Log ("Creating and initializing GVR API controller object.");
api = gvr_controller_create_and_init_android (IntPtr.Zero, androidContextPtr, classLoaderPtr,
options, IntPtr.Zero);
AndroidJNI.DeleteLocalRef(androidContextPtr);
AndroidJNI.DeleteLocalRef(classLoaderPtr);
if (IntPtr.Zero == api) {
Debug.LogError("Error creating/initializing Daydream controller API.");
error = true;
errorDetails = "Failed to initialize Daydream controller API.";
return;
}
Debug.Log("GVR API successfully initialized. Now resuming it.");
gvr_controller_resume(api);
Debug.Log("GVR API resumed.");
#endif
}
~AndroidNativeControllerProvider() {
Debug.Log("Destroying GVR API structures.");
gvr_controller_state_destroy(ref statePtr);
gvr_controller_destroy(ref api);
Debug.Log("AndroidNativeControllerProvider destroyed.");
}
public void ReadState(ControllerState outState) {
if (error) {
outState.connectionState = GvrConnectionState.Error;
outState.apiStatus = GvrControllerApiStatus.Error;
outState.errorDetails = errorDetails;
return;
}
gvr_controller_state_update(api, 0, statePtr);
outState.connectionState = ConvertConnectionState(
gvr_controller_state_get_connection_state(statePtr));
outState.apiStatus = ConvertControllerApiStatus(
gvr_controller_state_get_api_status(statePtr));
gvr_quat rawOri = gvr_controller_state_get_orientation(statePtr);
gvr_vec3 rawAccel = gvr_controller_state_get_accel(statePtr);
gvr_vec3 rawGyro = gvr_controller_state_get_gyro(statePtr);
// Convert GVR API orientation (right-handed) into Unity axis system (left-handed).
pose3d.Set(Vector3.zero, new Quaternion(rawOri.x, rawOri.y, rawOri.z, rawOri.w));
pose3d.SetRightHanded(pose3d.Matrix);
outState.orientation = pose3d.Orientation;
// For accelerometer, we have to flip Z because the GVR API has Z pointing backwards
// and Unity has Z pointing forward.
outState.accel = new Vector3(rawAccel.x, rawAccel.y, -rawAccel.z);
// Gyro in GVR represents a right-handed angular velocity about each axis (positive means
// clockwise when sighting along axis). Since Unity uses a left-handed system, we flip the
// signs to adjust the sign of the rotational velocity (so that positive means
// counter-clockwise). In addition, since in Unity the Z axis points forward while GVR
// has Z pointing backwards, we flip the Z axis sign again. So the result is that
// we should use -X, -Y, +Z:
outState.gyro = new Vector3(-rawGyro.x, -rawGyro.y, rawGyro.z);
outState.isTouching = 0 != gvr_controller_state_is_touching(statePtr);
gvr_vec2 touchPos = gvr_controller_state_get_touch_pos(statePtr);
outState.touchPos = new Vector2(touchPos.x, touchPos.y);
outState.touchDown = 0 != gvr_controller_state_get_touch_down(statePtr);
outState.touchUp = 0 != gvr_controller_state_get_touch_up(statePtr);
outState.appButtonDown =
0 != gvr_controller_state_get_button_down(statePtr, GVR_CONTROLLER_BUTTON_APP);
outState.appButtonState =
0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_APP);
outState.appButtonUp =
0 != gvr_controller_state_get_button_up(statePtr, GVR_CONTROLLER_BUTTON_APP);
outState.homeButtonDown =
0 != gvr_controller_state_get_button_down(statePtr, GVR_CONTROLLER_BUTTON_HOME);
outState.homeButtonState =
0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_HOME);
outState.clickButtonDown =
0 != gvr_controller_state_get_button_down(statePtr, GVR_CONTROLLER_BUTTON_CLICK);
outState.clickButtonState =
0 != gvr_controller_state_get_button_state(statePtr, GVR_CONTROLLER_BUTTON_CLICK);
outState.clickButtonUp =
0 != gvr_controller_state_get_button_up(statePtr, GVR_CONTROLLER_BUTTON_CLICK);
outState.recentering = 0 != gvr_controller_state_get_recentering(statePtr);
outState.recentered = 0 != gvr_controller_state_get_recentered(statePtr);
outState.gvrPtr = statePtr;
// Update battery information.
try {
outState.isCharging = 0 != gvr_controller_state_get_battery_charging(statePtr);
outState.batteryLevel = (GvrControllerBatteryLevel)gvr_controller_state_get_battery_level(statePtr);
} catch (EntryPointNotFoundException) {
// Older VrCore version. Does not support battery indicator.
}
}
public void OnPause() {
if (IntPtr.Zero != api) {
gvr_controller_pause(api);
}
}
public void OnResume() {
if (IntPtr.Zero != api) {
gvr_controller_resume(api);
}
}
private GvrConnectionState ConvertConnectionState(int connectionState) {
switch (connectionState) {
case GVR_CONTROLLER_CONNECTED:
return GvrConnectionState.Connected;
case GVR_CONTROLLER_CONNECTING:
return GvrConnectionState.Connecting;
case GVR_CONTROLLER_SCANNING:
return GvrConnectionState.Scanning;
default:
return GvrConnectionState.Disconnected;
}
}
private GvrControllerApiStatus ConvertControllerApiStatus(int gvrControllerApiStatus) {
switch (gvrControllerApiStatus) {
case GVR_CONTROLLER_API_OK:
return GvrControllerApiStatus.Ok;
case GVR_CONTROLLER_API_UNSUPPORTED:
return GvrControllerApiStatus.Unsupported;
case GVR_CONTROLLER_API_NOT_AUTHORIZED:
return GvrControllerApiStatus.NotAuthorized;
case GVR_CONTROLLER_API_SERVICE_OBSOLETE:
return GvrControllerApiStatus.ApiServiceObsolete;
case GVR_CONTROLLER_API_CLIENT_OBSOLETE:
return GvrControllerApiStatus.ApiClientObsolete;
case GVR_CONTROLLER_API_MALFUNCTION:
return GvrControllerApiStatus.ApiMalfunction;
case GVR_CONTROLLER_API_UNAVAILABLE:
default: // Fall through.
return GvrControllerApiStatus.Unavailable;
}
}
private static AndroidJavaObject GetClassLoaderFromActivity(AndroidJavaObject activity) {
AndroidJavaObject result = activity.Call<AndroidJavaObject>("getClassLoader");
if (result == null) {
Debug.LogErrorFormat("Failed to get class loader from Activity.");
return null;
}
return result;
}
private static int GetVrCoreClientApiVersion(AndroidJavaObject activity) {
try {
AndroidJavaClass utilsClass = new AndroidJavaClass(VRCORE_UTILS_CLASS);
int apiVersion = utilsClass.CallStatic<int>("getVrCoreClientApiVersion", activity);
Debug.LogFormat("VrCore client API version: " + apiVersion);
return apiVersion;
} catch (Exception exc) {
// Even though a catch-all block is normally frowned upon, in this case we really
// need it because this method has to be robust to unpredictable circumstances:
// VrCore might not exist in the device, the Java layer might be broken, etc, etc.
// None of those should abort the app.
Debug.LogError("Error obtaining VrCore client API version: " + exc);
return 0;
}
}
#endif // !UNITY_HAS_GOOGLEVR || (!UNITY_ANDROID && !UNITY_EDITOR)
}
}
/// @endcond
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System;
using System.Data;
using System.Threading.Tasks;
using System.Threading;
namespace System.Data.Common
{
public abstract class DbCommand :
IDisposable
{
protected DbCommand() : base()
{
}
abstract public string CommandText
{
get;
set;
}
abstract public int CommandTimeout
{
get;
set;
}
abstract public CommandType CommandType
{
get;
set;
}
public DbConnection Connection
{
get
{
return DbConnection;
}
set
{
DbConnection = value;
}
}
abstract protected DbConnection DbConnection
{
get;
set;
}
abstract protected DbParameterCollection DbParameterCollection
{
get;
}
abstract protected DbTransaction DbTransaction
{
get;
set;
}
public abstract bool DesignTimeVisible
{
get;
set;
}
public DbParameterCollection Parameters
{
get
{
return DbParameterCollection;
}
}
public DbTransaction Transaction
{
get
{
return DbTransaction;
}
set
{
DbTransaction = value;
}
}
abstract public UpdateRowSource UpdatedRowSource
{
get;
set;
}
internal void CancelIgnoreFailure()
{
// This method is used to route CancellationTokens to the Cancel method.
// Cancellation is a suggestion, and exceptions should be ignored
// rather than allowed to be unhandled, as the exceptions cannot be
// routed to the caller. These errors will be observed in the regular
// method instead.
try
{
Cancel();
}
catch (Exception)
{
}
}
abstract public void Cancel();
public DbParameter CreateParameter()
{
return CreateDbParameter();
}
abstract protected DbParameter CreateDbParameter();
abstract protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior);
abstract public int ExecuteNonQuery();
public DbDataReader ExecuteReader()
{
return (DbDataReader)ExecuteDbDataReader(CommandBehavior.Default);
}
public DbDataReader ExecuteReader(CommandBehavior behavior)
{
return (DbDataReader)ExecuteDbDataReader(behavior);
}
public Task<int> ExecuteNonQueryAsync()
{
return ExecuteNonQueryAsync(CancellationToken.None);
}
public virtual Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<int>();
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(CancelIgnoreFailure);
}
try
{
return Task.FromResult<int>(ExecuteNonQuery());
}
catch (Exception e)
{
registration.Dispose();
return ADP.CreatedTaskWithException<int>(e);
}
}
}
public Task<DbDataReader> ExecuteReaderAsync()
{
return ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None);
}
public Task<DbDataReader> ExecuteReaderAsync(CancellationToken cancellationToken)
{
return ExecuteReaderAsync(CommandBehavior.Default, cancellationToken);
}
public Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior)
{
return ExecuteReaderAsync(behavior, CancellationToken.None);
}
public Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
{
return ExecuteDbDataReaderAsync(behavior, cancellationToken);
}
protected virtual Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<DbDataReader>();
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(CancelIgnoreFailure);
}
try
{
return Task.FromResult<DbDataReader>(ExecuteReader(behavior));
}
catch (Exception e)
{
registration.Dispose();
return ADP.CreatedTaskWithException<DbDataReader>(e);
}
}
}
public Task<object> ExecuteScalarAsync()
{
return ExecuteScalarAsync(CancellationToken.None);
}
public virtual Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<object>();
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(CancelIgnoreFailure);
}
try
{
return Task.FromResult<object>(ExecuteScalar());
}
catch (Exception e)
{
registration.Dispose();
return ADP.CreatedTaskWithException<object>(e);
}
}
}
abstract public object ExecuteScalar();
abstract public void Prepare();
public void Dispose()
{
Dispose(disposing: true);
}
protected virtual void Dispose(bool disposing)
{
}
}
}
| |
// 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.ComponentModel.Composition.Hosting;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Primitives
{
/// <summary>
/// Represents a contract name and metadata-based import
/// required by a <see cref="ComposablePart"/> object.
/// </summary>
public class ContractBasedImportDefinition : ImportDefinition
{
// Unlike contract name, both metadata and required metadata has a sensible default; set it to an empty
// enumerable, so that derived definitions only need to override ContractName by default.
private readonly IEnumerable<KeyValuePair<string, Type>> _requiredMetadata = Enumerable.Empty<KeyValuePair<string, Type>>();
private Expression<Func<ExportDefinition, bool>> _constraint;
private readonly CreationPolicy _requiredCreationPolicy = CreationPolicy.Any;
private readonly string _requiredTypeIdentity = null;
private bool _isRequiredMetadataValidated = false;
/// <summary>
/// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class.
/// </summary>
/// <remarks>
/// <note type="inheritinfo">
/// Derived types calling this constructor can optionally override the
/// <see cref="ImportDefinition.ContractName"/>, <see cref="RequiredTypeIdentity"/>,
/// <see cref="RequiredMetadata"/>, <see cref="ImportDefinition.Cardinality"/>,
/// <see cref="ImportDefinition.IsPrerequisite"/>, <see cref="ImportDefinition.IsRecomposable"/>
/// and <see cref="RequiredCreationPolicy"/> properties.
/// </note>
/// </remarks>
protected ContractBasedImportDefinition()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class
/// with the specified contract name, required metadataq, cardinality, value indicating
/// if the import definition is recomposable and a value indicating if the import definition
/// is a prerequisite.
/// </summary>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the
/// <see cref="Export"/> required by the <see cref="ContractBasedImportDefinition"/>.
/// </param>
/// <param name="requiredTypeIdentity">
/// The type identity of the export type expected. Use <see cref="AttributedModelServices.GetTypeIdentity(Type)"/>
/// to generate a type identity for a given type. If no specific type is required pass <see langword="null"/>.
/// </param>
/// <param name="requiredMetadata">
/// An <see cref="IEnumerable{T}"/> of <see cref="String"/> objects containing
/// the metadata names of the <see cref="Export"/> required by the
/// <see cref="ContractBasedImportDefinition"/>; or <see langword="null"/> to
/// set the <see cref="RequiredMetadata"/> property to an empty <see cref="IEnumerable{T}"/>.
/// </param>
/// <param name="cardinality">
/// One of the <see cref="ImportCardinality"/> values indicating the
/// cardinality of the <see cref="Export"/> objects required by the
/// <see cref="ContractBasedImportDefinition"/>.
/// </param>
/// <param name="isRecomposable">
/// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> can be satisfied
/// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
/// <see langword="false"/>.
/// </param>
/// <param name="isPrerequisite">
/// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> is required to be
/// satisfied before a <see cref="ComposablePart"/> can start producing exported
/// objects; otherwise, <see langword="false"/>.
/// </param>
/// <param name="requiredCreationPolicy">
/// A value indicating that the importer requires a specific <see cref="CreationPolicy"/> for
/// the exports used to satisfy this import. If no specific <see cref="CreationPolicy"/> is needed
/// pass the default <see cref="CreationPolicy.Any"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="contractName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="contractName"/> is an empty string ("").
/// <para>
/// -or-
/// </para>
/// <paramref name="requiredMetadata"/> contains an element that is <see langword="null"/>.
/// <para>
/// -or-
/// </para>
/// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/>
/// values.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy)
: this(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, MetadataServices.EmptyMetadata)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class
/// with the specified contract name, required metadataq, cardinality, value indicating
/// if the import definition is recomposable and a value indicating if the import definition
/// is a prerequisite.
/// </summary>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the
/// <see cref="Export"/> required by the <see cref="ContractBasedImportDefinition"/>.
/// </param>
/// <param name="requiredTypeIdentity">
/// The type identity of the export type expected. Use <see cref="AttributedModelServices.GetTypeIdentity(Type)"/>
/// to generate a type identity for a given type. If no specific type is required pass <see langword="null"/>.
/// </param>
/// <param name="requiredMetadata">
/// An <see cref="IEnumerable{T}"/> of <see cref="String"/> objects containing
/// the metadata names of the <see cref="Export"/> required by the
/// <see cref="ContractBasedImportDefinition"/>; or <see langword="null"/> to
/// set the <see cref="RequiredMetadata"/> property to an empty <see cref="IEnumerable{T}"/>.
/// </param>
/// <param name="cardinality">
/// One of the <see cref="ImportCardinality"/> values indicating the
/// cardinality of the <see cref="Export"/> objects required by the
/// <see cref="ContractBasedImportDefinition"/>.
/// </param>
/// <param name="isRecomposable">
/// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> can be satisfied
/// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
/// <see langword="false"/>.
/// </param>
/// <param name="isPrerequisite">
/// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> is required to be
/// satisfied before a <see cref="ComposablePart"/> can start producing exported
/// objects; otherwise, <see langword="false"/>.
/// </param>
/// <param name="requiredCreationPolicy">
/// A value indicating that the importer requires a specific <see cref="CreationPolicy"/> for
/// the exports used to satisfy this import. If no specific <see cref="CreationPolicy"/> is needed
/// pass the default <see cref="CreationPolicy.Any"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="contractName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="contractName"/> is an empty string ("").
/// <para>
/// -or-
/// </para>
/// <paramref name="requiredMetadata"/> contains an element that is <see langword="null"/>.
/// <para>
/// -or-
/// </para>
/// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/>
/// values.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary<string, object> metadata)
: base(contractName, cardinality, isRecomposable, isPrerequisite, metadata)
{
Requires.NotNullOrEmpty(contractName, "contractName");
_requiredTypeIdentity = requiredTypeIdentity;
if (requiredMetadata != null)
{
_requiredMetadata = requiredMetadata;
}
_requiredCreationPolicy = requiredCreationPolicy;
}
/// <summary>
/// The type identity of the export type expected.
/// </summary>
/// <value>
/// A <see cref="string"/> that is generated by <see cref="AttributedModelServices.GetTypeIdentity(Type)"/>
/// on the type that this import expects. If the value is <see langword="null"/> then this import
/// doesn't expect a particular type.
/// </value>
public virtual string RequiredTypeIdentity
{
get { return _requiredTypeIdentity; }
}
/// <summary>
/// Gets the metadata names of the export required by the import definition.
/// </summary>
/// <value>
/// An <see cref="IEnumerable{T}"/> of pairs of metadata keys and types of the <see cref="Export"/> required by the
/// <see cref="ContractBasedImportDefinition"/>. The default is an empty
/// <see cref="IEnumerable{T}"/>.
/// </value>
/// <remarks>
/// <note type="inheritinfo">
/// Overriders of this property should never return <see langword="null"/>
/// or return an <see cref="IEnumerable{T}"/> that contains an element that is
/// <see langword="null"/>. If the definition does not contain required metadata,
/// return an empty <see cref="IEnumerable{T}"/> instead.
/// </note>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public virtual IEnumerable<KeyValuePair<string, Type>> RequiredMetadata
{
get
{
Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, Type>>>() != null);
// NOTE : unlike other arguments, we validate this one as late as possible, because its validation may lead to type loading
ValidateRequiredMetadata();
return _requiredMetadata;
}
}
private void ValidateRequiredMetadata()
{
if (!_isRequiredMetadataValidated)
{
foreach (KeyValuePair<string, Type> metadataItem in _requiredMetadata)
{
if ((metadataItem.Key == null) || (metadataItem.Value == null))
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, SR.Argument_NullElement, "requiredMetadata"));
}
}
_isRequiredMetadataValidated = true;
}
}
/// <summary>
/// Gets or sets a value indicating that the importer requires a specific
/// <see cref="CreationPolicy"/> for the exports used to satisfy this import. T
/// </summary>
/// <value>
/// <see cref="CreationPolicy.Any"/> - default value, used if the importer doesn't
/// require a specific <see cref="CreationPolicy"/>.
///
/// <see cref="CreationPolicy.Shared"/> - Requires that all exports used should be shared
/// by everyone in the container.
///
/// <see cref="CreationPolicy.NonShared"/> - Requires that all exports used should be
/// non-shared in a container and thus everyone gets their own instance.
/// </value>
public virtual CreationPolicy RequiredCreationPolicy
{
get { return _requiredCreationPolicy; }
}
/// <summary>
/// Gets an expression that defines conditions that must be matched for the import
/// described by the import definition to be satisfied.
/// </summary>
/// <returns>
/// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/>
/// that defines the conditions that must be matched for the
/// <see cref="ImportDefinition"/> to be satisfied by an <see cref="Export"/>.
/// </returns>
/// <remarks>
/// <para>
/// This property returns an expression that defines conditions based on the
/// <see cref="ImportDefinition.ContractName"/>, <see cref="RequiredTypeIdentity"/>,
/// <see cref="RequiredMetadata"/>, and <see cref="RequiredCreationPolicy"/>
/// properties.
/// </para>
/// </remarks>
public override Expression<Func<ExportDefinition, bool>> Constraint
{
get
{
if (_constraint == null)
{
_constraint = ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy);
}
return _constraint;
}
}
/// <summary>
/// Executes an optimized version of the contraint given by the <see cref="Constraint"/> property
/// </summary>
/// <param name="exportDefinition">
/// A definition for a <see cref="Export"/> used to determine if it satisfies the
/// requirements for this <see cref="ImportDefinition"/>.
/// </param>
/// <returns>
/// <see langword="True"/> if the <see cref="Export"/> satisfies the requirements for
/// this <see cref="ImportDefinition"/>, otherwise returns <see langword="False"/>.
/// </returns>
/// <remarks>
/// <note type="inheritinfo">
/// Overrides of this method can provide a more optimized execution of the
/// <see cref="Constraint"/> property but the result should remain consistent.
/// </note>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="exportDefinition"/> is <see langword="null"/>.
/// </exception>
public override bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition)
{
Requires.NotNull(exportDefinition, nameof(exportDefinition));
if (!StringComparers.ContractName.Equals(ContractName, exportDefinition.ContractName))
{
return false;
}
return MatchRequiredMetadata(exportDefinition);
}
private bool MatchRequiredMetadata(ExportDefinition definition)
{
if (!string.IsNullOrEmpty(RequiredTypeIdentity))
{
string exportTypeIdentity = definition.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
if (!StringComparers.ContractName.Equals(RequiredTypeIdentity, exportTypeIdentity))
{
return false;
}
}
foreach (KeyValuePair<string, Type> metadataItem in RequiredMetadata)
{
string metadataKey = metadataItem.Key;
Type metadataValueType = metadataItem.Value;
object metadataValue = null;
if (!definition.Metadata.TryGetValue(metadataKey, out metadataValue))
{
return false;
}
if (metadataValue != null)
{
// the metadata value is not null, we can rely on IsInstanceOfType to do the right thing
if (!metadataValueType.IsInstanceOfType(metadataValue))
{
return false;
}
}
else
{
// this is an unfortunate special case - typeof(object).IsInstanceofType(null) == false
// basically nulls are not considered valid values for anything
// We want them to match anything that is a reference type
if (metadataValueType.IsValueType)
{
// this is a pretty expensive check, but we only invoke it when metadata values are null, which is very rare
return false;
}
}
}
if (RequiredCreationPolicy == CreationPolicy.Any)
{
return true;
}
CreationPolicy exportPolicy = definition.Metadata.GetValue<CreationPolicy>(CompositionConstants.PartCreationPolicyMetadataName);
return exportPolicy == CreationPolicy.Any ||
exportPolicy == RequiredCreationPolicy;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(string.Format("\n\tContractName\t{0}", ContractName));
sb.Append(string.Format("\n\tRequiredTypeIdentity\t{0}", RequiredTypeIdentity));
if(_requiredCreationPolicy != CreationPolicy.Any)
{
sb.Append(string.Format("\n\tRequiredCreationPolicy\t{0}", RequiredCreationPolicy));
}
if(_requiredMetadata.Count() > 0)
{
sb.Append(string.Format("\n\tRequiredMetadata"));
foreach (KeyValuePair<string, Type> metadataItem in _requiredMetadata)
{
sb.Append(string.Format("\n\t\t{0}\t({1})", metadataItem.Key, metadataItem.Value));
}
}
return sb.ToString();
}
}
}
| |
using CSScriptLibrary;
using System;
using System.Diagnostics;
// Read in more details about all aspects of CS-Script hosting in applications
// here: http://www.csscript.net/help/Script_hosting_guideline_.html
//
// This file contains samples for the script hosting scenarios relying on CS-Script Evaluator interface (API).
// This API is a unified generic interface allowing dynamic switch of the underlying compiling services (Mono, Roslyn, CodeDom)
// without the need for changing the hosting code.
//
// Apart from Evaluator (compiler agnostic) API CS-Script offers alternative hosting model: CS-Script Native,
// which relies solely on CodeDom compiler. CS-Script Native offers some features that are not available with CS-Script Evaluator
// (e.g. script unloading).
//
// The choice of the underlying compiling engine (e.g. Mono vs CodeDom) when using CS-Script Evaluator is always dictated by the
// specifics of the hosting scenario. Thanks to in-process compiler hosting, Mono and Roslyn demonstrate much better compiling
// performance comparing to CodeDom engine. However they don't allow script debugging and caching easily supported with CodeDom.
// Mono and particularly Roslyn also leas create more memory pressure due to the higher volume of the temp assemblies loaded into
// the hosting AppDomain. Roslyn (at least CSharp.Scripting-v1.2.0.0) also has very high initial loading overhead up to 4 seconds.
//
// One of the possible approaches would be to use EvaluatorEngine.CodeDom during the active development and later on switch to Mono/Roslyn.
namespace CSScriptEvaluatorApi
{
public class HostApp
{
public static void Test()
{
// Just in case clear AlternativeCompiler so it is not set to Roslyn or anything else by
// the CS-Script installed (if any) on the host OS
CSScript.GlobalSettings.UseAlternativeCompiler = null;
var samples = new EvaluatorSamples();
Console.WriteLine("Testing compiling services");
Console.WriteLine("---------------------------------------------");
CSScript.EvaluatorConfig.Engine = EvaluatorEngine.Mono;
Console.WriteLine(CSScript.Evaluator.GetType().Name + "...");
samples.RunAll();
Console.WriteLine("---------------------------------------------");
CSScript.EvaluatorConfig.Engine = EvaluatorEngine.Roslyn;
Console.WriteLine(CSScript.Evaluator.GetType().Name + "...");
samples.RunAll();
Console.WriteLine("---------------------------------------------");
CSScript.EvaluatorConfig.Engine = EvaluatorEngine.CodeDom;
Console.WriteLine(CSScript.Evaluator.GetType().Name + "...");
samples.RunAll();
//samples.DebugTest(); //uncomment if want to fire an assertion during the script execution
//Profile(); //uncomment if want to test performance of the engines
}
class EvaluatorSamples
{
public void RunAll()
{
Action<Action, string> run = (action, name) => { action(); Console.WriteLine(name + " - OK"); };
//if you are using C#6 "nameof(CompileMethod_Instance)" would be a better approach
run(CompileMethod_Instance, "CompileMethod_Instance");
run(CompileMethod_Static, "CompileMethod_Static");
run(CreateDelegate, "CreateDelegate");
run(LoadDelegate, "LoadDelegate");
run(LoadCode, "LoadCode");
run(LoadMethod, "LoadMethod");
run(LoadMethodWithInterface, "LoadMethodWithInterface");
run(LoadCode_WithInterface, "LoadCode_WithInterface");
run(LoadCode_WithDuckTypedInterface, "LoadCode_WithDuckTypedInterface");
}
public void CompileMethod_Instance()
{
// 1- CompileMethod wraps method into a class definition and returns compiled assembly
// 2 - CreateObject creates instance of a first class in the assembly
dynamic script = CSScript.Evaluator
.CompileMethod(@"int Sqr(int data)
{
return data * data;
}")
.CreateObject("*");
var result = script.Sqr(7);
}
public void CompileMethod_Static()
{
// 1 - CompileMethod wraps method into a class definition and returns compiled assembly
// 2 - GetStaticMethod returns duck-typed delegate that accepts 'params object[]' arguments
// Note: GetStaticMethodWithArgs can be replaced with a more convenient/shorter version
// that takes the object instead of the Type and then queries objects type internally:
// "GetStaticMethod("*.Test", data)"
var test = CSScript.Evaluator
.CompileMethod(@"using CSScriptEvaluatorApi;
static void Test(InputData data)
{
data.Index = GetIndex();
}
static int GetIndex()
{
return Environment.TickCount;
}")
.GetStaticMethodWithArgs("*.Test", typeof(InputData));
var data = new InputData();
test(data);
}
public void CreateDelegate()
{
// Wraps method into a class definition, compiles it and loads the compiled assembly.
// It returns duck-typed delegate. A delegate with 'params object[]' arguments and
// without any specific return type.
var sqr = CSScript.Evaluator
.CreateDelegate(@"int Sqr(int a)
{
return a * a;
}");
var r = sqr(3);
}
public void LoadDelegate()
{
// Wraps method into a class definition, loads the compiled assembly
// and returns the method delegate for the method, which matches the delegate specified
// as the type parameter of LoadDelegate
var product = CSScript.Evaluator
.LoadDelegate<Func<int, int, int>>(
@"int Product(int a, int b)
{
return a * b;
}");
int result = product(3, 2);
}
public void LoadCode()
{
// LoadCode compiles code and returns instance of a first class
// in the compiled assembly
dynamic script = CSScript.Evaluator
.LoadCode(@"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
int result = script.Sum(1, 2);
}
public void LoadMethod()
{
// LoadMethod compiles code and returns instance of a first class
// in the compiled assembly.
// LoadMethod is essentially the same as LoadCode. It just deals not with the
// whole class definition but a single method(s) only. And the rest of the class definition is
// added automatically by CS-Script.
// 'public' is optional as it will be injected if the code doesn't start with it.
dynamic script = CSScript.Evaluator
.LoadMethod(@"using System;
public int Sum(int a, int b)
{
return a+b;
}");
int result = script.Sum(1, 2);
}
public void LoadMethodWithInterface()
{
// LoadMethod compiles code and returns instance of a first class
// in the compiled assembly.
// LoadMethod is essentially the same as LoadCode. It just deals not with the
// whole class definition but a single method(s) only. And the rest of the class definition is
// added automatically by CS-Script. The auto-generated class declaration also indicates
// that the class implements ICalc interface. Meaning that it will trigger compile error
// if the set of methods in the script code doesn't implement all interface members.
//This use-case uses Interface Alignment and this requires all assemblies involved to have
//non-empty Assembly.Location
CSScript.GlobalSettings.InMemoryAssembly = false;
ICalc script = CSScript.Evaluator
.LoadMethod<ICalc>(
@"int Sum(int a, int b)
{
return a+b;
}");
int result = script.Sum(1, 2);
}
public void LoadCode_WithInterface()
{
// 1 - LoadCode compiles code and returns instance of a first class in the compiled assembly
// 2 - The script class implements host app interface so the returned object can be type casted into it
var script = (ICalc)CSScript.Evaluator
.LoadCode(@"using System;
public class Script : CSScriptEvaluatorApi.ICalc
{
public int Sum(int a, int b)
{
return a+b;
}
}");
int result = script.Sum(1, 2);
}
public void LoadCode_WithDuckTypedInterface()
{
// 1 - LoadCode compiles code and returns instance of a first class in the compiled assembly
// 2- The script class doesn't implement host app interface but it can still be aligned to
// one as long at it implements the interface members
//This use-case uses Interface Alignment and this requires all assemblies involved to have
//non-empty Assembly.Location
CSScript.GlobalSettings.InMemoryAssembly = false;
ICalc script = CSScript.MonoEvaluator
.LoadCode<ICalc>(@"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
int result = script.Sum(1, 2);
}
public void PerformanceTest(int count = -1)
{
var code = @"int Sqr(int a)
{
return a * a;
}";
if (count != -1)
code += "//" + count; //this unique extra code comment ensures the code to be compiled cannot be cached
dynamic script = CSScript.Evaluator
.CompileMethod(code)
.CreateObject("*");
var r = script.Sqr(3);
}
public void DebugTest()
{
//pops up an assertion dialog
CSScript.EvaluatorConfig.DebugBuild = true;
CSScript.EvaluatorConfig.Engine = EvaluatorEngine.CodeDom;
dynamic script = CSScript.Evaluator
.LoadCode(@"using System;
using System.Diagnostics;
public class Script
{
public int Sum(int a, int b)
{
Debug.Assert(false,""Testing CS-Script debugging..."");
return a+b;
}
}");
var r = script.Sum(3, 4);
}
}
public static void Profile()
{
var sw = new Stopwatch();
var samples = new EvaluatorSamples();
var count = 20;
var inxed = 0;
bool preventCaching = false;
Action run = () =>
{
sw.Restart();
for (int i = 0; i < count; i++)
if (preventCaching)
samples.PerformanceTest(inxed++);
else
samples.PerformanceTest();
Console.WriteLine(CSScript.Evaluator.GetType().Name + ": " + sw.ElapsedMilliseconds);
};
Action runAll = () =>
{
Console.WriteLine("\n---------------------------------------------");
Console.WriteLine("Caching enabled: " + preventCaching + "\n");
CSScript.EvaluatorConfig.Engine = EvaluatorEngine.Mono;
run();
CSScript.EvaluatorConfig.Engine = EvaluatorEngine.CodeDom;
run();
CSScript.EvaluatorConfig.Engine = EvaluatorEngine.Roslyn;
run();
};
RoslynEvaluator.LoadCompilers(); //Roslyn is extremely heavy so exclude startup time from profiling
Console.WriteLine("Testing performance");
preventCaching = true;
runAll();
preventCaching = false;
runAll();
}
}
public interface ICalc
{
int Sum(int a, int b);
}
public class InputData
{
public int Index = 0;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using MGTK.Services;
namespace MGTK.Controls
{
public class NumericUpDown : Control
{
protected InnerTextBox innerTextBox;
protected Button btnUp;
protected Button btnDown;
private decimal _value = 0;
private decimal increment = 1;
private decimal maximum = 100;
private decimal minimum = 0;
private int MsToNextIndex = 150;
private double TotalMilliseconds = 0;
private string previousText;
public decimal Maximum
{
get
{
return maximum;
}
set
{
if (maximum != value)
{
maximum = value;
CheckValueBoundaries();
}
}
}
public decimal Minimum
{
get
{
return minimum;
}
set
{
if (minimum != value)
{
minimum = value;
CheckValueBoundaries();
}
}
}
public decimal Increment
{
get
{
return increment;
}
set
{
if (increment != value)
increment = value;
}
}
public decimal Value
{
get
{
return _value;
}
set
{
if (_value != value)
{
_value = value;
CheckValueBoundaries();
if (ValueChanged != null)
ValueChanged(this, new EventArgs());
UpdateTextBox();
}
}
}
public event EventHandler ValueChanged;
public NumericUpDown(Form formowner)
: base(formowner)
{
btnUp = new Button(formowner);
btnDown = new Button(formowner);
innerTextBox = new InnerTextBox(formowner);
btnUp.Parent = btnDown.Parent = innerTextBox.Parent = this;
innerTextBox.MultiLine = false;
btnUp.Image = Theme.NumericUpDownUpButton;
btnDown.Image = Theme.NumericUpDownDownButton;
btnUp.MouseLeftDown += new EventHandler(btn_MouseLeftDown);
btnDown.MouseLeftDown += new EventHandler(btn_MouseLeftDown);
btnUp.MouseLeftPressed += new EventHandler(btn_MouseLeftPressed);
btnDown.MouseLeftPressed += new EventHandler(btn_MouseLeftPressed);
this.Controls.AddRange(new Control[] { btnUp, btnDown, innerTextBox });
this.Init += new EventHandler(NumericUpDown_Init);
innerTextBox.TextChanged += new EventHandler(innerTextBox_TextChanged);
}
void innerTextBox_TextChanged(object sender, EventArgs e)
{
string t = innerTextBox.Text.Replace(Environment.NewLine, "");
if (previousText != t)
{
if (t.Trim().Length > 0)
{
if (!Regex.Match(t, @"^[-+]?\d+(,\d+)?$").Success)
UpdateTextBox();
else
Value = Convert.ToDecimal(t);
}
previousText = t;
}
}
void btn_MouseLeftPressed(object sender, EventArgs e)
{
(sender as Button).Tag = (double)0;
}
private void UpdateTextBox()
{
innerTextBox.Text = Value.ToString();
}
private void CheckValueBoundaries()
{
if (Value > Maximum) Value = Maximum;
if (Value < Minimum) Value = Minimum;
}
void btn_MouseLeftDown(object sender, EventArgs e)
{
Button btn = (sender as Button);
if (TotalMilliseconds - (double)btn.Tag > MsToNextIndex)
{
Value += Increment * (sender == btnDown ? -1 : 1);
btn.Tag = TotalMilliseconds;
}
}
void NumericUpDown_Init(object sender, EventArgs e)
{
ConfigureCoordinatesAndSizes();
UpdateTextBox();
}
public override void Draw()
{
DrawingService.DrawFrame(spriteBatch, Theme.NumericUpDownFrame, OwnerX + X, OwnerY + Y,
Width, Height, Z - 0.001f);
base.Draw();
}
public override void Update()
{
TotalMilliseconds = gameTime.TotalGameTime.TotalMilliseconds;
btnUp.Z = Z - 0.0015f;
btnDown.Z = Z - 0.0015f;
base.Update();
}
private void ConfigureCoordinatesAndSizes()
{
btnUp.Y = 2;
btnUp.Height = (Height - 4) / 2;
btnUp.Width = btnUp.Height * 2;
btnUp.X = Width - btnUp.Width - 2;
btnUp.Anchor = AnchorStyles.Right;
btnDown.Y = 2 + btnUp.Height;
btnDown.Height = (Height - 4) / 2;
btnDown.Width = btnDown.Height * 2;
btnDown.X = Width - btnDown.Width - 2;
btnDown.Anchor = AnchorStyles.Right;
innerTextBox.Y = 2;
innerTextBox.X = 2;
innerTextBox.Width = Width - btnUp.Width - 2 - 3;
innerTextBox.Height = Height - 4;
innerTextBox.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BackgroundWorker.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.ComponentModel
{
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Security.Permissions;
using System.Threading;
[
SRDescription(SR.BackgroundWorker_Desc),
DefaultEvent("DoWork"),
HostProtection(SharedState = true)
]
public class BackgroundWorker : Component
{
// Private statics
private static readonly object doWorkKey = new object();
private static readonly object runWorkerCompletedKey = new object();
private static readonly object progressChangedKey = new object();
// Private instance members
private bool canCancelWorker = false;
private bool workerReportsProgress = false;
private bool cancellationPending = false;
private bool isRunning = false;
private AsyncOperation asyncOperation = null;
private readonly WorkerThreadStartDelegate threadStart;
private readonly SendOrPostCallback operationCompleted;
private readonly SendOrPostCallback progressReporter;
public BackgroundWorker()
{
threadStart = new WorkerThreadStartDelegate(WorkerThreadStart);
operationCompleted = new SendOrPostCallback(AsyncOperationCompleted);
progressReporter = new SendOrPostCallback(ProgressReporter);
}
private void AsyncOperationCompleted(object arg)
{
isRunning = false;
cancellationPending = false;
OnRunWorkerCompleted((RunWorkerCompletedEventArgs)arg);
}
[
Browsable(false),
SRDescription(SR.BackgroundWorker_CancellationPending)
]
public bool CancellationPending
{
get { return cancellationPending; }
}
public void CancelAsync()
{
if (!WorkerSupportsCancellation)
{
throw new InvalidOperationException(SR.GetString(SR.BackgroundWorker_WorkerDoesntSupportCancellation));
}
cancellationPending = true;
}
[
SRCategory(SR.PropertyCategoryAsynchronous),
SRDescription(SR.BackgroundWorker_DoWork)
]
public event DoWorkEventHandler DoWork
{
add
{
this.Events.AddHandler(doWorkKey, value);
}
remove
{
this.Events.RemoveHandler(doWorkKey, value);
}
}
/// <include file='doc\BackgroundWorker.uex' path='docs/doc[@for="BackgroundWorker.IsBusy"]/*' />
[
Browsable(false),
SRDescription(SR.BackgroundWorker_IsBusy)
]
public bool IsBusy
{
get
{
return isRunning;
}
}
/// <include file='doc\BackgroundWorker.uex' path='docs/doc[@for="BackgroundWorker.OnDoWork"]/*' />
protected virtual void OnDoWork(DoWorkEventArgs e)
{
DoWorkEventHandler handler = (DoWorkEventHandler)(Events[doWorkKey]);
if (handler != null)
{
handler(this, e);
}
}
/// <include file='doc\BackgroundWorker.uex' path='docs/doc[@for="BackgroundWorker.OnRunWorkerCompleted"]/*' />
protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
RunWorkerCompletedEventHandler handler = (RunWorkerCompletedEventHandler)(Events[runWorkerCompletedKey]);
if (handler != null)
{
handler(this, e);
}
}
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
ProgressChangedEventHandler handler = (ProgressChangedEventHandler)(Events[progressChangedKey]);
if (handler != null)
{
handler(this, e);
}
}
[
SRCategory(SR.PropertyCategoryAsynchronous),
SRDescription(SR.BackgroundWorker_ProgressChanged)
]
public event ProgressChangedEventHandler ProgressChanged
{
add
{
this.Events.AddHandler(progressChangedKey, value);
}
remove
{
this.Events.RemoveHandler(progressChangedKey, value);
}
}
// Gets invoked through the AsyncOperation on the proper thread.
private void ProgressReporter(object arg)
{
OnProgressChanged((ProgressChangedEventArgs)arg);
}
// Cause progress update to be posted through current AsyncOperation.
public void ReportProgress(int percentProgress)
{
ReportProgress(percentProgress, null);
}
// Cause progress update to be posted through current AsyncOperation.
public void ReportProgress(int percentProgress, object userState)
{
if (!WorkerReportsProgress)
{
throw new InvalidOperationException(SR.GetString(SR.BackgroundWorker_WorkerDoesntReportProgress));
}
ProgressChangedEventArgs args = new ProgressChangedEventArgs(percentProgress, userState);
if (asyncOperation != null)
{
asyncOperation.Post(progressReporter, args);
}
else
{
progressReporter(args);
}
}
public void RunWorkerAsync()
{
RunWorkerAsync(null);
}
public void RunWorkerAsync(object argument)
{
if (isRunning)
{
throw new InvalidOperationException(SR.GetString(SR.BackgroundWorker_WorkerAlreadyRunning));
}
isRunning = true;
cancellationPending = false;
asyncOperation = AsyncOperationManager.CreateOperation(null);
threadStart.BeginInvoke(argument,
null,
null);
}
[
SRCategory(SR.PropertyCategoryAsynchronous),
SRDescription(SR.BackgroundWorker_RunWorkerCompleted)
]
public event RunWorkerCompletedEventHandler RunWorkerCompleted
{
add
{
this.Events.AddHandler(runWorkerCompletedKey, value);
}
remove
{
this.Events.RemoveHandler(runWorkerCompletedKey, value);
}
}
[ SRCategory(SR.PropertyCategoryAsynchronous),
SRDescription(SR.BackgroundWorker_WorkerReportsProgress),
DefaultValue(false)
]
public bool WorkerReportsProgress
{
get { return workerReportsProgress; }
set { workerReportsProgress = value; }
}
[
SRCategory(SR.PropertyCategoryAsynchronous),
SRDescription(SR.BackgroundWorker_WorkerSupportsCancellation),
DefaultValue(false)
]
public bool WorkerSupportsCancellation
{
get { return canCancelWorker; }
set { canCancelWorker = value; }
}
private delegate void WorkerThreadStartDelegate(object argument);
private void WorkerThreadStart(object argument)
{
object workerResult = null;
Exception error = null;
bool cancelled = false;
try
{
DoWorkEventArgs doWorkArgs = new DoWorkEventArgs(argument);
OnDoWork(doWorkArgs);
if (doWorkArgs.Cancel)
{
cancelled = true;
}
else
{
workerResult = doWorkArgs.Result;
}
}
catch (Exception exception)
{
error = exception;
}
RunWorkerCompletedEventArgs e =
new RunWorkerCompletedEventArgs(workerResult, error, cancelled);
asyncOperation.PostOperationCompleted(operationCompleted, e);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using Rainbow.Framework.Data;
using Rainbow.Framework.Settings;
using System.Web.Security;
namespace Rainbow.Framework.Monitoring
{
/// <summary>
/// strings used for actions
/// </summary>
public static class MonitoringAction
{
/// <summary>
/// Gets the page request.
/// </summary>
/// <value>The page request.</value>
static public string PageRequest
{
get { return "PageRequest"; }
}
}
/// <summary>
/// Utility Helper class for Rainbow Framework Monitoring purposes.
/// You get some static methods like
/// <list type="string">
/// <item>int GetTotalPortalHits(int portalID)</item>
/// <item>DataSet GetMonitoringStats(DateTime startDate</item>
/// </list>
/// </summary>
public static class Utility
{
/// <summary>
/// returns the total hit count for a portal
/// </summary>
/// <param name="portalID">portal id to get stats for</param>
/// <returns>
/// total number of hits to the portal of all types
/// </returns>
public static int GetTotalPortalHits(int portalID)
{
// TODO: THis should not display, login, logout, or administrator hits.
string sql = "Select count(ID) as hits " +
" from rb_monitoring " +
" where [PortalID] = " + portalID.ToString() + " ";
return Convert.ToInt32(DBHelper.ExecuteSQLScalar(sql));
}
/// <summary>
/// Get Users Online
/// Add to the Cache
/// HttpContext.Current.Cache.Insert("WhoIsOnlineAnonUserCount", anonUserCount, null, DateTime.Now.AddMinutes(cacheTimeout), TimeSpan.Zero);
/// HttpContext.Current.Cache.Insert("WhoIsOnlineRegUserCount", regUsersOnlineCount, null, DateTime.Now.AddMinutes(cacheTimeout), TimeSpan.Zero);
/// HttpContext.Current.Cache.Insert("WhoIsOnlineRegUsersString", regUsersString, null, DateTime.Now.AddMinutes(cacheTimeout), TimeSpan.Zero);
/// </summary>
/// <param name="portalID">The portal ID.</param>
/// <param name="minutesToCheckForUsers">The minutes to check for users.</param>
/// <param name="cacheTimeout">The cache timeout.</param>
/// <param name="anonUserCount">The anon user count.</param>
/// <param name="regUsersOnlineCount">The reg users online count.</param>
/// <param name="regUsersString">The reg users string.</param>
public static void FillUsersOnlineCache(int portalID,
int minutesToCheckForUsers,
int cacheTimeout,
out int anonUserCount,
out int regUsersOnlineCount,
out string regUsersString)
{
// Read from the cache if available
if (HttpContext.Current.Cache["WhoIsOnlineAnonUserCount"] == null ||
HttpContext.Current.Cache["WhoIsOnlineRegUserCount"] == null ||
HttpContext.Current.Cache["WhoIsOnlineRegUsersString"] == null)
{
// Firstly get the logged in users
SqlCommand sqlComm1 = new SqlCommand();
SqlConnection sqlConn1 = new SqlConnection(Config.ConnectionString);
sqlComm1.Connection = sqlConn1;
sqlComm1.CommandType = CommandType.StoredProcedure;
sqlComm1.CommandText = "rb_GetLoggedOnUsers";
SqlDataReader result;
// Add Parameters to SPROC
SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4);
parameterPortalID.Value = portalID;
sqlComm1.Parameters.Add(parameterPortalID);
SqlParameter parameterMinutesToCheck = new SqlParameter("@MinutesToCheck", SqlDbType.Int, 4);
parameterMinutesToCheck.Value = minutesToCheckForUsers;
sqlComm1.Parameters.Add(parameterMinutesToCheck);
sqlConn1.Open();
result = sqlComm1.ExecuteReader();
string onlineUsers = string.Empty;
int onlineUsersCount = 0;
try
{
while (result.Read())
{
if (Convert.ToString(result.GetValue(2)) != "Logoff")
{
onlineUsersCount++;
onlineUsers += Membership.GetUser( result.GetValue(1) ).UserName + ", ";
}
}
}
finally
{
result.Close(); //by Manu, fixed bug 807858
}
if (onlineUsers.Length > 0)
{
onlineUsers = onlineUsers.Remove(onlineUsers.Length - 2, 2);
}
regUsersString = onlineUsers;
regUsersOnlineCount = onlineUsersCount;
result.Close();
// Add Parameters to SPROC
SqlParameter parameterNumberOfUsers = new SqlParameter("@NoOfUsers", SqlDbType.Int, 4);
parameterNumberOfUsers.Direction = ParameterDirection.Output;
sqlComm1.Parameters.Add(parameterNumberOfUsers);
// Re-use the same result set to get the no of unregistered users
sqlComm1.CommandText = "rb_GetNumberOfActiveUsers";
// [The Bitland Prince] 8-1-2005
// If this query generates an exception, connection might be left open
try
{
sqlComm1.ExecuteNonQuery();
}
catch (Exception Ex)
{
// This takes care to close connection then throws a new
// exception (because I don't know if it's safe to go on...)
sqlConn1.Close();
throw new Exception("Unable to retrieve logged users. Error : " + Ex.Message);
}
int allUsersCount = Convert.ToInt32(parameterNumberOfUsers.Value);
sqlConn1.Close();
anonUserCount = allUsersCount - onlineUsersCount;
if (anonUserCount < 0)
{
anonUserCount = 0;
}
// Add to the Cache
HttpContext.Current.Cache.Insert("WhoIsOnlineAnonUserCount", anonUserCount, null,
DateTime.Now.AddMinutes(cacheTimeout), TimeSpan.Zero);
HttpContext.Current.Cache.Insert("WhoIsOnlineRegUserCount", regUsersOnlineCount, null,
DateTime.Now.AddMinutes(cacheTimeout), TimeSpan.Zero);
HttpContext.Current.Cache.Insert("WhoIsOnlineRegUsersString", regUsersString, null,
DateTime.Now.AddMinutes(cacheTimeout), TimeSpan.Zero);
}
else
{
anonUserCount = (int) HttpContext.Current.Cache["WhoIsOnlineAnonUserCount"];
regUsersOnlineCount = (int) HttpContext.Current.Cache["WhoIsOnlineRegUserCount"];
regUsersString = (string) HttpContext.Current.Cache["WhoIsOnlineRegUsersString"];
}
}
/// <summary>
/// Return a dataset of stats for a given data range and portal
/// Written by Paul Yarrow, paul@paulyarrow.com
/// </summary>
/// <param name="startDate">the first date you want to see stats from</param>
/// <param name="endDate">the last date you want to see stats up to</param>
/// <param name="reportType">type of report you are requesting</param>
/// <param name="currentTabID">page id you are requesting stats for</param>
/// <param name="includeMonitoringPage">include the monitoring page in the stats</param>
/// <param name="includeAdminUser">include hits by admin users</param>
/// <param name="includePageRequests">include page hits</param>
/// <param name="includeLogon">include the logon page</param>
/// <param name="includeLogoff">inlcude logogg page</param>
/// <param name="includeMyIPAddress">include the current ip address</param>
/// <param name="portalID">portal id to get stats for</param>
/// <returns></returns>
public static DataSet GetMonitoringStats(DateTime startDate,
DateTime endDate,
string reportType,
long currentTabID,
bool includeMonitoringPage,
bool includeAdminUser,
bool includePageRequests,
bool includeLogon,
bool includeLogoff,
bool includeMyIPAddress,
int portalID)
{
endDate = endDate.AddDays(1);
// Firstly get the logged in users
SqlConnection myConnection = Config.SqlConnectionString;
SqlDataAdapter myCommand = new SqlDataAdapter("rb_GetMonitoringEntries", myConnection);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4);
parameterPortalID.Value = portalID;
myCommand.SelectCommand.Parameters.Add(parameterPortalID);
SqlParameter parameterStartDate = new SqlParameter("@StartDate", SqlDbType.DateTime, 8);
parameterStartDate.Value = startDate;
myCommand.SelectCommand.Parameters.Add(parameterStartDate);
SqlParameter parameterEndDate = new SqlParameter("@EndDate", SqlDbType.DateTime, 8);
parameterEndDate.Value = endDate;
myCommand.SelectCommand.Parameters.Add(parameterEndDate);
SqlParameter parameterReportType = new SqlParameter("@ReportType", SqlDbType.VarChar, 50);
parameterReportType.Value = reportType;
myCommand.SelectCommand.Parameters.Add(parameterReportType);
SqlParameter parameterCurrentTabID = new SqlParameter("@CurrentTabID", SqlDbType.BigInt, 8);
parameterCurrentTabID.Value = currentTabID;
myCommand.SelectCommand.Parameters.Add(parameterCurrentTabID);
SqlParameter parameterIncludeMoni = new SqlParameter("@IncludeMonitorPage", SqlDbType.Bit, 1);
parameterIncludeMoni.Value = includeMonitoringPage;
myCommand.SelectCommand.Parameters.Add(parameterIncludeMoni);
SqlParameter parameterIncludeAdmin = new SqlParameter("@IncludeAdminUser", SqlDbType.Bit, 1);
parameterIncludeAdmin.Value = includeAdminUser;
myCommand.SelectCommand.Parameters.Add(parameterIncludeAdmin);
SqlParameter parameterIncludePageRequests = new SqlParameter("@IncludePageRequests", SqlDbType.Bit, 1);
parameterIncludePageRequests.Value = includePageRequests;
myCommand.SelectCommand.Parameters.Add(parameterIncludePageRequests);
SqlParameter parameterIncludeLogon = new SqlParameter("@IncludeLogon", SqlDbType.Bit, 1);
parameterIncludeLogon.Value = includeLogon;
myCommand.SelectCommand.Parameters.Add(parameterIncludeLogon);
SqlParameter parameterIncludeLogoff = new SqlParameter("@IncludeLogoff", SqlDbType.Bit, 1);
parameterIncludeLogoff.Value = includeLogoff;
myCommand.SelectCommand.Parameters.Add(parameterIncludeLogoff);
SqlParameter parameterIncludeIPAddress = new SqlParameter("@IncludeIPAddress", SqlDbType.Bit, 1);
parameterIncludeIPAddress.Value = includeMyIPAddress;
myCommand.SelectCommand.Parameters.Add(parameterIncludeIPAddress);
SqlParameter parameterIPAddress = new SqlParameter("@IPAddress", SqlDbType.VarChar, 16);
parameterIPAddress.Value = HttpContext.Current.Request.UserHostAddress;
myCommand.SelectCommand.Parameters.Add(parameterIPAddress);
// Create and Fill the DataSet
DataSet myDataSet = new DataSet();
try
{
myCommand.Fill(myDataSet);
}
finally
{
myConnection.Close();
}
// Return the DataSet
return myDataSet;
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="Resizer.Generated.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// <auto-generated>
// This code was generated by a tool. DO NOT EDIT
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// -----------------------------------------------------------------------
#region StyleCop Suppression - generated code
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// Resizer adds a resizing grip and behavior to any control.
/// </summary>
/// <remarks>
///
///
/// If a custom template is provided for this control, then the template MUST provide the following template parts:
///
/// PART_LeftGrip - A required template part which must be of type Thumb. The grip on the left.
/// PART_RightGrip - A required template part which must be of type Thumb. The grip on the right.
///
/// </remarks>
[TemplatePart(Name="PART_LeftGrip", Type=typeof(Thumb))]
[TemplatePart(Name="PART_RightGrip", Type=typeof(Thumb))]
[Localizability(LocalizationCategory.None)]
partial class Resizer
{
//
// Fields
//
private Thumb leftGrip;
private Thumb rightGrip;
//
// DraggingTemplate dependency property
//
/// <summary>
/// Identifies the DraggingTemplate dependency property.
/// </summary>
public static readonly DependencyProperty DraggingTemplateProperty = DependencyProperty.Register( "DraggingTemplate", typeof(DataTemplate), typeof(Resizer), new PropertyMetadata( null, DraggingTemplateProperty_PropertyChanged) );
/// <summary>
/// Gets or sets the template used for the dragging indicator when ResizeWhileDragging is false.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets the template used for the dragging indicator when ResizeWhileDragging is false.")]
[Localizability(LocalizationCategory.None)]
public DataTemplate DraggingTemplate
{
get
{
return (DataTemplate) GetValue(DraggingTemplateProperty);
}
set
{
SetValue(DraggingTemplateProperty,value);
}
}
static private void DraggingTemplateProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
Resizer obj = (Resizer) o;
obj.OnDraggingTemplateChanged( new PropertyChangedEventArgs<DataTemplate>((DataTemplate)e.OldValue, (DataTemplate)e.NewValue) );
}
/// <summary>
/// Occurs when DraggingTemplate property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<DataTemplate>> DraggingTemplateChanged;
/// <summary>
/// Called when DraggingTemplate property changes.
/// </summary>
protected virtual void OnDraggingTemplateChanged(PropertyChangedEventArgs<DataTemplate> e)
{
OnDraggingTemplateChangedImplementation(e);
RaisePropertyChangedEvent(DraggingTemplateChanged, e);
}
partial void OnDraggingTemplateChangedImplementation(PropertyChangedEventArgs<DataTemplate> e);
//
// GripBrush dependency property
//
/// <summary>
/// Identifies the GripBrush dependency property.
/// </summary>
public static readonly DependencyProperty GripBrushProperty = DependencyProperty.Register( "GripBrush", typeof(Brush), typeof(Resizer), new PropertyMetadata( new SolidColorBrush(Colors.Black), GripBrushProperty_PropertyChanged) );
/// <summary>
/// Gets or sets the color of the resize grips.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets the color of the resize grips.")]
[Localizability(LocalizationCategory.None)]
public Brush GripBrush
{
get
{
return (Brush) GetValue(GripBrushProperty);
}
set
{
SetValue(GripBrushProperty,value);
}
}
static private void GripBrushProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
Resizer obj = (Resizer) o;
obj.OnGripBrushChanged( new PropertyChangedEventArgs<Brush>((Brush)e.OldValue, (Brush)e.NewValue) );
}
/// <summary>
/// Occurs when GripBrush property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<Brush>> GripBrushChanged;
/// <summary>
/// Called when GripBrush property changes.
/// </summary>
protected virtual void OnGripBrushChanged(PropertyChangedEventArgs<Brush> e)
{
OnGripBrushChangedImplementation(e);
RaisePropertyChangedEvent(GripBrushChanged, e);
}
partial void OnGripBrushChangedImplementation(PropertyChangedEventArgs<Brush> e);
//
// GripLocation dependency property
//
/// <summary>
/// Identifies the GripLocation dependency property.
/// </summary>
public static readonly DependencyProperty GripLocationProperty = DependencyProperty.Register( "GripLocation", typeof(ResizeGripLocation), typeof(Resizer), new PropertyMetadata( ResizeGripLocation.Right, GripLocationProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value of what grips.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value of what grips.")]
[Localizability(LocalizationCategory.None)]
public ResizeGripLocation GripLocation
{
get
{
return (ResizeGripLocation) GetValue(GripLocationProperty);
}
set
{
SetValue(GripLocationProperty,value);
}
}
static private void GripLocationProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
Resizer obj = (Resizer) o;
obj.OnGripLocationChanged( new PropertyChangedEventArgs<ResizeGripLocation>((ResizeGripLocation)e.OldValue, (ResizeGripLocation)e.NewValue) );
}
/// <summary>
/// Occurs when GripLocation property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<ResizeGripLocation>> GripLocationChanged;
/// <summary>
/// Called when GripLocation property changes.
/// </summary>
protected virtual void OnGripLocationChanged(PropertyChangedEventArgs<ResizeGripLocation> e)
{
OnGripLocationChangedImplementation(e);
RaisePropertyChangedEvent(GripLocationChanged, e);
}
partial void OnGripLocationChangedImplementation(PropertyChangedEventArgs<ResizeGripLocation> e);
//
// GripWidth dependency property
//
/// <summary>
/// Identifies the GripWidth dependency property.
/// </summary>
public static readonly DependencyProperty GripWidthProperty = DependencyProperty.Register( "GripWidth", typeof(double), typeof(Resizer), new PropertyMetadata( 4.0, GripWidthProperty_PropertyChanged) );
/// <summary>
/// Gets or sets the width of the grips.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets the width of the grips.")]
[Localizability(LocalizationCategory.None)]
public double GripWidth
{
get
{
return (double) GetValue(GripWidthProperty);
}
set
{
SetValue(GripWidthProperty,value);
}
}
static private void GripWidthProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
Resizer obj = (Resizer) o;
obj.OnGripWidthChanged( new PropertyChangedEventArgs<double>((double)e.OldValue, (double)e.NewValue) );
}
/// <summary>
/// Occurs when GripWidth property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<double>> GripWidthChanged;
/// <summary>
/// Called when GripWidth property changes.
/// </summary>
protected virtual void OnGripWidthChanged(PropertyChangedEventArgs<double> e)
{
OnGripWidthChangedImplementation(e);
RaisePropertyChangedEvent(GripWidthChanged, e);
}
partial void OnGripWidthChangedImplementation(PropertyChangedEventArgs<double> e);
//
// ResizeWhileDragging dependency property
//
/// <summary>
/// Identifies the ResizeWhileDragging dependency property.
/// </summary>
public static readonly DependencyProperty ResizeWhileDraggingProperty = DependencyProperty.Register( "ResizeWhileDragging", typeof(bool), typeof(Resizer), new PropertyMetadata( BooleanBoxes.TrueBox, ResizeWhileDraggingProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating if resizing occurs while dragging.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating if resizing occurs while dragging.")]
[Localizability(LocalizationCategory.None)]
public bool ResizeWhileDragging
{
get
{
return (bool) GetValue(ResizeWhileDraggingProperty);
}
set
{
SetValue(ResizeWhileDraggingProperty,BooleanBoxes.Box(value));
}
}
static private void ResizeWhileDraggingProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
Resizer obj = (Resizer) o;
obj.OnResizeWhileDraggingChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when ResizeWhileDragging property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> ResizeWhileDraggingChanged;
/// <summary>
/// Called when ResizeWhileDragging property changes.
/// </summary>
protected virtual void OnResizeWhileDraggingChanged(PropertyChangedEventArgs<bool> e)
{
OnResizeWhileDraggingChangedImplementation(e);
RaisePropertyChangedEvent(ResizeWhileDraggingChanged, e);
}
partial void OnResizeWhileDraggingChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// ThumbGripLocation dependency property
//
/// <summary>
/// Identifies the ThumbGripLocation dependency property.
/// </summary>
public static readonly DependencyProperty ThumbGripLocationProperty = DependencyProperty.RegisterAttached( "ThumbGripLocation", typeof(ResizeGripLocation), typeof(Resizer), new PropertyMetadata( ResizeGripLocation.Right, ThumbGripLocationProperty_PropertyChanged) );
/// <summary>
/// Gets the location for a grip.
/// </summary>
/// <param name="element">The dependency object that the property is attached to.</param>
/// <returns>
/// The value of ThumbGripLocation that is attached to element.
/// </returns>
static public ResizeGripLocation GetThumbGripLocation(DependencyObject element)
{
return (ResizeGripLocation) element.GetValue(ThumbGripLocationProperty);
}
/// <summary>
/// Sets the location for a grip.
/// </summary>
/// <param name="element">The dependency object that the property will be attached to.</param>
/// <param name="value">The new value.</param>
static public void SetThumbGripLocation(DependencyObject element, ResizeGripLocation value)
{
element.SetValue(ThumbGripLocationProperty,value);
}
static private void ThumbGripLocationProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
ThumbGripLocationProperty_PropertyChangedImplementation(o, e);
}
static partial void ThumbGripLocationProperty_PropertyChangedImplementation(DependencyObject o, DependencyPropertyChangedEventArgs e);
//
// VisibleGripWidth dependency property
//
/// <summary>
/// Identifies the VisibleGripWidth dependency property.
/// </summary>
public static readonly DependencyProperty VisibleGripWidthProperty = DependencyProperty.Register( "VisibleGripWidth", typeof(double ), typeof(Resizer), new PropertyMetadata( 1.0, VisibleGripWidthProperty_PropertyChanged) );
/// <summary>
/// Gets or sets the visible width of the grips.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets the visible width of the grips.")]
[Localizability(LocalizationCategory.None)]
public double VisibleGripWidth
{
get
{
return (double ) GetValue(VisibleGripWidthProperty);
}
set
{
SetValue(VisibleGripWidthProperty,value);
}
}
static private void VisibleGripWidthProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
Resizer obj = (Resizer) o;
obj.OnVisibleGripWidthChanged( new PropertyChangedEventArgs<double >((double )e.OldValue, (double )e.NewValue) );
}
/// <summary>
/// Occurs when VisibleGripWidth property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<double >> VisibleGripWidthChanged;
/// <summary>
/// Called when VisibleGripWidth property changes.
/// </summary>
protected virtual void OnVisibleGripWidthChanged(PropertyChangedEventArgs<double > e)
{
OnVisibleGripWidthChangedImplementation(e);
RaisePropertyChangedEvent(VisibleGripWidthChanged, e);
}
partial void OnVisibleGripWidthChangedImplementation(PropertyChangedEventArgs<double > e);
/// <summary>
/// Called when a property changes.
/// </summary>
private void RaisePropertyChangedEvent<T>(EventHandler<PropertyChangedEventArgs<T>> eh, PropertyChangedEventArgs<T> e)
{
if(eh != null)
{
eh(this,e);
}
}
//
// OnApplyTemplate
//
/// <summary>
/// Called when ApplyTemplate is called.
/// </summary>
public override void OnApplyTemplate()
{
PreOnApplyTemplate();
base.OnApplyTemplate();
this.leftGrip = WpfHelp.GetTemplateChild<Thumb>(this,"PART_LeftGrip");
this.rightGrip = WpfHelp.GetTemplateChild<Thumb>(this,"PART_RightGrip");
PostOnApplyTemplate();
}
partial void PreOnApplyTemplate();
partial void PostOnApplyTemplate();
//
// Static constructor
//
/// <summary>
/// Called when the type is initialized.
/// </summary>
static Resizer()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Resizer), new FrameworkPropertyMetadata(typeof(Resizer)));
StaticConstructorImplementation();
}
static partial void StaticConstructorImplementation();
}
}
#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.Diagnostics;
using System.Runtime.CompilerServices;
namespace System
{
/// <summary>
/// Extension methods for Span<T>.
/// </summary>
public static class SpanExtensions
{
/// <summary>
/// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable<T>.Equals(T).
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The value to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf<T>(this Span<T> span, T value)
where T:struct, IEquatable<T>
{
return SpanHelpers.IndexOf<T>(ref span.DangerousGetPinnableReference(), value, span.Length);
}
/// <summary>
/// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1.
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The value to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf(this Span<byte> span, byte value)
{
return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), value, span.Length);
}
/// <summary>
/// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1.
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The value to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf(this Span<char> span, char value)
{
return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), value, span.Length);
}
/// <summary>
/// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable<T>.Equals(T).
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The sequence to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value)
where T : struct, IEquatable<T>
{
return SpanHelpers.IndexOf<T>(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length);
}
/// <summary>
/// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1.
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The sequence to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf(this Span<byte> span, ReadOnlySpan<byte> value)
{
return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length);
}
/// <summary>
/// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1.
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The sequence to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf(this Span<char> span, ReadOnlySpan<char> value)
{
return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length);
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements using IEquatable<T>.Equals(T).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool SequenceEqual<T>(this Span<T> first, ReadOnlySpan<T> second)
where T:struct, IEquatable<T>
{
int length = first.Length;
return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length);
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool SequenceEqual(this Span<byte> first, ReadOnlySpan<byte> second)
{
int length = first.Length;
return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length);
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool SequenceEqual(this Span<char> first, ReadOnlySpan<char> second)
{
int length = first.Length;
return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length);
}
/// <summary>
/// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable<T>.Equals(T).
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The value to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf<T>(this ReadOnlySpan<T> span, T value)
where T : struct, IEquatable<T>
{
return SpanHelpers.IndexOf<T>(ref span.DangerousGetPinnableReference(), value, span.Length);
}
/// <summary>
/// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1.
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The value to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf(this ReadOnlySpan<byte> span, byte value)
{
return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), value, span.Length);
}
/// <summary>
/// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1.
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The value to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf(this ReadOnlySpan<char> span, char value)
{
return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), value, span.Length);
}
/// <summary>
/// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable<T>.Equals(T).
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The sequence to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value)
where T : struct, IEquatable<T>
{
return SpanHelpers.IndexOf<T>(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length);
}
/// <summary>
/// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1.
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The sequence to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> value)
{
return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length);
}
/// <summary>
/// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1.
/// </summary>
/// <param name="span">The span to search.</param>
/// <param name="value">The sequence to search for.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
{
return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length);
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements using IEquatable<T>.Equals(T).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool SequenceEqual<T>(this ReadOnlySpan<T> first, ReadOnlySpan<T> second)
where T : struct, IEquatable<T>
{
int length = first.Length;
return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length);
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool SequenceEqual(this ReadOnlySpan<byte> first, ReadOnlySpan<byte> second)
{
int length = first.Length;
return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length);
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool SequenceEqual(this ReadOnlySpan<char> first, ReadOnlySpan<char> second)
{
int length = first.Length;
return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length);
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Data.SqlTypes
{
// Options that are used in comparison
[Flags]
public enum SqlCompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
BinarySort = 0x00008000, // binary sorting
BinarySort2 = 0x00004000, // binary sorting 2
}
/// <summary>
/// Represents a variable-length stream of characters to be stored in or retrieved from the database.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[XmlSchemaProvider("GetXsdType")]
public struct SqlString : INullable, IComparable, IXmlSerializable
{
private string _value;
private CompareInfo _cmpInfo;
private int _lcid; // Locale Id
private SqlCompareOptions _flag; // Compare flags
private bool _fNotNull; // false if null
/// <summary>
/// Represents a null value that can be assigned to the <see cref='System.Data.SqlTypes.SqlString.Value'/> property of an instance of
/// the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public static readonly SqlString Null = new SqlString(true);
internal static readonly UnicodeEncoding s_unicodeEncoding = new UnicodeEncoding();
/// <summary>
/// </summary>
public static readonly int IgnoreCase = 0x1;
/// <summary>
/// </summary>
public static readonly int IgnoreWidth = 0x10;
/// <summary>
/// </summary>
public static readonly int IgnoreNonSpace = 0x2;
/// <summary>
/// </summary>
public static readonly int IgnoreKanaType = 0x8;
/// <summary>
/// </summary>
public static readonly int BinarySort = 0x8000;
/// <summary>
/// </summary>
public static readonly int BinarySort2 = 0x4000;
private static readonly SqlCompareOptions s_iDefaultFlag =
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType |
SqlCompareOptions.IgnoreWidth;
private static readonly CompareOptions s_iValidCompareOptionMask =
CompareOptions.IgnoreCase | CompareOptions.IgnoreWidth |
CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreKanaType;
internal static readonly SqlCompareOptions s_iValidSqlCompareOptionMask =
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreWidth |
SqlCompareOptions.IgnoreNonSpace | SqlCompareOptions.IgnoreKanaType |
SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2;
internal static readonly int s_lcidUSEnglish = 0x00000409;
private static readonly int s_lcidBinary = 0x00008200;
// constructor
// construct a Null
private SqlString(bool fNull)
{
_value = null;
_cmpInfo = null;
_lcid = 0;
_flag = SqlCompareOptions.None;
_fNotNull = false;
}
// Constructor: Construct from both Unicode and NonUnicode data, according to fUnicode
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count, bool fUnicode)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
if (data == null)
{
_fNotNull = false;
_value = null;
_cmpInfo = null;
}
else
{
_fNotNull = true;
// m_cmpInfo is set lazily, so that we don't need to pay the cost
// unless the string is used in comparison.
_cmpInfo = null;
if (fUnicode)
{
_value = s_unicodeEncoding.GetString(data, index, count);
}
else
{
CultureInfo culInfo = new CultureInfo(_lcid);
Encoding cpe = System.Text.Encoding.GetEncoding(culInfo.TextInfo.ANSICodePage);
_value = cpe.GetString(data, index, count);
}
}
}
// Constructor: Construct from both Unicode and NonUnicode data, according to fUnicode
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, bool fUnicode)
: this(lcid, compareOptions, data, 0, data.Length, fUnicode)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count)
: this(lcid, compareOptions, data, index, count, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data)
: this(lcid, compareOptions, data, 0, data.Length, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(string data, int lcid, SqlCompareOptions compareOptions)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
_cmpInfo = null;
if (data == null)
{
_fNotNull = false;
_value = null;
}
else
{
_fNotNull = true;
_value = data; // PERF: do not String.Copy
}
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(string data, int lcid) : this(data, lcid, s_iDefaultFlag)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(string data) : this(data, System.Globalization.CultureInfo.CurrentCulture.LCID, s_iDefaultFlag)
{
}
private SqlString(int lcid, SqlCompareOptions compareOptions, string data, CompareInfo cmpInfo)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
if (data == null)
{
_fNotNull = false;
_value = null;
_cmpInfo = null;
}
else
{
_value = data;
_cmpInfo = cmpInfo;
_fNotNull = true;
}
}
// INullable
/// <summary>
/// Gets whether the <see cref='System.Data.SqlTypes.SqlString.Value'/> of the <see cref='System.Data.SqlTypes.SqlString'/> is <see cref='System.Data.SqlTypes.SqlString.Null'/>.
/// </summary>
public bool IsNull
{
get { return !_fNotNull; }
}
// property: Value
/// <summary>
/// Gets the string that is to be stored.
/// </summary>
public string Value
{
get
{
if (!IsNull)
return _value;
else
throw new SqlNullValueException();
}
}
public int LCID
{
get
{
if (!IsNull)
return _lcid;
else
throw new SqlNullValueException();
}
}
public CultureInfo CultureInfo
{
get
{
if (!IsNull)
return CultureInfo.GetCultureInfo(_lcid);
else
throw new SqlNullValueException();
}
}
private void SetCompareInfo()
{
Debug.Assert(!IsNull);
if (_cmpInfo == null)
_cmpInfo = (CultureInfo.GetCultureInfo(_lcid)).CompareInfo;
}
public CompareInfo CompareInfo
{
get
{
if (!IsNull)
{
SetCompareInfo();
return _cmpInfo;
}
else
throw new SqlNullValueException();
}
}
public SqlCompareOptions SqlCompareOptions
{
get
{
if (!IsNull)
return _flag;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from String to SqlString
public static implicit operator SqlString(string x)
{
return new SqlString(x);
}
// Explicit conversion from SqlString to String. Throw exception if x is Null.
public static explicit operator string (SqlString x)
{
return x.Value;
}
/// <summary>
/// Converts a <see cref='System.Data.SqlTypes.SqlString'/> object to a string.
/// </summary>
public override string ToString()
{
return IsNull ? SQLResource.NullString : _value;
}
public byte[] GetUnicodeBytes()
{
if (IsNull)
return null;
return s_unicodeEncoding.GetBytes(_value);
}
public byte[] GetNonUnicodeBytes()
{
if (IsNull)
return null;
// Get the CultureInfo
CultureInfo culInfo = new CultureInfo(_lcid);
Encoding cpe = System.Text.Encoding.GetEncoding(culInfo.TextInfo.ANSICodePage);
return cpe.GetBytes(_value);
}
/*
internal int GetSQLCID() {
if (IsNull)
throw new SqlNullValueException();
return MAKECID(m_lcid, m_flag);
}
*/
// Binary operators
// Concatenation
public static SqlString operator +(SqlString x, SqlString y)
{
if (x.IsNull || y.IsNull)
return SqlString.Null;
if (x._lcid != y._lcid || x._flag != y._flag)
throw new SqlTypeException(SQLResource.ConcatDiffCollationMessage);
return new SqlString(x._lcid, x._flag, x._value + y._value,
(x._cmpInfo == null) ? y._cmpInfo : x._cmpInfo);
}
// StringCompare: Common compare function which is used by Compare and CompareTo
// In the case of Compare (used by comparison operators) the int result needs to be converted to SqlBoolean type
// while CompareTo needs the result in int type
// Pre-requisite: the null condition of the both string needs to be checked and handled by the caller of this function
private static int StringCompare(SqlString x, SqlString y)
{
Debug.Assert(!x.IsNull && !y.IsNull,
"!x.IsNull && !y.IsNull", "Null condition should be handled by the caller of StringCompare method");
if (x._lcid != y._lcid || x._flag != y._flag)
throw new SqlTypeException(SQLResource.CompareDiffCollationMessage);
x.SetCompareInfo();
y.SetCompareInfo();
Debug.Assert(x.FBinarySort() || (x._cmpInfo != null && y._cmpInfo != null),
"x.FBinarySort() || (x.m_cmpInfo != null && y.m_cmpInfo != null)", "");
int iCmpResult;
if ((x._flag & SqlCompareOptions.BinarySort) != 0)
iCmpResult = CompareBinary(x, y);
else if ((x._flag & SqlCompareOptions.BinarySort2) != 0)
iCmpResult = CompareBinary2(x, y);
else
{
// SqlString can be padded with spaces (Padding is turn on by default in SQL Server 2008
// Trim the trailing space for comparison
// Avoid using String.TrimEnd function to avoid extra string allocations
string rgchX = x._value;
string rgchY = y._value;
int cwchX = rgchX.Length;
int cwchY = rgchY.Length;
while (cwchX > 0 && rgchX[cwchX - 1] == ' ')
cwchX--;
while (cwchY > 0 && rgchY[cwchY - 1] == ' ')
cwchY--;
CompareOptions options = CompareOptionsFromSqlCompareOptions(x._flag);
iCmpResult = x._cmpInfo.Compare(x._value, 0, cwchX, y._value, 0, cwchY, options);
}
return iCmpResult;
}
// Comparison operators
private static SqlBoolean Compare(SqlString x, SqlString y, EComparison ecExpectedResult)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
int iCmpResult = StringCompare(x, y);
bool fResult = false;
switch (ecExpectedResult)
{
case EComparison.EQ:
fResult = (iCmpResult == 0);
break;
case EComparison.LT:
fResult = (iCmpResult < 0);
break;
case EComparison.LE:
fResult = (iCmpResult <= 0);
break;
case EComparison.GT:
fResult = (iCmpResult > 0);
break;
case EComparison.GE:
fResult = (iCmpResult >= 0);
break;
default:
Debug.Assert(false, "Invalid ecExpectedResult");
return SqlBoolean.Null;
}
return new SqlBoolean(fResult);
}
// Implicit conversions
// Explicit conversions
// Explicit conversion from SqlBoolean to SqlString
public static explicit operator SqlString(SqlBoolean x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString());
}
// Explicit conversion from SqlByte to SqlString
public static explicit operator SqlString(SqlByte x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt16 to SqlString
public static explicit operator SqlString(SqlInt16 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt32 to SqlString
public static explicit operator SqlString(SqlInt32 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt64 to SqlString
public static explicit operator SqlString(SqlInt64 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlSingle to SqlString
public static explicit operator SqlString(SqlSingle x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlDouble to SqlString
public static explicit operator SqlString(SqlDouble x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlDecimal to SqlString
public static explicit operator SqlString(SqlDecimal x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlMoney to SqlString
public static explicit operator SqlString(SqlMoney x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlDateTime to SqlString
public static explicit operator SqlString(SqlDateTime x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlGuid to SqlString
public static explicit operator SqlString(SqlGuid x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
public SqlString Clone()
{
if (IsNull)
return new SqlString(true);
else
{
SqlString ret = new SqlString(_value, _lcid, _flag);
return ret;
}
}
// Overloading comparison operators
public static SqlBoolean operator ==(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.EQ);
}
public static SqlBoolean operator !=(SqlString x, SqlString y)
{
return !(x == y);
}
public static SqlBoolean operator <(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.LT);
}
public static SqlBoolean operator >(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.GT);
}
public static SqlBoolean operator <=(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.LE);
}
public static SqlBoolean operator >=(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.GE);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator +
public static SqlString Concat(SqlString x, SqlString y)
{
return x + y;
}
public static SqlString Add(SqlString x, SqlString y)
{
return x + y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlString x, SqlString y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlString x, SqlString y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlString x, SqlString y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlString x, SqlString y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlString x, SqlString y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlString x, SqlString y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlByte ToSqlByte()
{
return (SqlByte)this;
}
public SqlDateTime ToSqlDateTime()
{
return (SqlDateTime)this;
}
public SqlDouble ToSqlDouble()
{
return (SqlDouble)this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32()
{
return (SqlInt32)this;
}
public SqlInt64 ToSqlInt64()
{
return (SqlInt64)this;
}
public SqlMoney ToSqlMoney()
{
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal()
{
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle()
{
return (SqlSingle)this;
}
public SqlGuid ToSqlGuid()
{
return (SqlGuid)this;
}
// Utility functions and constants
private static void ValidateSqlCompareOptions(SqlCompareOptions compareOptions)
{
if ((compareOptions & s_iValidSqlCompareOptionMask) != compareOptions)
throw new ArgumentOutOfRangeException(nameof(compareOptions));
}
public static CompareOptions CompareOptionsFromSqlCompareOptions(SqlCompareOptions compareOptions)
{
CompareOptions options = CompareOptions.None;
ValidateSqlCompareOptions(compareOptions);
if ((compareOptions & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0)
throw ADP.ArgumentOutOfRange(nameof(compareOptions));
else
{
if ((compareOptions & SqlCompareOptions.IgnoreCase) != 0)
options |= CompareOptions.IgnoreCase;
if ((compareOptions & SqlCompareOptions.IgnoreNonSpace) != 0)
options |= CompareOptions.IgnoreNonSpace;
if ((compareOptions & SqlCompareOptions.IgnoreKanaType) != 0)
options |= CompareOptions.IgnoreKanaType;
if ((compareOptions & SqlCompareOptions.IgnoreWidth) != 0)
options |= CompareOptions.IgnoreWidth;
}
return options;
}
private bool FBinarySort()
{
return (!IsNull && (_flag & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0);
}
// Wide-character string comparison for Binary Unicode Collation
// Return values:
// -1 : wstr1 < wstr2
// 0 : wstr1 = wstr2
// 1 : wstr1 > wstr2
//
// Does a memory comparison.
private static int CompareBinary(SqlString x, SqlString y)
{
byte[] rgDataX = s_unicodeEncoding.GetBytes(x._value);
byte[] rgDataY = s_unicodeEncoding.GetBytes(y._value);
int cbX = rgDataX.Length;
int cbY = rgDataY.Length;
int cbMin = cbX < cbY ? cbX : cbY;
int i;
Debug.Assert(cbX % 2 == 0);
Debug.Assert(cbY % 2 == 0);
for (i = 0; i < cbMin; i++)
{
if (rgDataX[i] < rgDataY[i])
return -1;
else if (rgDataX[i] > rgDataY[i])
return 1;
}
i = cbMin;
int iCh;
int iSpace = ' ';
if (cbX < cbY)
{
for (; i < cbY; i += 2)
{
iCh = rgDataY[i + 1] << 8 + rgDataY[i];
if (iCh != iSpace)
return (iSpace > iCh) ? 1 : -1;
}
}
else
{
for (; i < cbX; i += 2)
{
iCh = rgDataX[i + 1] << 8 + rgDataX[i];
if (iCh != iSpace)
return (iCh > iSpace) ? 1 : -1;
}
}
return 0;
}
// Wide-character string comparison for Binary2 Unicode Collation
// Return values:
// -1 : wstr1 < wstr2
// 0 : wstr1 = wstr2
// 1 : wstr1 > wstr2
//
// Does a wchar comparison (different from memcmp of BinarySort).
private static int CompareBinary2(SqlString x, SqlString y)
{
Debug.Assert(!x.IsNull && !y.IsNull);
string rgDataX = x._value;
string rgDataY = y._value;
int cwchX = rgDataX.Length;
int cwchY = rgDataY.Length;
int cwchMin = cwchX < cwchY ? cwchX : cwchY;
int i;
for (i = 0; i < cwchMin; i++)
{
if (rgDataX[i] < rgDataY[i])
return -1;
else if (rgDataX[i] > rgDataY[i])
return 1;
}
// If compares equal up to one of the string terminates,
// pad it with spaces and compare with the rest of the other one.
//
char chSpace = ' ';
if (cwchX < cwchY)
{
for (i = cwchMin; i < cwchY; i++)
{
if (rgDataY[i] != chSpace)
return (chSpace > rgDataY[i]) ? 1 : -1;
}
}
else
{
for (i = cwchMin; i < cwchX; i++)
{
if (rgDataX[i] != chSpace)
return (rgDataX[i] > chSpace) ? 1 : -1;
}
}
return 0;
}
/*
private void Print() {
Debug.WriteLine("SqlString - ");
Debug.WriteLine("\tlcid = " + m_lcid.ToString());
Debug.Write("\t");
if ((m_flag & SqlCompareOptions.IgnoreCase) != 0)
Debug.Write("IgnoreCase, ");
if ((m_flag & SqlCompareOptions.IgnoreNonSpace) != 0)
Debug.Write("IgnoreNonSpace, ");
if ((m_flag & SqlCompareOptions.IgnoreKanaType) != 0)
Debug.Write("IgnoreKanaType, ");
if ((m_flag & SqlCompareOptions.IgnoreWidth) != 0)
Debug.Write("IgnoreWidth, ");
Debug.WriteLine("");
Debug.WriteLine("\tvalue = " + m_value);
Debug.WriteLine("\tcmpinfo = " + m_cmpInfo);
}
*/
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object value)
{
if (value is SqlString)
{
SqlString i = (SqlString)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlString));
}
public int CompareTo(SqlString value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
int returnValue = StringCompare(this, value);
// Conver the result into -1, 0, or 1 as this method never returned any other values
// This is to ensure the backcompat
if (returnValue < 0)
{
return -1;
}
if (returnValue > 0)
{
return 1;
}
return 0;
}
// Compares this instance with a specified object
public override bool Equals(object value)
{
if (!(value is SqlString))
{
return false;
}
SqlString i = (SqlString)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
public override int GetHashCode()
{
if (IsNull)
return 0;
byte[] rgbSortKey;
if (FBinarySort())
rgbSortKey = s_unicodeEncoding.GetBytes(_value.TrimEnd());
else
{
// GetHashCode should not throw just because this instance has an invalid LCID or compare options.
CompareInfo cmpInfo;
CompareOptions options;
try
{
SetCompareInfo();
cmpInfo = _cmpInfo;
options = CompareOptionsFromSqlCompareOptions(_flag);
}
catch (ArgumentException)
{
// SetCompareInfo throws this when instance's LCID is unsupported
// CompareOptionsFromSqlCompareOptions throws this when instance's options are invalid
cmpInfo = CultureInfo.InvariantCulture.CompareInfo;
options = CompareOptions.None;
}
rgbSortKey = cmpInfo.GetSortKey(_value.TrimEnd(), options).KeyData;
}
return SqlBinary.HashByteArray(rgbSortKey, rgbSortKey.Length);
}
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
_fNotNull = false;
}
else
{
_value = reader.ReadElementString();
_fNotNull = true;
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(_value);
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("string", XmlSchema.Namespace);
}
} // SqlString
/*
internal struct SLocaleMapItem {
public int lcid; // the primary key, not nullable
public String name; // unique, nullable
public int idCodePage; // the ANSI default code page of the locale
public SLocaleMapItem(int lid, String str, int cpid) {
lcid = lid;
name = str;
idCodePage = cpid;
}
}
// Struct to map lcid to ordinal
internal struct SLcidOrdMapItem {
internal int lcid;
internal int uiOrd;
};
// Class to store map of lcids to ordinal
internal class CBuildLcidOrdMap {
internal SLcidOrdMapItem[] m_rgLcidOrdMap;
internal int m_cValidLocales;
internal int m_uiPosEnglish; // Start binary searches here - this is index in array, not ordinal
// Constructor builds the array sorted by lcid
// We use a simple n**2 sort because the array is mostly sorted anyway
// and objects of this class will be const, hence this will be called
// only by VC compiler
public CBuildLcidOrdMap() {
int i,j;
m_rgLcidOrdMap = new SLcidOrdMapItem[SqlString.x_cLocales];
// Compact the array
for (i=0,j=0; i < SqlString.x_cLocales; i++) {
if (SqlString.x_rgLocaleMap[i].lcid != SqlString.x_lcidUnused) {
m_rgLcidOrdMap[j].lcid = SqlString.x_rgLocaleMap[i].lcid;
m_rgLcidOrdMap[j].uiOrd = i;
j++;
}
}
m_cValidLocales = j;
// Set the rest to invalid
while (j < SqlString.x_cLocales) {
m_rgLcidOrdMap[j].lcid = SqlString.x_lcidUnused;
m_rgLcidOrdMap[j].uiOrd = 0;
j++;
}
// Now sort in place
// Algo:
// Start from 1, assume list before i is sorted, if next item
// violates this assumption, exchange with prev items until the
// item is in its correct place
for (i=1; i<m_cValidLocales; i++) {
for (j=i; j>0 &&
m_rgLcidOrdMap[j].lcid < m_rgLcidOrdMap[j-1].lcid; j--) {
// Swap with prev element
int lcidTemp = m_rgLcidOrdMap[j-1].lcid;
int uiOrdTemp = m_rgLcidOrdMap[j-1].uiOrd;
m_rgLcidOrdMap[j-1].lcid = m_rgLcidOrdMap[j].lcid;
m_rgLcidOrdMap[j-1].uiOrd = m_rgLcidOrdMap[j].uiOrd;
m_rgLcidOrdMap[j].lcid = lcidTemp;
m_rgLcidOrdMap[j].uiOrd = uiOrdTemp;
}
}
// Set the position of the US_English LCID (Latin1_General)
for (i=0; i<m_cValidLocales && m_rgLcidOrdMap[i].lcid != SqlString.x_lcidUSEnglish; i++)
; // Deliberately empty
Debug.Assert(i<m_cValidLocales); // Latin1_General better be present
m_uiPosEnglish = i; // This is index in array, not ordinal
}
} // CBuildLcidOrdMap
*/
} // namespace System.Data.SqlTypes
| |
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
/// <summary>
/// Convert.ToString(System.Int16,System.Int32)
/// </summary>
public class ConvertToString14
{
public static int Main()
{
ConvertToString14 testObj = new ConvertToString14();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Int16,System.Int32)");
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;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string c_TEST_DESC = "PosTest1: Verify value is 323 and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P001";
Int16 int16Value =-123;
int radix;
String actualValue;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = "1111111110000101";
radix = 2;
String resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 8;
actualValue = "177605";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 10;
actualValue = "-123";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 16;
actualValue = "ff85";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string c_TEST_DESC = "PosTest2: Verify value is Int16.MaxValue and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P002";
Int16 int16Value = Int16.MaxValue;
int radix;
String actualValue;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = "111111111111111";
radix = 2;
String resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 8;
actualValue = "77777";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 10;
actualValue = "32767";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 16;
actualValue = "7fff";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string c_TEST_DESC = "PosTest3: Verify value is Int16.MinValue and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P003";
Int16 int16Value = Int16.MinValue;
int radix;
String actualValue;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = "1000000000000000";
radix = 2;
String resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 8;
actualValue = "100000";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 10;
actualValue = "-32768";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 16;
actualValue = "8000";
errorDesc = "";
resValue = Convert.ToString(int16Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int16Value, radix);
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("015", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTesting
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: the radix is 32...";
const string c_TEST_ID = "N001";
Int16 int16Value = TestLibrary.Generator.GetInt16(-55);
int radix = 32;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToString(int16Value, radix);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected ." + DataString(int16Value, radix));
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + DataString(int16Value, radix));
retVal = false;
}
return retVal;
}
#endregion
#region Help Methods
private string DataString(Int16 int16Value, int radix)
{
string str;
str = string.Format("\n[int16Value value]\n \"{0}\"", int16Value);
str += string.Format("\n[radix value ]\n {0}", radix);
return str;
}
#endregion
}
| |
#region Header
//
// Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
#endregion // Header
using System;
using System.Collections;
namespace RevitLookup.Snoop.Collectors
{
/// <summary>
/// Collect data about an CollectorXmlNode. Since everything we encounter
/// in XML will be restricted to XML and not Elements and such, keep these
/// all in their own Collector object so we don't waste time trying to traverse
/// a class hierarchy that we'll never be expected to deal with.
/// </summary>
public class CollectorXmlNode : Collector
{
public
CollectorXmlNode()
{
}
public void
Collect(System.Xml.XmlNode node)
{
m_dataObjs.Clear();
Stream(node);
// now that we've collected all the data that we know about,
// fire an event to any registered Snoop Collector Extensions so
// they can add their data
//FireEvent_CollectExt(node); // shouldn't be anyone else, we've taken care of it all
}
// main branch for anything derived from System.Xml.XmlNode
private void
Stream(System.Xml.XmlNode node)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlNode)));
m_dataObjs.Add(new Snoop.Data.String("Node type", node.NodeType.ToString()));
m_dataObjs.Add(new Snoop.Data.String("Name", node.Name));
m_dataObjs.Add(new Snoop.Data.String("Local name", node.LocalName));
m_dataObjs.Add(new Snoop.Data.String("Value", node.Value));
m_dataObjs.Add(new Snoop.Data.Bool("Has child nodes", node.HasChildNodes));
m_dataObjs.Add(new Snoop.Data.String("Inner text", node.InnerText));
m_dataObjs.Add(new Snoop.Data.Xml("Inner XML", node.InnerXml, false));
m_dataObjs.Add(new Snoop.Data.Xml("Outer XML", node.OuterXml, false));
m_dataObjs.Add(new Snoop.Data.Bool("Is read only", node.IsReadOnly));
m_dataObjs.Add(new Snoop.Data.String("BaseURI", node.BaseURI));
m_dataObjs.Add(new Snoop.Data.String("Namespace URI", node.NamespaceURI));
m_dataObjs.Add(new Snoop.Data.String("Prefix", node.Prefix));
// branch to all known major sub-classes
System.Xml.XmlAttribute att = node as System.Xml.XmlAttribute;
if (att != null) {
Stream(att);
return;
}
System.Xml.XmlDocument doc = node as System.Xml.XmlDocument;
if (doc != null) {
Stream(doc);
return;
}
System.Xml.XmlDocumentFragment docFrag = node as System.Xml.XmlDocumentFragment;
if (docFrag != null) {
Stream(docFrag);
return;
}
System.Xml.XmlEntity ent = node as System.Xml.XmlEntity;
if (ent != null) {
Stream(ent);
return;
}
System.Xml.XmlNotation notation = node as System.Xml.XmlNotation;
if (notation != null) {
Stream(notation);
return;
}
System.Xml.XmlLinkedNode lnkNode = node as System.Xml.XmlLinkedNode;
if (lnkNode != null) {
Stream(lnkNode);
return;
}
}
private void
Stream(System.Xml.XmlAttribute att)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlAttribute)));
m_dataObjs.Add(new Snoop.Data.Bool("Specified", att.Specified));
}
private void
Stream(System.Xml.XmlLinkedNode lnkNode)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlLinkedNode)));
// No data to show at this level, but we want to explicitly
// show that there is an intermediate class.
System.Xml.XmlElement elem = lnkNode as System.Xml.XmlElement;
if (elem != null) {
Stream(elem);
return;
}
System.Xml.XmlCharacterData charData = lnkNode as System.Xml.XmlCharacterData;
if (charData != null) {
Stream(charData);
return;
}
System.Xml.XmlDeclaration decl = lnkNode as System.Xml.XmlDeclaration;
if (decl != null) {
Stream(decl);
return;
}
System.Xml.XmlDocumentType dType = lnkNode as System.Xml.XmlDocumentType;
if (dType != null) {
Stream(dType);
return;
}
System.Xml.XmlEntityReference entRef = lnkNode as System.Xml.XmlEntityReference;
if (entRef != null) {
Stream(entRef);
return;
}
System.Xml.XmlProcessingInstruction pi = lnkNode as System.Xml.XmlProcessingInstruction;
if (pi != null) {
Stream(pi);
return;
}
}
private void
Stream(System.Xml.XmlElement elem)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlElement)));
m_dataObjs.Add(new Snoop.Data.Bool("Has attributes", elem.HasAttributes));
m_dataObjs.Add(new Snoop.Data.Bool("Is empty", elem.IsEmpty));
}
private void
Stream(System.Xml.XmlCharacterData charData)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlCharacterData)));
m_dataObjs.Add(new Snoop.Data.Int("Length", charData.Length));
m_dataObjs.Add(new Snoop.Data.String("Data", charData.Data));
System.Xml.XmlCDataSection cDataSection = charData as System.Xml.XmlCDataSection;
if (cDataSection != null) {
Stream(cDataSection);
return;
}
System.Xml.XmlComment comment = charData as System.Xml.XmlComment;
if (comment != null) {
Stream(comment);
return;
}
System.Xml.XmlSignificantWhitespace swSpace = charData as System.Xml.XmlSignificantWhitespace;
if (swSpace != null) {
Stream(swSpace);
return;
}
System.Xml.XmlText txt = charData as System.Xml.XmlText;
if (txt != null) {
Stream(txt);
return;
}
System.Xml.XmlWhitespace wSpace = charData as System.Xml.XmlWhitespace;
if (wSpace != null) {
Stream(wSpace);
return;
}
}
private void
Stream(System.Xml.XmlCDataSection cDataSection)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlCDataSection)));
// do data to display at this level
}
private void
Stream(System.Xml.XmlComment comment)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlComment)));
// no data to display at this level
}
private void
Stream(System.Xml.XmlDeclaration decl)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlDeclaration)));
m_dataObjs.Add(new Snoop.Data.String("Encoding", decl.Encoding));
m_dataObjs.Add(new Snoop.Data.String("Standalone", decl.Standalone));
m_dataObjs.Add(new Snoop.Data.String("Version", decl.Version));
}
private void
Stream(System.Xml.XmlDocument doc)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlDocument)));
m_dataObjs.Add(new Snoop.Data.Bool("Preserve whitespace", doc.PreserveWhitespace));
}
private void
Stream(System.Xml.XmlDocumentFragment doc)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlDocumentFragment)));
// no data to display at this level
}
private void
Stream(System.Xml.XmlDocumentType dType)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlDocumentType)));
m_dataObjs.Add(new Snoop.Data.String("Internal subset", dType.InternalSubset));
m_dataObjs.Add(new Snoop.Data.String("Public ID", dType.PublicId));
m_dataObjs.Add(new Snoop.Data.String("System ID", dType.SystemId));
}
private void
Stream(System.Xml.XmlEntity ent)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlEntity)));
m_dataObjs.Add(new Snoop.Data.String("Notation name", ent.NotationName));
m_dataObjs.Add(new Snoop.Data.String("Public ID", ent.PublicId));
m_dataObjs.Add(new Snoop.Data.String("System ID", ent.SystemId));
}
private void
Stream(System.Xml.XmlEntityReference entRef)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlEntityReference)));
// no data to display at this level
}
private void
Stream(System.Xml.XmlNotation notation)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlNotation)));
m_dataObjs.Add(new Snoop.Data.String("Public ID", notation.PublicId));
m_dataObjs.Add(new Snoop.Data.String("System ID", notation.SystemId));
}
private void
Stream(System.Xml.XmlProcessingInstruction pi)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlProcessingInstruction)));
m_dataObjs.Add(new Snoop.Data.String("Target", pi.Target));
}
private void
Stream(System.Xml.XmlSignificantWhitespace swSpace)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlSignificantWhitespace)));
// no data to display at this level
}
private void
Stream(System.Xml.XmlText text)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlText)));
// no data to display at this level
}
private void
Stream(System.Xml.XmlWhitespace wSpace)
{
m_dataObjs.Add(new Snoop.Data.ClassSeparator(typeof(System.Xml.XmlWhitespace)));
// no data to display at this level
}
}
}
| |
/**
* MetroFramework - Modern UI for WinForms
*
* The MIT License (MIT)
* Copyright (c) 2011 Sven Walter, http://github.com/viperneo
*
* 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.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Windows.Forms;
using MetroFramework.Components;
using MetroFramework.Drawing;
using MetroFramework.Interfaces;
using MetroFramework.Native;
namespace MetroFramework.Forms
{
#region Enums
public enum MetroFormTextAlign
{
Left,
Center,
Right
}
public enum MetroFormShadowType
{
None,
Flat,
DropShadow,
SystemShadow,
AeroShadow
}
public enum MetroFormBorderStyle
{
None,
FixedSingle
}
public enum BackLocation
{
TopLeft,
TopRight,
BottomLeft,
BottomRight
}
#endregion
public class MetroForm : Form, IMetroForm, IDisposable
{
#region Interface
private MetroColorStyle metroStyle = MetroColorStyle.Blue;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroColorStyle Style
{
get
{
if (StyleManager != null)
return StyleManager.Style;
return metroStyle;
}
set { metroStyle = value; }
}
private MetroThemeStyle metroTheme = MetroThemeStyle.Light;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroThemeStyle Theme
{
get
{
if (StyleManager != null)
return StyleManager.Theme;
return metroTheme;
}
set { metroTheme = value; }
}
private MetroStyleManager metroStyleManager = null;
[Browsable(false)]
public MetroStyleManager StyleManager
{
get { return metroStyleManager; }
set { metroStyleManager = value; }
}
#endregion
#region Fields
private MetroFormTextAlign textAlign = MetroFormTextAlign.Left;
[Browsable(true)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroFormTextAlign TextAlign
{
get { return textAlign; }
set { textAlign = value; }
}
[Browsable(false)]
public override Color BackColor
{
get { return MetroPaint.BackColor.Form(Theme); }
}
private MetroFormBorderStyle formBorderStyle = MetroFormBorderStyle.None;
[DefaultValue(MetroFormBorderStyle.None)]
[Browsable(true)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroFormBorderStyle BorderStyle
{
get { return formBorderStyle; }
set { formBorderStyle = value; }
}
private bool isMovable = true;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool Movable
{
get { return isMovable; }
set { isMovable = value; }
}
public new Padding Padding
{
get { return base.Padding; }
set
{
value.Top = Math.Max(value.Top, DisplayHeader ? 60 : 30);
base.Padding = value;
}
}
protected override Padding DefaultPadding
{
get { return new Padding(20, DisplayHeader ? 60 : 20, 20, 20); }
}
private bool displayHeader = true;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(true)]
public bool DisplayHeader
{
get { return displayHeader; }
set
{
if (value != displayHeader)
{
Padding p = base.Padding;
p.Top += value ? 30 : -30;
base.Padding = p;
}
displayHeader = value;
}
}
private bool isResizable = true;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool Resizable
{
get { return isResizable; }
set { isResizable = value; }
}
private MetroFormShadowType shadowType = MetroFormShadowType.Flat;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroFormShadowType.Flat)]
public MetroFormShadowType ShadowType
{
get { return IsMdiChild ? MetroFormShadowType.None : shadowType; }
set { shadowType = value; }
}
[Browsable(false)]
public new FormBorderStyle FormBorderStyle
{
get { return base.FormBorderStyle; }
set { base.FormBorderStyle = value; }
}
public new Form MdiParent
{
get { return base.MdiParent; }
set
{
if (value != null)
{
RemoveShadow();
shadowType = MetroFormShadowType.None;
}
base.MdiParent = value;
}
}
private const int borderWidth = 5;
private Bitmap _image = null;
private Image backImage;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(null)]
public Image BackImage
{
get { return backImage; }
set
{
backImage = value;
if(value != null) _image = ApplyInvert(new Bitmap(value));
Refresh();
}
}
private Padding backImagePadding;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public Padding BackImagePadding
{
get { return backImagePadding; }
set
{
backImagePadding = value;
Refresh();
}
}
private int backMaxSize;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public int BackMaxSize
{
get { return backMaxSize; }
set
{
backMaxSize = value;
Refresh();
}
}
private BackLocation backLocation;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(BackLocation.TopLeft)]
public BackLocation BackLocation
{
get { return backLocation; }
set
{
backLocation = value;
Refresh();
}
}
private bool _imageinvert;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(true)]
public bool ApplyImageInvert
{
get { return _imageinvert; }
set
{
_imageinvert = value;
Refresh();
}
}
#endregion
#region Constructor
public MetroForm()
{
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
FormBorderStyle = FormBorderStyle.None;
Name = "MetroForm";
StartPosition = FormStartPosition.CenterScreen;
TransparencyKey = Color.Lavender;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
RemoveShadow();
}
base.Dispose(disposing);
}
#endregion
#region Paint Methods
public Bitmap ApplyInvert(Bitmap bitmapImage)
{
byte A, R, G, B;
Color pixelColor;
for (int y = 0; y < bitmapImage.Height; y++)
{
for (int x = 0; x < bitmapImage.Width; x++)
{
pixelColor = bitmapImage.GetPixel(x, y);
A = pixelColor.A;
R = (byte)(255 - pixelColor.R);
G = (byte)(255 - pixelColor.G);
B = (byte)(255 - pixelColor.B);
if (R <= 0) R= 17;
if (G <= 0) G= 17;
if (B <= 0) B= 17;
//bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
bitmapImage.SetPixel(x, y, Color.FromArgb((int)R, (int)G, (int)B));
}
}
return bitmapImage;
}
protected override void OnPaint(PaintEventArgs e)
{
Color backColor = MetroPaint.BackColor.Form(Theme);
Color foreColor = MetroPaint.ForeColor.Title(Theme);
e.Graphics.Clear(backColor);
using (SolidBrush b = MetroPaint.GetStyleBrush(Style))
{
Rectangle topRect = new Rectangle(0, 0, Width, borderWidth);
e.Graphics.FillRectangle(b, topRect);
}
if (BorderStyle != MetroFormBorderStyle.None)
{
Color c = MetroPaint.BorderColor.Form(Theme);
using (Pen pen = new Pen(c))
{
e.Graphics.DrawLines(pen, new[]
{
new Point(0, borderWidth),
new Point(0, Height - 1),
new Point(Width - 1, Height - 1),
new Point(Width - 1, borderWidth)
});
}
}
if (backImage != null && backMaxSize != 0)
{
Image img = MetroImage.ResizeImage(backImage, new Rectangle(0, 0, backMaxSize, backMaxSize));
if (_imageinvert)
{
img = MetroImage.ResizeImage((Theme == MetroThemeStyle.Dark) ? _image : backImage, new Rectangle(0, 0, backMaxSize, backMaxSize));
}
switch (backLocation)
{
case BackLocation.TopLeft:
e.Graphics.DrawImage(img, 0 + backImagePadding.Left, 0 + backImagePadding.Top);
break;
case BackLocation.TopRight:
e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width), 0 + backImagePadding.Top);
break;
case BackLocation.BottomLeft:
e.Graphics.DrawImage(img, 0 + backImagePadding.Left, ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom));
break;
case BackLocation.BottomRight:
e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width),
ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom));
break;
}
}
if (displayHeader)
{
Rectangle bounds = new Rectangle(20, 20, ClientRectangle.Width - 2 * 20, 40);
TextFormatFlags flags = TextFormatFlags.EndEllipsis | GetTextFormatFlags();
TextRenderer.DrawText(e.Graphics, Text, MetroFonts.Title, bounds, foreColor, flags);
}
if (Resizable && (SizeGripStyle == SizeGripStyle.Auto || SizeGripStyle == SizeGripStyle.Show))
{
using (SolidBrush b = new SolidBrush(MetroPaint.ForeColor.Button.Disabled(Theme)))
{
Size resizeHandleSize = new Size(2, 2);
e.Graphics.FillRectangles(b, new Rectangle[] {
new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-6), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-10), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-6), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-10), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-14,ClientRectangle.Height-6), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-14), resizeHandleSize)
});
}
}
}
private TextFormatFlags GetTextFormatFlags()
{
switch (TextAlign)
{
case MetroFormTextAlign.Left: return TextFormatFlags.Left;
case MetroFormTextAlign.Center: return TextFormatFlags.HorizontalCenter;
case MetroFormTextAlign.Right: return TextFormatFlags.Right;
}
throw new InvalidOperationException();
}
#endregion
#region Management Methods
protected override void OnClosing(CancelEventArgs e)
{
if (!(this is MetroTaskWindow))
MetroTaskWindow.ForceClose();
base.OnClosing(e);
}
protected override void OnClosed(EventArgs e)
{
RemoveShadow();
base.OnClosed(e);
}
[SecuritySafeCritical]
public bool FocusMe()
{
return WinApi.SetForegroundWindow(Handle);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (DesignMode) return;
switch (StartPosition)
{
case FormStartPosition.CenterParent:
CenterToParent();
break;
case FormStartPosition.CenterScreen:
if (IsMdiChild)
{
CenterToParent();
}
else
{
CenterToScreen();
}
break;
}
RemoveCloseButton();
if (ControlBox)
{
AddWindowButton(WindowButtons.Close);
if (MaximizeBox)
AddWindowButton(WindowButtons.Maximize);
if (MinimizeBox)
AddWindowButton(WindowButtons.Minimize);
UpdateWindowButtonPosition();
}
CreateShadow();
}
protected override void OnActivated(EventArgs e)
{
base.OnActivated(e);
if (shadowType == MetroFormShadowType.AeroShadow &&
IsAeroThemeEnabled() && IsDropShadowSupported())
{
int val = 2;
DwmApi.DwmSetWindowAttribute(Handle, 2, ref val, 4);
var m = new DwmApi.MARGINS
{
cyBottomHeight = 1,
cxLeftWidth = 0,
cxRightWidth = 0,
cyTopHeight = 0
};
DwmApi.DwmExtendFrameIntoClientArea(Handle, ref m);
}
}
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
Invalidate();
}
protected override void OnResizeEnd(EventArgs e)
{
base.OnResizeEnd(e);
UpdateWindowButtonPosition();
}
protected override void WndProc(ref Message m)
{
if (DesignMode)
{
base.WndProc(ref m);
return;
}
switch (m.Msg)
{
case (int)WinApi.Messages.WM_SYSCOMMAND:
int sc = m.WParam.ToInt32() & 0xFFF0;
switch (sc)
{
case (int)WinApi.Messages.SC_MOVE:
if (!Movable) return;
break;
case (int)WinApi.Messages.SC_MAXIMIZE:
break;
case (int)WinApi.Messages.SC_RESTORE:
break;
}
break;
case (int)WinApi.Messages.WM_NCLBUTTONDBLCLK:
case (int)WinApi.Messages.WM_LBUTTONDBLCLK:
if (!MaximizeBox) return;
break;
case (int)WinApi.Messages.WM_NCHITTEST:
WinApi.HitTest ht = HitTestNCA(m.HWnd, m.WParam, m.LParam);
if (ht != WinApi.HitTest.HTCLIENT)
{
m.Result = (IntPtr)ht;
return;
}
break;
case (int)WinApi.Messages.WM_DWMCOMPOSITIONCHANGED:
break;
}
base.WndProc(ref m);
switch (m.Msg)
{
case (int)WinApi.Messages.WM_GETMINMAXINFO:
OnGetMinMaxInfo(m.HWnd, m.LParam);
break;
case (int)WinApi.Messages.WM_SIZE:
MetroFormButton btn;
windowButtonList.TryGetValue(WindowButtons.Maximize, out btn);
if (WindowState == FormWindowState.Normal) shadowForm.Visible = true;btn.Text = "1";
if(WindowState== FormWindowState.Maximized) btn.Text = "2";
break;
}
}
[SecuritySafeCritical]
private unsafe void OnGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
{
WinApi.MINMAXINFO* pmmi = (WinApi.MINMAXINFO*)lParam;
Screen s = Screen.FromHandle(hwnd);
pmmi->ptMaxSize.x = s.WorkingArea.Width;
pmmi->ptMaxSize.y = s.WorkingArea.Height;
pmmi->ptMaxPosition.x = Math.Abs(s.WorkingArea.Left - s.Bounds.Left);
pmmi->ptMaxPosition.y = Math.Abs(s.WorkingArea.Top - s.Bounds.Top);
//if (MinimumSize.Width > 0) pmmi->ptMinTrackSize.x = MinimumSize.Width;
//if (MinimumSize.Height > 0) pmmi->ptMinTrackSize.y = MinimumSize.Height;
//if (MaximumSize.Width > 0) pmmi->ptMaxTrackSize.x = MaximumSize.Width;
//if (MaximumSize.Height > 0) pmmi->ptMaxTrackSize.y = MaximumSize.Height;
}
private WinApi.HitTest HitTestNCA(IntPtr hwnd, IntPtr wparam, IntPtr lparam)
{
//Point vPoint = PointToClient(new Point((int)lparam & 0xFFFF, (int)lparam >> 16 & 0xFFFF));
//Point vPoint = PointToClient(new Point((Int16)lparam, (Int16)((int)lparam >> 16)));
Point vPoint = new Point((Int16)lparam, (Int16)((int)lparam >> 16));
int vPadding = Math.Max(Padding.Right, Padding.Bottom);
if (Resizable)
{
if (RectangleToScreen(new Rectangle(ClientRectangle.Width - vPadding, ClientRectangle.Height - vPadding, vPadding, vPadding)).Contains(vPoint))
return WinApi.HitTest.HTBOTTOMRIGHT;
}
if (RectangleToScreen(new Rectangle(borderWidth, borderWidth, ClientRectangle.Width - 2 * borderWidth, 50)).Contains(vPoint))
return WinApi.HitTest.HTCAPTION;
return WinApi.HitTest.HTCLIENT;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left && Movable)
{
if (WindowState == FormWindowState.Maximized) return;
if (Width - borderWidth > e.Location.X && e.Location.X > borderWidth && e.Location.Y > borderWidth)
{
MoveControl();
}
}
}
[SecuritySafeCritical]
private void MoveControl()
{
WinApi.ReleaseCapture();
WinApi.SendMessage(Handle, (int)WinApi.Messages.WM_NCLBUTTONDOWN, (int)WinApi.HitTest.HTCAPTION, 0);
}
[SecuritySafeCritical]
private static bool IsAeroThemeEnabled()
{
if (Environment.OSVersion.Version.Major <= 5) return false;
bool aeroEnabled;
DwmApi.DwmIsCompositionEnabled(out aeroEnabled);
return aeroEnabled;
}
private static bool IsDropShadowSupported()
{
return Environment.OSVersion.Version.Major > 5 && SystemInformation.IsDropShadowEnabled;
}
#endregion
#region Window Buttons
private enum WindowButtons
{
Minimize,
Maximize,
Close
}
private Dictionary<WindowButtons, MetroFormButton> windowButtonList;
private void AddWindowButton(WindowButtons button)
{
if (windowButtonList == null)
windowButtonList = new Dictionary<WindowButtons, MetroFormButton>();
if (windowButtonList.ContainsKey(button))
return;
MetroFormButton newButton = new MetroFormButton();
if (button == WindowButtons.Close)
{
newButton.Text = "r";
}
else if (button == WindowButtons.Minimize)
{
newButton.Text = "0";
}
else if (button == WindowButtons.Maximize)
{
if (WindowState == FormWindowState.Normal)
newButton.Text = "1";
else
newButton.Text = "2";
}
newButton.Style = Style;
newButton.Theme = Theme;
newButton.Tag = button;
newButton.Size = new Size(25, 20);
newButton.Anchor = AnchorStyles.Top | AnchorStyles.Right;
newButton.TabStop = false; //remove the form controls from the tab stop
newButton.Click += WindowButton_Click;
Controls.Add(newButton);
windowButtonList.Add(button, newButton);
}
private void WindowButton_Click(object sender, EventArgs e)
{
var btn = sender as MetroFormButton;
if (btn != null)
{
var btnFlag = (WindowButtons)btn.Tag;
if (btnFlag == WindowButtons.Close)
{
Close();
}
else if (btnFlag == WindowButtons.Minimize)
{
WindowState = FormWindowState.Minimized;
}
else if (btnFlag == WindowButtons.Maximize)
{
if (WindowState == FormWindowState.Normal)
{
WindowState = FormWindowState.Maximized;
btn.Text = "2";
}
else
{
WindowState = FormWindowState.Normal;
btn.Text = "1";
}
}
}
}
private void UpdateWindowButtonPosition()
{
if (!ControlBox) return;
Dictionary<int, WindowButtons> priorityOrder = new Dictionary<int, WindowButtons>(3) { {0, WindowButtons.Close}, {1, WindowButtons.Maximize}, {2, WindowButtons.Minimize} };
Point firstButtonLocation = new Point(ClientRectangle.Width - borderWidth - 25, borderWidth);
int lastDrawedButtonPosition = firstButtonLocation.X - 25;
MetroFormButton firstButton = null;
if (windowButtonList.Count == 1)
{
foreach (KeyValuePair<WindowButtons, MetroFormButton> button in windowButtonList)
{
button.Value.Location = firstButtonLocation;
}
}
else
{
foreach (KeyValuePair<int, WindowButtons> button in priorityOrder)
{
bool buttonExists = windowButtonList.ContainsKey(button.Value);
if (firstButton == null && buttonExists)
{
firstButton = windowButtonList[button.Value];
firstButton.Location = firstButtonLocation;
continue;
}
if (firstButton == null || !buttonExists) continue;
windowButtonList[button.Value].Location = new Point(lastDrawedButtonPosition, borderWidth);
lastDrawedButtonPosition = lastDrawedButtonPosition - 25;
}
}
Refresh();
}
private class MetroFormButton : Button, IMetroControl
{
#region Interface
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaintBackground;
protected virtual void OnCustomPaintBackground(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaintBackground != null)
{
CustomPaintBackground(this, e);
}
}
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaint;
protected virtual void OnCustomPaint(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaint != null)
{
CustomPaint(this, e);
}
}
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaintForeground;
protected virtual void OnCustomPaintForeground(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaintForeground != null)
{
CustomPaintForeground(this, e);
}
}
private MetroColorStyle metroStyle = MetroColorStyle.Default;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroColorStyle.Default)]
public MetroColorStyle Style
{
get
{
if (DesignMode || metroStyle != MetroColorStyle.Default)
{
return metroStyle;
}
if (StyleManager != null && metroStyle == MetroColorStyle.Default)
{
return StyleManager.Style;
}
if (StyleManager == null && metroStyle == MetroColorStyle.Default)
{
return MetroDefaults.Style;
}
return metroStyle;
}
set { metroStyle = value; }
}
private MetroThemeStyle metroTheme = MetroThemeStyle.Default;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroThemeStyle.Default)]
public MetroThemeStyle Theme
{
get
{
if (DesignMode || metroTheme != MetroThemeStyle.Default)
{
return metroTheme;
}
if (StyleManager != null && metroTheme == MetroThemeStyle.Default)
{
return StyleManager.Theme;
}
if (StyleManager == null && metroTheme == MetroThemeStyle.Default)
{
return MetroDefaults.Theme;
}
return metroTheme;
}
set { metroTheme = value; }
}
private MetroStyleManager metroStyleManager = null;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public MetroStyleManager StyleManager
{
get { return metroStyleManager; }
set { metroStyleManager = value; }
}
private bool useCustomBackColor = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseCustomBackColor
{
get { return useCustomBackColor; }
set { useCustomBackColor = value; }
}
private bool useCustomForeColor = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseCustomForeColor
{
get { return useCustomForeColor; }
set { useCustomForeColor = value; }
}
private bool useStyleColors = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseStyleColors
{
get { return useStyleColors; }
set { useStyleColors = value; }
}
[Browsable(false)]
[Category(MetroDefaults.PropertyCategory.Behaviour)]
[DefaultValue(false)]
public bool UseSelectable
{
get { return GetStyle(ControlStyles.Selectable); }
set { SetStyle(ControlStyles.Selectable, value); }
}
#endregion
#region Fields
private bool isHovered = false;
private bool isPressed = false;
#endregion
#region Constructor
public MetroFormButton()
{
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
}
#endregion
#region Paint Methods
protected override void OnPaint(PaintEventArgs e)
{
Color backColor, foreColor;
MetroThemeStyle _Theme = Theme;
if (Parent != null)
{
if (Parent is IMetroForm)
{
_Theme = ((IMetroForm)Parent).Theme;
backColor = MetroPaint.BackColor.Form(_Theme);
}
else if (Parent is IMetroControl)
{
backColor = MetroPaint.GetStyleColor(Style);
}
else
{
backColor = Parent.BackColor;
}
}
else
{
backColor = MetroPaint.BackColor.Form(_Theme);
}
if (isHovered && !isPressed && Enabled)
{
foreColor = MetroPaint.ForeColor.Button.Normal(_Theme);
backColor = MetroPaint.BackColor.Button.Normal(_Theme);
}
else if (isHovered && isPressed && Enabled)
{
foreColor = MetroPaint.ForeColor.Button.Press(_Theme);
backColor = MetroPaint.GetStyleColor(Style);
}
else if (!Enabled)
{
foreColor = MetroPaint.ForeColor.Button.Disabled(_Theme);
backColor = MetroPaint.BackColor.Button.Disabled(_Theme);
}
else
{
foreColor = MetroPaint.ForeColor.Button.Normal(_Theme);
}
e.Graphics.Clear(backColor);
Font buttonFont = new Font("Webdings", 9.25f);
TextRenderer.DrawText(e.Graphics, Text, buttonFont, ClientRectangle, foreColor, backColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
}
#endregion
#region Mouse Methods
protected override void OnMouseEnter(EventArgs e)
{
isHovered = true;
Invalidate();
base.OnMouseEnter(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isPressed = true;
Invalidate();
}
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
isPressed = false;
Invalidate();
base.OnMouseUp(e);
}
protected override void OnMouseLeave(EventArgs e)
{
isHovered = false;
Invalidate();
base.OnMouseLeave(e);
}
#endregion
}
#endregion
#region Shadows
private const int CS_DROPSHADOW = 0x20000;
const int WS_MINIMIZEBOX = 0x20000;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style |= WS_MINIMIZEBOX;
if (ShadowType == MetroFormShadowType.SystemShadow)
cp.ClassStyle |= CS_DROPSHADOW;
return cp;
}
}
private Form shadowForm;
private void CreateShadow()
{
switch (ShadowType)
{
case MetroFormShadowType.Flat:
shadowForm = new MetroFlatDropShadow(this);
return;
case MetroFormShadowType.DropShadow:
shadowForm = new MetroRealisticDropShadow(this);
return;
}
}
private void RemoveShadow()
{
if (shadowForm == null || shadowForm.IsDisposed) return;
shadowForm.Visible = false;
Owner = shadowForm.Owner;
shadowForm.Owner = null;
shadowForm.Dispose();
shadowForm = null;
}
#region MetroShadowBase
protected abstract class MetroShadowBase : Form
{
protected Form TargetForm { get; private set; }
private readonly int shadowSize;
private readonly int wsExStyle;
protected MetroShadowBase(Form targetForm, int shadowSize, int wsExStyle)
{
TargetForm = targetForm;
this.shadowSize = shadowSize;
this.wsExStyle = wsExStyle;
TargetForm.Activated += OnTargetFormActivated;
TargetForm.ResizeBegin += OnTargetFormResizeBegin;
TargetForm.ResizeEnd += OnTargetFormResizeEnd;
TargetForm.VisibleChanged += OnTargetFormVisibleChanged;
TargetForm.SizeChanged += OnTargetFormSizeChanged;
TargetForm.Move += OnTargetFormMove;
TargetForm.Resize += OnTargetFormResize;
if (TargetForm.Owner != null)
Owner = TargetForm.Owner;
TargetForm.Owner = this;
MaximizeBox = false;
MinimizeBox = false;
ShowInTaskbar = false;
ShowIcon = false;
FormBorderStyle = FormBorderStyle.None;
Bounds = GetShadowBounds();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= wsExStyle;
return cp;
}
}
private Rectangle GetShadowBounds()
{
Rectangle r = TargetForm.Bounds;
r.Inflate(shadowSize, shadowSize);
return r;
}
protected abstract void PaintShadow();
protected abstract void ClearShadow();
#region Event Handlers
private bool isBringingToFront;
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
isBringingToFront = true;
}
private void OnTargetFormActivated(object sender, EventArgs e)
{
if (Visible) Update();
if (isBringingToFront)
{
Visible = true;
isBringingToFront = false;
return;
}
BringToFront();
}
private void OnTargetFormVisibleChanged(object sender, EventArgs e)
{
Visible = TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized;
Update();
}
private long lastResizedOn;
private bool IsResizing { get { return lastResizedOn > 0; } }
private void OnTargetFormResizeBegin(object sender, EventArgs e)
{
lastResizedOn = DateTime.Now.Ticks;
}
private void OnTargetFormMove(object sender, EventArgs e)
{
if (!TargetForm.Visible || TargetForm.WindowState != FormWindowState.Normal)
{
Visible = false;
}
else
{
Bounds = GetShadowBounds();
}
}
private void OnTargetFormResize(object sender, EventArgs e)
{
ClearShadow();
}
private void OnTargetFormSizeChanged(object sender, EventArgs e)
{
Bounds = GetShadowBounds();
if (IsResizing)
{
return;
}
PaintShadowIfVisible();
}
private void OnTargetFormResizeEnd(object sender, EventArgs e)
{
lastResizedOn = 0;
PaintShadowIfVisible();
}
private void PaintShadowIfVisible()
{
if (TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized)
PaintShadow();
}
#endregion
#region Constants
protected const int WS_EX_TRANSPARENT = 0x20;
protected const int WS_EX_LAYERED = 0x80000;
protected const int WS_EX_NOACTIVATE = 0x8000000;
private const int TICKS_PER_MS = 10000;
private const long RESIZE_REDRAW_INTERVAL = 1000 * TICKS_PER_MS;
#endregion
}
#endregion
#region Aero DropShadow
protected class MetroAeroDropShadow : MetroShadowBase
{
public MetroAeroDropShadow(Form targetForm)
: base(targetForm, 0, WS_EX_TRANSPARENT | WS_EX_NOACTIVATE )
{
FormBorderStyle = FormBorderStyle.SizableToolWindow;
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
if (specified == BoundsSpecified.Size) return;
base.SetBoundsCore(x, y, width, height, specified);
}
protected override void PaintShadow() { Visible = true; }
protected override void ClearShadow() { }
}
#endregion
#region Flat DropShadow
protected class MetroFlatDropShadow : MetroShadowBase
{
private Point Offset = new Point(-6, -6);
public MetroFlatDropShadow(Form targetForm)
: base(targetForm, 6, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE)
{
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
PaintShadow();
}
protected override void OnPaint(PaintEventArgs e)
{
Visible = true;
PaintShadow();
}
protected override void PaintShadow()
{
using( Bitmap getShadow = DrawBlurBorder() )
SetBitmap(getShadow, 255);
}
protected override void ClearShadow()
{
Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
g.Clear(Color.Transparent);
g.Flush();
g.Dispose();
SetBitmap(img, 255);
img.Dispose();
}
#region Drawing methods
[SecuritySafeCritical]
private void SetBitmap(Bitmap bitmap, byte opacity)
{
if (bitmap.PixelFormat != PixelFormat.Format32bppArgb)
throw new ApplicationException("The bitmap must be 32ppp with alpha-channel.");
IntPtr screenDc = WinApi.GetDC(IntPtr.Zero);
IntPtr memDc = WinApi.CreateCompatibleDC(screenDc);
IntPtr hBitmap = IntPtr.Zero;
IntPtr oldBitmap = IntPtr.Zero;
try
{
hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
oldBitmap = WinApi.SelectObject(memDc, hBitmap);
WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height);
WinApi.POINT pointSource = new WinApi.POINT(0, 0);
WinApi.POINT topPos = new WinApi.POINT(Left, Top);
WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION();
blend.BlendOp = WinApi.AC_SRC_OVER;
blend.BlendFlags = 0;
blend.SourceConstantAlpha = opacity;
blend.AlphaFormat = WinApi.AC_SRC_ALPHA;
WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA);
}
finally
{
WinApi.ReleaseDC(IntPtr.Zero, screenDc);
if (hBitmap != IntPtr.Zero)
{
WinApi.SelectObject(memDc, oldBitmap);
WinApi.DeleteObject(hBitmap);
}
WinApi.DeleteDC(memDc);
}
}
private Bitmap DrawBlurBorder()
{
return (Bitmap)DrawOutsetShadow(Color.Black, new Rectangle(0, 0, ClientRectangle.Width, ClientRectangle.Height));
}
private Image DrawOutsetShadow(Color color, Rectangle shadowCanvasArea)
{
Rectangle rOuter = shadowCanvasArea;
Rectangle rInner = new Rectangle(shadowCanvasArea.X + (-Offset.X - 1), shadowCanvasArea.Y + (-Offset.Y - 1), shadowCanvasArea.Width - (-Offset.X * 2 - 1), shadowCanvasArea.Height - (-Offset.Y * 2 - 1));
Bitmap img = new Bitmap(rOuter.Width, rOuter.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
using (Brush bgBrush = new SolidBrush(Color.FromArgb(30, Color.Black)))
{
g.FillRectangle(bgBrush, rOuter);
}
using (Brush bgBrush = new SolidBrush(Color.FromArgb(60, Color.Black)))
{
g.FillRectangle(bgBrush, rInner);
}
g.Flush();
g.Dispose();
return img;
}
#endregion
}
#endregion
#region Realistic DropShadow
protected class MetroRealisticDropShadow : MetroShadowBase
{
public MetroRealisticDropShadow(Form targetForm)
: base(targetForm, 15, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE)
{
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
PaintShadow();
}
protected override void OnPaint(PaintEventArgs e)
{
Visible = true;
PaintShadow();
}
protected override void PaintShadow()
{
using( Bitmap getShadow = DrawBlurBorder() )
SetBitmap(getShadow, 255);
}
protected override void ClearShadow()
{
Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
g.Clear(Color.Transparent);
g.Flush();
g.Dispose();
SetBitmap(img, 255);
img.Dispose();
}
#region Drawing methods
[SecuritySafeCritical]
private void SetBitmap(Bitmap bitmap, byte opacity)
{
if (bitmap.PixelFormat != PixelFormat.Format32bppArgb)
throw new ApplicationException("The bitmap must be 32ppp with alpha-channel.");
IntPtr screenDc = WinApi.GetDC(IntPtr.Zero);
IntPtr memDc = WinApi.CreateCompatibleDC(screenDc);
IntPtr hBitmap = IntPtr.Zero;
IntPtr oldBitmap = IntPtr.Zero;
try
{
hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
oldBitmap = WinApi.SelectObject(memDc, hBitmap);
WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height);
WinApi.POINT pointSource = new WinApi.POINT(0, 0);
WinApi.POINT topPos = new WinApi.POINT(Left, Top);
WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION
{
BlendOp = WinApi.AC_SRC_OVER,
BlendFlags = 0,
SourceConstantAlpha = opacity,
AlphaFormat = WinApi.AC_SRC_ALPHA
};
WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA);
}
finally
{
WinApi.ReleaseDC(IntPtr.Zero, screenDc);
if (hBitmap != IntPtr.Zero)
{
WinApi.SelectObject(memDc, oldBitmap);
WinApi.DeleteObject(hBitmap);
}
WinApi.DeleteDC(memDc);
}
}
private Bitmap DrawBlurBorder()
{
return (Bitmap)DrawOutsetShadow(0, 0, 40, 1, Color.Black, new Rectangle(1, 1, ClientRectangle.Width, ClientRectangle.Height));
}
private Image DrawOutsetShadow(int hShadow, int vShadow, int blur, int spread, Color color, Rectangle shadowCanvasArea)
{
Rectangle rOuter = shadowCanvasArea;
Rectangle rInner = shadowCanvasArea;
rInner.Offset(hShadow, vShadow);
rInner.Inflate(-blur, -blur);
rOuter.Inflate(spread, spread);
rOuter.Offset(hShadow, vShadow);
Rectangle originalOuter = rOuter;
Bitmap img = new Bitmap(originalOuter.Width, originalOuter.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
var currentBlur = 0;
do
{
var transparency = (rOuter.Height - rInner.Height) / (double)(blur * 2 + spread * 2);
var shadowColor = Color.FromArgb(((int)(200 * (transparency * transparency))), color);
var rOutput = rInner;
rOutput.Offset(-originalOuter.Left, -originalOuter.Top);
DrawRoundedRectangle(g, rOutput, currentBlur, Pens.Transparent, shadowColor);
rInner.Inflate(1, 1);
currentBlur = (int)((double)blur * (1 - (transparency * transparency)));
} while (rOuter.Contains(rInner));
g.Flush();
g.Dispose();
return img;
}
private void DrawRoundedRectangle(Graphics g, Rectangle bounds, int cornerRadius, Pen drawPen, Color fillColor)
{
int strokeOffset = Convert.ToInt32(Math.Ceiling(drawPen.Width));
bounds = Rectangle.Inflate(bounds, -strokeOffset, -strokeOffset);
var gfxPath = new GraphicsPath();
if (cornerRadius > 0)
{
gfxPath.AddArc(bounds.X, bounds.Y, cornerRadius, cornerRadius, 180, 90);
gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y, cornerRadius, cornerRadius, 270, 90);
gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 0, 90);
gfxPath.AddArc(bounds.X, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 90, 90);
}
else
{
gfxPath.AddRectangle(bounds);
}
gfxPath.CloseAllFigures();
if (cornerRadius > 5)
{
using (SolidBrush b = new SolidBrush(fillColor))
{
g.FillPath(b, gfxPath);
}
}
if (drawPen != Pens.Transparent)
{
using (Pen p = new Pen(drawPen.Color))
{
p.EndCap = p.StartCap = LineCap.Round;
g.DrawPath(p, gfxPath);
}
}
}
#endregion
}
#endregion
#endregion
#region Helper Methods
[SecuritySafeCritical]
public void RemoveCloseButton()
{
IntPtr hMenu = WinApi.GetSystemMenu(Handle, false);
if (hMenu == IntPtr.Zero) return;
int n = WinApi.GetMenuItemCount(hMenu);
if (n <= 0) return;
WinApi.RemoveMenu(hMenu, (uint)(n - 1), WinApi.MfByposition | WinApi.MfRemove);
WinApi.RemoveMenu(hMenu, (uint)(n - 2), WinApi.MfByposition | WinApi.MfRemove);
WinApi.DrawMenuBar(Handle);
}
private Rectangle MeasureText(Graphics g, Rectangle clientRectangle, Font font, string text, TextFormatFlags flags)
{
var proposedSize = new Size(int.MaxValue, int.MinValue);
var actualSize = TextRenderer.MeasureText(g, text, font, proposedSize, flags);
return new Rectangle(clientRectangle.X, clientRectangle.Y, actualSize.Width, actualSize.Height);
}
#endregion
}
}
| |
// 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.Globalization;
using System.Linq;
using Microsoft.VisualStudio.Debugger.Metadata;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class TypeImpl : Type
{
internal readonly System.Type Type;
private TypeImpl(System.Type type)
{
Debug.Assert(type != null);
this.Type = type;
}
public static explicit operator TypeImpl(System.Type type)
{
return type == null ? null : new TypeImpl(type);
}
public override Assembly Assembly
{
get { return new AssemblyImpl(this.Type.Assembly); }
}
public override string AssemblyQualifiedName
{
get { throw new NotImplementedException(); }
}
public override Type BaseType
{
get { return (TypeImpl)this.Type.BaseType; }
}
public override bool ContainsGenericParameters
{
get { throw new NotImplementedException(); }
}
public override Type DeclaringType
{
get { return (TypeImpl)this.Type.DeclaringType; }
}
public override bool IsEquivalentTo(MemberInfo other)
{
throw new NotImplementedException();
}
public override string FullName
{
get { return this.Type.FullName; }
}
public override Guid GUID
{
get { throw new NotImplementedException(); }
}
public override MemberTypes MemberType
{
get
{
return (MemberTypes)this.Type.MemberType;
}
}
public override int MetadataToken
{
get { throw new NotImplementedException(); }
}
public override Module Module
{
get { return new ModuleImpl(this.Type.Module); }
}
public override string Name
{
get { return Type.Name; }
}
public override string Namespace
{
get { return Type.Namespace; }
}
public override Type ReflectedType
{
get { throw new NotImplementedException(); }
}
public override Type UnderlyingSystemType
{
get { return (TypeImpl)Type.UnderlyingSystemType; }
}
public override bool Equals(Type o)
{
return o != null && o.GetType() == this.GetType() && ((TypeImpl)o).Type == this.Type;
}
public override bool Equals(object objOther)
{
return Equals(objOther as Type);
}
public override int GetHashCode()
{
return Type.GetHashCode();
}
public override int GetArrayRank()
{
return Type.GetArrayRank();
}
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return Type.GetConstructors((System.Reflection.BindingFlags)bindingAttr).Select(c => new ConstructorInfoImpl(c)).ToArray();
}
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotImplementedException();
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return Type.GetCustomAttributesData().Select(a => new CustomAttributeDataImpl(a)).ToArray();
}
public override Type GetElementType()
{
return (TypeImpl)(Type.GetElementType());
}
public override EventInfo GetEvent(string name, BindingFlags flags)
{
throw new NotImplementedException();
}
public override EventInfo[] GetEvents(BindingFlags flags)
{
throw new NotImplementedException();
}
public override FieldInfo GetField(string name, BindingFlags bindingAttr)
{
return new FieldInfoImpl(Type.GetField(name, (System.Reflection.BindingFlags)bindingAttr));
}
public override FieldInfo[] GetFields(BindingFlags flags)
{
return Type.GetFields((System.Reflection.BindingFlags)flags).Select(f => new FieldInfoImpl(f)).ToArray();
}
public override Type GetGenericTypeDefinition()
{
return (TypeImpl)this.Type.GetGenericTypeDefinition();
}
public override Type[] GetGenericArguments()
{
return Type.GetGenericArguments().Select(t => new TypeImpl(t)).ToArray();
}
public override Type GetInterface(string name, bool ignoreCase)
{
throw new NotImplementedException();
}
public override Type[] GetInterfaces()
{
return Type.GetInterfaces().Select(i => new TypeImpl(i)).ToArray();
}
public override System.Reflection.InterfaceMapping GetInterfaceMap(Type interfaceType)
{
throw new NotImplementedException();
}
public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
{
return Type.GetMember(name, (System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray();
}
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
return Type.GetMembers((System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray();
}
private static MemberInfo GetMember(System.Reflection.MemberInfo member)
{
switch (member.MemberType)
{
case System.Reflection.MemberTypes.Constructor:
return new ConstructorInfoImpl((System.Reflection.ConstructorInfo)member);
case System.Reflection.MemberTypes.Event:
return new EventInfoImpl((System.Reflection.EventInfo)member);
case System.Reflection.MemberTypes.Field:
return new FieldInfoImpl((System.Reflection.FieldInfo)member);
case System.Reflection.MemberTypes.Method:
return new MethodInfoImpl((System.Reflection.MethodInfo)member);
case System.Reflection.MemberTypes.NestedType:
return new TypeImpl((System.Reflection.TypeInfo)member);
case System.Reflection.MemberTypes.Property:
return new PropertyInfoImpl((System.Reflection.PropertyInfo)member);
default:
throw new NotImplementedException(member.MemberType.ToString());
}
}
public override MethodInfo[] GetMethods(BindingFlags flags)
{
return this.Type.GetMethods((System.Reflection.BindingFlags)flags).Select(m => new MethodInfoImpl(m)).ToArray();
}
public override Type GetNestedType(string name, BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override PropertyInfo[] GetProperties(BindingFlags flags)
{
throw new NotImplementedException();
}
public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
{
throw new NotImplementedException();
}
public override bool IsAssignableFrom(Type c)
{
throw new NotImplementedException();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override bool IsEnum
{
get { return this.Type.IsEnum; }
}
public override bool IsGenericParameter
{
get { return Type.IsGenericParameter; }
}
public override bool IsGenericType
{
get { return Type.IsGenericType; }
}
public override bool IsGenericTypeDefinition
{
get { return Type.IsGenericTypeDefinition; }
}
public override int GenericParameterPosition
{
get { return Type.GenericParameterPosition; }
}
public override ExplicitInterfaceInfo[] GetExplicitInterfaceImplementations()
{
var interfaceMaps = Type.GetInterfaces().Select(i => Type.GetInterfaceMap(i));
// A dot is neither necessary nor sufficient for determining whether a member explicitly
// implements an interface member, but it does characterize the set of members we're
// interested in displaying differently. For example, if the property is from VB, it will
// be an explicit interface implementation, but will not have a dot. Therefore, this is
// good enough for our mock implementation.
var infos = interfaceMaps.SelectMany(map =>
map.InterfaceMethods.Zip(map.TargetMethods, (interfaceMethod, implementingMethod) =>
implementingMethod.Name.Contains(".")
? MakeExplicitInterfaceInfo(interfaceMethod, implementingMethod)
: null));
return infos.Where(i => i != null).ToArray();
}
private static ExplicitInterfaceInfo MakeExplicitInterfaceInfo(System.Reflection.MethodInfo interfaceMethod, System.Reflection.MethodInfo implementingMethod)
{
return (ExplicitInterfaceInfo)typeof(ExplicitInterfaceInfo).Instantiate(
new MethodInfoImpl(interfaceMethod), new MethodInfoImpl(implementingMethod));
}
public override bool IsInstanceOfType(object o)
{
throw new NotImplementedException();
}
public override bool IsSubclassOf(Type c)
{
throw new NotImplementedException();
}
public override Type MakeArrayType()
{
return (TypeImpl)this.Type.MakeArrayType();
}
public override Type MakeArrayType(int rank)
{
return (TypeImpl)this.Type.MakeArrayType(rank);
}
public override Type MakeByRefType()
{
throw new NotImplementedException();
}
public override Type MakeGenericType(params Type[] argTypes)
{
return (TypeImpl)this.Type.MakeGenericType(argTypes.Select(t => ((TypeImpl)t).Type).ToArray());
}
public override Type MakePointerType()
{
return (TypeImpl)this.Type.MakePointerType();
}
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl()
{
System.Reflection.TypeAttributes result = 0;
if (this.Type.IsClass)
{
result |= System.Reflection.TypeAttributes.Class;
}
if (this.Type.IsInterface)
{
result |= System.Reflection.TypeAttributes.Interface;
}
if (this.Type.IsAbstract)
{
result |= System.Reflection.TypeAttributes.Abstract;
}
if (this.Type.IsSealed)
{
result |= System.Reflection.TypeAttributes.Sealed;
}
return result;
}
protected override bool IsValueTypeImpl()
{
return this.Type.IsValueType;
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
Debug.Assert(binder == null, "NYI");
Debug.Assert(returnType == null, "NYI");
Debug.Assert(types == null, "NYI");
Debug.Assert(modifiers == null, "NYI");
return new PropertyInfoImpl(Type.GetProperty(name, (System.Reflection.BindingFlags)bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: new System.Reflection.ParameterModifier[0]));
}
protected override TypeCode GetTypeCodeImpl()
{
return (TypeCode)System.Type.GetTypeCode(this.Type);
}
protected override bool HasElementTypeImpl()
{
throw new NotImplementedException();
}
protected override bool IsArrayImpl()
{
return Type.IsArray;
}
protected override bool IsByRefImpl()
{
throw new NotImplementedException();
}
protected override bool IsCOMObjectImpl()
{
throw new NotImplementedException();
}
protected override bool IsContextfulImpl()
{
throw new NotImplementedException();
}
protected override bool IsMarshalByRefImpl()
{
throw new NotImplementedException();
}
protected override bool IsPointerImpl()
{
return Type.IsPointer;
}
protected override bool IsPrimitiveImpl()
{
throw new NotImplementedException();
}
public override string ToString()
{
return this.Type.ToString();
}
public override Type[] GetInterfacesOnType()
{
var t = this.Type;
var builder = ArrayBuilder<Type>.GetInstance();
foreach (var @interface in t.GetInterfaces())
{
var map = t.GetInterfaceMap(@interface);
if (map.TargetMethods.Any(m => m.DeclaringType == t))
{
builder.Add((TypeImpl)@interface);
}
}
return builder.ToArrayAndFree();
}
}
}
| |
using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Xml;
namespace Stetic.Wrapper {
public class Table : Container {
const Gtk.AttachOptions expandOpts = Gtk.AttachOptions.Expand | Gtk.AttachOptions.Fill;
const Gtk.AttachOptions fillOpts = Gtk.AttachOptions.Fill;
public static new Gtk.Table CreateInstance ()
{
Gtk.Table t = new Gtk.Table (3, 3, false);
t.RowSpacing = 6;
t.ColumnSpacing = 6;
return t;
}
public override void Wrap (object obj, bool initialized)
{
base.Wrap (obj, initialized);
Sync ();
}
private Gtk.Table table {
get {
return (Gtk.Table)Wrapped;
}
}
public override void Delete (Stetic.Placeholder ph)
{
// Placeholders are deleted using commands.
}
protected override void DoSync ()
{
if (!AllowPlaceholders)
return;
using (UndoManager.AtomicChange) {
uint left, right, top, bottom;
uint row, col;
Gtk.Widget w;
Gtk.Widget[,] grid;
Gtk.Table.TableChild tc;
Gtk.Widget[] children;
bool addedPlaceholders = false;
children = table.Children;
grid = new Gtk.Widget[NRows,NColumns];
// First fill in the placeholders in the grid. If we find any
// placeholders covering more than one grid square, remove them.
// (New ones will be created below.)
foreach (Gtk.Widget child in children) {
if (!(child is Placeholder))
continue;
tc = table[child] as Gtk.Table.TableChild;
left = tc.LeftAttach;
right = tc.RightAttach;
top = tc.TopAttach;
bottom = tc.BottomAttach;
if (right == left + 1 && bottom == top + 1)
grid[top,left] = child;
else {
table.Remove (child);
child.Destroy ();
}
}
// Now fill in the real widgets, knocking out any placeholders
// they overlap. (If there are real widgets that overlap
// placeholders, neither will be knocked out, and the layout
// will probably end up wrong as well. But this situation
// happens at least temporarily during glade import.)
foreach (Gtk.Widget child in children) {
if (child is Placeholder)
continue;
tc = table[child] as Gtk.Table.TableChild;
left = tc.LeftAttach;
right = tc.RightAttach;
top = tc.TopAttach;
bottom = tc.BottomAttach;
for (row = top; row < bottom; row++) {
for (col = left; col < right; col++) {
w = grid[row,col];
if (w is Placeholder) {
table.Remove (w);
w.Destroy ();
}
grid[row,col] = child;
}
}
}
// Scan each row; if there are any empty cells, fill them in
// with placeholders. If a row contains only placeholders, then
// set them all to expand vertically so the row won't collapse.
// OTOH, if the row contains any real widget, set any placeholders
// in that row to not expand vertically, so they don't force the
// real widgets to expand further than they should. If any row
// is vertically expandable, then the table as a whole is.
vexpandable = false;
for (row = 0; row < NRows; row++) {
bool allPlaceholders = true;
for (col = 0; col < NColumns; col++) {
w = grid[row,col];
if (w == null) {
w = CreatePlaceholder ();
table.Attach (w, col, col + 1, row, row + 1);
NotifyChildAdded (w);
grid[row,col] = w;
addedPlaceholders = true;
} else if (!ChildVExpandable (w) || !AutoSize[w])
allPlaceholders = false;
}
for (col = 0; col < NColumns; col++) {
w = grid[row,col];
if (!AutoSize[w])
continue;
tc = table[w] as Gtk.Table.TableChild;
// We can't play with the vertical expansion property of
// widgets which span more than one row
if (tc.BottomAttach != tc.TopAttach + 1)
continue;
Gtk.AttachOptions opts = allPlaceholders ? expandOpts : fillOpts;
if (tc.YOptions != opts)
tc.YOptions = opts;
}
if (allPlaceholders)
vexpandable = true;
}
// Now do the same for columns and horizontal expansion (but we
// don't have to worry about empty cells this time).
hexpandable = false;
for (col = 0; col < NColumns; col++) {
bool allPlaceholders = true;
for (row = 0; row < NRows; row++) {
w = grid[row,col];
if (!ChildHExpandable (w) || !AutoSize[w]) {
allPlaceholders = false;
break;
}
}
for (row = 0; row < NRows; row++) {
w = grid[row,col];
if (!AutoSize[w])
continue;
tc = table[w] as Gtk.Table.TableChild;
// We can't play with the horizontal expansion property of
// widgets which span more than one column
if (tc.RightAttach != tc.LeftAttach + 1)
continue;
Gtk.AttachOptions opts = allPlaceholders ? expandOpts : fillOpts;
if (tc.XOptions != opts)
tc.XOptions = opts;
}
if (allPlaceholders)
hexpandable = true;
}
if (addedPlaceholders)
EmitContentsChanged ();
}
}
public override Placeholder AddPlaceholder ()
{
// Placeholders are added by Sync ()
return null;
}
public uint NRows {
get {
return table.NRows;
}
set {
using (UndoManager.AtomicChange) {
Freeze ();
while (value < table.NRows)
DeleteRow (table.NRows - 1);
table.NRows = value;
Thaw ();
}
}
}
public uint NColumns {
get {
return table.NColumns;
}
set {
using (UndoManager.AtomicChange) {
Freeze ();
while (value < table.NColumns)
DeleteColumn (table.NColumns - 1);
table.NColumns = value;
Thaw ();
}
}
}
void AddRow (uint row)
{
using (UndoManager.AtomicChange) {
Freeze ();
table.NRows++;
foreach (Gtk.Widget w in table.Children) {
Gtk.Table.TableChild tc = table[w] as Gtk.Table.TableChild;
if (tc.BottomAttach > row)
tc.BottomAttach++;
if (tc.TopAttach >= row)
tc.TopAttach++;
}
Thaw ();
}
}
void DeleteRow (uint row)
{
Gtk.Widget[] children = table.Children;
Gtk.Table.TableChild tc;
using (UndoManager.AtomicChange) {
Freeze ();
foreach (Gtk.Widget child in children) {
tc = table[child] as Gtk.Table.TableChild;
if (tc.TopAttach == row) {
if (tc.BottomAttach == tc.TopAttach + 1) {
table.Remove (child);
child.Destroy ();
}
else
tc.BottomAttach--;
} else {
if (tc.TopAttach > row)
tc.TopAttach--;
if (tc.BottomAttach > row)
tc.BottomAttach--;
}
}
table.NRows--;
Thaw ();
}
}
void AddColumn (uint col)
{
using (UndoManager.AtomicChange) {
Freeze ();
table.NColumns++;
foreach (Gtk.Widget w in table.Children) {
Gtk.Table.TableChild tc = table[w] as Gtk.Table.TableChild;
if (tc.RightAttach > col)
tc.RightAttach++;
if (tc.LeftAttach >= col)
tc.LeftAttach++;
}
Thaw ();
}
}
void DeleteColumn (uint col)
{
using (UndoManager.AtomicChange) {
Gtk.Widget[] children = table.Children;
Gtk.Table.TableChild tc;
Freeze ();
foreach (Gtk.Widget child in children) {
tc = table[child] as Gtk.Table.TableChild;
if (tc.LeftAttach == col) {
if (tc.RightAttach == tc.LeftAttach + 1) {
table.Remove (child);
child.Destroy ();
}
else
tc.RightAttach--;
} else {
if (tc.LeftAttach > col)
tc.LeftAttach--;
if (tc.RightAttach > col)
tc.RightAttach--;
}
}
table.NColumns--;
Thaw ();
}
}
public override IEnumerable GladeChildren {
get {
ArrayList list = new ArrayList ();
foreach (object ob in base.GladeChildren)
list.Add (ob);
list.Sort (new NameComparer ());
return list;
}
}
class NameComparer: IComparer
{
public int Compare (object x, object y)
{
return string.Compare (((Gtk.Widget)x).Name, ((Gtk.Widget)y).Name);
}
}
internal void InsertRowBefore (Gtk.Widget context)
{
Gtk.Table.TableChild tc = table[context] as Gtk.Table.TableChild;
AddRow (tc.TopAttach);
}
internal void InsertRowAfter (Gtk.Widget context)
{
Gtk.Table.TableChild tc = table[context] as Gtk.Table.TableChild;
AddRow (tc.BottomAttach);
}
internal void InsertColumnBefore (Gtk.Widget context)
{
Gtk.Table.TableChild tc = table[context] as Gtk.Table.TableChild;
AddColumn (tc.LeftAttach);
}
internal void InsertColumnAfter (Gtk.Widget context)
{
Gtk.Table.TableChild tc = table[context] as Gtk.Table.TableChild;
AddColumn (tc.RightAttach);
}
internal void DeleteRow (Gtk.Widget context)
{
Gtk.Table.TableChild tc = table[context] as Gtk.Table.TableChild;
DeleteRow (tc.TopAttach);
}
internal void DeleteColumn (Gtk.Widget context)
{
Gtk.Table.TableChild tc = table[context] as Gtk.Table.TableChild;
DeleteColumn (tc.LeftAttach);
}
private bool hexpandable, vexpandable;
public override bool HExpandable { get { return hexpandable; } }
public override bool VExpandable { get { return vexpandable; } }
protected override void ChildContentsChanged (Container child)
{
using (UndoManager.AtomicChange) {
Gtk.Widget widget = child.Wrapped;
Freeze ();
if (AutoSize[widget]) {
Gtk.Table.TableChild tc = table[widget] as Gtk.Table.TableChild;
tc.XOptions = 0;
tc.YOptions = 0;
}
Thaw ();
}
base.ChildContentsChanged (child);
}
public class TableChild : Container.ContainerChild {
bool freeze;
Gtk.Table.TableChild tc {
get {
return (Gtk.Table.TableChild)Wrapped;
}
}
public bool XExpand {
get {
return (tc.XOptions & Gtk.AttachOptions.Expand) != 0;
}
set {
freeze = true;
if (value)
tc.XOptions |= Gtk.AttachOptions.Expand;
else
tc.XOptions &= ~Gtk.AttachOptions.Expand;
freeze = false;
EmitNotify ("XExpand");
}
}
public bool XFill {
get {
return (tc.XOptions & Gtk.AttachOptions.Fill) != 0;
}
set {
freeze = true;
if (value)
tc.XOptions |= Gtk.AttachOptions.Fill;
else
tc.XOptions &= ~Gtk.AttachOptions.Fill;
freeze = false;
EmitNotify ("XFill");
}
}
public bool XShrink {
get {
return (tc.XOptions & Gtk.AttachOptions.Shrink) != 0;
}
set {
freeze = true;
if (value)
tc.XOptions |= Gtk.AttachOptions.Shrink;
else
tc.XOptions &= ~Gtk.AttachOptions.Shrink;
freeze = false;
EmitNotify ("XShrink");
}
}
public bool YExpand {
get {
return (tc.YOptions & Gtk.AttachOptions.Expand) != 0;
}
set {
freeze = true;
if (value)
tc.YOptions |= Gtk.AttachOptions.Expand;
else
tc.YOptions &= ~Gtk.AttachOptions.Expand;
freeze = false;
EmitNotify ("YExpand");
}
}
public bool YFill {
get {
return (tc.YOptions & Gtk.AttachOptions.Fill) != 0;
}
set {
freeze = true;
if (value)
tc.YOptions |= Gtk.AttachOptions.Fill;
else
tc.YOptions &= ~Gtk.AttachOptions.Fill;
freeze = false;
EmitNotify ("YFill");
}
}
public bool YShrink {
get {
return (tc.YOptions & Gtk.AttachOptions.Shrink) != 0;
}
set {
freeze = true;
if (value)
tc.YOptions |= Gtk.AttachOptions.Shrink;
else
tc.YOptions &= ~Gtk.AttachOptions.Shrink;
freeze = false;
EmitNotify ("YShrink");
}
}
protected override void EmitNotify (string propertyName)
{
if (freeze || Loading) return;
if (propertyName == "x-options" || propertyName == "AutoSize") {
base.EmitNotify ("XExpand");
base.EmitNotify ("XFill");
base.EmitNotify ("XShrink");
}
if (propertyName == "y-options" || propertyName == "AutoSize") {
base.EmitNotify ("YExpand");
base.EmitNotify ("YFill");
base.EmitNotify ("YShrink");
}
base.EmitNotify (propertyName);
}
// Properties to be used by the wrapper commands
public bool CellXExpand {
get { return XExpand; }
set { AutoSize = false; XExpand = value; }
}
public bool CellXFill{
get { return XFill; }
set { AutoSize = false; XFill = value; }
}
public bool CellYExpand {
get { return YExpand; }
set { AutoSize = false; YExpand = value; }
}
public bool CellYFill{
get { return YFill; }
set { AutoSize = false; YFill = value; }
}
}
}
}
| |
// Copyright 2015-2016 Google Inc. All Rights Reserved.
// Licensed under the Apache License Version 2.0.
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;
using Google.Apis.Storage.v1;
using Google.Apis.Storage.v1.Data;
using Google.Apis.Upload;
using Google.PowerShell.Common;
using Google.PowerShell.Provider;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Object = Google.Apis.Storage.v1.Data.Object;
namespace Google.PowerShell.CloudStorage
{
/// <summary>
/// A powershell provider that connects to Google Cloud Storage.
/// </summary>
[CmdletProvider(ProviderName, ProviderCapabilities.ShouldProcess)]
public class GoogleCloudStorageProvider : NavigationCmdletProvider, IContentCmdletProvider
{
/// <summary>
/// Dynamic parameters for "Set-Content".
/// </summary>
public class GcsGetContentWriterDynamicParameters
{
[Parameter]
public string ContentType { get; set; }
}
/// <summary>
/// Dynamic paramters for Copy-Item.
/// </summary>
public class GcsCopyItemDynamicParameters
{
[Parameter]
public ObjectsResource.CopyRequest.DestinationPredefinedAclEnum? DestinationAcl { get; set; }
[Parameter]
public long? SourceGeneration { get; set; }
}
/// <summary>
/// Dynamic paramters for New-Item with an object path.
/// </summary>
public class NewGcsObjectDynamicParameters
{
/// <summary>
/// <para type="description">
/// Local path to the file to upload.
/// </para>
/// </summary>
[Parameter]
public string File { get; set; }
/// <summary>
/// <para type="description">
/// Content type of the Cloud Storage object. e.g. "image/png" or "text/plain".
/// </para>
/// <para type="description">
/// For file uploads, the type will be inferred based on the file extension, defaulting to
/// "application/octet-stream" if no match is found. When passing object content via the
/// -Contents parameter, the type will default to "text/plain; charset=utf-8".
/// </para>
/// </summary>
[Parameter]
public string ContentType { get; set; }
/// <summary>
/// <para type="description">
/// Provide a predefined ACL to the object. e.g. "publicRead" where the project owner gets
/// OWNER access, and allUsers get READER access.
/// </para>
/// <para type="description">
/// See: https://cloud.google.com/storage/docs/json_api/v1/objects/insert
/// </para>
/// </summary>
[Parameter(Mandatory = false)]
public ObjectsResource.InsertMediaUpload.PredefinedAclEnum? PredefinedAcl { get; set; }
}
/// <summary>
/// Dynamic paramters for New-Item with a bucket path.
/// </summary>
public class NewGcsBucketDynamicParameters
{
/// <summary>
/// <para type="description">
/// The name of the project associated with the command. If not set via PowerShell parameter processing, will
/// default to the Cloud SDK's DefaultProject property.
/// </para>
/// </summary>
[Parameter]
[ConfigPropertyName(CloudSdkSettings.CommonProperties.Project)]
public string Project { get; set; }
/// <summary>
/// <para type="description">
/// Storage class for the bucket. COLDLINE, DURABLE_REDUCED_AVAILABILITY, MULTI_REGIONAL, NEARLINE,
/// REGIONAL or STANDARD. See https://cloud.google.com/storage/docs/storage-classes for more information.
/// </para>
/// </summary>
[Parameter]
[ValidateSet(
"COLDLINE",
"DURABLE_REDUCED_AVAILABILITY",
"MULTI_REGIONAL",
"NEARLINE",
"REGIONAL",
"STANDARD",
IgnoreCase = true)]
public string StorageClass { get; set; }
/// <summary>
/// <para type="description">
/// Location for the bucket. e.g. ASIA, EU, US.
/// </para>
/// </summary>
[Parameter]
[ValidateSet("ASIA", "EU", "US", IgnoreCase = false)]
public string Location { get; set; }
/// <summary>
/// <para type="description">
/// Default ACL for the bucket.
/// "Private__" gives the bucket owner "OWNER" permission. All other permissions are removed.
/// "ProjectPrivate" gives permission to the project team based on their roles. Anyone who is part of the team has "READER" permission.
/// Project owners and project editors have "OWNER" permission. All other permissions are removed.
/// "AuthenticatedRead" gives the bucket owner "OWNER" permission and gives all authenticated Google account holders "READER" permission.
/// All other permissions are removed.
/// "PublicRead" gives the bucket owner "OWNER" permission and gives all users "READER" permission. All other permissions are removed.
/// "PublicReadWrite" gives the bucket owner "OWNER" permission and gives all user "READER" and "WRITER" permission.
/// All other permissions are removed.
/// </para>
/// <para type="description">
/// To set fine-grained (e.g. individual users or domains) ACLs using PowerShell, use Add-GcsBucketAcl cmdlets.
/// </para>
/// </summary>
[Parameter]
public BucketsResource.InsertRequest.PredefinedAclEnum? DefaultBucketAcl { get; set; }
/// <summary>
/// <para type="description">
/// Default ACL for objects added to the bucket.
/// "Private__" gives the object owner "OWNER" permission. All other permissions are removed.
/// "ProjectPrivate" gives permission to the project team based on their roles. Anyone who is part of the team has "READER" permission.
/// Project owners and project editors have "OWNER" permission. All other permissions are removed.
/// "AuthenticatedRead" gives the object owner "OWNER" permission and gives all authenticated Google account holders "READER" permission.
/// All other permissions are removed.
/// "PublicRead" gives the object owner "OWNER" permission and gives all users "READER" permission. All other permissions are removed.
/// "BucketOwnerRead" gives the object owner "OWNER" permission and the bucket owner "READER" permission. All other permissions are removed.
/// "BucketOwnerFullControl" gives the object and bucket owners "OWNER" permission. All other permissions are removed.
/// </para>
/// <para type="description">
/// To set fine-grained (e.g. individual users or domains) ACLs using PowerShell, use Add-GcsObjectAcl cmdlets.
/// </para>
/// </summary>
[Parameter]
public BucketsResource.InsertRequest.PredefinedDefaultObjectAclEnum? DefaultObjectAcl { get; set; }
}
/// <summary>
/// The parsed structure of a path.
/// </summary>
private class GcsPath
{
public enum GcsPathType
{
Drive,
Bucket,
Object
}
public string Bucket { get; } = null;
public string ObjectPath { get; } = null;
private GcsPath(string bucket, string objectPath)
{
Bucket = bucket;
ObjectPath = objectPath;
}
public GcsPath(Object input) : this(input.Bucket, input.Name) { }
public static GcsPath Parse(string path)
{
string bucket;
string objectPath;
if (string.IsNullOrEmpty(path))
{
bucket = null;
objectPath = null;
}
else
{
int bucketLength = path.IndexOfAny(new[] { '/', '\\' });
if (bucketLength < 0)
{
bucket = path;
objectPath = null;
}
else
{
bucket = path.Substring(0, bucketLength);
objectPath = path.Substring(bucketLength + 1).Replace("\\", "/");
}
}
return new GcsPath(bucket, objectPath);
}
public GcsPathType Type
{
get
{
if (string.IsNullOrEmpty(Bucket))
{
return GcsPathType.Drive;
}
else if (string.IsNullOrEmpty(ObjectPath))
{
return GcsPathType.Bucket;
}
else
{
return GcsPathType.Object;
}
}
}
public override string ToString()
{
return $"{Bucket}/{ObjectPath}";
}
public string RelativePathToChild(string childObjectPath)
{
if (!childObjectPath.StartsWith(ObjectPath ?? ""))
{
throw new InvalidOperationException($"{childObjectPath} does not start with {ObjectPath}");
}
return childObjectPath.Substring(ObjectPath?.Length ?? 0);
}
}
/// <summary>
/// The Google Cloud Storage service.
/// </summary>
private static StorageService Service { get; } = GetNewService();
/// <summary>
/// This service is used to get all the accessible projects.
/// </summary>
private static CloudResourceManagerService ResourceService { get; } =
new CloudResourceManagerService(GCloudCmdlet.GetBaseClientServiceInitializer());
/// <summary>
/// Maps the name of a bucket to a cache of data about the objects in that bucket.
/// </summary>
private static Dictionary<string, CacheItem<BucketModel>> BucketModels { get; } =
new Dictionary<string, CacheItem<BucketModel>>();
/// <summary>
/// Maps the name of a bucket to a cahced object describing that bucket.
/// </summary>
private static CacheItem<Dictionary<string, Bucket>> BucketCache { get; } =
new CacheItem<Dictionary<string, Bucket>>();
/// <summary>
/// Reports on the usage of the provider.
/// </summary>
private static IReportCmdletResults TelemetryReporter = NewTelemetryReporter();
private const string ProviderName = "GoogleCloudStorage";
/// <summary>
/// A random number generator for progress bar ids.
/// </summary>
private static Random ActivityIdGenerator { get; } = new Random();
/// <summary>
/// This methods returns a new storage service.
/// </summary>
private static StorageService GetNewService()
{
return new StorageService(GCloudCmdlet.GetBaseClientServiceInitializer());
}
private static IReportCmdletResults NewTelemetryReporter()
{
if (CloudSdkSettings.GetOptIntoUsageReporting())
{
string clientID = CloudSdkSettings.GetAnonymousClientID();
return new GoogleAnalyticsCmdletReporter(clientID, AnalyticsEventCategory.ProviderInvocation);
}
else
{
return new InMemoryCmdletResultReporter();
}
}
/// <summary>
/// Creates a default Google Cloud Storage drive named gs.
/// </summary>
/// <returns>A single drive named gs.</returns>
protected override Collection<PSDriveInfo> InitializeDefaultDrives()
{
return new Collection<PSDriveInfo>
{
new PSDriveInfo("gs", ProviderInfo, "", ProviderName, PSCredential.Empty)
};
}
/// <summary>
/// Dispose the resources used by the provider. Specifically the services.
/// </summary>
protected override void Stop()
{
Service.Dispose();
ResourceService.Dispose();
base.Stop();
}
/// <summary>
/// Checks if a path is a legal string of characters. Shoudl pretty much always return null.
/// </summary>
/// <param name="path">The path to check.</param>
/// <returns>True if GcsPath.Parse() can parse it.</returns>
protected override bool IsValidPath(string path)
{
return true;
}
/// <summary>
/// PowerShell uses this to check if items exist.
/// </summary>
protected override bool ItemExists(string path)
{
var gcsPath = GcsPath.Parse(path);
switch (gcsPath.Type)
{
case GcsPath.GcsPathType.Drive:
return true;
case GcsPath.GcsPathType.Bucket:
Dictionary<string, Bucket> bucketDict = null;
// If the bucket cache is not initialized, then don't bother initializing it
// because that will cause a long wait time and we may not even know whether
// the user needs to use all the other buckets right away. Also, we should not
// refresh the whole cache right at this instance (which is why we call
// GetValueWithoutUpdate) for the same reason.
bucketDict = BucketCache.GetLastValueWithoutUpdate();
if (bucketDict != null && bucketDict.ContainsKey(gcsPath.Bucket))
{
return true;
}
try
{
var bucket = Service.Buckets.Get(gcsPath.Bucket).Execute();
if (bucketDict != null)
{
bucketDict[bucket.Name] = bucket;
}
return true;
}
catch
{
return false;
}
case GcsPath.GcsPathType.Object:
BucketModel model = GetBucketModel(gcsPath.Bucket);
bool objectExists = model.ObjectExists(gcsPath.ObjectPath);
return objectExists;
default:
throw new InvalidOperationException($"Unknown Path Type {gcsPath.Type}");
}
}
/// <summary>
/// PowerShell uses this to check if an item is a container. All drives, all buckets, objects that end
/// with "/", and prefixes to objects are containers.
/// </summary>
/// <param name="path">The path of the item to check.</param>
/// <returns>True if the item at the path is a container.</returns>
protected override bool IsItemContainer(string path)
{
var gcsPath = GcsPath.Parse(path);
switch (gcsPath.Type)
{
case GcsPath.GcsPathType.Drive:
case GcsPath.GcsPathType.Bucket:
return true;
case GcsPath.GcsPathType.Object:
return GetBucketModel(gcsPath.Bucket).IsContainer(gcsPath.ObjectPath);
default:
throw new InvalidOperationException($"Unknown GcsPathType {gcsPath.Type}");
}
}
/// <summary>
/// Checks if a container actually contains items.
/// </summary>
/// <param name="path">The path to the container.</param>
/// <returns>True if the container contains items.</returns>
protected override bool HasChildItems(string path)
{
var gcsPath = GcsPath.Parse(path);
switch (gcsPath.Type)
{
case GcsPath.GcsPathType.Drive:
return true;
case GcsPath.GcsPathType.Bucket:
case GcsPath.GcsPathType.Object:
return GetBucketModel(gcsPath.Bucket).HasChildren(gcsPath.ObjectPath);
default:
throw new InvalidOperationException($"Unknown Path Type {gcsPath.Type}");
}
}
/// <summary>
/// Writes the object describing the item to the output. Used by Get-Item.
/// </summary>
/// <param name="path">The path of the item to get.</param>
protected override void GetItem(string path)
{
var gcsPath = GcsPath.Parse(path);
switch (gcsPath.Type)
{
case GcsPath.GcsPathType.Drive:
WriteItemObject(PSDriveInfo, path, true);
break;
case GcsPath.GcsPathType.Bucket:
Dictionary<string, Bucket> bucketDict = null;
Bucket bucket;
// If the bucket cache is not initialized, then don't bother initializing it
// because that will cause a long wait time and we may not even know whether
// the user needs to use all the other buckets right away. Also, we should not
// refresh the whole cache right at this instance (which is why we call
// GetValueWithoutUpdate) for the same reason.
bucketDict = BucketCache.GetLastValueWithoutUpdate();
if (bucketDict != null && bucketDict.ContainsKey(gcsPath.Bucket))
{
bucket = bucketDict[gcsPath.Bucket];
break;
}
bucket = Service.Buckets.Get(gcsPath.Bucket).Execute();
if (bucketDict != null)
{
bucketDict[bucket.Name] = bucket;
}
WriteItemObject(bucket, path, true);
break;
case GcsPath.GcsPathType.Object:
Object gcsObject = GetBucketModel(gcsPath.Bucket).GetGcsObject(gcsPath.ObjectPath);
WriteItemObject(gcsObject, path, IsItemContainer(path));
break;
default:
throw new InvalidOperationException($"Unknown Path Type {gcsPath.Type}");
}
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(GetItem),
CloudSdkSettings.GetDefaultProject());
}
/// <summary>
/// Writes the names of the children of the container to the output. Used for tab-completion.
/// </summary>
/// <param name="path">The path to the container to get the children of.</param>
/// <param name="returnContainers">The names of the children of the container.</param>
protected override void GetChildNames(string path, ReturnContainers returnContainers)
{
var gcsPath = GcsPath.Parse(path);
if (gcsPath.Type == GcsPath.GcsPathType.Drive)
{
Action<Bucket> writeBucket = (bucket) => WriteItemObject(GetChildName(bucket.Name), bucket.Name, true);
PerformActionOnBucketAndOptionallyUpdateCache(writeBucket);
}
else
{
foreach (Object child in ListChildren(gcsPath, false, false))
{
var childGcsPath = new GcsPath(child);
bool isContainer = IsItemContainer(childGcsPath.ToString());
string childName = GetChildName(childGcsPath.ToString());
WriteItemObject(childName, childGcsPath.ToString().TrimEnd('/'), isContainer);
}
}
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(GetChildNames),
CloudSdkSettings.GetDefaultProject());
}
/// <summary>
/// Write out a bucket to the command line.
/// If recurse is set to true, call GetChildItems on the bucket to process its children.
/// </summary>
private void GetChildItemBucketHelper(Bucket bucket, bool recurse)
{
WriteItemObject(bucket, bucket.Name, true);
if (recurse)
{
try
{
GetChildItems(bucket.Name, true);
}
// It is possible to not have access to objects even if we have access to the bucket.
// We ignore those objects as if they did not exist.
catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.Forbidden)
{
WriteVerbose($"Access to objects in bucket {bucket.Name} is restricted.");
}
catch (AggregateException e)
{
foreach (Exception innerException in e.InnerExceptions)
{
WriteError(new ErrorRecord(
innerException, null, ErrorCategory.NotSpecified, bucket.Name));
}
}
catch (Exception e)
{
WriteError(new ErrorRecord(e, null, ErrorCategory.NotSpecified, bucket.Name));
}
}
}
/// <summary>
/// Writes the object descriptions of the items in the container to the output. Used by Get-ChildItem.
/// </summary>
/// <param name="path">The path of the container.</param>
/// <param name="recurse">If true, get all descendents of the container, not just immediate children.</param>
protected override void GetChildItems(string path, bool recurse)
{
var gcsPath = GcsPath.Parse(path);
switch (gcsPath.Type)
{
case GcsPath.GcsPathType.Drive:
Action<Bucket> actionOnBuckets = (bucket) => GetChildItemBucketHelper(bucket, recurse);
PerformActionOnBucketAndOptionallyUpdateCache((bucket) => GetChildItemBucketHelper(bucket, recurse));
break;
case GcsPath.GcsPathType.Bucket:
case GcsPath.GcsPathType.Object:
if (IsItemContainer(path))
{
foreach (Object gcsObject in ListChildren(gcsPath, recurse))
{
string gcsObjectPath = new GcsPath(gcsObject).ToString();
bool isContainer = IsItemContainer(gcsObjectPath);
WriteItemObject(gcsObject, gcsObjectPath, isContainer);
}
}
else
{
GetItem(path);
}
break;
default:
throw new InvalidOperationException($"Unknown Path Type {gcsPath.Type}");
}
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(GetChildItems),
CloudSdkSettings.GetDefaultProject());
}
/// <summary>
/// Creates a new item at the given path.
/// </summary>
/// <param name="path">The path of the item ot create.</param>
/// <param name="itemTypeName">The type of item to create. "Directory" is the only special one.
/// That will create an object with a name ending in "/".</param>
/// <param name="newItemValue">The value of the item to create. We assume it is a string.</param>
protected override void NewItem(string path, string itemTypeName, object newItemValue)
{
if (!ShouldProcess(path, "New-Item"))
{
return;
}
bool newFolder = itemTypeName == "Directory";
if (newFolder && !path.EndsWith("/"))
{
path += "/";
}
var gcsPath = GcsPath.Parse(path);
switch (gcsPath.Type)
{
case GcsPath.GcsPathType.Drive:
throw new InvalidOperationException("Use New-PSDrive to create a new drive.");
case GcsPath.GcsPathType.Bucket:
Bucket newBucket = NewBucket(gcsPath, (NewGcsBucketDynamicParameters)DynamicParameters);
WriteItemObject(newBucket, path, true);
break;
case GcsPath.GcsPathType.Object:
var dynamicParameters = (NewGcsObjectDynamicParameters)DynamicParameters;
Stream contentStream = GetContentStream(newItemValue, dynamicParameters);
Object newObject = NewObject(gcsPath, dynamicParameters, contentStream);
WriteItemObject(newObject, path, newFolder);
break;
default:
throw new InvalidOperationException($"Unknown Path Type {gcsPath.Type}");
}
BucketModels.Clear();
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(NewItem),
CloudSdkSettings.GetDefaultProject());
}
protected override object NewItemDynamicParameters(string path, string itemTypeName, object newItemValue)
{
var gcsPath = GcsPath.Parse(path);
switch (gcsPath.Type)
{
case GcsPath.GcsPathType.Drive:
return null;
case GcsPath.GcsPathType.Bucket:
return new NewGcsBucketDynamicParameters();
case GcsPath.GcsPathType.Object:
return new NewGcsObjectDynamicParameters();
default:
return null;
}
}
/// <summary>
/// Copies a Google Cloud Storage object or folder to another object or folder. Used by Copy-Item.
/// </summary>
/// <param name="path">The path to copy from.</param>
/// <param name="copyPath">The path to copy to.</param>
/// <param name="recurse">If true, will copy all decendent objects as well.</param>
protected override void CopyItem(string path, string copyPath, bool recurse)
{
if (!ShouldProcess($"Copy-Item from {path} to {copyPath}"))
{
return;
}
var dyanmicParameters = (GcsCopyItemDynamicParameters)DynamicParameters;
if (recurse)
{
char directorySeparator = Path.DirectorySeparatorChar;
path = path.TrimEnd(directorySeparator) + directorySeparator;
copyPath = copyPath.TrimEnd(directorySeparator) + directorySeparator;
}
var gcsPath = GcsPath.Parse(path);
var gcsCopyPath = GcsPath.Parse(copyPath);
if (recurse)
{
IEnumerable<Object> children = ListChildren(gcsPath, true);
foreach (Object child in children)
{
string objectSubPath = gcsPath.RelativePathToChild(child.Name);
string destinationObject = GcsPath.Parse(MakePath(copyPath, objectSubPath)).ObjectPath;
ObjectsResource.CopyRequest childRequest = Service.Objects.Copy(null, child.Bucket,
child.Name, gcsCopyPath.Bucket, destinationObject);
childRequest.SourceGeneration = dyanmicParameters.SourceGeneration;
childRequest.DestinationPredefinedAcl = dyanmicParameters.DestinationAcl;
childRequest.Projection = ObjectsResource.CopyRequest.ProjectionEnum.Full;
Object childObject = childRequest.Execute();
bool isContainer = (new GcsPath(childObject).Type != GcsPath.GcsPathType.Object);
WriteItemObject(childObject, copyPath, isContainer);
}
}
if (!recurse || GetBucketModel(gcsPath.Bucket).IsReal(gcsPath.ObjectPath))
{
ObjectsResource.CopyRequest request =
Service.Objects.Copy(null, gcsPath.Bucket, gcsPath.ObjectPath, gcsCopyPath.Bucket,
gcsCopyPath.ObjectPath);
request.SourceGeneration = dyanmicParameters.SourceGeneration;
request.DestinationPredefinedAcl = dyanmicParameters.DestinationAcl;
request.Projection = ObjectsResource.CopyRequest.ProjectionEnum.Full;
Object response = request.Execute();
WriteItemObject(response, copyPath, gcsCopyPath.Type != GcsPath.GcsPathType.Object);
}
BucketModels.Clear();
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(CopyItem),
CloudSdkSettings.GetDefaultProject());
}
protected override object CopyItemDynamicParameters(string path, string destination, bool recurse)
{
return new GcsCopyItemDynamicParameters();
}
/// <summary>
/// Gets a content reader to read the contents of a downloaded Google Cloud Storage object.
/// Used by Get-Contents.
/// </summary>
/// <param name="path">The path to the object to read.</param>
/// <returns>A content reader of the contents of a given object.</returns>
public IContentReader GetContentReader(string path)
{
var gcsPath = GcsPath.Parse(path);
if (gcsPath.ObjectPath == null)
{
throw new InvalidOperationException($"Can not get the contents of a {gcsPath.Type}");
}
Object gcsObject = Service.Objects.Get(gcsPath.Bucket, gcsPath.ObjectPath).Execute();
var stream = Service.HttpClient.GetStreamAsync(gcsObject.MediaLink).Result;
IContentReader contentReader = new GcsStringReader(stream);
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(GetContentReader),
CloudSdkSettings.GetDefaultProject());
return contentReader;
}
/// <summary>
/// Required by IContentCmdletProvider, along with GetContentReader(string). Returns null because we
/// have no need for dynamic parameters on Get-Content.
/// </summary>
public object GetContentReaderDynamicParameters(string path)
{
return null;
}
/// <summary>
/// Gets a writer used to upload data to a Google Cloud Storage object. Used by Set-Content.
/// </summary>
/// <param name="path">The path of the object to upload to.</param>
/// <returns>The writer.</returns>
public IContentWriter GetContentWriter(string path)
{
var gcsPath = GcsPath.Parse(path);
Object body = new Object
{
Name = gcsPath.ObjectPath,
Bucket = gcsPath.Bucket
};
var inputStream = new AnonymousPipeServerStream(PipeDirection.Out);
var outputStream = new AnonymousPipeClientStream(PipeDirection.In, inputStream.ClientSafePipeHandle);
var contentType = ((GcsGetContentWriterDynamicParameters)DynamicParameters).ContentType ?? GcsCmdlet.UTF8TextMimeType;
ObjectsResource.InsertMediaUpload request =
Service.Objects.Insert(body, gcsPath.Bucket, outputStream, contentType);
request.UploadAsync();
IContentWriter contentWriter = new GcsContentWriter(inputStream);
// Force the bucket models to refresh with the potentially new object.
BucketModels.Clear();
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(GetContentWriter),
CloudSdkSettings.GetDefaultProject());
return contentWriter;
}
public object GetContentWriterDynamicParameters(string path)
{
return new GcsGetContentWriterDynamicParameters();
}
/// <summary>
/// Clears the content of an object. Used by Clear-Content.
/// </summary>
/// <param name="path">The path of the object to clear.</param>
public void ClearContent(string path)
{
if (!ShouldProcess(path, "Clear-Content"))
{
return;
}
var gcsPath = GcsPath.Parse(path);
Object body = new Object
{
Name = gcsPath.ObjectPath,
Bucket = gcsPath.Bucket
};
var memoryStream = new MemoryStream();
var contentType = GcsCmdlet.UTF8TextMimeType;
ObjectsResource.InsertMediaUpload request =
Service.Objects.Insert(body, gcsPath.Bucket, memoryStream, contentType);
IUploadProgress response = request.Upload();
if (response.Exception != null)
{
throw response.Exception;
}
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(ClearContent),
CloudSdkSettings.GetDefaultProject());
}
public object ClearContentDynamicParameters(string path)
{
return null;
}
/// <summary>
/// Deletes a Google Cloud Storage object or bucket. Used by Remove-Item.
/// </summary>
/// <param name="path">The path to the object or bucket to remove.</param>
/// <param name="recurse">If true, will remove the desendants of the item as well. Required for a
/// non-empty bucket.</param>
protected override void RemoveItem(string path, bool recurse)
{
if (!ShouldProcess(path, "Remove-Item"))
{
return;
}
var gcsPath = GcsPath.Parse(path);
switch (gcsPath.Type)
{
case GcsPath.GcsPathType.Drive:
throw new InvalidOperationException("Use Remove-PSDrive to remove a drive.");
case GcsPath.GcsPathType.Bucket:
RemoveBucket(gcsPath, recurse);
// If the bucket cache is not initialized, then don't bother initializing it
// because that will cause a long wait time and we may not even know whether
// the user needs to use all the other buckets right away. Also, we should not
// refresh the whole cache right at this instance (which is why we call
// GetValueWithoutUpdate) for the same reason.
Dictionary<string, Bucket> bucketDict = BucketCache.GetLastValueWithoutUpdate();
if (bucketDict != null)
{
bucketDict.Remove(gcsPath.Bucket);
}
break;
case GcsPath.GcsPathType.Object:
if (IsItemContainer(path))
{
path = path.TrimEnd("/\\".ToCharArray());
RemoveFolder(GcsPath.Parse(path + "/"), recurse);
}
else
{
Service.Objects.Delete(gcsPath.Bucket, gcsPath.ObjectPath).Execute();
}
BucketModels.Clear();
break;
default:
throw new InvalidOperationException($"Unknown Path Type {gcsPath.Type}");
}
TelemetryReporter.ReportSuccess(
nameof(GoogleCloudStorageProvider),
nameof(RemoveItem),
CloudSdkSettings.GetDefaultProject());
}
protected override object RemoveItemDynamicParameters(string path, bool recurse)
{
return null;
}
private void RemoveFolder(GcsPath gcsPath, bool recurse)
{
if (GetBucketModel(gcsPath.Bucket).IsReal(gcsPath.ObjectPath))
{
Service.Objects.Delete(gcsPath.Bucket, gcsPath.ObjectPath).Execute();
}
if (recurse)
{
foreach (var childObject in ListChildren(gcsPath, true))
{
Service.Objects.Delete(childObject.Bucket, childObject.Name).Execute();
}
}
}
private void RemoveBucket(GcsPath gcsPath, bool removeObjects)
{
if (removeObjects)
{
DeleteObjects(gcsPath);
}
try
{
Service.Buckets.Delete(gcsPath.Bucket).Execute();
}
catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.Conflict)
{
// The objects my not have been cleared yet.
Service.Buckets.Delete(gcsPath.Bucket).Execute();
}
}
private void DeleteObjects(GcsPath gcsPath)
{
string bucketName = gcsPath.Bucket;
List<Task<string>> deleteTasks = new List<Task<string>>();
ObjectsResource.ListRequest request = Service.Objects.List(bucketName);
do
{
Objects gcsObjects = request.Execute();
foreach (Object gcsObject in gcsObjects.Items ?? Enumerable.Empty<Object>())
{
deleteTasks.Add(Service.Objects.Delete(bucketName, gcsObject.Name).ExecuteAsync());
}
request.PageToken = gcsObjects.NextPageToken;
} while (request.PageToken != null && !Stopping);
WaitDeleteTasks(deleteTasks);
}
/// <summary>
/// Waits on the list of delete tasks to compelete, updating progress as it does so.
/// </summary>
private void WaitDeleteTasks(List<Task<string>> deleteTasks)
{
int totalTasks = deleteTasks.Count;
int activityId = ActivityIdGenerator.Next();
while (deleteTasks.Count > 0)
{
Task<string> deleteTask = Task.WhenAny(deleteTasks).Result;
deleteTasks.Remove(deleteTask);
WriteProgress(
new ProgressRecord(activityId, "Delete bucket objects", "Deleting objects")
{
PercentComplete = ((totalTasks - deleteTasks.Count) * 100) / totalTasks,
RecordType = ProgressRecordType.Processing
});
}
WriteProgress(
new ProgressRecord(activityId, "Delete bucket objects", "Objects deleted")
{
PercentComplete = 100,
RecordType = ProgressRecordType.Completed
});
}
private Stream GetContentStream(object newItemValue, NewGcsObjectDynamicParameters dynamicParameters)
{
if (dynamicParameters.File != null)
{
dynamicParameters.ContentType =
dynamicParameters.ContentType ?? GcsCmdlet.InferContentType(dynamicParameters.File);
return new FileStream(dynamicParameters.File, FileMode.Open);
}
else
{
dynamicParameters.ContentType = dynamicParameters.ContentType ?? GcsCmdlet.UTF8TextMimeType;
return new MemoryStream(Encoding.UTF8.GetBytes(newItemValue?.ToString() ?? ""));
}
}
private BucketModel GetBucketModel(string bucket)
{
if (!BucketModels.ContainsKey(bucket))
{
BucketModels.Add(bucket, new CacheItem<BucketModel>(() => new BucketModel(bucket, Service)));
}
return BucketModels[bucket].Value;
}
private Object NewObject(GcsPath gcsPath, NewGcsObjectDynamicParameters dynamicParameters, Stream contentStream)
{
Object newGcsObject = new Object
{
Bucket = gcsPath.Bucket,
Name = gcsPath.ObjectPath,
ContentType = dynamicParameters.ContentType
};
ObjectsResource.InsertMediaUpload insertReq = Service.Objects.Insert(
newGcsObject, newGcsObject.Bucket, contentStream, newGcsObject.ContentType);
insertReq.PredefinedAcl = dynamicParameters.PredefinedAcl;
insertReq.Projection = ObjectsResource.InsertMediaUpload.ProjectionEnum.Full;
IUploadProgress finalProgress = insertReq.Upload();
if (finalProgress.Exception != null)
{
throw finalProgress.Exception;
}
return insertReq.ResponseBody;
}
private Bucket NewBucket(GcsPath gcsPath, NewGcsBucketDynamicParameters dynamicParams)
{
if (dynamicParams.Project == null)
{
var property = dynamicParams.GetType().GetProperty(nameof(Project));
ConfigPropertyNameAttribute configPropertyName =
(ConfigPropertyNameAttribute)Attribute.GetCustomAttribute(
property, typeof(ConfigPropertyNameAttribute));
configPropertyName.SetObjectConfigDefault(property, dynamicParams);
}
var bucket = new Bucket
{
Name = gcsPath.Bucket,
Location = dynamicParams.Location,
StorageClass = dynamicParams.StorageClass
};
BucketsResource.InsertRequest insertReq = Service.Buckets.Insert(bucket, dynamicParams.Project);
insertReq.PredefinedAcl = dynamicParams.DefaultBucketAcl;
insertReq.PredefinedDefaultObjectAcl = dynamicParams.DefaultObjectAcl;
Bucket newBucket = insertReq.Execute();
// If the bucket cache is not initialized, then don't bother initializing it
// because that will cause a long wait time and we may not even know whether
// the user needs to use all the other buckets right away. Also, we should not
// refresh the whole cache right at this instance (which is why we call
// GetValueWithoutUpdate) for the same reason.
Dictionary<string, Bucket> bucketDict = BucketCache.GetLastValueWithoutUpdate();
if (bucketDict != null)
{
bucketDict[newBucket.Name] = newBucket;
}
return newBucket;
}
private IEnumerable<Object> ListChildren(GcsPath gcsPath, bool recurse, bool allPages = true)
{
ObjectsResource.ListRequest request = Service.Objects.List(gcsPath.Bucket);
request.Projection = ObjectsResource.ListRequest.ProjectionEnum.Full;
request.Prefix = gcsPath.ObjectPath;
if (!string.IsNullOrEmpty(request.Prefix) && !request.Prefix.EndsWith("/"))
{
request.Prefix = request.Prefix + "/";
}
if (!recurse)
{
request.Delimiter = "/";
}
do
{
Objects response = request.Execute();
foreach (Object gcsObject in response.Items ?? Enumerable.Empty<Object>())
{
if (gcsObject.Name != request.Prefix)
{
GetBucketModel(gcsPath.Bucket).AddObject(gcsObject);
yield return gcsObject;
}
}
foreach (string prefix in response.Prefixes ?? Enumerable.Empty<string>())
{
yield return new Object { Name = $"{prefix}", Bucket = gcsPath.Bucket };
}
request.PageToken = response.NextPageToken;
} while (allPages && !Stopping && request.PageToken != null);
}
/// <summary>
/// Retrieves all buckets from the specified project and adding them to the blocking collection.
/// </summary>
/// <param name="project">Project to retrieve buckets from.</param>
/// <param name="collections">Blocking collection to add buckets to.</param>
private static async Task ListBucketsAsync(Project project, BlockingCollection<Bucket> collections)
{
// Using a new service on every request here ensures they can all be handled at the same time.
BucketsResource.ListRequest request = GetNewService().Buckets.List(project.ProjectId);
var allBuckets = new List<Bucket>();
try
{
do
{
Buckets buckets = await request.ExecuteAsync();
if (buckets.Items != null)
{
foreach (Bucket bucket in buckets.Items)
{
// BlockingCollecton does not have AddRange so we have to add each item individually.
collections.Add(bucket);
}
}
request.PageToken = buckets.NextPageToken;
} while (request.PageToken != null);
}
// Swallow any GoogleApiException when listing a bucket for projects, otherwise, if user has an
// erroneous project, this will stop the execution of Get-ChildItem for other projects.
catch (GoogleApiException) { }
}
private static IEnumerable<Project> ListAllProjects()
{
ProjectsResource.ListRequest request = ResourceService.Projects.List();
do
{
ListProjectsResponse projects = request.Execute();
foreach (Project project in projects.Projects ?? Enumerable.Empty<Project>())
{
// The Storage Service considers invactive projects to not exist.
if (project.LifecycleState == "ACTIVE")
{
yield return project;
}
}
request.PageToken = projects.NextPageToken;
} while (request.PageToken != null);
}
/// <summary>
/// If the BucketCache is not out of date, simply perform the action on each bucket.
/// Otherwise, we update the cache and perform the action while doing that (for example,
/// we can write the bucket to the command line as they become available instead of writing
/// all at once).
/// </summary>
/// <param name="actionOnBucket">Action to be performed on each bucket if cache is out of date.</param>
private void PerformActionOnBucketAndOptionallyUpdateCache(Action<Bucket> actionOnBucket)
{
// If the cache is already initialized and not stale, simply perform the action on each bucket.
// Otherwise, we update the cache and perform action on each of the item while doing so.
if (!BucketCache.CacheOutOfDate())
{
Dictionary<string, Bucket> bucketDict = BucketCache.GetLastValueWithoutUpdate();
foreach(Bucket bucket in bucketDict.Values)
{
actionOnBucket(bucket);
}
}
else
{
Func<Dictionary<string, Bucket>> functionToUpdateCacheAndPerformActionOnBucket = () => UpdateBucketCacheAndPerformActionOnBucket(actionOnBucket);
BucketCache.GetValueWithUpdateFunction(functionToUpdateCacheAndPerformActionOnBucket);
}
}
/// <summary>
/// Update BucketCache and perform action on each of the bucket while doing so.
/// </summary>
/// <param name="action">Action to be performed on each bucket.</param>
/// <returns>Returns a dictionary where key is bucket name and value is the bucket.</returns>
private Dictionary<string, Bucket> UpdateBucketCacheAndPerformActionOnBucket(Action<Bucket> action)
{
BlockingCollection<Bucket> bucketCollections = new BlockingCollection<Bucket>();
ConcurrentDictionary<string, Bucket> bucketDict = new ConcurrentDictionary<string, Bucket>();
// If we don't do these steps in a new thread, it will block until the task array (taskWithActions)
// is created and this may take a while if there are lots of projects.
Task.Factory.StartNew(() =>
{
IEnumerable<Project> projects = ListAllProjects();
// In each of these tasks, the buckets will be added to the blocking collection bucketCollections.
IEnumerable<Task> taskWithActions = projects.Select(project => ListBucketsAsync(project, bucketCollections));
// Once all the tasks are done, we signal to the blocking collection that there is nothing to be added.
Task.Factory.ContinueWhenAll(taskWithActions.ToArray(), result => { bucketCollections.CompleteAdding(); });
});
// bucketCollections.IsCompleted is true if CompleteAdding is called.
while (!bucketCollections.IsCompleted)
{
// bucketCollections.Take() will block until something is added.
try
{
Bucket bucket = bucketCollections.Take();
action(bucket);
bucketDict[bucket.Name] = bucket;
}
// This exception is thrown if a thread call CompleteAdding before we call bucketCollections.Take()
// and after we passed the IsCompleted check. We can just swallow it.
catch (InvalidOperationException ex)
{
WriteVerbose(ex.Message);
}
}
return bucketDict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.AzureStack.Management
{
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
/// more information)
/// </summary>
internal partial class CloudOperations : IServiceOperations<AzureStackClient>, ICloudOperations
{
/// <summary>
/// Initializes a new instance of the CloudOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal CloudOperations(AzureStackClient client)
{
this._client = client;
}
private AzureStackClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.AzureStack.Management.AzureStackClient.
/// </summary>
public AzureStackClient Client
{
get { return this._client; }
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Your documentation here.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public async Task<CloudCreateOrUpdateResult> CreateOrUpdateAsync(CloudCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Cloud == null)
{
throw new ArgumentNullException("parameters.Cloud");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.SkyBridge.Admin/clouds/";
if (parameters.Cloud.Name != null)
{
url = url + Uri.EscapeDataString(parameters.Cloud.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject cloudCreateOrUpdateParametersValue = new JObject();
requestDoc = cloudCreateOrUpdateParametersValue;
if (parameters.Cloud.Name != null)
{
cloudCreateOrUpdateParametersValue["name"] = parameters.Cloud.Name;
}
if (parameters.Cloud.DisplayName != null)
{
cloudCreateOrUpdateParametersValue["displayName"] = parameters.Cloud.DisplayName;
}
if (parameters.Cloud.ManagementApiEndpoint != null)
{
cloudCreateOrUpdateParametersValue["managementApiEndpoint"] = parameters.Cloud.ManagementApiEndpoint.AbsoluteUri;
}
if (parameters.Cloud.AuthenticationProviderEndpoint != null)
{
cloudCreateOrUpdateParametersValue["authenticationProviderEndpoint"] = parameters.Cloud.AuthenticationProviderEndpoint.AbsoluteUri;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CloudCreateOrUpdateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CloudCreateOrUpdateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CloudDefinition cloudInstance = new CloudDefinition();
result.Cloud = cloudInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
cloudInstance.Name = nameInstance;
}
JToken displayNameValue = responseDoc["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
cloudInstance.DisplayName = displayNameInstance;
}
JToken managementApiEndpointValue = responseDoc["managementApiEndpoint"];
if (managementApiEndpointValue != null && managementApiEndpointValue.Type != JTokenType.Null)
{
Uri managementApiEndpointInstance = TypeConversion.TryParseUri(((string)managementApiEndpointValue));
cloudInstance.ManagementApiEndpoint = managementApiEndpointInstance;
}
JToken authenticationProviderEndpointValue = responseDoc["authenticationProviderEndpoint"];
if (authenticationProviderEndpointValue != null && authenticationProviderEndpointValue.Type != JTokenType.Null)
{
Uri authenticationProviderEndpointInstance = TypeConversion.TryParseUri(((string)authenticationProviderEndpointValue));
cloudInstance.AuthenticationProviderEndpoint = authenticationProviderEndpointInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='cloudId'>
/// Required. Your documentation here.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string cloudId, CancellationToken cancellationToken)
{
// Validate
if (cloudId == null)
{
throw new ArgumentNullException("cloudId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudId", cloudId);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.SkyBridge.Admin/clouds/";
url = url + Uri.EscapeDataString(cloudId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='cloudId'>
/// Required. Your documentation here.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public async Task<CloudGetResult> GetAsync(string cloudId, CancellationToken cancellationToken)
{
// Validate
if (cloudId == null)
{
throw new ArgumentNullException("cloudId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudId", cloudId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.SkyBridge.Admin/clouds/";
url = url + Uri.EscapeDataString(cloudId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CloudGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CloudGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CloudDefinition cloudInstance = new CloudDefinition();
result.Cloud = cloudInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
cloudInstance.Name = nameInstance;
}
JToken displayNameValue = responseDoc["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
cloudInstance.DisplayName = displayNameInstance;
}
JToken managementApiEndpointValue = responseDoc["managementApiEndpoint"];
if (managementApiEndpointValue != null && managementApiEndpointValue.Type != JTokenType.Null)
{
Uri managementApiEndpointInstance = TypeConversion.TryParseUri(((string)managementApiEndpointValue));
cloudInstance.ManagementApiEndpoint = managementApiEndpointInstance;
}
JToken authenticationProviderEndpointValue = responseDoc["authenticationProviderEndpoint"];
if (authenticationProviderEndpointValue != null && authenticationProviderEndpointValue.Type != JTokenType.Null)
{
Uri authenticationProviderEndpointInstance = TypeConversion.TryParseUri(((string)authenticationProviderEndpointValue));
cloudInstance.AuthenticationProviderEndpoint = authenticationProviderEndpointInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public async Task<CloudListResult> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.SkyBridge.Admin/clouds";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CloudListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CloudListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
CloudDefinition cloudDefinitionInstance = new CloudDefinition();
result.Clouds.Add(cloudDefinitionInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
cloudDefinitionInstance.Name = nameInstance;
}
JToken displayNameValue = valueValue["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
cloudDefinitionInstance.DisplayName = displayNameInstance;
}
JToken managementApiEndpointValue = valueValue["managementApiEndpoint"];
if (managementApiEndpointValue != null && managementApiEndpointValue.Type != JTokenType.Null)
{
Uri managementApiEndpointInstance = TypeConversion.TryParseUri(((string)managementApiEndpointValue));
cloudDefinitionInstance.ManagementApiEndpoint = managementApiEndpointInstance;
}
JToken authenticationProviderEndpointValue = valueValue["authenticationProviderEndpoint"];
if (authenticationProviderEndpointValue != null && authenticationProviderEndpointValue.Type != JTokenType.Null)
{
Uri authenticationProviderEndpointInstance = TypeConversion.TryParseUri(((string)authenticationProviderEndpointValue));
cloudDefinitionInstance.AuthenticationProviderEndpoint = authenticationProviderEndpointInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='nextLink'>
/// Required. Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public async Task<CloudListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + Uri.EscapeDataString(nextLink);
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CloudListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CloudListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
CloudDefinition cloudDefinitionInstance = new CloudDefinition();
result.Clouds.Add(cloudDefinitionInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
cloudDefinitionInstance.Name = nameInstance;
}
JToken displayNameValue = valueValue["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
cloudDefinitionInstance.DisplayName = displayNameInstance;
}
JToken managementApiEndpointValue = valueValue["managementApiEndpoint"];
if (managementApiEndpointValue != null && managementApiEndpointValue.Type != JTokenType.Null)
{
Uri managementApiEndpointInstance = TypeConversion.TryParseUri(((string)managementApiEndpointValue));
cloudDefinitionInstance.ManagementApiEndpoint = managementApiEndpointInstance;
}
JToken authenticationProviderEndpointValue = valueValue["authenticationProviderEndpoint"];
if (authenticationProviderEndpointValue != null && authenticationProviderEndpointValue.Type != JTokenType.Null)
{
Uri authenticationProviderEndpointInstance = TypeConversion.TryParseUri(((string)authenticationProviderEndpointValue));
cloudDefinitionInstance.AuthenticationProviderEndpoint = authenticationProviderEndpointInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Net;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using Moq;
using ReactiveUIMicro;
using Squirrel.Client;
using Squirrel.Core;
using Squirrel.Tests.TestHelpers;
using Xunit;
namespace Squirrel.Tests.Client
{
public class DownloadReleasesTests : IEnableLogger
{
[Fact]
public void ChecksumShouldPassOnValidPackages()
{
var filename = "Squirrel.Core.1.0.0.0.nupkg";
var nuGetPkg = IntegrationTestHelper.GetPath("fixtures", filename);
var fs = new Mock<IFileSystemFactory>();
var urlDownloader = new Mock<IUrlDownloader>();
ReleaseEntry entry;
using (var f = File.OpenRead(nuGetPkg)) {
entry = ReleaseEntry.GenerateFromFile(f, filename);
}
var fileInfo = new Mock<FileInfoBase>();
fileInfo.Setup(x => x.OpenRead()).Returns(File.OpenRead(nuGetPkg));
fileInfo.Setup(x => x.Exists).Returns(true);
fileInfo.Setup(x => x.Length).Returns(new FileInfo(nuGetPkg).Length);
fs.Setup(x => x.GetFileInfo(Path.Combine(".", "theApp", "packages", filename))).Returns(fileInfo.Object);
var fixture = ExposedObject.From(
new UpdateManager("http://lol", "theApp", FrameworkVersion.Net40, ".", fs.Object, urlDownloader.Object));
fixture.checksumPackage(entry);
}
[Fact]
public void ChecksumShouldFailIfFilesAreMissing()
{
var filename = "Squirrel.Core.1.0.0.0.nupkg";
var nuGetPkg = IntegrationTestHelper.GetPath("fixtures", filename);
var fs = new Mock<IFileSystemFactory>();
var urlDownloader = new Mock<IUrlDownloader>();
ReleaseEntry entry;
using (var f = File.OpenRead(nuGetPkg)) {
entry = ReleaseEntry.GenerateFromFile(f, filename);
}
var fileInfo = new Mock<FileInfoBase>();
fileInfo.Setup(x => x.OpenRead()).Returns(File.OpenRead(nuGetPkg));
fileInfo.Setup(x => x.Exists).Returns(false);
fs.Setup(x => x.GetFileInfo(Path.Combine(".", "theApp", "packages", filename))).Returns(fileInfo.Object);
var fixture = ExposedObject.From(
new UpdateManager("http://lol", "theApp", FrameworkVersion.Net40, ".", fs.Object, urlDownloader.Object));
bool shouldDie = true;
try {
// NB: We can't use Assert.Throws here because the binder
// will try to pick the wrong method
fixture.checksumPackage(entry);
} catch (Exception) {
shouldDie = false;
}
shouldDie.ShouldBeFalse();
}
[Fact]
public void ChecksumShouldFailIfFilesAreBogus()
{
var filename = "Squirrel.Core.1.0.0.0.nupkg";
var nuGetPkg = IntegrationTestHelper.GetPath("fixtures", filename);
var fs = new Mock<IFileSystemFactory>();
var urlDownloader = new Mock<IUrlDownloader>();
ReleaseEntry entry;
using (var f = File.OpenRead(nuGetPkg)) {
entry = ReleaseEntry.GenerateFromFile(f, filename);
}
var fileInfo = new Mock<FileInfoBase>();
fileInfo.Setup(x => x.OpenRead()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("Lol broken")));
fileInfo.Setup(x => x.Exists).Returns(true);
fileInfo.Setup(x => x.Length).Returns(new FileInfo(nuGetPkg).Length);
fileInfo.Setup(x => x.Delete()).Verifiable();
fs.Setup(x => x.GetFileInfo(Path.Combine(".", "theApp", "packages", filename))).Returns(fileInfo.Object);
var fixture = ExposedObject.From(
new UpdateManager("http://lol", "theApp", FrameworkVersion.Net40, ".", fs.Object, urlDownloader.Object));
bool shouldDie = true;
try {
fixture.checksumPackage(entry);
} catch (Exception ex) {
this.Log().InfoException("Checksum failure", ex);
shouldDie = false;
}
shouldDie.ShouldBeFalse();
fileInfo.Verify(x => x.Delete(), Times.Once());
}
[Fact]
public void DownloadReleasesFromHttpServerIntegrationTest()
{
string tempDir = null;
var updateDir = new DirectoryInfo(IntegrationTestHelper.GetPath("..", "SampleUpdatingApp", "SampleReleasesFolder"));
IDisposable disp;
try {
var httpServer = new StaticHttpServer(30405, updateDir.FullName);
disp = httpServer.Start();
}
catch (HttpListenerException) {
Assert.False(true, @"Windows sucks, go run 'netsh http add urlacl url=http://+:30405/ user=MYMACHINE\MyUser");
return;
}
var entriesToDownload = updateDir.GetFiles("*.nupkg")
.Select(x => ReleaseEntry.GenerateFromFile(x.FullName))
.ToArray();
entriesToDownload.Count().ShouldBeGreaterThan(0);
using (disp)
using (Utility.WithTempDirectory(out tempDir)) {
// NB: This is normally done by CheckForUpdates, but since
// we're skipping that in the test we have to do it ourselves
Directory.CreateDirectory(Path.Combine(tempDir, "SampleUpdatingApp", "packages"));
var fixture = new UpdateManager("http://localhost:30405", "SampleUpdatingApp", FrameworkVersion.Net40, tempDir);
using (fixture) {
var progress = new ReplaySubject<int>();
fixture.DownloadReleases(entriesToDownload, progress).First();
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress.Buffer(2,1).All(x => x.Count != 2 || x[1] > x[0]).First().ShouldBeTrue();
progress.Last().ShouldEqual(100);
}
entriesToDownload.ForEach(x => {
this.Log().Info("Looking for {0}", x.Filename);
var actualFile = Path.Combine(tempDir, "SampleUpdatingApp", "packages", x.Filename);
File.Exists(actualFile).ShouldBeTrue();
var actualEntry = ReleaseEntry.GenerateFromFile(actualFile);
actualEntry.SHA1.ShouldEqual(x.SHA1);
actualEntry.Version.ShouldEqual(x.Version);
});
}
}
[Fact]
public void DownloadReleasesFromFileDirectoryIntegrationTest()
{
string tempDir = null;
var updateDir = new DirectoryInfo(IntegrationTestHelper.GetPath("..", "SampleUpdatingApp", "SampleReleasesFolder"));
var entriesToDownload = updateDir.GetFiles("*.nupkg")
.Select(x => ReleaseEntry.GenerateFromFile(x.FullName))
.ToArray();
entriesToDownload.Count().ShouldBeGreaterThan(0);
using (Utility.WithTempDirectory(out tempDir)) {
// NB: This is normally done by CheckForUpdates, but since
// we're skipping that in the test we have to do it ourselves
Directory.CreateDirectory(Path.Combine(tempDir, "SampleUpdatingApp", "packages"));
var fixture = new UpdateManager(updateDir.FullName, "SampleUpdatingApp", FrameworkVersion.Net40, tempDir);
using (fixture) {
var progress = new ReplaySubject<int>();
fixture.DownloadReleases(entriesToDownload, progress).First();
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress.Buffer(2,1).All(x => x.Count != 2 || x[1] > x[0]).First().ShouldBeTrue();
progress.Last().ShouldEqual(100);
}
entriesToDownload.ForEach(x => {
this.Log().Info("Looking for {0}", x.Filename);
var actualFile = Path.Combine(tempDir, "SampleUpdatingApp", "packages", x.Filename);
File.Exists(actualFile).ShouldBeTrue();
var actualEntry = ReleaseEntry.GenerateFromFile(actualFile);
actualEntry.SHA1.ShouldEqual(x.SHA1);
actualEntry.Version.ShouldEqual(x.Version);
});
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using InstallerLib;
using NUnit.Framework;
using dotNetUnitTestsRunner;
using System.IO;
using System.Xml;
using Vestris.ResourceLib;
using System.Reflection;
using System.Web;
namespace InstallerLibUnitTests
{
[TestFixture]
public class InstallerLinkerTests
{
[Test]
public void TestLinkBasics()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
try
{
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
List<Resource> custom = ri.Resources[new ResourceId("CUSTOM")];
Assert.IsNotNull(custom);
Assert.AreEqual(2, custom.Count);
// default banner
Assert.AreEqual(custom[0].Name, new ResourceId("RES_BANNER"));
// embedded configuration
Assert.AreEqual(custom[1].Name, new ResourceId("RES_CONFIGURATION"));
Assert.AreEqual(custom[1].Size, new FileInfo(args.config).Length);
}
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestLinkUnicows()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
try
{
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
args.mslu = true;
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
List<Resource> custom = ri.Resources[new ResourceId("CUSTOM")];
Assert.IsNotNull(custom);
Assert.AreEqual(3, custom.Count);
// default banner
Assert.AreEqual(custom[0].Name, new ResourceId("RES_BANNER"));
// embedded configuration
Assert.AreEqual(custom[1].Name, new ResourceId("RES_CONFIGURATION"));
Assert.AreEqual(custom[1].Size, new FileInfo(args.config).Length);
// unicows
Assert.AreEqual(custom[2].Name, new ResourceId("RES_UNICOWS"));
}
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestLinkDefaultManifest()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
try
{
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
List<Resource> manifests = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_MANIFEST)]; // RT_MANIFEST
Assert.IsNotNull(manifests);
Assert.AreEqual(1, manifests.Count);
ManifestResource manifest = (ManifestResource) manifests[0]; // RT_MANIFEST
Console.WriteLine(manifest.Manifest.OuterXml);
XmlNamespaceManager manifestNamespaceManager = new XmlNamespaceManager(manifest.Manifest.NameTable);
manifestNamespaceManager.AddNamespace("v1", "urn:schemas-microsoft-com:asm.v1");
manifestNamespaceManager.AddNamespace("v3", "urn:schemas-microsoft-com:asm.v3");
string level = manifest.Manifest.SelectSingleNode("//v3:requestedExecutionLevel",
manifestNamespaceManager).Attributes["level"].Value;
Assert.AreEqual(level, "requireAdministrator");
}
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestLinkEmbedManifest()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
try
{
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
// manifest
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
args.manifest = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Manifests\\asInvoker.manifest");
// link
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
List<Resource> manifests = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_MANIFEST)]; // RT_MANIFEST
Assert.IsNotNull(manifests);
Assert.AreEqual(1, manifests.Count);
ManifestResource manifest = (ManifestResource) manifests[0]; // RT_MANIFEST
Console.WriteLine(manifest.Manifest.OuterXml);
XmlNamespaceManager manifestNamespaceManager = new XmlNamespaceManager(manifest.Manifest.NameTable);
manifestNamespaceManager.AddNamespace("v1", "urn:schemas-microsoft-com:asm.v1");
manifestNamespaceManager.AddNamespace("v3", "urn:schemas-microsoft-com:asm.v3");
string level = manifest.Manifest.SelectSingleNode("//v3:requestedExecutionLevel",
manifestNamespaceManager).Attributes["level"].Value;
Assert.AreEqual(level, "asInvoker");
}
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestLinkEmbedFilesAndFolders()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
try
{
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
args.embedFolders = new string[] { binPath };
args.embed = true;
args.embedResourceSize = 0;
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
List<Resource> custom = ri.Resources[new ResourceId("RES_CAB")];
Assert.IsNotNull(custom);
Assert.AreEqual(1, custom.Count);
}
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestLinkNoEmbedFilesAndFolders()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
try
{
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
args.embedFolders = new string[] { binPath };
args.embed = false;
args.embedResourceSize = 0;
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
Assert.IsFalse(ri.Resources.ContainsKey(new ResourceId("RES_CAB")));
}
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestLinkEmbedFilesAndFoldersSegments()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
try
{
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
args.embedFolders = new string[] { binPath };
args.embed = true;
args.embedResourceSize = 64 * 1024;
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
List<Resource> custom = ri.Resources[new ResourceId("RES_CAB")];
Assert.IsNotNull(custom);
Console.WriteLine("Segments: {0}", custom.Count);
Assert.IsTrue(custom.Count > 1);
}
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestEmbedSplashScreen()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
try
{
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b 0";
setupConfiguration.Children.Add(cmd);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
args.splash = Path.Combine(dotNetInstallerExeUtils.Location, @"..\res\banner.bmp");
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
Assert.IsTrue(ri.Resources.ContainsKey(new ResourceId("CUSTOM")));
List<Resource> custom = ri.Resources[new ResourceId("CUSTOM")];
Assert.AreEqual("RES_BANNER", custom[0].Name.Name);
Assert.AreEqual("RES_CONFIGURATION", custom[1].Name.ToString());
Assert.AreEqual("RES_SPLASH", custom[2].Name.ToString());
}
// execute with and without splash
dotNetInstallerExeUtils.Run(args.output, "/qb");
dotNetInstallerExeUtils.Run(args.output, "/qb /nosplash");
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestControlLicenseResources()
{
InstallerLinkerArguments args = new InstallerLinkerArguments();
string licenseFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".txt");
try
{
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlLicense license = new ControlLicense();
license.LicenseFile = licenseFile;
Console.WriteLine("Writing '{0}'", license.LicenseFile);
File.WriteAllText(license.LicenseFile, "Lorem ipsum");
setupConfiguration.Children.Add(license);
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
Assert.IsTrue(ri.Resources.ContainsKey(new ResourceId("CUSTOM")));
List<Resource> custom = ri.Resources[new ResourceId("CUSTOM")];
Assert.AreEqual("RES_BANNER", custom[0].Name.Name);
Assert.AreEqual("RES_CONFIGURATION", custom[1].Name.ToString());
Assert.AreEqual("RES_LICENSE", custom[2].Name.ToString());
}
}
finally
{
if (File.Exists(licenseFile))
File.Delete(licenseFile);
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
[Test]
public void TestLinkProcessorArchitectureFilter()
{
// configurations
SetupConfiguration nofilterConfiguration = new SetupConfiguration();
SetupConfiguration x86Configuration = new SetupConfiguration();
x86Configuration.processor_architecture_filter = "x86";
SetupConfiguration x64Configuration = new SetupConfiguration();
x64Configuration.processor_architecture_filter = "x64";
SetupConfiguration mipsConfiguration = new SetupConfiguration();
mipsConfiguration.processor_architecture_filter = "mips";
// components
ComponentCmd nofilterComponent = new ComponentCmd();
ComponentCmd x86Component = new ComponentCmd();
x86Component.processor_architecture_filter = "x86";
ComponentCmd x64Component = new ComponentCmd();
x64Component.processor_architecture_filter = "x64";
ComponentCmd mipsComponent = new ComponentCmd();
mipsComponent.processor_architecture_filter = "mips";
// make a tree
nofilterConfiguration.Children.Add(nofilterComponent);
nofilterConfiguration.Children.Add(x86Component);
nofilterConfiguration.Children.Add(x64Component);
nofilterConfiguration.Children.Add(mipsComponent);
x86Configuration.Children.Add(nofilterComponent);
x86Configuration.Children.Add(x86Component);
x86Configuration.Children.Add(x64Component);
x86Configuration.Children.Add(mipsComponent);
x64Configuration.Children.Add(nofilterComponent);
x64Configuration.Children.Add(x86Component);
x64Configuration.Children.Add(x64Component);
x64Configuration.Children.Add(mipsComponent);
mipsConfiguration.Children.Add(nofilterComponent);
mipsConfiguration.Children.Add(x86Component);
mipsConfiguration.Children.Add(x64Component);
mipsConfiguration.Children.Add(mipsComponent);
// configfile
ConfigFile configFile = new ConfigFile();
configFile.Children.Add(nofilterConfiguration);
configFile.Children.Add(x86Configuration);
configFile.Children.Add(x64Configuration);
configFile.Children.Add(mipsConfiguration);
// write a configuration
InstallerLinkerArguments args = new InstallerLinkerArguments();
args.processorArchitecture = "x86,alpha";
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
Console.WriteLine("Writing '{0}'", args.config);
try
{
configFile.SaveAs(args.config);
Console.WriteLine("Linking '{0}'", args.output);
args.template = dotNetInstallerExeUtils.Executable;
InstallerLib.InstallerLinker.CreateInstaller(args);
// check that the linker generated output
Assert.IsTrue(File.Exists(args.output));
Assert.IsTrue(new FileInfo(args.output).Length > 0);
using (ResourceInfo ri = new ResourceInfo())
{
ri.Load(args.output);
List<Resource> custom = ri.Resources[new ResourceId("CUSTOM")];
Assert.AreEqual(custom[1].Name, new ResourceId("RES_CONFIGURATION"));
byte[] data = custom[1].WriteAndGetBytes();
// skip BOM
String config = Encoding.UTF8.GetString(data, 3, data.Length - 3);
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(config);
ConfigFile filteredConfig = new ConfigFile();
filteredConfig.LoadXml(xmldoc);
Assert.AreEqual(2, filteredConfig.ConfigurationCount);
Assert.AreEqual(4, filteredConfig.ComponentCount);
}
}
finally
{
if (File.Exists(args.config))
File.Delete(args.config);
if (File.Exists(args.output))
File.Delete(args.output);
}
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Licence...
using System;
using System.Collections.Generic;
using System.Linq;
using WixSharp.CommonTasks;
using IO = System.IO;
namespace WixSharp
{
/// <summary>
/// Defines all files of a given source directory and all subdirectories to be installed on target system.
/// <para>
/// Use this class to define files to be automatically included into the deployment solution
/// if their name matches specified wildcard character pattern (<see cref="Files.IncludeMask"/>).
/// </para>
/// <para>
/// This class is a logical equivalent of <see cref="DirFiles"/> except it also analyses all files in all subdirectories.
/// <see cref="DirFiles"/> excludes files in subdirectories.
/// </para>
/// <para>You can control inclusion of empty directories during wild card resolving by adjusting the compiler setting
/// <c>Compiler.AutoGeneration.IgnoreWildCardEmptyDirectories.</c></para>
/// </summary>
/// <remarks>
/// Note that all files matching wildcard are resolved into absolute path thus it may not always be suitable
/// if the Wix# script is to be compiled into WiX XML source only (Compiler.<see cref="WixSharp.Compiler.BuildWxs(WixSharp.Project)"/>). Though it is not a problem at all if the Wix# script
/// is compiled into MSI file (Compiler.<see cref="Compiler.BuildMsi(WixSharp.Project)"/>).
/// </remarks>b
/// <example>The following is an example of defining installation files with wildcard character pattern.
/// <code>
/// new Project("MyProduct",
/// new Dir(@"%ProgramFiles%\MyCompany\MyProduct",
/// new Files(@"Release\Bin\*.*"),
/// ...
/// </code>
/// </example>
public partial class Files : WixEntity
{
/// <summary>
/// Aggregates the files from the build directory. It is nothing else but a simplified creation of the
/// <see cref="WixSharp.Files"/> as below:
/// <code>
/// new Files(buildDir.PathJoin("*.*"),
/// f => f.EndsWithAny(ignoreCase: true, new[]{".exe",".dll,".xml",".config", ".json"}))
/// </code>
/// </summary>
/// <param name="buildDir">The build dir.</param>
/// <param name="fileExtensions">The file extensions to match the files that need to be included in the deployment.</param>
/// <returns></returns>
public static Files FromBuildDir(string buildDir, string fileExtensions = ".exe|.dll|.xml|.config|.json")
=> new Files(buildDir.PathJoin("*.*"),
f => f.EndsWithAny(true, fileExtensions.Split('|')));
/// <summary>
/// Initializes a new instance of the <see cref="Files"/> class.
/// </summary>
public Files()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Files"/> class with properties/fields initialized with specified parameters.
/// <para>You can control inclusion of empty folders (if picked by the wild card patter) by setting
/// <see cref="AutoGenerationOptions.IgnoreWildCardEmptyDirectories"/> to <c>true</c>.</para>
/// <para>If more specific control is required you can always use a flat list of <c>Dirs</c> of the
/// Project.<see cref="Project.AllDirs"/> to remove the undesired folder from its parent collection.
/// </para>
/// </summary>
/// <param name="sourcePath">The relative path to source directory. It must include wildcard pattern for files to be included
/// into MSI (e.g. <c>new Files(@"Release\Bin\*.*")</c>).</param>
public Files(string sourcePath)
{
IncludeMask = IO.Path.GetFileName(sourcePath);
Directory = IO.Path.GetDirectoryName(sourcePath);
}
/// <summary>
/// Initializes a new instance of the <see cref="Files"/> class with properties/fields initialized with specified parameters.
/// <para>You can control inclusion of empty folders (if picked by the wild card patter) by setting
/// <see cref="AutoGenerationOptions.IgnoreWildCardEmptyDirectories"/> to <c>true</c>.</para>
/// <para>If more specific control is required you can always use a flat list of <c>Dirs</c> of the
/// Project.<see cref="Project.AllDirs"/> to remove the undesired folder from its parent collection.
/// </para>
/// </summary>
/// <param name="sourcePath">The relative path to source directory. It must include wildcard pattern for files to be included
/// into MSI (e.g. <c>new Files(@"Release\Bin\*.*")</c>).</param>
/// <param name="filter">Filter to be applied for every file to be evaluated for the inclusion into MSI.
/// (e.g. <c>new Files(typical, @"Release\Bin\*.dll", f => !f.EndsWith(".Test.dll"))</c>).</param>
public Files(string sourcePath, Predicate<string> filter)
{
IncludeMask = IO.Path.GetFileName(sourcePath);
Directory = IO.Path.GetDirectoryName(sourcePath);
Filter = filter;
}
/// <summary>
/// Initializes a new instance of the <see cref="Files"/> class with properties/fields initialized with specified parameters.
/// <para>You can control inclusion of empty folders (if picked by the wild card patter) by setting
/// <see cref="AutoGenerationOptions.IgnoreWildCardEmptyDirectories"/> to <c>true</c>.</para>
/// <para>If more specific control is required you can always use a flat list of <c>Dirs</c> of the
/// Project.<see cref="Project.AllDirs"/> to remove the undesired folder from its parent collection.
/// </para>
/// </summary>
/// <param name="feature"><see cref="Feature"></see> the directory files should be included in.</param>
/// <param name="sourcePath">The relative path to source directory. It must include wildcard pattern for files to be included
/// into MSI (e.g. <c>new Files(@"Release\Bin\*.*")</c>).</param>
public Files(Feature feature, string sourcePath)
{
IncludeMask = IO.Path.GetFileName(sourcePath);
Directory = IO.Path.GetDirectoryName(sourcePath);
Feature = feature;
}
/// <summary>
/// Initializes a new instance of the <see cref="Files"/> class with properties/fields initialized with specified parameters.
/// <para>You can control inclusion of empty folders (if picked by the wild card patter) by setting
/// <see cref="AutoGenerationOptions.IgnoreWildCardEmptyDirectories"/> to <c>true</c>.</para>
/// <para>If more specific control is required you can always use a flat list of <c>Dirs</c> of the
/// Project.<see cref="Project.AllDirs"/> to remove the undesired folder from its parent collection.
/// </para>
/// </summary>
/// <param name="feature"><see cref="Feature"></see> the directory files should be included in.</param>
/// <param name="sourcePath">The relative path to source directory. It must include wildcard pattern for files to be included
/// into MSI (e.g. <c>new Files(@"Release\Bin\*.*")</c>).</param>
/// <param name="filter">Filter to be applied for every file to be evaluated for the inclusion into MSI.
/// (e.g. <c>new Files(typical, @"Release\Bin\*.dll", f => !f.EndsWith(".Test.dll"))</c>).</param>
public Files(Feature feature, string sourcePath, Predicate<string> filter)
{
IncludeMask = IO.Path.GetFileName(sourcePath);
Directory = IO.Path.GetDirectoryName(sourcePath);
Filter = filter;
Feature = feature;
}
/// <summary>
/// The relative path to source directory to search for files matching the <see cref="Files.IncludeMask"/>.
/// </summary>
public string Directory = "";
/// <summary>
/// The filter delegate. It is applied for every file to be evaluated for the inclusion into MSI.
/// </summary>
public Predicate<string> Filter = (file => true);
/// <summary>
/// The delegate that is called when a file matching the wildcard of the sourcePath is processed
/// and a <see cref="WixSharp.File"/> item is added to the project. It is the most convenient way of
/// adjusting the <see cref="WixSharp.File"/> item properties.
/// </summary>
public Action<File> OnProcess = null;
/// <summary>
/// Wildcard pattern for files to be included into MSI.
/// <para>Default value is <c>*.*</c>.</para>
/// </summary>
public string IncludeMask = "*.*";
/// <summary>
/// Analyses <paramref name="baseDirectory"/> and returns all files (including subdirectories) matching <see cref="Files.IncludeMask"/>.
/// </summary>
/// <param name="baseDirectory">The base directory for file analysis. It is used in conjunction with
/// relative <see cref="Files.Directory"/>. Though <see cref="Files.Directory"/> takes precedence if it is an absolute path.</param>
/// <returns>Array of <see cref="WixEntity"/> instances, which are either <see cref="File"/> or/and <see cref="Dir"/> objects.</returns>
/// <param name="parentWixDir">Parent Wix# directory</param>
// in anticipation of issues#48
//public WixEntity[] GetAllItems(string baseDirectory)
public WixEntity[] GetAllItems(string baseDirectory, Dir parentWixDir = null)
{
if (IO.Path.IsPathRooted(Directory))
baseDirectory = Directory;
if (baseDirectory.IsEmpty())
baseDirectory = Environment.CurrentDirectory;
baseDirectory = IO.Path.GetFullPath(baseDirectory);
string rootDirPath;
if (IO.Path.IsPathRooted(Directory))
rootDirPath = Directory;
else
rootDirPath = Utils.PathCombine(baseDirectory, Directory);
void AgregateSubDirs(Dir parentDir, string dirPath)
{
foreach (var subDirPath in IO.Directory.GetDirectories(dirPath))
{
var dirName = IO.Path.GetFileName(subDirPath);
Dir subDir = parentDir.Dirs.FirstOrDefault(dir => dir.Name.SameAs(dirName, ignoreCase: true));
if (subDir == null)
{
subDir = new Dir(dirName);
parentDir.AddDir(subDir);
}
subDir.AddFeatures(this.ActualFeatures);
subDir.AddDirFileCollection(
new DirFiles(IO.Path.Combine(subDirPath, this.IncludeMask))
{
Feature = this.Feature,
Features = this.Features,
AttributesDefinition = this.AttributesDefinition,
Attributes = this.Attributes,
Filter = this.Filter,
OnProcess = this.OnProcess
});
AgregateSubDirs(subDir, subDirPath);
}
};
var items = new List<WixEntity>
{
new DirFiles(IO.Path.Combine(rootDirPath, this.IncludeMask))
{
Feature = this.Feature,
Features = this.Features,
AttributesDefinition = this.AttributesDefinition,
Attributes = this.Attributes.Clone(),
Filter = this.Filter,
OnProcess = this.OnProcess
}
};
if (!IO.Directory.Exists(rootDirPath))
throw new IO.DirectoryNotFoundException(rootDirPath);
foreach (var subDirPath in System.IO.Directory.GetDirectories(rootDirPath))
{
var dirName = IO.Path.GetFileName(subDirPath);
var subDir = parentWixDir?.Dirs.FirstOrDefault(dir => dir.Name.SameAs(dirName, ignoreCase: true));
if (subDir == null)
{
subDir = new Dir(dirName);
items.Add(subDir);
}
subDir.AddFeatures(this.ActualFeatures);
subDir.AddDirFileCollection(
new DirFiles(IO.Path.Combine(subDirPath, this.IncludeMask))
{
Feature = this.Feature,
Features = this.Features,
AttributesDefinition = this.AttributesDefinition,
Attributes = this.Attributes,
Filter = this.Filter,
OnProcess = this.OnProcess
});
AgregateSubDirs(subDir, subDirPath);
}
return items.ToArray();
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using AView = Android.Views.View;
using AListView = Android.Widget.ListView;
namespace Xamarin.Forms.Platform.Android
{
public class TableViewModelRenderer : CellAdapter
{
readonly TableView _view;
protected readonly Context Context;
ITableViewController Controller => _view;
Cell _restoreFocus;
Cell[] _cellCache;
Cell[] CellCache
{
get
{
if (_cellCache == null)
FillCache();
return _cellCache;
}
}
bool[] _isHeaderCache;
bool[] IsHeaderCache
{
get
{
if (_isHeaderCache == null)
FillCache();
return _isHeaderCache;
}
}
bool[] _nextIsHeaderCache;
bool[] NextIsHeaderCache
{
get
{
if (_nextIsHeaderCache == null)
FillCache();
return _nextIsHeaderCache;
}
}
public TableViewModelRenderer(Context context, AListView listView, TableView view) : base(context)
{
_view = view;
Context = context;
Controller.ModelChanged += (sender, args) =>
{
InvalidateCellCache();
NotifyDataSetChanged();
};
listView.OnItemClickListener = this;
listView.OnItemLongClickListener = this;
}
public override int Count => CellCache.Length;
public override object this[int position]
{
get
{
if (position < 0 || position >= CellCache.Length)
return null;
return CellCache[position];
}
}
public override int ViewTypeCount
{
get
{
// 1 for the headers + 1 for each non header cell
var viewTypeCount = 1;
foreach (var b in IsHeaderCache)
if (!b)
viewTypeCount++;
return viewTypeCount;
}
}
public override bool AreAllItemsEnabled()
{
return false;
}
public override long GetItemId(int position)
{
return position;
}
public override AView GetView(int position, AView convertView, ViewGroup parent)
{
bool isHeader, nextIsHeader;
Cell item = GetCellForPosition(position, out isHeader, out nextIsHeader);
if (item == null)
return new AView(Context);
var makeBline = true;
var layout = convertView as ConditionalFocusLayout;
if (layout != null)
{
makeBline = false;
convertView = layout.GetChildAt(0);
}
else
layout = new ConditionalFocusLayout(Context) { Orientation = Orientation.Vertical };
AView aview = CellFactory.GetCell(item, convertView, parent, Context, _view);
if (!makeBline)
{
if (convertView != aview)
{
layout.RemoveViewAt(0);
layout.AddView(aview, 0);
}
}
else
layout.AddView(aview, 0);
AView bline;
if (makeBline)
{
bline = new AView(Context) { LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 1) };
layout.AddView(bline);
}
else
bline = layout.GetChildAt(1);
if (isHeader)
//NOTE: Headers seperator color default to transparent for headings
bline.SetBackgroundColor(Color.Transparent.ToAndroid());
else if (nextIsHeader)
bline.SetBackgroundColor(global::Android.Graphics.Color.Transparent);
else
{
using (var value = new TypedValue())
{
int id = global::Android.Resource.Drawable.DividerHorizontalDark;
if (Context.Theme.ResolveAttribute(global::Android.Resource.Attribute.ListDivider, value, true))
id = value.ResourceId;
else if (Context.Theme.ResolveAttribute(global::Android.Resource.Attribute.Divider, value, true))
id = value.ResourceId;
bline.SetBackgroundResource(id);
}
}
layout.ApplyTouchListenersToSpecialCells(item);
if (_restoreFocus == item)
{
if (!aview.HasFocus)
aview.RequestFocus();
_restoreFocus = null;
}
else if (aview.HasFocus)
aview.ClearFocus();
return layout;
}
public override bool IsEnabled(int position)
{
bool isHeader, nextIsHeader;
Cell item = GetCellForPosition(position, out isHeader, out nextIsHeader);
return !isHeader && item.IsEnabled;
}
protected override Cell GetCellForPosition(int position)
{
bool isHeader, nextIsHeader;
return GetCellForPosition(position, out isHeader, out nextIsHeader);
}
protected override void HandleItemClick(AdapterView parent, AView nview, int position, long id)
{
ITableModel model = Controller.Model;
if (position < 0 || position >= CellCache.Length)
return;
if (IsHeaderCache[position])
return;
model.RowSelected(CellCache[position]);
}
Cell GetCellForPosition(int position, out bool isHeader, out bool nextIsHeader)
{
isHeader = false;
nextIsHeader = false;
if (position < 0 || position >= CellCache.Length)
return null;
isHeader = IsHeaderCache[position];
nextIsHeader = NextIsHeaderCache[position];
return CellCache[position];
}
void FillCache()
{
ITableModel model = Controller.Model;
int sectionCount = model.GetSectionCount();
var newCellCache = new List<Cell>();
var newIsHeaderCache = new List<bool>();
var newNextIsHeaderCache = new List<bool>();
for (var sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++)
{
var sectionTitle = model.GetSectionTitle(sectionIndex);
var sectionRowCount = model.GetRowCount(sectionIndex);
if (!string.IsNullOrEmpty(sectionTitle))
{
Cell headerCell = model.GetHeaderCell(sectionIndex);
if (headerCell == null)
headerCell = new TextCell { Text = sectionTitle };
headerCell.Parent = _view;
newIsHeaderCache.Add(true);
newNextIsHeaderCache.Add(sectionRowCount == 0 && sectionIndex < sectionCount - 1);
newCellCache.Add(headerCell);
}
for (int i = 0; i < sectionRowCount; i++)
{
newIsHeaderCache.Add(false);
newNextIsHeaderCache.Add(i == sectionRowCount - 1 && sectionIndex < sectionCount - 1);
newCellCache.Add((Cell)model.GetItem(sectionIndex, i));
}
}
_cellCache = newCellCache.ToArray();
_isHeaderCache = newIsHeaderCache.ToArray();
_nextIsHeaderCache = newNextIsHeaderCache.ToArray();
}
void InvalidateCellCache()
{
_cellCache = null;
_isHeaderCache = null;
_nextIsHeaderCache = null;
}
protected override void Dispose(bool disposing)
{
if (disposing)
InvalidateCellCache();
base.Dispose(disposing);
}
}
}
| |
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright notice shall be
* included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Facebook.Unity
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
internal static class Utilities
{
private const string WarningMissingParameter = "Did not find expected value '{0}' in dictionary";
private static Dictionary<string, string> commandLineArguments;
public delegate void Callback<T>(T obj);
public static Dictionary<string, string> CommandLineArguments
{
get
{
if (commandLineArguments != null)
{
return commandLineArguments;
}
var localCommandLineArguments = new Dictionary<string, string>();
var arguments = Environment.GetCommandLineArgs();
for (int i = 0; i < arguments.Length; i++)
{
if (arguments[i].StartsWith("/") || arguments[i].StartsWith("-"))
{
var value = i + 1 < arguments.Length ? arguments[i + 1] : null;
localCommandLineArguments.Add(arguments[i], value);
}
}
commandLineArguments = localCommandLineArguments;
return commandLineArguments;
}
}
public static bool TryGetValue<T>(
this IDictionary<string, object> dictionary,
string key,
out T value)
{
object resultObj;
if (dictionary.TryGetValue(key, out resultObj) && resultObj is T)
{
value = (T)resultObj;
return true;
}
value = default(T);
return false;
}
public static long TotalSeconds(this DateTime dateTime)
{
TimeSpan t = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long secondsSinceEpoch = (long)t.TotalSeconds;
return secondsSinceEpoch;
}
public static T GetValueOrDefault<T>(
this IDictionary<string, object> dictionary,
string key,
bool logWarning = true)
{
T result;
if (!dictionary.TryGetValue<T>(key, out result) && logWarning)
{
FacebookLogger.Warn(WarningMissingParameter, key);
}
return result;
}
public static string ToCommaSeparateList(this IEnumerable<string> list)
{
if (list == null)
{
return string.Empty;
}
return string.Join(",", list.ToArray());
}
public static string AbsoluteUrlOrEmptyString(this Uri uri)
{
if (uri == null)
{
return string.Empty;
}
return uri.AbsoluteUri;
}
public static string GetUserAgent(string productName, string productVersion)
{
return string.Format(
CultureInfo.InvariantCulture,
"{0}/{1}",
productName,
productVersion);
}
public static string ToJson(this IDictionary<string, object> dictionary)
{
return MiniJSON.Json.Serialize(dictionary);
}
public static void AddAllKVPFrom<T1, T2>(this IDictionary<T1, T2> dest, IDictionary<T1, T2> source)
{
foreach (T1 key in source.Keys)
{
dest[key] = source[key];
}
}
public static AccessToken ParseAccessTokenFromResult(IDictionary<string, object> resultDictionary)
{
string userID = resultDictionary.GetValueOrDefault<string>(LoginResult.UserIdKey);
string accessToken = resultDictionary.GetValueOrDefault<string>(LoginResult.AccessTokenKey);
DateTime expiration = Utilities.ParseExpirationDateFromResult(resultDictionary);
ICollection<string> permissions = Utilities.ParsePermissionFromResult(resultDictionary);
DateTime? lastRefresh = Utilities.ParseLastRefreshFromResult(resultDictionary);
return new AccessToken(
accessToken,
userID,
expiration,
permissions,
lastRefresh);
}
public static string ToStringNullOk(this object obj)
{
if (obj == null)
{
return "null";
}
return obj.ToString();
}
// Use this instead of reflection to avoid crashing at
// runtime due to Unity's stripping
public static string FormatToString(
string baseString,
string className,
IDictionary<string, string> propertiesAndValues)
{
StringBuilder sb = new StringBuilder();
if (baseString != null)
{
sb.Append(baseString);
}
sb.AppendFormat("\n{0}:", className);
foreach (var kvp in propertiesAndValues)
{
string value = kvp.Value != null ? kvp.Value : "null";
sb.AppendFormat("\n\t{0}: {1}", kvp.Key, value);
}
return sb.ToString();
}
private static DateTime ParseExpirationDateFromResult(IDictionary<string, object> resultDictionary)
{
DateTime expiration;
if (Constants.IsWeb)
{
// For canvas we get back the time as seconds since now instead of in epoch time.
long timeTillExpiration = resultDictionary.GetValueOrDefault<long>(LoginResult.ExpirationTimestampKey);
expiration = DateTime.UtcNow.AddSeconds(timeTillExpiration);
}
else
{
string expirationStr = resultDictionary.GetValueOrDefault<string>(LoginResult.ExpirationTimestampKey);
int expiredTimeSeconds;
if (int.TryParse(expirationStr, out expiredTimeSeconds) && expiredTimeSeconds > 0)
{
expiration = Utilities.FromTimestamp(expiredTimeSeconds);
}
else
{
expiration = DateTime.MaxValue;
}
}
return expiration;
}
private static DateTime? ParseLastRefreshFromResult(IDictionary<string, object> resultDictionary)
{
string lastRefreshStr = resultDictionary.GetValueOrDefault<string>(LoginResult.LastRefreshKey, false);
int lastRefresh;
if (int.TryParse(lastRefreshStr, out lastRefresh) && lastRefresh > 0)
{
return Utilities.FromTimestamp(lastRefresh);
}
else
{
return null;
}
}
private static ICollection<string> ParsePermissionFromResult(IDictionary<string, object> resultDictionary)
{
string permissions;
IEnumerable<object> permissionList;
// For permissions we can get the result back in either a comma separated string or
// a list depending on the platform.
if (resultDictionary.TryGetValue(LoginResult.PermissionsKey, out permissions))
{
permissionList = permissions.Split(',');
}
else if (!resultDictionary.TryGetValue(LoginResult.PermissionsKey, out permissionList))
{
permissionList = new string[0];
FacebookLogger.Warn("Failed to find parameter '{0}' in login result", LoginResult.PermissionsKey);
}
return permissionList.Select(permission => permission.ToString()).ToList();
}
private static DateTime FromTimestamp(int timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
}
}
}
| |
// complete.c
#region OMIT_COMPLETE
#if !OMIT_COMPLETE
using System;
using System.Diagnostics;
namespace Core
{
public partial class Parser
{
enum TKC : byte
{
SEMI = 0,
WS = 1,
OTHER = 2,
#if !OMIT_TRIGGER
EXPLAIN = 3,
CREATE = 4,
TEMP = 5,
TRIGGER = 6,
END = 7,
#endif
}
#if !OMIT_TRIGGER
static byte[][] _trans = new byte[][]
{
/* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
/* 0 INVALID: */ new byte[]{ 1, 0, 2, 3, 4, 2, 2, 2, },
/* 1 START: */ new byte[]{ 1, 1, 2, 3, 4, 2, 2, 2, },
/* 2 NORMAL: */ new byte[]{ 1, 2, 2, 2, 2, 2, 2, 2, },
/* 3 EXPLAIN: */ new byte[]{ 1, 3, 3, 2, 4, 2, 2, 2, },
/* 4 CREATE: */ new byte[]{ 1, 4, 2, 2, 2, 4, 5, 2, },
/* 5 TRIGGER: */ new byte[]{ 6, 5, 5, 5, 5, 5, 5, 5, },
/* 6 SEMI: */ new byte[]{ 6, 6, 5, 5, 5, 5, 5, 7, },
/* 7 END: */ new byte[]{ 1, 7, 5, 5, 5, 5, 5, 5, } };
#else
static byte[][] _trans = new byte[][] {
/* State: ** SEMI WS OTHER */
/* 0 INVALID: */new byte[] { 1, 0, 2, },
/* 1 START: */new byte[] { 1, 1, 2, },
/* 2 NORMAL: */new byte[] { 1, 2, 2, } };
#endif
public static bool Complete(string sql)
{
int state = 0; // Current state, using numbers defined in header comment
TKC token; // Value of the next token
int sqlIdx = 0;
while (sqlIdx < sql.Length)
{
switch (sql[sqlIdx])
{
case ';':
{ // A semicolon
token = TKC.SEMI;
break;
}
case ' ':
case '\r':
case '\t':
case '\n':
case '\f':
{ // White space is ignored
token = TKC.WS;
break;
}
case '/':
{ // C-style comments
if (sql[sqlIdx + 1] != '*')
{
token = TKC.OTHER;
break;
}
sqlIdx += 2;
while (sqlIdx < sql.Length && sql[sqlIdx] != '*' || sqlIdx < sql.Length - 1 && sql[sqlIdx + 1] != '/') sqlIdx++;
if (sqlIdx == sql.Length) return false;
sqlIdx++;
token = TKC.WS;
break;
}
case '-':
{ // SQL-style comments from "--" to end of line
if (sql[sqlIdx + 1] != '-')
{
token = TKC.OTHER;
break;
}
while (sqlIdx < sql.Length && sql[sqlIdx] != '\n') sqlIdx++;
if (sqlIdx == sql.Length) return (state == 1);
token = TKC.WS;
break;
}
case '[':
{ // Microsoft-style identifiers in [...]
sqlIdx++;
while (sqlIdx < sql.Length && sql[sqlIdx] != ']') sqlIdx++;
if (sqlIdx == sql.Length) return false;
token = TKC.OTHER;
break;
}
case '`': // Grave-accent quoted symbols used by MySQL
case '"': // single- and double-quoted strings
case '\'':
{
int c = sql[sqlIdx];
sqlIdx++;
while (sqlIdx < sql.Length && sql[sqlIdx] != c) sqlIdx++;
if (sqlIdx == sql.Length) return false;
token = TKC.OTHER;
break;
}
default:
{
if (char.IsIdChar(sql[sqlIdx]))
{
// Keywords and unquoted identifiers
int id;
for (id = 1; (sqlIdx + id) < sql.Length && char.IdChar(sql[sqlIdx + id]); id++) { }
#if OMIT_TRIGGER
token = TKC.OTHER;
#else
switch (sql[sqlIdx])
{
case 'c':
case 'C':
{
if (id == 6 && string.Compare(sql, sqlIdx, "create", 0, 6, StringComparison.OrdinalIgnoreCase) == 0) token = TKC.CREATE;
else token = TKC.OTHER;
break;
}
case 't':
case 'T':
{
if (id == 7 && string.Compare(sql, sqlIdx, "trigger", 0, 7, StringComparison.OrdinalIgnoreCase) == 0) token = TKC.TRIGGER;
else if (id == 4 && string.Compare(sql, sqlIdx, "temp", 0, 4, StringComparison.OrdinalIgnoreCase) == 0) token = TKC.TEMP;
else if (id == 9 && string.Compare(sql, sqlIdx, "temporary", 0, 9, StringComparison.OrdinalIgnoreCase) == 0) token = TKC.TEMP;
else token = TKC.OTHER;
break;
}
case 'e':
case 'E':
{
if (id == 3 && string.Compare(sql, sqlIdx, "end", 0, 3, StringComparison.OrdinalIgnoreCase) == 0) token = TKC.END;
else
#if !OMIT_EXPLAIN
if (id == 7 && string.Compare(sql, sqlIdx, "explain", 0, 7, StringComparison.OrdinalIgnoreCase) == 0) token = TKC.EXPLAIN;
else
#endif
token = TKC.OTHER;
break;
}
default:
{
token = TKC.OTHER;
break;
}
}
#endif
sqlIdx += id - 1;
}
else token = TKC.OTHER; // Operators and special symbols
break;
}
}
state = _trans[state][(int)token];
sqlIdx++;
}
return (state == 1);
}
#if !OMIT_UTF16
public static bool Complete16(string sql)
{
RC rc = RC.NOMEM;
#if !OMIT_AUTOINIT
rc = SysEx.Initialize();
if (rc != RC.OK) return rc;
#endif
Mem val = sqlite3ValueNew(0);
sqlite3ValueSetStr(val, -1, sql, TEXTENCODE.UTF16NATIVE, DESTRUCTOR.STATIC);
string sql8 = sqlite3ValueText(val, TEXTENCODE.UTF8);
rc = (sql8 != null ? (RC)Complete(sql8) : RC.NOMEM);
else rc = RC.NOMEM;
sqlite3ValueFree(val);
return Context.ApiExit(null, rc);
}
#endif
}
}
#endif
#endregion
| |
// --------------------------------------------------------------------------------------------
// <copyright file="StringFieldFixture.cs" company="Effort Team">
// Copyright (C) Effort Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------
using System;
using System.Data.Common;
using Effort.Provider;
namespace Effort.Test.Features
{
using System.Data.Entity;
using System.Linq;
using Effort.Test.Data.Features;
using NUnit.Framework;
[TestFixture]
public class StringFieldFixture
{
private FeatureDbContext context;
public EffortConnection connection;
[SetUp]
public void Initialize()
{
if (connection == null)
{
connection = Effort.DbConnectionFactory.CreateTransient();
this.context =
new FeatureDbContext(
connection,
CompiledModels.GetModel<
StringFieldEntity>());
this.context.Database.CreateIfNotExists();
}
}
protected IDbSet<StringFieldEntity> Entities
{
get { return this.context.StringFieldEntities; }
}
protected void Add(params string[] values)
{
this.connection.ClearTables(this.context);
foreach (var value in values)
{
this.Entities.Add(new StringFieldEntity { Value = value });
}
this.context.SaveChanges();
}
[Test]
public void String_Equals()
{
this.Add("John", "Doe");
var res = this.Entities
.Where(x => x.Value == "John")
.Count();
Assert.AreEqual(1, res);
}
[Test]
public void String_Equals2()
{
this.Add("John", null, null);
var res = this.Entities
.Where(x => x.Value == null)
.Count();
Assert.AreEqual(2, res);
}
[Test]
public void String_NotEquals()
{
this.Add("John", "Doe", "John");
var res = this.Entities
.Where(x => x.Value != "John")
.Count();
Assert.AreEqual(1, res);
}
[Test]
public void String_NotEqualsNull()
{
this.Add("John", "Doe", null);
var res = this.Entities
.Where(x => x.Value != null)
.Count();
Assert.AreEqual(2, res);
}
[Test]
public void String_GreaterThan()
{
this.Add("Indie", "Imp", "Huge");
var res = this.Entities
.Where(x => x.Value.CompareTo("Imp") > 0)
.Count();
Assert.AreEqual(1, res);
}
[Test]
public void String_GreaterThanOrEquals()
{
try
{
this.connection.IsCaseSensitive = true;
this.Add("Indie", "Imp", "Huge");
var res = this.Entities
.Where(x => x.Value.CompareTo("I") >= 0)
.Count();
Assert.AreEqual(2, res);
}
finally
{
this.connection.IsCaseSensitive = true;
}
}
[Test]
public void String_LessThan()
{
this.Add("Indie", "Imp", "Huge");
var res = this.Entities
.Where(x => x.Value.CompareTo("Imp") < 0)
.Count();
Assert.AreEqual(1, res);
}
[Test]
public void String_LessThanOrEquals()
{
this.Add("Indie", "Imp", "Huge");
var res = this.Entities
.Where(x => x.Value.CompareTo("Imp") <= 0)
.Count();
Assert.AreEqual(2, res);
}
[Test]
public void String_CompareNull()
{
this.Add("Indie", "Imp", null);
var res = this.Entities
.Where(x => x.Value.CompareTo(null) == -1)
.Count();
Assert.AreEqual(2, res);
}
[Test]
public void String_EqualsSensitiveCase()
{
try
{
this.connection.IsCaseSensitive = false;
this.Add("john2", "DOE2");
var res = this.Entities
.Where(x => x.Value == "John2").ToList();
Assert.AreEqual(1, res.Count);
Assert.AreEqual("john2", res.FirstOrDefault().Value);
var res2 = this.Entities
.Where(x => x.Value == "doe2").ToList();
Assert.AreEqual(1, res2.Count);
Assert.AreEqual("DOE2", res2.FirstOrDefault().Value);
}
finally
{
this.connection.IsCaseSensitive = true;
}
}
[Test]
public void String_EqualsSensitiveCase2()
{
try
{
this.connection.IsCaseSensitive = false;
this.Add("John", null, null);
var res = this.Entities
.Where(x => x.Value == null)
.Count();
Assert.AreEqual(2, res);
}
finally
{
this.connection.IsCaseSensitive = true;
}
}
[Test]
public void String_NotEqualsSensitiveCase()
{
try
{
this.connection.IsCaseSensitive = false;
this.Add("John", "Doe", "John");
var res = this.Entities
.Where(x => x.Value != "John")
.Count();
Assert.AreEqual(1, res);
}
finally
{
this.connection.IsCaseSensitive = true;
}
}
[Test]
public void String_NotEqualsSensitiveCaseNull()
{
try
{
this.connection.IsCaseSensitive = false;
this.Add("John", "Doe", null);
var res = this.Entities
.Where(x => x.Value != null)
.Count();
Assert.AreEqual(2, res);
}
finally
{
this.connection.IsCaseSensitive = true;
}
}
[Test]
public void String_GreaterThanSensitiveCase()
{
try
{
this.connection.IsCaseSensitive = false;
this.Add("Indie", "Imp", "Huge");
var res = this.Entities
.Where(x => x.Value.CompareTo("Imp") > 0)
.Count();
Assert.AreEqual(1, res);
}
finally
{
this.connection.IsCaseSensitive = true;
}
}
[Test]
public void String_GreaterThanOrEqualsSensitiveCase()
{
try
{
this.connection.IsCaseSensitive = false;
this.Add("Indie", "Imp", "Huge");
var res = this.Entities
.Where(x => x.Value.CompareTo("I") >= 0)
.Count();
Assert.AreEqual(2, res);
}
finally
{
this.connection.IsCaseSensitive = true;
}
}
[Test]
public void String_LessThanSensitiveCase()
{
this.Add("Indie", "Imp", "Huge");
var res = this.Entities
.Where(x => x.Value.CompareTo("Imp") < 0)
.Count();
Assert.AreEqual(1, res);
}
[Test]
public void String_LessThanOrEqualsSensitiveCase()
{
this.Add("Indie", "Imp", "Huge");
var res = this.Entities
.Where(x => x.Value.CompareTo("Imp") <= 0)
.Count();
Assert.AreEqual(2, res);
}
}
}
| |
using UnityEngine;
using System.Collections;
using Pathfinding;
/** Moves a grid graph to follow a target.
*
* Attach this to some object in the scene and assign the target to e.g the player.
* Then the graph will follow that object around as it moves.
*
* This is useful if pathfinding is only necessary in a small region around an object (for example the player).
* It makes it possible to have vast open worlds (maybe procedurally generated) and still be able to use pathfinding on them.
*
* When the graph is moved you may notice an fps drop.
* If this grows too large you can try a few things:
* - Reduce the #updateDistance. This will make the updates smaller but more frequent.
* This only works to some degree however since an update has an inherent overhead.
* - Turn off erosion on the grid graph. This will reduce the number of nodes that need updating.
* - Reduce the grid size.
* - Turn on multithreading (A* Inspector -> Settings)
* - Disable Height Testing or Collision Testing in the grid graph. This can give a minor performance boost.
*
* \see Take a look at the example scene called "Procedural" for an example of how to use this script
*
* \version Since 3.6.8 this class can handle graph rotation other options such as isometric angle and aspect ratio.
*/
public class ProceduralGridMover : MonoBehaviour {
/** Graph will be updated if the target is more than this number of nodes from the graph center.
* Note that this is in nodes, not world units.
*
* \version The unit was changed to nodes instead of world units in 3.6.8.
*/
public float updateDistance = 10;
/** Graph will be moved to follow this target */
public Transform target;
/** Flood fill the graph after updating.
* If this is set to false, areas of the graph will not be recalculated.
* Enable this only if the graph will only have a single area (i.e
* from all walkable nodes there is a valid path to every other walkable
* node). One case where this might be appropriate is a large
* outdoor area such as a forrest.
* If there are multiple areas in the graph and this
* is not enabled, pathfinding could fail later on.
*
* Enabling it will make the graph updates faster.
*/
public bool floodFill;
/** Grid graph to update */
GridGraph graph;
/** Temporary buffer */
GridNode[] tmp;
/** True while the graph is being updated by this script */
public bool updatingGraph {get; private set;}
public void Start () {
if ( AstarPath.active == null ) throw new System.Exception ("There is no AstarPath object in the scene");
graph = AstarPath.active.astarData.gridGraph;
if ( graph == null ) throw new System.Exception ("The AstarPath object has no GridGraph");
UpdateGraph ();
}
/** Update is called once per frame */
void Update () {
// Calculate where the graph center and the target position is in graph space
var graphCenterInGraphSpace = PointToGraphSpace(graph.center);
var targetPositionInGraphSpace = PointToGraphSpace (target.position);
// Check the distance in graph space
// We only care about the X and Z axes since the Y axis is the "height" coordinate of the nodes (in graph space)
// We only care about the plane that the nodes are placed in
if ( AstarMath.SqrMagnitudeXZ(graphCenterInGraphSpace, targetPositionInGraphSpace) > updateDistance*updateDistance ) {
UpdateGraph ();
}
}
/** Transforms a point from world space to graph space.
* In graph space, (0,0,0) is bottom left corner of the graph
* and one unit along the X and Z axes equals distance between two nodes
* the Y axis still uses world units
*/
Vector3 PointToGraphSpace (Vector3 p) {
// Multiply with the inverse matrix of the graph
// to get the point in graph space
return graph.inverseMatrix.MultiplyPoint(p);
}
/** Updates the graph asynchronously.
* This will move the graph so that the target's position is the center of the graph.
* If the graph is already being updated, the call will be ignored.
*/
public void UpdateGraph () {
if (updatingGraph) {
// We are already updating the graph
// so ignore this call
return;
}
updatingGraph = true;
// Start a work item for updating the graph
// This will pause the pathfinding threads
// so that it is safe to update the graph
// and then do it over several frames
// (hence the IEnumerator coroutine)
// to avoid too large FPS drops
IEnumerator ie = UpdateGraphCoroutine ();
AstarPath.active.AddWorkItem (new AstarPath.AstarWorkItem (
force => {
// If force is true we need to calculate all steps at once
if ( force ) while ( ie.MoveNext () ) {}
// Calculate one step. True will be returned when there are no more steps
bool done = !ie.MoveNext ();
if (done) {
updatingGraph = false;
}
return done;
}));
}
/** Async method for moving the graph */
IEnumerator UpdateGraphCoroutine () {
// Find the direction
// that we want to move the graph in.
// Calcuculate this in graph space (where a distance of one is the size of one node)
Vector3 dir = PointToGraphSpace(target.position) - PointToGraphSpace(graph.center);
// Snap to a whole number of nodes
dir.x = Mathf.Round(dir.x);
dir.z = Mathf.Round(dir.z);
dir.y = 0;
// Nothing do to
if ( dir == Vector3.zero ) yield break;
// Number of nodes to offset in each direction
Int2 offset = new Int2(-Mathf.RoundToInt(dir.x), -Mathf.RoundToInt(dir.z));
// Move the center (this is in world units, so we need to convert it back from graph space)
graph.center += graph.matrix.MultiplyVector (dir);
graph.GenerateMatrix ();
// Create a temporary buffer
// required for the calculations
if ( tmp == null || tmp.Length != graph.nodes.Length ) {
tmp = new GridNode[graph.nodes.Length];
}
// Cache some variables for easier access
int width = graph.width;
int depth = graph.depth;
GridNode[] nodes = graph.nodes;
// Check if we have moved
// less than a whole graph
// width in any direction
if ( Mathf.Abs(offset.x) <= width && Mathf.Abs(offset.y) <= depth ) {
// Offset each node by the #offset variable
// nodes which would end up outside the graph
// will wrap around to the other side of it
for ( int z=0; z < depth; z++ ) {
int pz = z*width;
int tz = ((z+offset.y + depth)%depth)*width;
for ( int x=0; x < width; x++ ) {
tmp[tz + ((x+offset.x + width) % width)] = nodes[pz + x];
}
}
yield return null;
// Copy the nodes back to the graph
// and set the correct indices
for ( int z=0; z < depth; z++ ) {
int pz = z*width;
for ( int x=0; x < width; x++ ) {
GridNode node = tmp[pz + x];
node.NodeInGridIndex = pz + x;
nodes[pz + x] = node;
}
}
IntRect r = new IntRect ( 0, 0, offset.x, offset.y );
int minz = r.ymax;
int maxz = depth;
// If offset.x < 0, adjust the rect
if ( r.xmin > r.xmax ) {
int tmp2 = r.xmax;
r.xmax = width + r.xmin;
r.xmin = width + tmp2;
}
// If offset.y < 0, adjust the rect
if ( r.ymin > r.ymax ) {
int tmp2 = r.ymax;
r.ymax = depth + r.ymin;
r.ymin = depth + tmp2;
minz = 0;
maxz = r.ymin;
}
// Make sure erosion is taken into account
// Otherwise we would end up with ugly artifacts
r = r.Expand ( graph.erodeIterations + 1 );
// Makes sure the rect stays inside the grid
r = IntRect.Intersection ( r, new IntRect ( 0, 0, width, depth ) );
yield return null;
// Update all nodes along one edge of the graph
// With the same width as the rect
for ( int z = r.ymin; z < r.ymax; z++ ) {
for ( int x = 0; x < width; x++ ) {
graph.UpdateNodePositionCollision ( nodes[z*width + x], x, z, false );
}
}
yield return null;
// Update all nodes along the other edge of the graph
// With the same width as the rect
for ( int z = minz; z < maxz; z++ ) {
for ( int x = r.xmin; x < r.xmax; x++ ) {
graph.UpdateNodePositionCollision ( nodes[z*width + x], x, z, false );
}
}
yield return null;
// Calculate all connections for the nodes
// that might have changed
for ( int z = r.ymin; z < r.ymax; z++ ) {
for ( int x = 0; x < width; x++ ) {
graph.CalculateConnections (nodes, x, z, nodes[z*width+x]);
}
}
yield return null;
// Calculate all connections for the nodes
// that might have changed
for ( int z = minz; z < maxz; z++ ) {
for ( int x = r.xmin; x < r.xmax; x++ ) {
graph.CalculateConnections (nodes, x, z, nodes[z*width+x]);
}
}
yield return null;
// Calculate all connections for the nodes along the boundary
// of the graph, these always need to be updated
/** \todo Optimize to not traverse all nodes in the graph, only those at the edges */
for ( int z = 0; z < depth; z++ ) {
for ( int x = 0; x < width; x++ ) {
if ( x == 0 || z == 0 || x >= width-1 || z >= depth-1 ) graph.CalculateConnections (nodes, x, z, nodes[z*width+x]);
}
}
} else {
// Just update all nodes
for ( int z = 0; z < depth; z++ ) {
for ( int x = 0; x < width; x++ ) {
graph.UpdateNodePositionCollision ( nodes[z*width + x], x, z, false );
}
}
// Recalculate the connections of all nodes
for ( int z = 0; z < depth; z++ ) {
for ( int x = 0; x < width; x++ ) {
graph.CalculateConnections (nodes, x, z, nodes[z*width+x]);
}
}
}
if ( floodFill ) {
yield return null;
// Make sure the areas for the graph
// have been recalculated
// not doing this can cause pathfinding to fail
AstarPath.active.QueueWorkItemFloodFill ();
}
}
}
| |
// 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 gcgv = Google.Cloud.GSuiteAddOns.V1;
using sys = System;
namespace Google.Cloud.GSuiteAddOns.V1
{
/// <summary>Resource name for the <c>Authorization</c> resource.</summary>
public sealed partial class AuthorizationName : gax::IResourceName, sys::IEquatable<AuthorizationName>
{
/// <summary>The possible contents of <see cref="AuthorizationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/authorization</c>.</summary>
Project = 1,
}
private static gax::PathTemplate s_project = new gax::PathTemplate("projects/{project}/authorization");
/// <summary>Creates a <see cref="AuthorizationName"/> 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="AuthorizationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AuthorizationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AuthorizationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AuthorizationName"/> with the pattern <c>projects/{project}/authorization</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AuthorizationName"/> constructed from the provided ids.</returns>
public static AuthorizationName FromProject(string projectId) =>
new AuthorizationName(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AuthorizationName"/> with pattern
/// <c>projects/{project}/authorization</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AuthorizationName"/> with pattern
/// <c>projects/{project}/authorization</c>.
/// </returns>
public static string Format(string projectId) => FormatProject(projectId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AuthorizationName"/> with pattern
/// <c>projects/{project}/authorization</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AuthorizationName"/> with pattern
/// <c>projects/{project}/authorization</c>.
/// </returns>
public static string FormatProject(string projectId) =>
s_project.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AuthorizationName"/> 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}/authorization</c></description></item></list>
/// </remarks>
/// <param name="authorizationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AuthorizationName"/> if successful.</returns>
public static AuthorizationName Parse(string authorizationName) => Parse(authorizationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AuthorizationName"/> 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}/authorization</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="authorizationName">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="AuthorizationName"/> if successful.</returns>
public static AuthorizationName Parse(string authorizationName, bool allowUnparsed) =>
TryParse(authorizationName, allowUnparsed, out AuthorizationName 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="AuthorizationName"/> 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}/authorization</c></description></item></list>
/// </remarks>
/// <param name="authorizationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AuthorizationName"/>, 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 authorizationName, out AuthorizationName result) =>
TryParse(authorizationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AuthorizationName"/> 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}/authorization</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="authorizationName">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="AuthorizationName"/>, 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 authorizationName, bool allowUnparsed, out AuthorizationName result)
{
gax::GaxPreconditions.CheckNotNull(authorizationName, nameof(authorizationName));
gax::TemplatedResourceName resourceName;
if (s_project.TryParseName(authorizationName, out resourceName))
{
result = FromProject(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(authorizationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AuthorizationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AuthorizationName"/> class from the component parts of pattern
/// <c>projects/{project}/authorization</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
public AuthorizationName(string projectId) : this(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)))
{
}
/// <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>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.Project: return s_project.Expand(ProjectId);
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 AuthorizationName);
/// <inheritdoc/>
public bool Equals(AuthorizationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AuthorizationName a, AuthorizationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AuthorizationName a, AuthorizationName b) => !(a == b);
}
/// <summary>Resource name for the <c>InstallStatus</c> resource.</summary>
public sealed partial class InstallStatusName : gax::IResourceName, sys::IEquatable<InstallStatusName>
{
/// <summary>The possible contents of <see cref="InstallStatusName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </summary>
ProjectDeployment = 1,
}
private static gax::PathTemplate s_projectDeployment = new gax::PathTemplate("projects/{project}/deployments/{deployment}/installStatus");
/// <summary>Creates a <see cref="InstallStatusName"/> 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="InstallStatusName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static InstallStatusName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new InstallStatusName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="InstallStatusName"/> with the pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="InstallStatusName"/> constructed from the provided ids.</returns>
public static InstallStatusName FromProjectDeployment(string projectId, string deploymentId) =>
new InstallStatusName(ResourceNameType.ProjectDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstallStatusName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstallStatusName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </returns>
public static string Format(string projectId, string deploymentId) => FormatProjectDeployment(projectId, deploymentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstallStatusName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstallStatusName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>.
/// </returns>
public static string FormatProjectDeployment(string projectId, string deploymentId) =>
s_projectDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="InstallStatusName"/> 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}/deployments/{deployment}/installStatus</c></description></item>
/// </list>
/// </remarks>
/// <param name="installStatusName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="InstallStatusName"/> if successful.</returns>
public static InstallStatusName Parse(string installStatusName) => Parse(installStatusName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="InstallStatusName"/> 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}/deployments/{deployment}/installStatus</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="installStatusName">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="InstallStatusName"/> if successful.</returns>
public static InstallStatusName Parse(string installStatusName, bool allowUnparsed) =>
TryParse(installStatusName, allowUnparsed, out InstallStatusName 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="InstallStatusName"/> 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}/deployments/{deployment}/installStatus</c></description></item>
/// </list>
/// </remarks>
/// <param name="installStatusName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstallStatusName"/>, 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 installStatusName, out InstallStatusName result) =>
TryParse(installStatusName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstallStatusName"/> 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}/deployments/{deployment}/installStatus</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="installStatusName">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="InstallStatusName"/>, 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 installStatusName, bool allowUnparsed, out InstallStatusName result)
{
gax::GaxPreconditions.CheckNotNull(installStatusName, nameof(installStatusName));
gax::TemplatedResourceName resourceName;
if (s_projectDeployment.TryParseName(installStatusName, out resourceName))
{
result = FromProjectDeployment(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(installStatusName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private InstallStatusName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeploymentId = deploymentId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="InstallStatusName"/> class from the component parts of pattern
/// <c>projects/{project}/deployments/{deployment}/installStatus</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
public InstallStatusName(string projectId, string deploymentId) : this(ResourceNameType.ProjectDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)))
{
}
/// <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>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeploymentId { 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.ProjectDeployment: return s_projectDeployment.Expand(ProjectId, DeploymentId);
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 InstallStatusName);
/// <inheritdoc/>
public bool Equals(InstallStatusName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(InstallStatusName a, InstallStatusName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(InstallStatusName a, InstallStatusName b) => !(a == b);
}
/// <summary>Resource name for the <c>Deployment</c> resource.</summary>
public sealed partial class DeploymentName : gax::IResourceName, sys::IEquatable<DeploymentName>
{
/// <summary>The possible contents of <see cref="DeploymentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/deployments/{deployment}</c>.</summary>
ProjectDeployment = 1,
}
private static gax::PathTemplate s_projectDeployment = new gax::PathTemplate("projects/{project}/deployments/{deployment}");
/// <summary>Creates a <see cref="DeploymentName"/> 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="DeploymentName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static DeploymentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new DeploymentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="DeploymentName"/> with the pattern <c>projects/{project}/deployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="DeploymentName"/> constructed from the provided ids.</returns>
public static DeploymentName FromProjectDeployment(string projectId, string deploymentId) =>
new DeploymentName(ResourceNameType.ProjectDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeploymentName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DeploymentName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}</c>.
/// </returns>
public static string Format(string projectId, string deploymentId) => FormatProjectDeployment(projectId, deploymentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeploymentName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DeploymentName"/> with pattern
/// <c>projects/{project}/deployments/{deployment}</c>.
/// </returns>
public static string FormatProjectDeployment(string projectId, string deploymentId) =>
s_projectDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>Parses the given resource name string into a new <see cref="DeploymentName"/> 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}/deployments/{deployment}</c></description></item>
/// </list>
/// </remarks>
/// <param name="deploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="DeploymentName"/> if successful.</returns>
public static DeploymentName Parse(string deploymentName) => Parse(deploymentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="DeploymentName"/> 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}/deployments/{deployment}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="deploymentName">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="DeploymentName"/> if successful.</returns>
public static DeploymentName Parse(string deploymentName, bool allowUnparsed) =>
TryParse(deploymentName, allowUnparsed, out DeploymentName 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="DeploymentName"/> 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}/deployments/{deployment}</c></description></item>
/// </list>
/// </remarks>
/// <param name="deploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DeploymentName"/>, 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 deploymentName, out DeploymentName result) =>
TryParse(deploymentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DeploymentName"/> 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}/deployments/{deployment}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="deploymentName">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="DeploymentName"/>, 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 deploymentName, bool allowUnparsed, out DeploymentName result)
{
gax::GaxPreconditions.CheckNotNull(deploymentName, nameof(deploymentName));
gax::TemplatedResourceName resourceName;
if (s_projectDeployment.TryParseName(deploymentName, out resourceName))
{
result = FromProjectDeployment(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(deploymentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private DeploymentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeploymentId = deploymentId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="DeploymentName"/> class from the component parts of pattern
/// <c>projects/{project}/deployments/{deployment}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
public DeploymentName(string projectId, string deploymentId) : this(ResourceNameType.ProjectDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)))
{
}
/// <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>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeploymentId { 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.ProjectDeployment: return s_projectDeployment.Expand(ProjectId, DeploymentId);
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 DeploymentName);
/// <inheritdoc/>
public bool Equals(DeploymentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(DeploymentName a, DeploymentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(DeploymentName a, DeploymentName b) => !(a == b);
}
public partial class GetAuthorizationRequest
{
/// <summary>
/// <see cref="gcgv::AuthorizationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::AuthorizationName AuthorizationName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::AuthorizationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Authorization
{
/// <summary>
/// <see cref="gcgv::AuthorizationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::AuthorizationName AuthorizationName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::AuthorizationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateDeploymentRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListDeploymentsRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class InstallDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class UninstallDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetInstallStatusRequest
{
/// <summary>
/// <see cref="gcgv::InstallStatusName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::InstallStatusName InstallStatusName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::InstallStatusName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class InstallStatus
{
/// <summary>
/// <see cref="gcgv::InstallStatusName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::InstallStatusName InstallStatusName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::InstallStatusName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Deployment
{
/// <summary>
/// <see cref="gcgv::DeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::DeploymentName DeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::DeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.WindowsAzure.Management.StorSimple;
using Microsoft.WindowsAzure.Management.StorSimple.Models;
namespace Microsoft.WindowsAzure.Management.StorSimple
{
/// <summary>
/// All Operations related to Backup
/// </summary>
internal partial class BackupOperations : IServiceOperations<StorSimpleManagementClient>, IBackupOperations
{
/// <summary>
/// Initializes a new instance of the BackupOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal BackupOperations(StorSimpleManagementClient client)
{
this._client = client;
}
private StorSimpleManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.StorSimpleManagementClient.
/// </summary>
public StorSimpleManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Begin a backup operation for the policyId and backupRequest
/// specified.
/// </summary>
/// <param name='deviceId'>
/// Required. The device id for which the call will be made.
/// </param>
/// <param name='policyId'>
/// Required. The policy id for which the call will be made.
/// </param>
/// <param name='backupRequest'>
/// Required. Parameters supplied to the Begin Backup operation.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// This is the Task Response for all Async Calls
/// </returns>
public async Task<TaskResponse> BeginCreatingBackupAsync(string deviceId, string policyId, BackupNowRequest backupRequest, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (deviceId == null)
{
throw new ArgumentNullException("deviceId");
}
if (policyId == null)
{
throw new ArgumentNullException("policyId");
}
if (backupRequest == null)
{
throw new ArgumentNullException("backupRequest");
}
if (customRequestHeaders == null)
{
throw new ArgumentNullException("customRequestHeaders");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceId", deviceId);
tracingParameters.Add("policyId", policyId);
tracingParameters.Add("backupRequest", backupRequest);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "BeginCreatingBackupAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/~/";
url = url + "CisVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/api/devices/";
url = url + Uri.EscapeDataString(deviceId);
url = url + "/policies/";
url = url + Uri.EscapeDataString(policyId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-01-01.1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2014-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement backupNowRequestElement = new XElement(XName.Get("BackupNowRequest", "http://windowscloudbackup.com/CiS/V2013_03"));
requestDoc.Add(backupNowRequestElement);
XElement typeElement = new XElement(XName.Get("Type", "http://windowscloudbackup.com/CiS/V2013_03"));
typeElement.Value = backupRequest.Type.ToString();
backupNowRequestElement.Add(typeElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TaskResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TaskResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/"));
if (stringElement != null)
{
string stringInstance = stringElement.Value;
result.TaskId = stringInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Begin deleting a backup set represented by the backSetId provided.
/// </summary>
/// <param name='deviceId'>
/// Required. The device id for which the call will be made.
/// </param>
/// <param name='backupSetId'>
/// Required. The backup set ID to delete.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// This is the Task Response for all Async Calls
/// </returns>
public async Task<TaskResponse> BeginDeletingAsync(string deviceId, string backupSetId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (deviceId == null)
{
throw new ArgumentNullException("deviceId");
}
if (backupSetId == null)
{
throw new ArgumentNullException("backupSetId");
}
if (customRequestHeaders == null)
{
throw new ArgumentNullException("customRequestHeaders");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceId", deviceId);
tracingParameters.Add("backupSetId", backupSetId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/~/";
url = url + "CisVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/api/devices/";
url = url + Uri.EscapeDataString(deviceId);
url = url + "/backups/";
url = url + Uri.EscapeDataString(backupSetId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-01-01.1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2014-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TaskResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TaskResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/"));
if (stringElement != null)
{
string stringInstance = stringElement.Value;
result.TaskId = stringInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Begin restoring a backup set.
/// </summary>
/// <param name='deviceId'>
/// Required. The device id for which the call will be made.
/// </param>
/// <param name='backupDetailsForRestore'>
/// Required. The details of the backup to be restored.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// This is the Task Response for all Async Calls
/// </returns>
public async Task<TaskResponse> BeginRestoringAsync(string deviceId, RestoreBackupRequest backupDetailsForRestore, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (deviceId == null)
{
throw new ArgumentNullException("deviceId");
}
if (backupDetailsForRestore == null)
{
throw new ArgumentNullException("backupDetailsForRestore");
}
if (backupDetailsForRestore.BackupSetId == null)
{
throw new ArgumentNullException("backupDetailsForRestore.BackupSetId");
}
if (customRequestHeaders == null)
{
throw new ArgumentNullException("customRequestHeaders");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceId", deviceId);
tracingParameters.Add("backupDetailsForRestore", backupDetailsForRestore);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "BeginRestoringAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/~/";
url = url + "CisVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/api/devices/";
url = url + Uri.EscapeDataString(deviceId);
url = url + "/backups";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-01-01.1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2014-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement restoreBackupRequestElement = new XElement(XName.Get("RestoreBackupRequest", "http://windowscloudbackup.com/CiS/V2013_03"));
requestDoc.Add(restoreBackupRequestElement);
XElement backupSetIdElement = new XElement(XName.Get("BackupSetId", "http://windowscloudbackup.com/CiS/V2013_03"));
backupSetIdElement.Value = backupDetailsForRestore.BackupSetId;
restoreBackupRequestElement.Add(backupSetIdElement);
if (backupDetailsForRestore.SnapshotId != null)
{
XElement snapshotIdElement = new XElement(XName.Get("SnapshotId", "http://windowscloudbackup.com/CiS/V2013_03"));
snapshotIdElement.Value = backupDetailsForRestore.SnapshotId;
restoreBackupRequestElement.Add(snapshotIdElement);
}
else
{
XElement emptyElement = new XElement(XName.Get("SnapshotId", "http://windowscloudbackup.com/CiS/V2013_03"));
XAttribute nilAttribute = new XAttribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"), "");
nilAttribute.Value = "true";
emptyElement.Add(nilAttribute);
restoreBackupRequestElement.Add(emptyElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TaskResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TaskResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/"));
if (stringElement != null)
{
string stringInstance = stringElement.Value;
result.TaskId = stringInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <param name='deviceId'>
/// Required. The device id for which the call will be made.
/// </param>
/// <param name='policyId'>
/// Required. The policy id for which the call will be made.
/// </param>
/// <param name='backupRequest'>
/// Required. Parameters supplied to the Begin Backup operation.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Info about the async task
/// </returns>
public async Task<TaskStatusInfo> CreateAsync(string deviceId, string policyId, BackupNowRequest backupRequest, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
StorSimpleManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceId", deviceId);
tracingParameters.Add("policyId", policyId);
tracingParameters.Add("backupRequest", backupRequest);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
TaskResponse response = await client.Backup.BeginCreatingBackupAsync(deviceId, policyId, backupRequest, customRequestHeaders, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
TaskStatusInfo result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 5;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 5;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <param name='deviceId'>
/// Required. The device id for which the call will be made.
/// </param>
/// <param name='backupSetId'>
/// Required. The backup set ID to delete.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Info about the async task
/// </returns>
public async Task<TaskStatusInfo> DeleteAsync(string deviceId, string backupSetId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
StorSimpleManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceId", deviceId);
tracingParameters.Add("backupSetId", backupSetId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
TaskResponse response = await client.Backup.BeginDeletingAsync(deviceId, backupSetId, customRequestHeaders, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
TaskStatusInfo result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 5;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 5;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <param name='deviceId'>
/// Required. The device id for which the call will be made.
/// </param>
/// <param name='filterType'>
/// Optional. If isAllSelected = true, then specify Volume or
/// BackupPolicy here
/// </param>
/// <param name='isAllSelected'>
/// Required. To retrieve Volume or BackupPolicy or both
/// </param>
/// <param name='filterValue'>
/// Optional. If isAllSelected = true then specify VolumeId or
/// BackupPolicy here
/// </param>
/// <param name='startTime'>
/// Optional. StartTime for filtering BackupSets
/// </param>
/// <param name='endTime'>
/// Optional. EndTime for filtering BackupSets
/// </param>
/// <param name='skip'>
/// Optional. Number of elements to be skipped as part of pagination
/// </param>
/// <param name='top'>
/// Optional. Number of elements to retrieve in the current page
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list of BackupSets.
/// </returns>
public async Task<GetBackupResponse> GetAsync(string deviceId, string filterType, string isAllSelected, string filterValue, string startTime, string endTime, string skip, string top, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (deviceId == null)
{
throw new ArgumentNullException("deviceId");
}
if (isAllSelected == null)
{
throw new ArgumentNullException("isAllSelected");
}
if (customRequestHeaders == null)
{
throw new ArgumentNullException("customRequestHeaders");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceId", deviceId);
tracingParameters.Add("filterType", filterType);
tracingParameters.Add("isAllSelected", isAllSelected);
tracingParameters.Add("filterValue", filterValue);
tracingParameters.Add("startTime", startTime);
tracingParameters.Add("endTime", endTime);
tracingParameters.Add("skip", skip);
tracingParameters.Add("top", top);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/~/";
url = url + "CisVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/api/devices/";
url = url + Uri.EscapeDataString(deviceId);
url = url + "/backups";
List<string> queryParameters = new List<string>();
if (filterType != null)
{
queryParameters.Add("filterType=" + Uri.EscapeDataString(filterType));
}
queryParameters.Add("isAllSelected=" + Uri.EscapeDataString(isAllSelected));
if (filterValue != null)
{
queryParameters.Add("filterValue=" + Uri.EscapeDataString(filterValue));
}
if (startTime != null)
{
queryParameters.Add("startTime=" + Uri.EscapeDataString(startTime));
}
if (endTime != null)
{
queryParameters.Add("endTime=" + Uri.EscapeDataString(endTime));
}
if (skip != null)
{
queryParameters.Add("skip=" + Uri.EscapeDataString(skip));
}
if (top != null)
{
queryParameters.Add("top=" + Uri.EscapeDataString(top));
}
queryParameters.Add("api-version=2014-01-01.1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2014-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GetBackupResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GetBackupResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement backupSetsQueryResultV2Element = responseDoc.Element(XName.Get("BackupSetsQueryResult_V2", "http://windowscloudbackup.com/CiS/V2013_03"));
if (backupSetsQueryResultV2Element != null)
{
XElement backupSetsListSequenceElement = backupSetsQueryResultV2Element.Element(XName.Get("BackupSetsList", "http://windowscloudbackup.com/CiS/V2013_03"));
if (backupSetsListSequenceElement != null)
{
foreach (XElement backupSetsListElement in backupSetsListSequenceElement.Elements(XName.Get("BackupSetInfo", "http://windowscloudbackup.com/CiS/V2013_03")))
{
Backup backupSetInfoInstance = new Backup();
result.BackupSetsList.Add(backupSetInfoInstance);
XElement backupJobCreationTypeElement = backupSetsListElement.Element(XName.Get("BackupJobCreationType", "http://windowscloudbackup.com/CiS/V2013_03"));
if (backupJobCreationTypeElement != null)
{
BackupJobCreationType backupJobCreationTypeInstance = ((BackupJobCreationType)Enum.Parse(typeof(BackupJobCreationType), backupJobCreationTypeElement.Value, true));
backupSetInfoInstance.BackupJobCreationType = backupJobCreationTypeInstance;
}
XElement createdOnElement = backupSetsListElement.Element(XName.Get("CreatedOn", "http://windowscloudbackup.com/CiS/V2013_03"));
if (createdOnElement != null)
{
DateTime createdOnInstance = DateTime.Parse(createdOnElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
backupSetInfoInstance.CreatedOn = createdOnInstance;
}
XElement sSMHostNameElement = backupSetsListElement.Element(XName.Get("SSMHostName", "http://windowscloudbackup.com/CiS/V2013_03"));
if (sSMHostNameElement != null)
{
string sSMHostNameInstance = sSMHostNameElement.Value;
backupSetInfoInstance.SSMHostName = sSMHostNameInstance;
}
XElement sizeInBytesElement = backupSetsListElement.Element(XName.Get("SizeInBytes", "http://windowscloudbackup.com/CiS/V2013_03"));
if (sizeInBytesElement != null)
{
long sizeInBytesInstance = long.Parse(sizeInBytesElement.Value, CultureInfo.InvariantCulture);
backupSetInfoInstance.SizeInBytes = sizeInBytesInstance;
}
XElement snapshotsSequenceElement = backupSetsListElement.Element(XName.Get("Snapshots", "http://windowscloudbackup.com/CiS/V2013_03"));
if (snapshotsSequenceElement != null)
{
foreach (XElement snapshotsElement in snapshotsSequenceElement.Elements(XName.Get("Snapshot", "http://windowscloudbackup.com/CiS/V2013_03")))
{
Snapshot snapshotInstance = new Snapshot();
backupSetInfoInstance.Snapshots.Add(snapshotInstance);
XElement dataContainerIdElement = snapshotsElement.Element(XName.Get("DataContainerId", "http://windowscloudbackup.com/CiS/V2013_03"));
if (dataContainerIdElement != null)
{
string dataContainerIdInstance = dataContainerIdElement.Value;
snapshotInstance.DataContainerId = dataContainerIdInstance;
}
XElement idElement = snapshotsElement.Element(XName.Get("Id", "http://windowscloudbackup.com/CiS/V2013_03"));
if (idElement != null)
{
string idInstance = idElement.Value;
snapshotInstance.Id = idInstance;
}
XElement nameElement = snapshotsElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
snapshotInstance.Name = nameInstance;
}
XElement sizeInBytesElement2 = snapshotsElement.Element(XName.Get("SizeInBytes", "http://windowscloudbackup.com/CiS/V2013_03"));
if (sizeInBytesElement2 != null)
{
long sizeInBytesInstance2 = long.Parse(sizeInBytesElement2.Value, CultureInfo.InvariantCulture);
snapshotInstance.SizeInBytes = sizeInBytesInstance2;
}
XElement volumeIdElement = snapshotsElement.Element(XName.Get("VolumeId", "http://windowscloudbackup.com/CiS/V2013_03"));
if (volumeIdElement != null)
{
string volumeIdInstance = volumeIdElement.Value;
snapshotInstance.VolumeId = volumeIdInstance;
}
}
}
XElement typeElement = backupSetsListElement.Element(XName.Get("Type", "http://windowscloudbackup.com/CiS/V2013_03"));
if (typeElement != null)
{
BackupType typeInstance = ((BackupType)Enum.Parse(typeof(BackupType), typeElement.Value, true));
backupSetInfoInstance.Type = typeInstance;
}
XElement nameElement2 = backupSetsListElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03"));
if (nameElement2 != null)
{
string nameInstance2 = nameElement2.Value;
backupSetInfoInstance.Name = nameInstance2;
}
XElement instanceIdElement = backupSetsListElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03"));
if (instanceIdElement != null)
{
string instanceIdInstance = instanceIdElement.Value;
backupSetInfoInstance.InstanceId = instanceIdInstance;
}
XElement operationInProgressElement = backupSetsListElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03"));
if (operationInProgressElement != null)
{
OperationInProgress operationInProgressInstance = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement.Value, true));
backupSetInfoInstance.OperationInProgress = operationInProgressInstance;
}
}
}
XElement totalBackupSetCountElement = backupSetsQueryResultV2Element.Element(XName.Get("TotalBackupSetCount", "http://windowscloudbackup.com/CiS/V2013_03"));
if (totalBackupSetCountElement != null)
{
long totalBackupSetCountInstance = long.Parse(totalBackupSetCountElement.Value, CultureInfo.InvariantCulture);
result.TotalBackupCount = totalBackupSetCountInstance;
}
XElement nextPageStartIdentifierElement = backupSetsQueryResultV2Element.Element(XName.Get("NextPageStartIdentifier", "http://windowscloudbackup.com/CiS/V2013_03"));
if (nextPageStartIdentifierElement != null)
{
string nextPageStartIdentifierInstance = nextPageStartIdentifierElement.Value;
result.NextPageStartIdentifier = nextPageStartIdentifierInstance;
}
XElement nextPageUriElement = backupSetsQueryResultV2Element.Element(XName.Get("NextPageUri", "http://windowscloudbackup.com/CiS/V2013_03"));
if (nextPageUriElement != null)
{
Uri nextPageUriInstance = TypeConversion.TryParseUri(nextPageUriElement.Value);
result.NextPageUri = nextPageUriInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Restore a backup set.
/// </summary>
/// <param name='deviceId'>
/// Required. The device id for which the call will be made.
/// </param>
/// <param name='backupDetailsForRestore'>
/// Required. The details of the backup to be restored.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Info about the async task
/// </returns>
public async Task<TaskStatusInfo> RestoreAsync(string deviceId, RestoreBackupRequest backupDetailsForRestore, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
StorSimpleManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceId", deviceId);
tracingParameters.Add("backupDetailsForRestore", backupDetailsForRestore);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "RestoreAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
TaskResponse response = await client.Backup.BeginRestoringAsync(deviceId, backupDetailsForRestore, customRequestHeaders, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
TaskStatusInfo result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 5;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 5;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System.DirectoryServices.AccountManagement
{
internal class PrincipalCollectionEnumerator : IEnumerator<Principal>, IEnumerator
{
//
// Public properties
//
public Principal Current
{
get
{
CheckDisposed();
// Since MoveNext() saved off the current value for us, this is largely trivial.
if (_endReached == true || _currentMode == CurrentEnumeratorMode.None)
{
// Either we're at the end or before the beginning
// (CurrentEnumeratorMode.None implies we're _before_ the first value)
GlobalDebug.WriteLineIf(
GlobalDebug.Warn,
"PrincipalCollectionEnumerator",
"Current: bad position, endReached={0}, currentMode={1}",
_endReached,
_currentMode);
throw new InvalidOperationException(SR.PrincipalCollectionEnumInvalidPos);
}
Debug.Assert(_current != null);
return _current;
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
//
// Public methods
//
public bool MoveNext()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "Entering MoveNext");
CheckDisposed();
CheckChanged();
// We previously reached the end, nothing more to do
if (_endReached)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: endReached");
return false;
}
lock (_resultSet)
{
if (_currentMode == CurrentEnumeratorMode.None)
{
// At the very beginning
// In case this ResultSet was previously used with another PrincipalCollectionEnumerator instance
// (e.g., two foreach loops in a row)
_resultSet.Reset();
if (!_memberCollection.Cleared && !_memberCollection.ClearCompleted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: None mode, starting with existing values");
// Start by enumerating the existing values in the store
_currentMode = CurrentEnumeratorMode.ResultSet;
_enumerator = null;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: None mode, skipping existing values");
// The member collection was cleared. Skip the ResultSet phase
_currentMode = CurrentEnumeratorMode.InsertedValuesCompleted;
_enumerator = (IEnumerator<Principal>)_insertedValuesCompleted.GetEnumerator();
}
}
Debug.Assert(_resultSet != null);
if (_currentMode == CurrentEnumeratorMode.ResultSet)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: ResultSet mode");
bool needToRepeat = false;
do
{
bool f = _resultSet.MoveNext();
if (f)
{
Principal principal = (Principal)_resultSet.CurrentAsPrincipal;
if (_removedValuesCompleted.Contains(principal) || _removedValuesPending.Contains(principal))
{
// It's a value that's been removed (either a pending remove that hasn't completed, or a remove
// that completed _after_ we loaded the ResultSet from the store).
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: ResultSet mode, found remove, skipping");
needToRepeat = true;
continue;
}
else if (_insertedValuesCompleted.Contains(principal) || _insertedValuesPending.Contains(principal))
{
// insertedValuesCompleted: We must have gotten the ResultSet after the inserted committed.
// We don't want to return
// the principal twice, so we'll skip it here and later return it in
// the CurrentEnumeratorMode.InsertedValuesCompleted mode.
//
// insertedValuesPending: The principal must have been originally in the ResultSet, but then
// removed, saved, and re-added, with the re-add still pending.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: ResultSet mode, found insert, skipping");
needToRepeat = true;
continue;
}
else
{
needToRepeat = false;
_current = principal;
return true;
}
}
else
{
// No more values left to retrieve. Now try the insertedValuesCompleted list.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: ResultSet mode, moving to InsValuesComp mode");
_currentMode = CurrentEnumeratorMode.InsertedValuesCompleted;
_enumerator = (IEnumerator<Principal>)_insertedValuesCompleted.GetEnumerator();
needToRepeat = false;
}
}
while (needToRepeat);
}
// These are values whose insertion has completed, but after we already loaded the ResultSet from the store.
if (_currentMode == CurrentEnumeratorMode.InsertedValuesCompleted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: InsValuesComp mode");
bool f = _enumerator.MoveNext();
if (f)
{
_current = _enumerator.Current;
return true;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: InsValuesComp mode, moving to InsValuesPend mode");
_currentMode = CurrentEnumeratorMode.InsertedValuesPending;
_enumerator = (IEnumerator<Principal>)_insertedValuesPending.GetEnumerator();
}
}
// These are values whose insertion has not yet been committed to the store.
if (_currentMode == CurrentEnumeratorMode.InsertedValuesPending)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: InsValuesPend mode");
bool f = _enumerator.MoveNext();
if (f)
{
_current = _enumerator.Current;
return true;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "MoveNext: InsValuesPend mode, nothing left");
_endReached = true;
return false;
}
}
}
Debug.Fail(string.Format(CultureInfo.CurrentCulture, "PrincipalCollectionEnumerator.MoveNext: fell off end of function, mode = {0}", _currentMode.ToString()));
return false;
}
bool IEnumerator.MoveNext()
{
return MoveNext();
}
public void Reset()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "Reset");
CheckDisposed();
CheckChanged();
// Set us up to start enumerating from the very beginning again
_endReached = false;
_enumerator = null;
_currentMode = CurrentEnumeratorMode.None;
}
void IEnumerator.Reset()
{
Reset();
}
public void Dispose() // IEnumerator<Principal> inherits from IDisposable
{
_disposed = true;
}
//
// Internal constructors
//
internal PrincipalCollectionEnumerator(
ResultSet resultSet,
PrincipalCollection memberCollection,
List<Principal> removedValuesCompleted,
List<Principal> removedValuesPending,
List<Principal> insertedValuesCompleted,
List<Principal> insertedValuesPending
)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollectionEnumerator", "Ctor");
Debug.Assert(resultSet != null);
_resultSet = resultSet;
_memberCollection = memberCollection;
_removedValuesCompleted = removedValuesCompleted;
_removedValuesPending = removedValuesPending;
_insertedValuesCompleted = insertedValuesCompleted;
_insertedValuesPending = insertedValuesPending;
}
//
// Private implementation
//
private Principal _current;
// Remember: these are references to objects held by the PrincipalCollection class from which we came.
// We don't own these, and shouldn't Dispose the ResultSet.
//
// SYNCHRONIZATION
// Access to:
// resultSet
// must be synchronized, since multiple enumerators could be iterating over us at once.
// Synchronize by locking on resultSet.
private ResultSet _resultSet;
private List<Principal> _insertedValuesPending;
private List<Principal> _insertedValuesCompleted;
private List<Principal> _removedValuesPending;
private List<Principal> _removedValuesCompleted;
private bool _endReached = false; // true if there are no results left to iterate over
private IEnumerator<Principal> _enumerator = null; // The insertedValues{Completed,Pending} enumerator, used by MoveNext
private enum CurrentEnumeratorMode // The set of values that MoveNext is currently iterating over
{
None,
ResultSet,
InsertedValuesCompleted,
InsertedValuesPending
}
private CurrentEnumeratorMode _currentMode = CurrentEnumeratorMode.None;
// To support IDisposable
private bool _disposed = false;
private void CheckDisposed()
{
if (_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollectionEnumerator", "CheckDisposed: accessing disposed object");
throw new ObjectDisposedException("PrincipalCollectionEnumerator");
}
}
// When this enumerator was constructed, to detect changes made to the PrincipalCollection after it was constructed
private DateTime _creationTime = DateTime.UtcNow;
private PrincipalCollection _memberCollection = null;
private void CheckChanged()
{
// Make sure the app hasn't changed our underlying list
if (_memberCollection.LastChange > _creationTime)
{
GlobalDebug.WriteLineIf(
GlobalDebug.Warn,
"PrincipalCollectionEnumerator",
"CheckChanged: has changed (last change={0}, creation={1})",
_memberCollection.LastChange,
_creationTime);
throw new InvalidOperationException(SR.PrincipalCollectionEnumHasChanged);
}
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Zeus;
using Zeus.UserInterface;
using Zeus.UserInterface.WinForms;
using MyMeta;
namespace MyGeneration
{
/// <summary>
/// Summary description for WebTemplateLibrary.
/// </summary>
public class WebTemplateLibrary : Form
{
private const int INDEX_TEMPLATE = 6;
private const int INDEX_CLOSED_FOLDER = 3;
private const int INDEX_OPEN_FOLDER = 4;
private System.Windows.Forms.ToolBar toolBarToolbar;
private System.Windows.Forms.ToolBarButton toolBarSeparator2;
private System.Windows.Forms.ImageList imageListFormIcons;
private System.Windows.Forms.TreeView treeViewTemplates;
private System.Windows.Forms.ToolBarButton toolBarButtonRefresh;
private System.Windows.Forms.ToolTip toolTipTemplateBrowser;
private System.Windows.Forms.ContextMenu contextMenuTree;
private System.Windows.Forms.MenuItem menuItemOpen;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.ToolBarButton toolBarButtonSaveLocal;
private System.Windows.Forms.MenuItem menuItemSave;
private System.Windows.Forms.ToolBarButton toolBarButtonView;
private TemplateTreeBuilder treeBuilder;
private Hashtable existingTemplates;
private ArrayList updatedTemplateIDs;
public WebTemplateLibrary(Hashtable existingTemplates)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.existingTemplates = existingTemplates;
treeViewTemplates.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeViewTemplates_MouseDown);
treeViewTemplates.DoubleClick += new System.EventHandler(this.treeViewTemplates_OnDoubleClick);
treeViewTemplates.AfterExpand += new TreeViewEventHandler(this.treeViewTemplates_AfterExpand);
treeViewTemplates.AfterCollapse += new TreeViewEventHandler(this.treeViewTemplates_AfterCollapse);
treeViewTemplates.KeyDown += new KeyEventHandler(this.treeViewTemplates_KeyDown);
treeViewTemplates.MouseMove += new MouseEventHandler(treeViewTemplates_MouseMove);
treeBuilder = new TemplateTreeBuilder(treeViewTemplates);
treeBuilder.LoadTemplatesFromWeb();
}
public ArrayList UpdatedTemplateIDs
{
get
{
if (updatedTemplateIDs == null) updatedTemplateIDs = new ArrayList();
return updatedTemplateIDs;
}
}
private void View()
{
TemplateTreeNode node = this.treeViewTemplates.SelectedNode as TemplateTreeNode;
if (node != null)
{
try
{
Program.LaunchBrowser(node.Url);
}
catch
{
Help.ShowHelp(this, node.Url);
}
}
}
private void Save()
{
TreeNode node = this.treeViewTemplates.SelectedNode as TreeNode;
if(node != null)
{
if (node.Parent == null)
{
MessageBox.Show("Cannot Save from the Root Level", "Not Allowed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
Cursor.Current = Cursors.WaitCursor;
Save(node, false);
Cursor.Current = Cursors.Default;
}
}
}
private void Save(TreeNode node, bool isGrouped)
{
if ( node is TemplateTreeNode )
{
TemplateTreeNode tnode = node as TemplateTreeNode;
string path = tnode.Tag.ToString();
string id = tnode.UniqueId.ToUpper();
if (this.existingTemplates.Contains( tnode.UniqueId.ToUpper() ))
{
path = existingTemplates[id].ToString();
}
if (!UpdatedTemplateIDs.Contains(tnode.UniqueId))
{
UpdatedTemplateIDs.Add(tnode.UniqueId);
}
TemplateWebUpdateHelper.WebUpdate(tnode.UniqueId, path, isGrouped);
}
else if (node != null)
{
foreach (TreeNode child in node.Nodes)
{
Save(child, true);
}
}
}
public void RefreshTree()
{
treeBuilder.Clear();
this.treeBuilder.LoadTemplatesFromWeb();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
private void treeViewTemplates_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
if (e.Node is FolderTreeNode)
{
e.Node.SelectedImageIndex = INDEX_OPEN_FOLDER;
e.Node.ImageIndex = INDEX_OPEN_FOLDER;
}
}
private void treeViewTemplates_AfterCollapse(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
if (e.Node is FolderTreeNode)
{
e.Node.SelectedImageIndex = INDEX_CLOSED_FOLDER;
e.Node.ImageIndex = INDEX_CLOSED_FOLDER;
}
}
private void treeViewTemplates_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
TreeNode node = (TreeNode)treeViewTemplates.GetNodeAt(e.X, e.Y);
treeViewTemplates.SelectedNode = node;
}
private void treeViewTemplates_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F5)
{
this.treeBuilder.Clear();
this.treeBuilder.LoadTemplatesFromWeb();
return;
}
}
private void treeViewTemplates_OnDoubleClick(object sender, System.EventArgs e)
{
View();
}
private void treeViewTemplates_MouseMove(object sender, MouseEventArgs e)
{
object obj = treeViewTemplates.GetNodeAt(e.X, e.Y);
if (obj is TemplateTreeNode)
{
this.toolTipTemplateBrowser.SetToolTip(treeViewTemplates, string.Empty);
}
else if ((obj is RootTreeNode) && (DateTime.Now.Hour == 1))
{
this.toolTipTemplateBrowser.SetToolTip(treeViewTemplates, "Worship me as I generate your code.");
}
else
{
this.toolTipTemplateBrowser.SetToolTip(treeViewTemplates, string.Empty);
}
}
private void toolBarToolbar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
if (e.Button == this.toolBarButtonRefresh)
{
this.RefreshTree();
}
else if (e.Button == this.toolBarButtonView)
{
this.View();
}
else if (e.Button == this.toolBarButtonSaveLocal)
{
this.Save();
}
}
private void contextMenuTree_Popup(object sender, System.EventArgs e)
{
System.Drawing.Point point = this.treeViewTemplates.PointToClient(Cursor.Position);
object node = this.treeViewTemplates.GetNodeAt(point.X, point.Y);
if (node is TemplateTreeNode)
{
foreach (MenuItem item in contextMenuTree.MenuItems) item.Visible = true;
}
else if (node is FolderTreeNode)
{
this.menuItemOpen.Visible = false;
this.menuItemSave.Visible = true;
}
else if (node is RootTreeNode)
{
this.menuItemOpen.Visible = false;
this.menuItemSave.Visible = false;
}
else
{
foreach (MenuItem item in contextMenuTree.MenuItems) item.Visible = false;
}
}
private void TemplateBrowser_MouseLeave(object sender, System.EventArgs e)
{
this.toolTipTemplateBrowser.SetToolTip(treeViewTemplates, string.Empty);
}
private void menuItemSave_Click(object sender, System.EventArgs e)
{
this.Save();
}
private void menuItemView_Click(object sender, System.EventArgs e)
{
this.View();
}
#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(WebTemplateLibrary));
this.toolBarToolbar = new System.Windows.Forms.ToolBar();
this.toolBarButtonRefresh = new System.Windows.Forms.ToolBarButton();
this.toolBarSeparator2 = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonView = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonSaveLocal = new System.Windows.Forms.ToolBarButton();
this.imageListFormIcons = new System.Windows.Forms.ImageList(this.components);
this.treeViewTemplates = new System.Windows.Forms.TreeView();
this.contextMenuTree = new System.Windows.Forms.ContextMenu();
this.menuItemOpen = new System.Windows.Forms.MenuItem();
this.menuItemSave = new System.Windows.Forms.MenuItem();
this.toolTipTemplateBrowser = new System.Windows.Forms.ToolTip(this.components);
this.SuspendLayout();
//
// toolBarToolbar
//
this.toolBarToolbar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBarToolbar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.toolBarButtonRefresh,
this.toolBarSeparator2,
this.toolBarButtonView,
this.toolBarButtonSaveLocal});
this.toolBarToolbar.DropDownArrows = true;
this.toolBarToolbar.ImageList = this.imageListFormIcons;
this.toolBarToolbar.Location = new System.Drawing.Point(0, 0);
this.toolBarToolbar.Name = "toolBarToolbar";
this.toolBarToolbar.ShowToolTips = true;
this.toolBarToolbar.Size = new System.Drawing.Size(464, 28);
this.toolBarToolbar.TabIndex = 0;
this.toolBarToolbar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBarToolbar_ButtonClick);
//
// toolBarButtonRefresh
//
this.toolBarButtonRefresh.ImageIndex = 2;
this.toolBarButtonRefresh.Name = "toolBarButtonRefresh";
this.toolBarButtonRefresh.ToolTipText = "Refresh Template Browser";
//
// toolBarSeparator2
//
this.toolBarSeparator2.Name = "toolBarSeparator2";
this.toolBarSeparator2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// toolBarButtonView
//
this.toolBarButtonView.ImageIndex = 7;
this.toolBarButtonView.Name = "toolBarButtonView";
this.toolBarButtonView.ToolTipText = "View Template Information";
//
// toolBarButtonSaveLocal
//
this.toolBarButtonSaveLocal.ImageIndex = 10;
this.toolBarButtonSaveLocal.Name = "toolBarButtonSaveLocal";
this.toolBarButtonSaveLocal.ToolTipText = "Save template to the local hard drive.";
//
// imageListFormIcons
//
this.imageListFormIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListFormIcons.ImageStream")));
this.imageListFormIcons.TransparentColor = System.Drawing.Color.Fuchsia;
this.imageListFormIcons.Images.SetKeyName(0, "");
this.imageListFormIcons.Images.SetKeyName(1, "");
this.imageListFormIcons.Images.SetKeyName(2, "");
this.imageListFormIcons.Images.SetKeyName(3, "");
this.imageListFormIcons.Images.SetKeyName(4, "");
this.imageListFormIcons.Images.SetKeyName(5, "");
this.imageListFormIcons.Images.SetKeyName(6, "");
this.imageListFormIcons.Images.SetKeyName(7, "");
this.imageListFormIcons.Images.SetKeyName(8, "");
this.imageListFormIcons.Images.SetKeyName(9, "");
this.imageListFormIcons.Images.SetKeyName(10, "");
this.imageListFormIcons.Images.SetKeyName(11, "icon_template_locked.bmp");
//
// treeViewTemplates
//
this.treeViewTemplates.ContextMenu = this.contextMenuTree;
this.treeViewTemplates.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeViewTemplates.ImageIndex = 0;
this.treeViewTemplates.ImageList = this.imageListFormIcons;
this.treeViewTemplates.Location = new System.Drawing.Point(0, 28);
this.treeViewTemplates.Name = "treeViewTemplates";
this.treeViewTemplates.SelectedImageIndex = 0;
this.treeViewTemplates.Size = new System.Drawing.Size(464, 338);
this.treeViewTemplates.TabIndex = 1;
//
// contextMenuTree
//
this.contextMenuTree.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemOpen,
this.menuItemSave});
this.contextMenuTree.Popup += new System.EventHandler(this.contextMenuTree_Popup);
//
// menuItemOpen
//
this.menuItemOpen.Index = 0;
this.menuItemOpen.Text = "&View";
this.menuItemOpen.Click += new System.EventHandler(this.menuItemView_Click);
//
// menuItemSave
//
this.menuItemSave.Index = 1;
this.menuItemSave.Text = "&Save";
this.menuItemSave.Click += new System.EventHandler(this.menuItemSave_Click);
//
// WebTemplateLibrary
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(464, 366);
this.Controls.Add(this.treeViewTemplates);
this.Controls.Add(this.toolBarToolbar);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "WebTemplateLibrary";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Online Template Library";
this.MouseLeave += new System.EventHandler(this.TemplateBrowser_MouseLeave);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose:
**
**
===========================================================*/
namespace System
{
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using CultureInfo = System.Globalization.CultureInfo;
using NumberStyles = System.Globalization.NumberStyles;
// A Version object contains four hierarchical numeric components: major, minor,
// build and revision. Build and revision may be unspecified, which is represented
// internally as a -1. By definition, an unspecified component matches anything
// (both unspecified and specified), and an unspecified component is "less than" any
// specified component.
[Serializable]
public sealed class Version : ICloneable, IComparable
, IComparable<Version>, IEquatable<Version>
{
// AssemblyName depends on the order staying the same
private readonly int _Major;
private readonly int _Minor;
private readonly int _Build = -1;
private readonly int _Revision = -1;
public Version(int major, int minor, int build, int revision)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (revision < 0)
throw new ArgumentOutOfRangeException(nameof(revision), Environment.GetResourceString("ArgumentOutOfRange_Version"));
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
_Build = build;
_Revision = revision;
}
public Version(int major, int minor, int build)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), Environment.GetResourceString("ArgumentOutOfRange_Version"));
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
_Build = build;
}
public Version(int major, int minor)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), Environment.GetResourceString("ArgumentOutOfRange_Version"));
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), Environment.GetResourceString("ArgumentOutOfRange_Version"));
Contract.EndContractBlock();
_Major = major;
_Minor = minor;
}
public Version(String version)
{
Version v = Version.Parse(version);
_Major = v.Major;
_Minor = v.Minor;
_Build = v.Build;
_Revision = v.Revision;
}
public Version()
{
_Major = 0;
_Minor = 0;
}
private Version(Version version)
{
Debug.Assert(version != null);
_Major = version._Major;
_Minor = version._Minor;
_Build = version._Build;
_Revision = version._Revision;
}
// Properties for setting and getting version numbers
public int Major
{
get { return _Major; }
}
public int Minor
{
get { return _Minor; }
}
public int Build
{
get { return _Build; }
}
public int Revision
{
get { return _Revision; }
}
public short MajorRevision
{
get { return (short)(_Revision >> 16); }
}
public short MinorRevision
{
get { return (short)(_Revision & 0xFFFF); }
}
public Object Clone()
{
return new Version(this);
}
public int CompareTo(Object version)
{
if (version == null)
{
return 1;
}
Version v = version as Version;
if (v == null)
{
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeVersion"));
}
return CompareTo(v);
}
public int CompareTo(Version value)
{
return
object.ReferenceEquals(value, this) ? 0 :
object.ReferenceEquals(value, null) ? 1 :
_Major != value._Major ? (_Major > value._Major ? 1 : -1) :
_Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) :
_Build != value._Build ? (_Build > value._Build ? 1 : -1) :
_Revision != value._Revision ? (_Revision > value._Revision ? 1 : -1) :
0;
}
public override bool Equals(Object obj)
{
return Equals(obj as Version);
}
public bool Equals(Version obj)
{
return object.ReferenceEquals(obj, this) ||
(!object.ReferenceEquals(obj, null) &&
_Major == obj._Major &&
_Minor == obj._Minor &&
_Build == obj._Build &&
_Revision == obj._Revision);
}
public override int GetHashCode()
{
// Let's assume that most version numbers will be pretty small and just
// OR some lower order bits together.
int accumulator = 0;
accumulator |= (_Major & 0x0000000F) << 28;
accumulator |= (_Minor & 0x000000FF) << 20;
accumulator |= (_Build & 0x000000FF) << 12;
accumulator |= (_Revision & 0x00000FFF);
return accumulator;
}
public override String ToString()
{
if (_Build == -1) return (ToString(2));
if (_Revision == -1) return (ToString(3));
return (ToString(4));
}
public String ToString(int fieldCount)
{
StringBuilder sb;
switch (fieldCount)
{
case 0:
return (String.Empty);
case 1:
return (_Major.ToString());
case 2:
sb = StringBuilderCache.Acquire();
AppendPositiveNumber(_Major, sb);
sb.Append('.');
AppendPositiveNumber(_Minor, sb);
return StringBuilderCache.GetStringAndRelease(sb);
default:
if (_Build == -1)
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "2"), nameof(fieldCount));
if (fieldCount == 3)
{
sb = StringBuilderCache.Acquire();
AppendPositiveNumber(_Major, sb);
sb.Append('.');
AppendPositiveNumber(_Minor, sb);
sb.Append('.');
AppendPositiveNumber(_Build, sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
if (_Revision == -1)
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "3"), nameof(fieldCount));
if (fieldCount == 4)
{
sb = StringBuilderCache.Acquire();
AppendPositiveNumber(_Major, sb);
sb.Append('.');
AppendPositiveNumber(_Minor, sb);
sb.Append('.');
AppendPositiveNumber(_Build, sb);
sb.Append('.');
AppendPositiveNumber(_Revision, sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "4"), nameof(fieldCount));
}
}
//
// AppendPositiveNumber is an optimization to append a number to a StringBuilder object without
// doing any boxing and not even creating intermediate string.
// Note: as we always have positive numbers then it is safe to convert the number to string
// regardless of the current culture as we'll not have any punctuation marks in the number
//
private const int ZERO_CHAR_VALUE = (int)'0';
private static void AppendPositiveNumber(int num, StringBuilder sb)
{
Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
int index = sb.Length;
int reminder;
do
{
reminder = num % 10;
num = num / 10;
sb.Insert(index, (char)(ZERO_CHAR_VALUE + reminder));
} while (num > 0);
}
public static Version Parse(string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Contract.EndContractBlock();
VersionResult r = new VersionResult();
r.Init(nameof(input), true);
if (!TryParseVersion(input, ref r))
{
throw r.GetVersionParseException();
}
return r.m_parsedVersion;
}
public static bool TryParse(string input, out Version result)
{
VersionResult r = new VersionResult();
r.Init(nameof(input), false);
bool b = TryParseVersion(input, ref r);
result = r.m_parsedVersion;
return b;
}
private static bool TryParseVersion(string version, ref VersionResult result)
{
int major, minor, build, revision;
if ((Object)version == null)
{
result.SetFailure(ParseFailureKind.ArgumentNullException);
return false;
}
String[] parsedComponents = version.Split('.');
int parsedComponentsLength = parsedComponents.Length;
if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4))
{
result.SetFailure(ParseFailureKind.ArgumentException);
return false;
}
if (!TryParseComponent(parsedComponents[0], nameof(version), ref result, out major))
{
return false;
}
if (!TryParseComponent(parsedComponents[1], nameof(version), ref result, out minor))
{
return false;
}
parsedComponentsLength -= 2;
if (parsedComponentsLength > 0)
{
if (!TryParseComponent(parsedComponents[2], "build", ref result, out build))
{
return false;
}
parsedComponentsLength--;
if (parsedComponentsLength > 0)
{
if (!TryParseComponent(parsedComponents[3], "revision", ref result, out revision))
{
return false;
}
else
{
result.m_parsedVersion = new Version(major, minor, build, revision);
}
}
else
{
result.m_parsedVersion = new Version(major, minor, build);
}
}
else
{
result.m_parsedVersion = new Version(major, minor);
}
return true;
}
private static bool TryParseComponent(string component, string componentName, ref VersionResult result, out int parsedComponent)
{
if (!Int32.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent))
{
result.SetFailure(ParseFailureKind.FormatException, component);
return false;
}
if (parsedComponent < 0)
{
result.SetFailure(ParseFailureKind.ArgumentOutOfRangeException, componentName);
return false;
}
return true;
}
public static bool operator ==(Version v1, Version v2)
{
if (Object.ReferenceEquals(v1, null))
{
return Object.ReferenceEquals(v2, null);
}
return v1.Equals(v2);
}
public static bool operator !=(Version v1, Version v2)
{
return !(v1 == v2);
}
public static bool operator <(Version v1, Version v2)
{
if ((Object)v1 == null)
throw new ArgumentNullException(nameof(v1));
Contract.EndContractBlock();
return (v1.CompareTo(v2) < 0);
}
public static bool operator <=(Version v1, Version v2)
{
if ((Object)v1 == null)
throw new ArgumentNullException(nameof(v1));
Contract.EndContractBlock();
return (v1.CompareTo(v2) <= 0);
}
public static bool operator >(Version v1, Version v2)
{
return (v2 < v1);
}
public static bool operator >=(Version v1, Version v2)
{
return (v2 <= v1);
}
internal enum ParseFailureKind
{
ArgumentNullException,
ArgumentException,
ArgumentOutOfRangeException,
FormatException
}
internal struct VersionResult
{
internal Version m_parsedVersion;
internal ParseFailureKind m_failure;
internal string m_exceptionArgument;
internal string m_argumentName;
internal bool m_canThrow;
internal void Init(string argumentName, bool canThrow)
{
m_canThrow = canThrow;
m_argumentName = argumentName;
}
internal void SetFailure(ParseFailureKind failure)
{
SetFailure(failure, String.Empty);
}
internal void SetFailure(ParseFailureKind failure, string argument)
{
m_failure = failure;
m_exceptionArgument = argument;
if (m_canThrow)
{
throw GetVersionParseException();
}
}
internal Exception GetVersionParseException()
{
switch (m_failure)
{
case ParseFailureKind.ArgumentNullException:
return new ArgumentNullException(m_argumentName);
case ParseFailureKind.ArgumentException:
return new ArgumentException(Environment.GetResourceString("Arg_VersionString"));
case ParseFailureKind.ArgumentOutOfRangeException:
return new ArgumentOutOfRangeException(m_exceptionArgument, Environment.GetResourceString("ArgumentOutOfRange_Version"));
case ParseFailureKind.FormatException:
// Regenerate the FormatException as would be thrown by Int32.Parse()
try
{
Int32.Parse(m_exceptionArgument, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
return e;
}
catch (OverflowException e)
{
return e;
}
Debug.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
return new FormatException(Environment.GetResourceString("Format_InvalidString"));
default:
Debug.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
return new ArgumentException(Environment.GetResourceString("Arg_VersionString"));
}
}
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Discord.API;
using Discord.Rest;
namespace Discord.WebSocket
{
/// <summary>
/// Represents the base of a WebSocket-based Discord client.
/// </summary>
public abstract partial class BaseSocketClient : BaseDiscordClient, IDiscordClient
{
protected readonly DiscordSocketConfig BaseConfig;
/// <summary>
/// Gets the estimated round-trip latency, in milliseconds, to the gateway server.
/// </summary>
/// <returns>
/// An <see cref="int"/> that represents the round-trip latency to the WebSocket server. Please
/// note that this value does not represent a "true" latency for operations such as sending a message.
/// </returns>
public abstract int Latency { get; protected set; }
/// <summary>
/// Gets the status for the logged-in user.
/// </summary>
/// <returns>
/// A status object that represents the user's online presence status.
/// </returns>
public abstract UserStatus Status { get; protected set; }
/// <summary>
/// Gets the activity for the logged-in user.
/// </summary>
/// <returns>
/// An activity object that represents the user's current activity.
/// </returns>
public abstract IActivity Activity { get; protected set; }
/// <summary>
/// Provides access to a REST-only client with a shared state from this client.
/// </summary>
public abstract DiscordSocketRestClient Rest { get; }
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
/// <summary>
/// Gets the current logged-in user.
/// </summary>
public new SocketSelfUser CurrentUser { get => base.CurrentUser as SocketSelfUser; protected set => base.CurrentUser = value; }
/// <summary>
/// Gets a collection of guilds that the user is currently in.
/// </summary>
/// <returns>
/// A read-only collection of guilds that the current user is in.
/// </returns>
public abstract IReadOnlyCollection<SocketGuild> Guilds { get; }
/// <summary>
/// Gets a collection of private channels opened in this session.
/// </summary>
/// <remarks>
/// This method will retrieve all private channels (including direct-message, group channel and such) that
/// are currently opened in this session.
/// <note type="warning">
/// This method will not return previously opened private channels outside of the current session! If
/// you have just started the client, this may return an empty collection.
/// </note>
/// </remarks>
/// <returns>
/// A read-only collection of private channels that the user currently partakes in.
/// </returns>
public abstract IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels { get; }
/// <summary>
/// Gets a collection of available voice regions.
/// </summary>
/// <returns>
/// A read-only collection of voice regions that the user has access to.
/// </returns>
public abstract IReadOnlyCollection<RestVoiceRegion> VoiceRegions { get; }
internal BaseSocketClient(DiscordSocketConfig config, DiscordRestApiClient client)
: base(config, client) => BaseConfig = config;
private static DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config)
=> new DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent,
rateLimitPrecision: config.RateLimitPrecision,
useSystemClock: config.UseSystemClock);
/// <summary>
/// Gets a Discord application information for the logged-in user.
/// </summary>
/// <remarks>
/// This method reflects your application information you submitted when creating a Discord application via
/// the Developer Portal.
/// </remarks>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the application
/// information.
/// </returns>
public abstract Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null);
/// <summary>
/// Gets a generic user.
/// </summary>
/// <param name="id">The user snowflake ID.</param>
/// <remarks>
/// This method gets the user present in the WebSocket cache with the given condition.
/// <note type="warning">
/// Sometimes a user may return <c>null</c> due to Discord not sending offline users in large guilds
/// (i.e. guild with 100+ members) actively. To download users on startup and to see more information
/// about this subject, see <see cref="Discord.WebSocket.DiscordSocketConfig.AlwaysDownloadUsers" />.
/// </note>
/// <note>
/// This method does not attempt to fetch users that the logged-in user does not have access to (i.e.
/// users who don't share mutual guild(s) with the current user). If you wish to get a user that you do
/// not have access to, consider using the REST implementation of
/// <see cref="DiscordRestClient.GetUserAsync(System.UInt64,Discord.RequestOptions)" />.
/// </note>
/// </remarks>
/// <returns>
/// A generic WebSocket-based user; <c>null</c> when the user cannot be found.
/// </returns>
public abstract SocketUser GetUser(ulong id);
/// <summary>
/// Gets a user.
/// </summary>
/// <remarks>
/// This method gets the user present in the WebSocket cache with the given condition.
/// <note type="warning">
/// Sometimes a user may return <c>null</c> due to Discord not sending offline users in large guilds
/// (i.e. guild with 100+ members) actively. To download users on startup and to see more information
/// about this subject, see <see cref="Discord.WebSocket.DiscordSocketConfig.AlwaysDownloadUsers" />.
/// </note>
/// <note>
/// This method does not attempt to fetch users that the logged-in user does not have access to (i.e.
/// users who don't share mutual guild(s) with the current user). If you wish to get a user that you do
/// not have access to, consider using the REST implementation of
/// <see cref="DiscordRestClient.GetUserAsync(System.UInt64,Discord.RequestOptions)" />.
/// </note>
/// </remarks>
/// <param name="username">The name of the user.</param>
/// <param name="discriminator">The discriminator value of the user.</param>
/// <returns>
/// A generic WebSocket-based user; <c>null</c> when the user cannot be found.
/// </returns>
public abstract SocketUser GetUser(string username, string discriminator);
/// <summary>
/// Gets a channel.
/// </summary>
/// <param name="id">The snowflake identifier of the channel (e.g. `381889909113225237`).</param>
/// <returns>
/// A generic WebSocket-based channel object (voice, text, category, etc.) associated with the identifier;
/// <c>null</c> when the channel cannot be found.
/// </returns>
public abstract SocketChannel GetChannel(ulong id);
/// <summary>
/// Gets a guild.
/// </summary>
/// <param name="id">The guild snowflake identifier.</param>
/// <returns>
/// A WebSocket-based guild associated with the snowflake identifier; <c>null</c> when the guild cannot be
/// found.
/// </returns>
public abstract SocketGuild GetGuild(ulong id);
/// <summary>
/// Gets a voice region.
/// </summary>
/// <param name="id">The identifier of the voice region (e.g. <c>eu-central</c> ).</param>
/// <returns>
/// A REST-based voice region associated with the identifier; <c>null</c> if the voice region is not
/// found.
/// </returns>
public abstract RestVoiceRegion GetVoiceRegion(string id);
/// <inheritdoc />
public abstract Task StartAsync();
/// <inheritdoc />
public abstract Task StopAsync();
/// <summary>
/// Sets the current status of the user (e.g. Online, Do not Disturb).
/// </summary>
/// <param name="status">The new status to be set.</param>
/// <returns>
/// A task that represents the asynchronous set operation.
/// </returns>
public abstract Task SetStatusAsync(UserStatus status);
/// <summary>
/// Sets the game of the user.
/// </summary>
/// <param name="name">The name of the game.</param>
/// <param name="streamUrl">If streaming, the URL of the stream. Must be a valid Twitch URL.</param>
/// <param name="type">The type of the game.</param>
/// <returns>
/// A task that represents the asynchronous set operation.
/// </returns>
public abstract Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing);
/// <summary>
/// Sets the <paramref name="activity"/> of the logged-in user.
/// </summary>
/// <remarks>
/// This method sets the <paramref name="activity"/> of the user.
/// <note type="note">
/// Discord will only accept setting of name and the type of activity.
/// </note>
/// <note type="warning">
/// Rich Presence cannot be set via this method or client. Rich Presence is strictly limited to RPC
/// clients only.
/// </note>
/// </remarks>
/// <param name="activity">The activity to be set.</param>
/// <returns>
/// A task that represents the asynchronous set operation.
/// </returns>
public abstract Task SetActivityAsync(IActivity activity);
/// <summary>
/// Attempts to download users into the user cache for the selected guilds.
/// </summary>
/// <param name="guilds">The guilds to download the members from.</param>
/// <returns>
/// A task that represents the asynchronous download operation.
/// </returns>
public abstract Task DownloadUsersAsync(IEnumerable<IGuild> guilds);
/// <summary>
/// Creates a guild for the logged-in user who is in less than 10 active guilds.
/// </summary>
/// <remarks>
/// This method creates a new guild on behalf of the logged-in user.
/// <note type="warning">
/// Due to Discord's limitation, this method will only work for users that are in less than 10 guilds.
/// </note>
/// </remarks>
/// <param name="name">The name of the new guild.</param>
/// <param name="region">The voice region to create the guild with.</param>
/// <param name="jpegIcon">The icon of the guild.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the created guild.
/// </returns>
public Task<RestGuild> CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null, RequestOptions options = null)
=> ClientHelper.CreateGuildAsync(this, name, region, jpegIcon, options ?? RequestOptions.Default);
/// <summary>
/// Gets the connections that the user has set up.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of connections.
/// </returns>
public Task<IReadOnlyCollection<RestConnection>> GetConnectionsAsync(RequestOptions options = null)
=> ClientHelper.GetConnectionsAsync(this, options ?? RequestOptions.Default);
/// <summary>
/// Gets an invite.
/// </summary>
/// <param name="inviteId">The invitation identifier.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the invite information.
/// </returns>
public Task<RestInviteMetadata> GetInviteAsync(string inviteId, RequestOptions options = null)
=> ClientHelper.GetInviteAsync(this, inviteId, options ?? RequestOptions.Default);
// IDiscordClient
/// <inheritdoc />
async Task<IApplication> IDiscordClient.GetApplicationInfoAsync(RequestOptions options)
=> await GetApplicationInfoAsync(options).ConfigureAwait(false);
/// <inheritdoc />
Task<IChannel> IDiscordClient.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IChannel>(GetChannel(id));
/// <inheritdoc />
Task<IReadOnlyCollection<IPrivateChannel>> IDiscordClient.GetPrivateChannelsAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IPrivateChannel>>(PrivateChannels);
/// <inheritdoc />
async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options)
=> await GetConnectionsAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
=> await GetInviteAsync(inviteId, options).ConfigureAwait(false);
/// <inheritdoc />
Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuild>(GetGuild(id));
/// <inheritdoc />
Task<IReadOnlyCollection<IGuild>> IDiscordClient.GetGuildsAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IGuild>>(Guilds);
/// <inheritdoc />
async Task<IGuild> IDiscordClient.CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon, RequestOptions options)
=> await CreateGuildAsync(name, region, jpegIcon, options).ConfigureAwait(false);
/// <inheritdoc />
Task<IUser> IDiscordClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(id));
/// <inheritdoc />
Task<IUser> IDiscordClient.GetUserAsync(string username, string discriminator, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(username, discriminator));
/// <inheritdoc />
Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options)
=> Task.FromResult<IVoiceRegion>(GetVoiceRegion(id));
/// <inheritdoc />
Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions);
}
}
| |
using System;
using System.Text;
using Loyc.MiniTest;
using Pixie;
using Wasm.Interpret;
namespace Wasm.Text
{
[TestFixture]
public class AssemblerTests
{
[Test]
public void AssembleEmptyModule()
{
var module = AssembleModule("(module)");
Assert.AreEqual(0, module.Sections.Count);
}
[Test]
public void AssembleNamedEmptyModule()
{
var module = AssembleModule("(module $test_module)");
Assert.AreEqual(1, module.Sections.Count);
Assert.AreEqual(1, module.GetFirstSectionOrNull<NameSection>().Names.Count);
Assert.AreEqual("test_module", module.ModuleName);
}
[Test]
public void AssembleModulesWithMemory()
{
var module = AssembleModule("(module (memory $mem 10 40))");
Assert.AreEqual(1, module.Sections.Count);
var memSection = module.GetFirstSectionOrNull<MemorySection>();
Assert.IsNotNull(memSection);
Assert.AreEqual(1, memSection.Memories.Count);
var memory = memSection.Memories[0];
Assert.AreEqual(10u, memory.Limits.Initial);
Assert.IsTrue(memory.Limits.HasMaximum);
Assert.AreEqual(40u, memory.Limits.Maximum);
module = AssembleModule("(module (memory 10))");
Assert.AreEqual(1, module.Sections.Count);
memSection = module.GetFirstSectionOrNull<MemorySection>();
Assert.IsNotNull(memSection);
Assert.AreEqual(1, memSection.Memories.Count);
memory = memSection.Memories[0];
Assert.AreEqual(10u, memory.Limits.Initial);
Assert.IsFalse(memory.Limits.HasMaximum);
module = AssembleModule("(module (memory (data \"hello world\")))");
Assert.AreEqual(2, module.Sections.Count);
memSection = module.GetFirstSectionOrNull<MemorySection>();
Assert.IsNotNull(memSection);
Assert.AreEqual(1, memSection.Memories.Count);
memory = memSection.Memories[0];
Assert.AreEqual(1u, memory.Limits.Initial);
Assert.IsTrue(memory.Limits.HasMaximum);
Assert.AreEqual(1u, memory.Limits.Maximum);
var dataSection = module.GetFirstSectionOrNull<DataSection>();
Assert.IsNotNull(dataSection);
Assert.AreEqual(1, dataSection.Segments.Count);
var segment = dataSection.Segments[0];
Assert.AreEqual(0u, segment.MemoryIndex);
Assert.AreEqual("hello world", Encoding.UTF8.GetString(segment.Data));
module = AssembleModule("(module (memory (import \"mod\" \"mem\") 10 40))");
Assert.AreEqual(1, module.Sections.Count);
var importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
var import = importSection.Imports[0];
Assert.AreEqual(ExternalKind.Memory, import.Kind);
Assert.AreEqual("mod", import.ModuleName);
Assert.AreEqual("mem", import.FieldName);
memory = ((ImportedMemory)import).Memory;
Assert.AreEqual(10u, memory.Limits.Initial);
Assert.IsTrue(memory.Limits.HasMaximum);
Assert.AreEqual(40u, memory.Limits.Maximum);
module = AssembleModule("(module (memory (export \"mem\") (import \"mod\" \"mem\") 10 40))");
Assert.AreEqual(2, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
import = importSection.Imports[0];
Assert.AreEqual(ExternalKind.Memory, import.Kind);
Assert.AreEqual("mod", import.ModuleName);
Assert.AreEqual("mem", import.FieldName);
memory = ((ImportedMemory)import).Memory;
Assert.AreEqual(10u, memory.Limits.Initial);
Assert.IsTrue(memory.Limits.HasMaximum);
Assert.AreEqual(40u, memory.Limits.Maximum);
var exportSection = module.GetFirstSectionOrNull<ExportSection>();
Assert.IsNotNull(exportSection);
Assert.AreEqual(1, exportSection.Exports.Count);
var export = exportSection.Exports[0];
Assert.AreEqual("mem", export.Name);
Assert.AreEqual(0u, export.Index);
Assert.AreEqual(ExternalKind.Memory, export.Kind);
}
[Test]
public void AssembleModulesWithExports()
{
var module = AssembleModule("(module (memory $mem1 10 40) (memory $mem2 10 40) (export \"mem\" (memory $mem2)))");
Assert.AreEqual(2, module.Sections.Count);
var memSection = module.GetFirstSectionOrNull<MemorySection>();
Assert.IsNotNull(memSection);
Assert.AreEqual(2, memSection.Memories.Count);
var memory = memSection.Memories[1];
Assert.AreEqual(10u, memory.Limits.Initial);
Assert.IsTrue(memory.Limits.HasMaximum);
Assert.AreEqual(40u, memory.Limits.Maximum);
var exportSection = module.GetFirstSectionOrNull<ExportSection>();
Assert.IsNotNull(exportSection);
Assert.AreEqual(1, exportSection.Exports.Count);
var export = exportSection.Exports[0];
Assert.AreEqual("mem", export.Name);
Assert.AreEqual(1u, export.Index);
Assert.AreEqual(ExternalKind.Memory, export.Kind);
}
[Test]
public void AssembleModulesWithImports()
{
var module = AssembleModule("(module (import \"spectest\" \"memory\" (memory 1 2)))");
Assert.AreEqual(1, module.Sections.Count);
var importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
var memoryImport = (ImportedMemory)importSection.Imports[0];
Assert.AreEqual("spectest", memoryImport.ModuleName);
Assert.AreEqual("memory", memoryImport.FieldName);
var memory = memoryImport.Memory;
Assert.AreEqual(1u, memory.Limits.Initial);
Assert.IsTrue(memory.Limits.HasMaximum);
Assert.AreEqual(2u, memory.Limits.Maximum);
module = AssembleModule("(module (import \"spectest\" \"memory\" (func)))");
Assert.AreEqual(2, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
var funcImport = (ImportedFunction)importSection.Imports[0];
Assert.AreEqual("spectest", funcImport.ModuleName);
Assert.AreEqual("memory", funcImport.FieldName);
var funcTypeIndex = funcImport.TypeIndex;
Assert.AreEqual(0u, funcTypeIndex);
var typeSection = module.GetFirstSectionOrNull<TypeSection>();
Assert.AreEqual(1, typeSection.FunctionTypes.Count);
var funcType = typeSection.FunctionTypes[0];
Assert.AreEqual(0, funcType.ParameterTypes.Count);
Assert.AreEqual(0, funcType.ReturnTypes.Count);
module = AssembleModule("(module (import \"spectest\" \"memory\" (func (param) (result))))");
Assert.AreEqual(2, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
funcImport = (ImportedFunction)importSection.Imports[0];
Assert.AreEqual("spectest", funcImport.ModuleName);
Assert.AreEqual("memory", funcImport.FieldName);
funcTypeIndex = funcImport.TypeIndex;
Assert.AreEqual(0u, funcTypeIndex);
typeSection = module.GetFirstSectionOrNull<TypeSection>();
Assert.AreEqual(1, typeSection.FunctionTypes.Count);
funcType = typeSection.FunctionTypes[0];
Assert.AreEqual(0, funcType.ParameterTypes.Count);
Assert.AreEqual(0, funcType.ReturnTypes.Count);
module = AssembleModule("(module (import \"spectest\" \"memory\" (func (param i32 i64 f32 f64) (result f64))))");
Assert.AreEqual(2, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
funcImport = (ImportedFunction)importSection.Imports[0];
Assert.AreEqual("spectest", funcImport.ModuleName);
Assert.AreEqual("memory", funcImport.FieldName);
funcTypeIndex = funcImport.TypeIndex;
Assert.AreEqual(0u, funcTypeIndex);
typeSection = module.GetFirstSectionOrNull<TypeSection>();
Assert.AreEqual(1, typeSection.FunctionTypes.Count);
funcType = typeSection.FunctionTypes[0];
Assert.AreEqual(4, funcType.ParameterTypes.Count);
Assert.AreEqual(WasmValueType.Int32, funcType.ParameterTypes[0]);
Assert.AreEqual(WasmValueType.Int64, funcType.ParameterTypes[1]);
Assert.AreEqual(WasmValueType.Float32, funcType.ParameterTypes[2]);
Assert.AreEqual(WasmValueType.Float64, funcType.ParameterTypes[3]);
Assert.AreEqual(1, funcType.ReturnTypes.Count);
Assert.AreEqual(WasmValueType.Float64, funcType.ReturnTypes[0]);
module = AssembleModule("(module (func (import \"spectest\" \"memory\") (param i32 i64 f32 f64) (result f64)))");
Assert.AreEqual(2, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
funcImport = (ImportedFunction)importSection.Imports[0];
Assert.AreEqual("spectest", funcImport.ModuleName);
Assert.AreEqual("memory", funcImport.FieldName);
funcTypeIndex = funcImport.TypeIndex;
Assert.AreEqual(0u, funcTypeIndex);
typeSection = module.GetFirstSectionOrNull<TypeSection>();
Assert.AreEqual(1, typeSection.FunctionTypes.Count);
funcType = typeSection.FunctionTypes[0];
Assert.AreEqual(4, funcType.ParameterTypes.Count);
Assert.AreEqual(WasmValueType.Int32, funcType.ParameterTypes[0]);
Assert.AreEqual(WasmValueType.Int64, funcType.ParameterTypes[1]);
Assert.AreEqual(WasmValueType.Float32, funcType.ParameterTypes[2]);
Assert.AreEqual(WasmValueType.Float64, funcType.ParameterTypes[3]);
Assert.AreEqual(1, funcType.ReturnTypes.Count);
Assert.AreEqual(WasmValueType.Float64, funcType.ReturnTypes[0]);
module = AssembleModule("(module (import \"spectest\" \"global_i32\" (global $x i32)))");
Assert.AreEqual(1, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
var globalImport = (ImportedGlobal)importSection.Imports[0];
Assert.AreEqual("spectest", globalImport.ModuleName);
Assert.AreEqual("global_i32", globalImport.FieldName);
Assert.AreEqual(WasmValueType.Int32, globalImport.Global.ContentType);
Assert.IsFalse(globalImport.Global.IsMutable);
module = AssembleModule("(module (global $x (import \"spectest\" \"global_i32\") i32))");
Assert.AreEqual(1, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
globalImport = (ImportedGlobal)importSection.Imports[0];
Assert.AreEqual("spectest", globalImport.ModuleName);
Assert.AreEqual("global_i32", globalImport.FieldName);
Assert.AreEqual(WasmValueType.Int32, globalImport.Global.ContentType);
Assert.IsFalse(globalImport.Global.IsMutable);
module = AssembleModule("(module (import \"spectest\" \"global_i32\" (global (mut i32))))");
Assert.AreEqual(1, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
globalImport = (ImportedGlobal)importSection.Imports[0];
Assert.AreEqual("spectest", globalImport.ModuleName);
Assert.AreEqual("global_i32", globalImport.FieldName);
Assert.AreEqual(WasmValueType.Int32, globalImport.Global.ContentType);
Assert.IsTrue(globalImport.Global.IsMutable);
module = AssembleModule("(module (global (import \"spectest\" \"global_i32\") (mut i32)))");
Assert.AreEqual(1, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
globalImport = (ImportedGlobal)importSection.Imports[0];
Assert.AreEqual("spectest", globalImport.ModuleName);
Assert.AreEqual("global_i32", globalImport.FieldName);
Assert.AreEqual(WasmValueType.Int32, globalImport.Global.ContentType);
Assert.IsTrue(globalImport.Global.IsMutable);
module = AssembleModule("(module (import \"spectest\" \"table\" (table 10 20 funcref)))");
Assert.AreEqual(1, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
var tableImport = (ImportedTable)importSection.Imports[0];
Assert.AreEqual("spectest", tableImport.ModuleName);
Assert.AreEqual("table", tableImport.FieldName);
Assert.AreEqual(WasmType.AnyFunc, tableImport.Table.ElementType);
Assert.AreEqual(10u, tableImport.Table.Limits.Initial);
Assert.IsTrue(tableImport.Table.Limits.HasMaximum);
Assert.AreEqual(20u, tableImport.Table.Limits.Maximum);
module = AssembleModule("(module " +
"(type $g (func (param i32) (result f64))) " +
"(type $f (func (param i32 i64 f32 f64) (result f64))) " +
"(import \"spectest\" \"f\" (func (type $f) (param i32 i64 f32 f64) (result f64))) " +
"(import \"spectest\" \"f\" (func (type 1) (param i32 i64 f32 f64) (result f64))) " +
"(import \"spectest\" \"f\" (func (param i32 i64 f32 f64) (result f64))) " +
"(import \"spectest\" \"f\" (func (type 1))) " +
"(import \"spectest\" \"f\" (func (type $f))))");
Assert.AreEqual(2, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(5, importSection.Imports.Count);
for (int i = 0; i < importSection.Imports.Count; i++)
{
funcImport = (ImportedFunction)importSection.Imports[i];
Assert.AreEqual("spectest", funcImport.ModuleName);
Assert.AreEqual("f", funcImport.FieldName);
funcTypeIndex = funcImport.TypeIndex;
Assert.AreEqual(1u, funcTypeIndex);
}
typeSection = module.GetFirstSectionOrNull<TypeSection>();
Assert.AreEqual(2, typeSection.FunctionTypes.Count);
funcType = typeSection.FunctionTypes[1];
Assert.AreEqual(4, funcType.ParameterTypes.Count);
Assert.AreEqual(WasmValueType.Int32, funcType.ParameterTypes[0]);
Assert.AreEqual(WasmValueType.Int64, funcType.ParameterTypes[1]);
Assert.AreEqual(WasmValueType.Float32, funcType.ParameterTypes[2]);
Assert.AreEqual(WasmValueType.Float64, funcType.ParameterTypes[3]);
Assert.AreEqual(1, funcType.ReturnTypes.Count);
Assert.AreEqual(WasmValueType.Float64, funcType.ReturnTypes[0]);
}
[Test]
public void AssembleModulesWithTables()
{
var module = AssembleModule("(module (table 0 funcref))");
Assert.AreEqual(1, module.Sections.Count);
var tableSection = module.GetFirstSectionOrNull<TableSection>();
Assert.IsNotNull(tableSection);
Assert.AreEqual(1, tableSection.Tables.Count);
var table = (TableType)tableSection.Tables[0];
Assert.AreEqual(WasmType.AnyFunc, table.ElementType);
Assert.AreEqual(0u, table.Limits.Initial);
Assert.IsFalse(table.Limits.HasMaximum);
module = AssembleModule("(module (table 0 1 funcref))");
Assert.AreEqual(1, module.Sections.Count);
tableSection = module.GetFirstSectionOrNull<TableSection>();
Assert.IsNotNull(tableSection);
Assert.AreEqual(1, tableSection.Tables.Count);
table = (TableType)tableSection.Tables[0];
Assert.AreEqual(WasmType.AnyFunc, table.ElementType);
Assert.AreEqual(0u, table.Limits.Initial);
Assert.IsTrue(table.Limits.HasMaximum);
Assert.AreEqual(1u, table.Limits.Maximum);
module = AssembleModule("(module (table (import \"spectest\" \"table\") 10 20 funcref))");
Assert.AreEqual(1, module.Sections.Count);
var importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
var tableImport = (ImportedTable)importSection.Imports[0];
Assert.AreEqual("spectest", tableImport.ModuleName);
Assert.AreEqual("table", tableImport.FieldName);
Assert.AreEqual(WasmType.AnyFunc, tableImport.Table.ElementType);
Assert.AreEqual(10u, tableImport.Table.Limits.Initial);
Assert.IsTrue(tableImport.Table.Limits.HasMaximum);
Assert.AreEqual(20u, tableImport.Table.Limits.Maximum);
module = AssembleModule("(module (table (export \"table1\") (export \"table2\") (import \"spectest\" \"table\") 10 20 funcref))");
Assert.AreEqual(2, module.Sections.Count);
importSection = module.GetFirstSectionOrNull<ImportSection>();
Assert.IsNotNull(importSection);
Assert.AreEqual(1, importSection.Imports.Count);
tableImport = (ImportedTable)importSection.Imports[0];
Assert.AreEqual("spectest", tableImport.ModuleName);
Assert.AreEqual("table", tableImport.FieldName);
Assert.AreEqual(WasmType.AnyFunc, tableImport.Table.ElementType);
Assert.AreEqual(10u, tableImport.Table.Limits.Initial);
Assert.IsTrue(tableImport.Table.Limits.HasMaximum);
Assert.AreEqual(20u, tableImport.Table.Limits.Maximum);
var exportSection = module.GetFirstSectionOrNull<ExportSection>();
Assert.IsNotNull(exportSection);
Assert.AreEqual("table1", exportSection.Exports[0].Name);
Assert.AreEqual(ExternalKind.Table, exportSection.Exports[0].Kind);
Assert.AreEqual(0u, exportSection.Exports[0].Index);
Assert.AreEqual("table2", exportSection.Exports[1].Name);
Assert.AreEqual(ExternalKind.Table, exportSection.Exports[1].Kind);
Assert.AreEqual(0u, exportSection.Exports[1].Index);
}
[Test]
public void AssembleModulesWithStart()
{
var module = AssembleModule("(module (func $f nop) (func $entry nop) (start $entry))");
Assert.AreEqual((uint?)1u, module.StartFunctionIndex);
}
[Test]
public void AssembleBadMemoryModules()
{
AssertInvalidModule("(module (memory))");
AssertInvalidModule("(module (memory (limits 10 50)))");
AssertInvalidModule("(module (memory $mem 78359126329586239865823 725357639275693276582334525))");
AssertInvalidModule("(module (memory $mem 10e7 10e8))");
AssertInvalidModule("(module (memory +10 +40))");
AssertInvalidModule("(module (memory $mem1 $mem2 10 40))");
AssertInvalidModule("(module (memory 10 40 10 40))");
AssertInvalidModule("(module (memory (import \"mod\" \"mem\")))");
}
[Test]
public void AssembleBadExportModules()
{
AssertInvalidModule("(module (export \"mem\" (memory $mem)))");
}
[Test]
public void AssembleInstructions()
{
Assert.AreEqual(10, EvaluateConstExpr(WasmType.Int32, "i32.const 10"));
Assert.AreEqual(15, EvaluateConstExpr(WasmType.Int32, "i32.const 10 i32.const 5 i32.add"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "i32.const 10 i32.const -5 i32.add"));
Assert.AreEqual(15, EvaluateConstExpr(WasmType.Int32, "(i32.add (i32.const 10) (i32.const 5))"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "(block $block (result i32) i32.const 10 i32.const -5 i32.add)"));
Assert.AreEqual(15, EvaluateConstExpr(WasmType.Int32, "block $block (result i32) i32.const 10 i32.const -5 i32.add end i32.const 10 i32.add"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "(if $block (result i32) i32.const 0 (then i32.const 10) (else i32.const 5))"));
Assert.AreEqual(10, EvaluateConstExpr(WasmType.Int32, "(if $block (result i32) i32.const 0 (then i32.const 5) (else i32.const 10))"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "(if $block (result i32) i32.const 1 (then i32.const 5) (else i32.const 10))"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "i32.const 1 (if $block (result i32) (then i32.const 5) (else i32.const 10))"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "i32.const 1 (if (then)) i32.const 5"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "i32.const 1 if $block (result i32) i32.const 5 else i32.const 10 end"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "i32.const 0 i32.const 5 i32.store offset=2 align=2 i32.const 0 i32.load offset=2 align=2"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "(i32.const 0) (i32.const 5) (i32.store offset=2 align=2) (i32.const 0) (i32.load offset=2 align=2)"));
Assert.AreEqual(10.0f, EvaluateConstExpr(WasmType.Float32, "f32.const 10"));
Assert.AreEqual(10.0, EvaluateConstExpr(WasmType.Float64, "f64.const 10"));
Assert.AreEqual(10.0f, EvaluateConstExpr(WasmType.Float32, "f32.const 10.0"));
Assert.AreEqual(10.0, EvaluateConstExpr(WasmType.Float64, "f64.const 10.0"));
Assert.AreEqual(-10.0f, EvaluateConstExpr(WasmType.Float32, "f32.const -10"));
Assert.AreEqual(-10.0, EvaluateConstExpr(WasmType.Float64, "f64.const -10"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "(local $x i32) i32.const 5 local.set $x local.get $x"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "(local $x i32) i32.const 5 local.tee $x"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "call $constant_five"));
Assert.AreEqual(1, EvaluateConstExpr(WasmType.Int32, "memory.size"));
Assert.AreEqual(3, EvaluateConstExpr(WasmType.Int32, "i32.const 1 memory.grow memory.size i32.add"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "(block $block (result i32) (i32.const 5) (br $block) (drop) (i32.const 3))"));
Assert.AreEqual(22, EvaluateConstExpr(WasmType.Int32, "(block (block (br_table 1 0 (i32.const 0)) (return (i32.const 21)) ) (return (i32.const 20)) ) (i32.const 22)"));
Assert.AreEqual(20, EvaluateConstExpr(WasmType.Int32, "(block (block (br_table 1 0 (i32.const 1)) (return (i32.const 21)) ) (return (i32.const 20)) ) (i32.const 22)"));
Assert.AreEqual(5, EvaluateConstExpr(WasmType.Int32, "global.get $five"));
Assert.AreEqual(20, EvaluateConstExpr(WasmType.Int32, "i32.const 20 global.set $five global.get $five"));
}
private static void AssertInvalidModule(string text)
{
Assert.Throws(
typeof(PixieException),
() => AssembleModule(text));
}
private static WasmFile AssembleModule(string text)
{
var log = new TestLog(new[] { Severity.Error }, NullLog.Instance);
var assembler = new Assembler(log);
return assembler.AssembleModule(text);
}
private static object EvaluateConstExpr(WasmType resultType, string expr)
{
var asm = AssembleModule($"(module (memory 1) (global $five (mut i32) (i32.const 5)) (func $f (export \"f\") (result {DumpHelpers.WasmTypeToString(resultType)}) {expr}) (func $constant_five (result i32) i32.const 5))");
var instance = ModuleInstance.Instantiate(asm, new PredefinedImporter());
return instance.ExportedFunctions["f"].Invoke(Array.Empty<object>())[0];
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using DiscUtils;
using DiscUtils.Common;
using DiscUtils.Ntfs;
using DiscUtils.Ntfs.Internals;
using DiscUtils.Streams;
namespace FileRecover
{
class Program : ProgramBase
{
private CommandLineMultiParameter _diskFiles;
private CommandLineSwitch _recoverFile;
private CommandLineSwitch _showMeta;
private CommandLineSwitch _showZeroSize;
static void Main(string[] args)
{
Program program = new Program();
program.Run(args);
}
protected override ProgramBase.StandardSwitches DefineCommandLine(CommandLineParser parser)
{
_diskFiles = FileOrUriMultiParameter("disk", "The disks to inspect.", false);
_recoverFile = new CommandLineSwitch("r", "recover", "file_index", "Tries to recover the file at MFT index file_index from the disk.");
_showMeta = new CommandLineSwitch("M", "meta", null, "Don't hide files and directories that are part of the file system itself.");
_showZeroSize = new CommandLineSwitch("Z", "empty", null, "Don't hide files shown as zero size.");
parser.AddMultiParameter(_diskFiles);
parser.AddSwitch(_recoverFile);
parser.AddSwitch(_showMeta);
parser.AddSwitch(_showZeroSize);
return StandardSwitches.UserAndPassword | StandardSwitches.PartitionOrVolume;
}
protected override string[] HelpRemarks
{
get
{
return new string[] {
"By default this utility shows the files that it may be possible to recover from an NTFS formatted virtual disk. Once a "
+ "candidate file is determined, use the '-r' option to attempt recovery of the file's contents." };
}
}
protected override void DoRun()
{
VolumeManager volMgr = new VolumeManager();
foreach (string disk in _diskFiles.Values)
{
volMgr.AddDisk(VirtualDisk.OpenDisk(disk, FileAccess.Read, UserName, Password));
}
VolumeInfo volInfo = null;
if (!string.IsNullOrEmpty(VolumeId))
{
volInfo = volMgr.GetVolume(VolumeId);
}
else if (Partition >= 0)
{
volInfo = volMgr.GetPhysicalVolumes()[Partition];
}
else
{
volInfo = volMgr.GetLogicalVolumes()[0];
}
using (NtfsFileSystem fs = new NtfsFileSystem(volInfo.Open()))
{
MasterFileTable mft = fs.GetMasterFileTable();
if (_recoverFile.IsPresent)
{
MasterFileTableEntry entry = mft[long.Parse(_recoverFile.Value)];
IBuffer content = GetContent(entry);
if (content == null)
{
Console.WriteLine("Sorry, unable to recover content");
Environment.Exit(1);
}
string outFile = _recoverFile.Value + "__recovered.bin";
if (File.Exists(outFile))
{
Console.WriteLine("Sorry, the file already exists: " + outFile);
Environment.Exit(1);
}
using (FileStream outFileStream = new FileStream(outFile, FileMode.CreateNew, FileAccess.Write))
{
Pump(content, outFileStream);
}
Console.WriteLine("Possible file contents saved as: " + outFile);
Console.WriteLine();
Console.WriteLine("Caution! It is rare for the file contents of deleted files to be intact - most");
Console.WriteLine("likely the contents recovered are corrupt as the space has been reused.");
}
else
{
foreach (var entry in mft.GetEntries(EntryStates.NotInUse))
{
// Skip entries with no attributes, they've probably never been used. We're certainly
// not going to manage to recover any useful data from them.
if (entry.Attributes.Count == 0)
continue;
// Skip directories - any useful files inside will be found separately
if ((entry.Flags & MasterFileTableEntryFlags.IsDirectory) != 0)
continue;
long size = GetSize(entry);
string path = GetPath(mft, entry);
if (!_showMeta.IsPresent && path.StartsWith(@"<root>\$Extend"))
continue;
if (!_showZeroSize.IsPresent && size == 0)
continue;
Console.WriteLine("Index: {0,-4} Size: {1,-8} Path: {2}", entry.Index, Utilities.ApproximateDiskSize(size), path);
}
}
}
}
static IBuffer GetContent(MasterFileTableEntry entry)
{
foreach (var attr in entry.Attributes)
{
if (attr.AttributeType == AttributeType.Data)
{
return attr.Content;
}
}
return null;
}
static long GetSize(MasterFileTableEntry entry)
{
foreach (var attr in entry.Attributes)
{
FileNameAttribute fna = attr as FileNameAttribute;
if (fna != null)
{
return fna.RealSize;
}
}
return 0;
}
static string GetPath(MasterFileTable mft, MasterFileTableEntry entry)
{
if (entry.SequenceNumber == MasterFileTable.RootDirectoryIndex)
{
return "<root>";
}
FileNameAttribute fna = null;
foreach (var attr in entry.Attributes)
{
FileNameAttribute thisFna = attr as FileNameAttribute;
if (thisFna != null)
{
if (fna == null || thisFna.FileNameNamespace == NtfsNamespace.Win32 || thisFna.FileNameNamespace == NtfsNamespace.Win32AndDos)
{
fna = thisFna;
}
}
}
if (fna == null)
{
return "<unknown>";
}
string parentPath = "<unknown>";
MasterFileTableEntry parentEntry = mft[fna.ParentDirectory.RecordIndex];
if (parentEntry != null)
{
if (parentEntry.SequenceNumber == fna.ParentDirectory.RecordSequenceNumber || parentEntry.SequenceNumber == fna.ParentDirectory.RecordSequenceNumber + 1)
{
parentPath = GetPath(mft, parentEntry);
}
}
return parentPath + "\\" + fna.FileName;
}
private static void Pump(IBuffer inBuffer, Stream outStream)
{
long inPos = 0;
byte[] buffer = new byte[4096];
int bytesRead = inBuffer.Read(inPos, buffer, 0, 4096);
while (bytesRead != 0 && inPos < inBuffer.Capacity)
{
inPos += bytesRead;
outStream.Write(buffer, 0, bytesRead);
bytesRead = inBuffer.Read(inPos, buffer, 0, 4096);
}
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using IO = System.IO;
using Crypto = System.Security.Cryptography;
// 18/5/03
public class Encryption
{
private Encryption()
{
}
public static void Encrypt(string username, string password, byte[] salt, out byte[] result1, out byte[] result2)
{
byte[] byteUsername = ASCIIEncoding.ASCII.GetBytes(username);
byte[] bytePassword = ASCIIEncoding.ASCII.GetBytes(password);
// ok, heres the dirty stuff.
// take the 16th character from the yahoo seed string and take the modulus of it
int sv = (int)salt[15];
sv = (sv % 8) % 5;
// md5 encrypt the password
Crypto.MD5CryptoServiceProvider md5 = new Crypto.MD5CryptoServiceProvider();
byte[] passwordResult = ToMac64(md5.ComputeHash(bytePassword));
byte[] cryptResult = ToMac64(md5.ComputeHash(YahooCrypt(password, "_2S43d5f")));
// the order of the strings depends on the value of sv (calculated above)
byte checksum;
IO.MemoryStream result1Stream = new IO.MemoryStream();
IO.MemoryStream result2Stream = new IO.MemoryStream();
switch (sv)
{
case 0:
checksum = salt[salt[7] % 16];
result1Stream.WriteByte(checksum);
result1Stream.Write(passwordResult, 0, passwordResult.Length);
result1Stream.Write(byteUsername, 0, byteUsername.Length);
result1Stream.Write(salt, 0, salt.Length);
result2Stream.WriteByte(checksum);
result2Stream.Write(cryptResult, 0, cryptResult.Length);
result2Stream.Write(byteUsername, 0, byteUsername.Length);
result2Stream.Write(salt, 0, salt.Length);
break;
case 1:
checksum = salt[salt[9] % 16];
result1Stream.WriteByte(checksum);
result1Stream.Write(byteUsername, 0, byteUsername.Length);
result1Stream.Write(salt, 0, salt.Length);
result1Stream.Write(passwordResult, 0, passwordResult.Length);
result2Stream.WriteByte(checksum);
result2Stream.Write(byteUsername, 0, byteUsername.Length);
result2Stream.Write(salt, 0, salt.Length);
result2Stream.Write(cryptResult, 0, cryptResult.Length);
break;
case 2:
checksum = salt[salt[15] % 16];
result1Stream.WriteByte(checksum);
result1Stream.Write(salt, 0, salt.Length);
result1Stream.Write(passwordResult, 0, passwordResult.Length);
result1Stream.Write(byteUsername, 0, byteUsername.Length);
result2Stream.WriteByte(checksum);
result2Stream.Write(salt, 0, salt.Length);
result2Stream.Write(cryptResult, 0, cryptResult.Length);
result2Stream.Write(byteUsername, 0, byteUsername.Length);
break;
case 3:
checksum = salt[salt[1] % 16];
result1Stream.WriteByte(checksum);
result1Stream.Write(byteUsername, 0, byteUsername.Length);
result1Stream.Write(passwordResult, 0, passwordResult.Length);
result1Stream.Write(salt, 0, salt.Length);
result2Stream.WriteByte(checksum);
result2Stream.Write(byteUsername, 0, byteUsername.Length);
result2Stream.Write(cryptResult, 0, cryptResult.Length);
result2Stream.Write(salt, 0, salt.Length);
break;
case 4:
checksum = salt[salt[3] % 16];
result1Stream.WriteByte(checksum);
result1Stream.Write(passwordResult, 0, passwordResult.Length);
result1Stream.Write(salt, 0, salt.Length);
result1Stream.Write(byteUsername, 0, byteUsername.Length);
result2Stream.WriteByte(checksum);
result2Stream.Write(cryptResult, 0, cryptResult.Length);
result2Stream.Write(salt, 0, salt.Length);
result2Stream.Write(byteUsername, 0, byteUsername.Length);
break;
}
result1 = ToMac64(md5.ComputeHash(result1Stream.ToArray()), 0, 16);
result2 = ToMac64(md5.ComputeHash(result2Stream.ToArray()), 0, 16);
result1Stream.Close();
result2Stream.Close();
}
public static byte[] YahooCrypt(string key, string salt)
{
const string md5SaltPrefix = "$1$";
byte[] byteSaltPrefix = ASCIIEncoding.ASCII.GetBytes(md5SaltPrefix);
byte[] byteKey = ASCIIEncoding.ASCII.GetBytes(key);
byte[] byteSalt = ASCIIEncoding.ASCII.GetBytes(salt);
// create a memory stream for the result
IO.MemoryStream result = new IO.MemoryStream();
result.Write(byteKey, 0, byteKey.Length);
result.Write(byteSaltPrefix, 0, byteSaltPrefix.Length);
result.Write(byteSalt, 0, byteSalt.Length);
// create an alternate string for encyption
IO.MemoryStream altResult = new IO.MemoryStream();
altResult.Write(byteKey, 0, byteKey.Length);
altResult.Write(byteSalt, 0, byteSalt.Length);
altResult.Write(byteKey, 0, byteKey.Length);
// encrypt alternate result
Crypto.MD5CryptoServiceProvider md5 = new Crypto.MD5CryptoServiceProvider();
byte[] altResultHash = md5.ComputeHash(altResult.ToArray());
// Add for any character in the key one byte of the alternate sum.
int cnt;
for (cnt = byteKey.Length; cnt > 16; cnt -= 16)
result.Write(altResultHash, 0, 16);
result.Write(altResultHash, 0, cnt);
/* For the following code we need a NUL byte. */
altResultHash[0] = 0;
/* The original implementation now does something weird: for every 1
bit in the key the first 0 is added to the buffer, for every 0
bit the first character of the key. This does not seem to be
what was intended but we have to follow this to be compatible. */
for (cnt = key.Length; cnt > 0; cnt >>= 1)
result.Write( ((cnt & 1) != 0 ? altResultHash : byteKey), 0, 1);
// create intermediate result
altResultHash = md5.ComputeHash(result.ToArray());
/* Now comes another weirdness. In fear of password crackers here
comes a quite long loop which just processes the output of the
previous round again. We cannot ignore this here. */
for (cnt = 0; cnt < 1000; ++cnt)
{
result.Seek(0, IO.SeekOrigin.Begin);
result.SetLength(0);
/* Add key or last result. */
if ((cnt & 1) != 0)
result.Write(byteKey, 0, byteKey.Length);
else
result.Write(altResultHash, 0, 16);
/* Add salt for numbers not divisible by 3. */
if (cnt % 3 != 0)
result.Write(byteSalt, 0, byteSalt.Length);
/* Add key for numbers not divisible by 7. */
if (cnt % 7 != 0)
result.Write(byteKey, 0, byteKey.Length);
/* Add key or last result. */
if ((cnt & 1) != 0)
result.Write(altResultHash, 0, 16);
else
result.Write(byteKey, 0, byteKey.Length);
/* Create intermediate result. */
altResultHash = md5.ComputeHash(result.ToArray());
}
/* Now we can construct the result string. It consists of three
parts. */
// start with the salt prefix
IO.MemoryStream finalResult = new IO.MemoryStream();
finalResult.Write(byteSaltPrefix, 0, byteSaltPrefix.Length);
finalResult.Write(byteSalt, 0, byteSalt.Length);
finalResult.WriteByte((byte)'$');
b64_from_24bit (altResultHash[0], altResultHash[6], altResultHash[12], 4, finalResult);
b64_from_24bit (altResultHash[1], altResultHash[7], altResultHash[13], 4, finalResult);
b64_from_24bit (altResultHash[2], altResultHash[8], altResultHash[14], 4, finalResult);
b64_from_24bit (altResultHash[3], altResultHash[9], altResultHash[15], 4, finalResult);
b64_from_24bit (altResultHash[4], altResultHash[10], altResultHash[5], 4, finalResult);
b64_from_24bit (0, 0, altResultHash[11], 2, finalResult);
result.Close();
altResult.Close();
byte[] done = finalResult.ToArray();
finalResult.Close();
return done;
}
private static void b64_from_24bit(byte b2, byte b1, byte b0, int n, IO.MemoryStream finalResult)
{
const string b64t = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int w = ((b2) << 16) | ((b1) << 8) | (b0);
while (n-- > 0)
{
finalResult.WriteByte((byte)b64t[w & 0x3f]);
w >>= 6;
}
}
public static byte[] ToMac64(byte[] str)
{
return ToMac64(str, 0, str.Length);
}
public static byte[] ToMac64(byte[] str, int index, int length)
{
string stringBase64digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._";
byte[] base64digits = ASCIIEncoding.ASCII.GetBytes(stringBase64digits);
IO.MemoryStream result = new IO.MemoryStream();
/* raw bytes in quasi-big-endian order to base 64 string (NUL-terminated) */
int inputStringPosition = index;
int inputStringLength = length;
for (; inputStringLength >= 3; inputStringLength -= 3)
{
result.WriteByte(base64digits[str[inputStringPosition] >> 2]);
result.WriteByte(base64digits[((str[inputStringPosition]<<4) & 0x30) | (str[inputStringPosition+1]>>4)]);
result.WriteByte(base64digits[((str[inputStringPosition+1]<<2) & 0x3c) | (str[inputStringPosition+2]>>6)]);
result.WriteByte(base64digits[str[inputStringPosition+2] & 0x3f]);
inputStringPosition += 3;
}
if (inputStringLength > 0)
{
int fragment;
result.WriteByte(base64digits[str[inputStringPosition] >> 2]);
fragment = (str[inputStringPosition] << 4) & 0x30;
if (inputStringLength > 1)
fragment |= str[inputStringPosition+1] >> 4;
result.WriteByte(base64digits[fragment]);
result.WriteByte((inputStringLength < 2) ? (byte)'-' : base64digits[(str[inputStringPosition+1] << 2) & 0x3c]);
result.WriteByte((byte)'-');
}
byte[] final = result.ToArray();
result.Close();
return final;
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
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.Text;
using System.Threading;
using System.Windows.Forms;
using System.Reflection;
namespace Tilde.LuaDebugger
{
public class Target
{
private DebugManager mDebugManager;
private Form mForm;
private IConnection mConnection;
private Thread m_thread;
private AutoResetEvent mHostEvent;
private AutoResetEvent mTargetEvent;
private MessageQueue mMessageQueue;
private bool m_shutdown = false;
StateUpdateEventArgs mLastUpdateMessage;
ReceiveMessageBuffer m_readBuffer;
SendMessageBuffer m_writeBuffer;
int m_callingProcessId;
private object m_lock = new object();
public Target(DebugManager debugger, Form form, IConnection connection)
{
mDebugManager = debugger;
mForm = form;
mConnection = connection;
mConnection.ConnectionClosed += new ConnectionClosedEventHandler(Connection_ConnectionClosed);
mConnection.ConnectionAborted += new ConnectionAbortedEventHandler(Connection_ConnectionAborted);
mConnection.DataReceived += new ConnectionDataReceivedEventHandler(Connection_DataReceived);
mMessageQueue = new MessageQueue();
mHostEvent = new AutoResetEvent(false);
mTargetEvent = new AutoResetEvent(false);
m_readBuffer = new ReceiveMessageBuffer(512 * 1024);
m_writeBuffer = new SendMessageBuffer(4 * 1024);
m_thread = new Thread(new ThreadStart(ThreadMain));
m_thread.Name = "LuaDebuggerThread";
m_thread.Start();
}
public Form Form
{
get { return mForm; }
}
public MessageQueue MessageQueue
{
get { return mMessageQueue; }
}
public AutoResetEvent Event
{
get { return mHostEvent; }
}
public bool IsShutdown
{
get { return m_shutdown; }
}
void ProcessEvents()
{
while(!mMessageQueue.Empty)
{
// Retrieve a message from the queue
MessageQueue.Message message = mMessageQueue.Pop();
// Execute it
message.Invoke();
}
}
void Abort()
{
m_shutdown = true;
mHostEvent.Set();
}
void Abort(string message)
{
if (!message.Contains("forcibly closed"))
OnErrorMessage("Connection error", message);
Abort();
}
private delegate void VoidDelegate();
private delegate object ReturnDelegate();
/// <summary>
/// Thread main loop. The thread blocks waiting for an event to be signalled, then grabs
/// the lock before performing any further processing. Any functions called within this loop
/// should complete as soon as possible so the lock can be retrieved.
/// </summary>
private void ThreadMain()
{
List<WaitHandle> handleList = new List<WaitHandle>();
handleList.Add(mHostEvent);
handleList.Add(mTargetEvent);
handleList.AddRange(mConnection.Handles);
WaitHandle [] handleArray = handleList.ToArray();
handleList = null;
while (!m_shutdown)
{
mConnection.Connect(/*this*/);
try
{
// Wait for a signal
int signalledIndex = WaitHandle.WaitAny(handleArray);
WaitHandle signalledHandle = handleArray[signalledIndex];
if (signalledHandle == mHostEvent)
{
// Process any messages that have been sent from the debugger
ProcessEvents();
}
else if(signalledHandle == mTargetEvent)
{
// Process any messages that have been sent from the target
ProcessMessages();
}
else
{
mConnection.OnSignalled(signalledHandle);
}
}
catch (TargetException ex)
{
Abort(ex.ToString());
}
}
mConnection.Shutdown();
OnStateUpdate(TargetState.Disconnected);
}
void Connection_ConnectionClosed(IConnection sender)
{
Abort();
}
void Connection_ConnectionAborted(IConnection sender, string message)
{
Abort(message);
}
void Connection_DataReceived(IConnection sender, byte[] buffer, int bytes)
{
lock (m_lock)
{
Array.Copy(buffer, 0, m_readBuffer.Buffer, m_readBuffer.DataLength, bytes);
m_readBuffer.DataLength += bytes;
mTargetEvent.Set();
}
}
internal void ProcessMessages()
{
lock (m_lock)
{
if (m_readBuffer.DataLength > 0)
{
// Try and process as many complete messages as possible
m_readBuffer.BeginRead();
while (m_readBuffer.DataAvailable > 0 && !m_shutdown)
{
int msgstart = m_readBuffer.Position;
int msglen = m_readBuffer.PeekInt32();
if (m_readBuffer.DataAvailable < msglen)
break;
m_readBuffer.BeginMessage();
TargetMessage cmd = (TargetMessage)m_readBuffer.ReadInt32();
switch (cmd)
{
case TargetMessage.Connect: ProcessMessage_Connect(); break;
case TargetMessage.Disconnect: ProcessMessage_Disconnect(); break;
case TargetMessage.ErrorMessage: ProcessMessage_ErrorMessage(); break;
case TargetMessage.StateUpdate: ProcessMessage_StateUpdate(); break;
case TargetMessage.BreakpointAdded: ProcessMessage_BreakpointAdded(); break;
case TargetMessage.BreakpointRemoved: ProcessMessage_BreakpointRemoved(); break;
case TargetMessage.CallstackUpdate: ProcessMessage_CallstackUpdate(); break;
case TargetMessage.ValueCached: ProcessMessage_ValueCached(); break;
case TargetMessage.LocalsUpdate: ProcessMessage_LocalsUpdate(); break;
case TargetMessage.WatchUpdate: ProcessMessage_WatchUpdate(); break;
case TargetMessage.ThreadsUpdate: ProcessMessage_ThreadsUpdate(); break;
case TargetMessage.UploadFile: ProcessMessage_UploadFile(); break;
case TargetMessage.SnippetResult: ProcessMessage_SnippetResult(); break;
case TargetMessage.AutocompleteOptions: ProcessMessage_AutocompleteOptions(); break;
case TargetMessage.ExMessage: ProcessMessage_ExMessage(); break;
}
m_readBuffer.EndMessage();
}
m_readBuffer.EndRead();
}
}
}
void ProcessMessage_Connect()
{
int version = m_readBuffer.ReadInt32();
if (version != Protocol.Version)
{
m_readBuffer.Skip(m_readBuffer.MessageAvailable);
Abort(String.Format("Tilde cannot connect to the target because the protocol versions are different.\r\n\r\nTilde protocol version {0};\r\nTarget protocol version {1}.", Protocol.Version, version));
return;
}
// Get the object sizes from the target
int sizeofObjectID = m_readBuffer.ReadInt32();
int sizeofNumber = m_readBuffer.ReadInt32();
m_callingProcessId = m_readBuffer.ReadInt32();
m_readBuffer.SizeofObjectID = sizeofObjectID;
m_readBuffer.SizeofNumber = sizeofNumber;
m_writeBuffer.SizeofObjectID = sizeofObjectID;
m_writeBuffer.SizeofNumber = sizeofNumber;
// Let the debug manager do its thing (send breakpoints etc)
OnStateUpdate(TargetState.Connected);
// Now set the target running
if(mDebugManager.Options.BreakOnConnection)
CreateMessage_Run(ExecutionMode.Break);
else
CreateMessage_Run(ExecutionMode.Go);
}
void ProcessMessage_Disconnect()
{
string message = m_readBuffer.ReadString();
Abort(String.Format("The target has disconnected because:\r\n\r\n{0}", message));
}
void ProcessMessage_StateUpdate()
{
TargetState state = (TargetState)m_readBuffer.ReadInt32();
Int64 thread = m_readBuffer.ReadObjectID();
int line = m_readBuffer.ReadInt32();
string filename = m_readBuffer.ReadString();
OnStateUpdate(state, new LuaValue(thread, LuaValueType.THREAD), mDebugManager.FindSourceFile(filename), line);
}
private void ProcessMessage_ErrorMessage()
{
string message = m_readBuffer.ReadString();
OnErrorMessage("Lua Error", message);
}
void ProcessMessage_BreakpointAdded()
{
int bkptid = m_readBuffer.ReadInt32();
int success = m_readBuffer.ReadInt32();
OnBreakpointUpdate(bkptid, success != 0 ? BreakpointUpdateEventState.Added : BreakpointUpdateEventState.Invalid);
}
void ProcessMessage_BreakpointRemoved()
{
int bkptid = m_readBuffer.ReadInt32();
OnBreakpointUpdate(bkptid, BreakpointUpdateEventState.Removed);
}
void ProcessMessage_CallstackUpdate()
{
Int64 currentThread = m_readBuffer.ReadObjectID();
int currentFrame = m_readBuffer.ReadInt32();
int stackCount = m_readBuffer.ReadInt32();
LuaStackFrame[] stackFrames = new LuaStackFrame[stackCount];
for (int index = 0; index < stackCount; ++index)
{
string function = m_readBuffer.ReadString();
string filename = m_readBuffer.ReadString();
int line = m_readBuffer.ReadInt32();
stackFrames[index] = new LuaStackFrame(index, function, mDebugManager.FindSourceFile(filename), line);
}
OnCallstackUpdate(new CallstackUpdateEventArgs(new LuaValue(currentThread, LuaValueType.THREAD), stackFrames, currentFrame));
}
void ProcessMessage_ValueCached()
{
LuaValue value = m_readBuffer.ReadValue();
string desc = m_readBuffer.ReadString();
OnValueCached(value, desc);
}
void ProcessMessage_LocalsUpdate()
{
Int64 currentThread = m_readBuffer.ReadObjectID();
int stackFrame = m_readBuffer.ReadInt32();
bool cacheFlush = m_readBuffer.ReadInt32() != 0;
int count = m_readBuffer.ReadInt32();
List<VariableDetails> vars = new List<VariableDetails>();
List<LuaValue> path = new List<LuaValue>();
ReadVariables(vars, path, 0, count, 1);
LuaValue threadValue = new LuaValue(currentThread, LuaValueType.THREAD);
OnVariableUpdate(new VariableUpdateEventArgs(VariableUpdateType.Locals, threadValue, vars.ToArray(), cacheFlush));
}
void ProcessMessage_WatchUpdate()
{
Int64 currentThread = m_readBuffer.ReadObjectID();
int count = m_readBuffer.ReadInt32();
List<VariableDetails> vars = new List<VariableDetails>();
for (int index = 0; index < count; ++index)
{
int watchid = m_readBuffer.ReadInt32();
List<LuaValue> path = new List<LuaValue>();
ReadVariables(vars, path, watchid, 1, 1);
}
LuaValue threadValue = new LuaValue(currentThread, LuaValueType.THREAD);
OnVariableUpdate(new VariableUpdateEventArgs(VariableUpdateType.Watches, threadValue, vars.ToArray(), false));
}
void ProcessMessage_ThreadsUpdate()
{
int count = m_readBuffer.ReadInt32();
List<ThreadDetails> threads = new List<ThreadDetails>();
for (int index = 0; index < count; ++index)
{
LuaValue thread = new LuaValue(m_readBuffer.ReadObjectID(), LuaValueType.THREAD);
LuaValue parent = new LuaValue(m_readBuffer.ReadObjectID(), LuaValueType.THREAD);
string name = m_readBuffer.ReadString();
int threadid = m_readBuffer.ReadInt32();
string location = m_readBuffer.ReadString();
LuaThreadState state = (LuaThreadState)m_readBuffer.ReadInt32();
int stackSize = m_readBuffer.ReadInt16();
int stackUsed = m_readBuffer.ReadInt16();
double peak = m_readBuffer.ReadNumber();
double average = m_readBuffer.ReadNumber();
bool modified = m_readBuffer.ReadInt16() != 0;
bool valid = m_readBuffer.ReadInt16() != 0;
ThreadDetails details = new ThreadDetails(thread, parent, name, threadid, location, state, stackSize, stackUsed, peak, average, valid);
threads.Add(details);
}
OnThreadUpdate(new ThreadUpdateEventArgs(threads.ToArray()));
}
void ProcessMessage_UploadFile()
{
string fileName = m_readBuffer.ReadString();
int size = m_readBuffer.ReadInt32();
byte[] data = m_readBuffer.ReadBytes(size);
string contents = new String(Encoding.ASCII.GetChars(data));
OnFileUpload(fileName, data);
}
void ProcessMessage_SnippetResult()
{
bool success = m_readBuffer.ReadInt32() != 0;
string output = m_readBuffer.ReadString();
string result = m_readBuffer.ReadString();
OnSnippetResult(success, output, result);
}
void ProcessMessage_AutocompleteOptions()
{
AutocompleteResult[] options = null;
int seqid = m_readBuffer.ReadInt32();
int count = m_readBuffer.ReadInt32();
if (count >= 0)
{
options = new AutocompleteResult[count];
for (int index = 0; index < count; ++index)
{
LuaValue key = m_readBuffer.ReadValue();
LuaValueType valueType = (LuaValueType)m_readBuffer.ReadInt32();
options[index] = new AutocompleteResult(key, valueType);
}
}
string message = m_readBuffer.ReadString();
OnAutocompleteOptions(seqid, options, message);
}
void ProcessMessage_ExMessage()
{
string command = m_readBuffer.ReadString();
int datasize = m_readBuffer.ReadInt32();
byte[] data = null;
if (datasize > 0)
data = m_readBuffer.ReadBytes(datasize);
OnExMessage(command, data);
}
void ReadVariables(List<VariableDetails> vars, List<LuaValue> path, int watchid, int count, int depth)
{
for (int index = 0; index < count; ++index)
{
LuaValue key = m_readBuffer.ReadValue();
LuaValue value = m_readBuffer.ReadValue();
VariableInfoFlag flags = (VariableInfoFlag)m_readBuffer.ReadInt16();
bool valid = (flags & VariableInfoFlag.Valid) != 0;
bool expanded = (flags & VariableInfoFlag.Expanded) != 0;
bool hasEntries = (flags & VariableInfoFlag.HasEntries) != 0;
bool hasMetadata = (flags & VariableInfoFlag.HasMetadata) != 0;
VariableClass varclass = (VariableClass)m_readBuffer.ReadInt16();
VariableDetails var = new VariableDetails(watchid, path.ToArray(), key, value, expanded, hasEntries, hasMetadata, valid, varclass);
vars.Add(var);
int expansionCount = m_readBuffer.ReadInt32();
if (expansionCount > 0)
{
path.Add(key);
ReadVariables(vars, path, watchid, expansionCount, depth + 1);
path.RemoveAt(path.Count - 1);
}
}
}
void OnDebugPrint(String message)
{
DebugPrintEventArgs args = new DebugPrintEventArgs(message);
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.DebugPrint != null)
this.DebugPrint(this, args);
}));
}
// This message is synchronous, blocking the communications thread until the user has confirmed it.
private void OnErrorMessage(String title, String message)
{
ErrorMessageEventArgs args = new ErrorMessageEventArgs(title, message);
if (mForm != null && mForm.IsHandleCreated)
mForm.Invoke(new MethodInvoker(delegate()
{
if (this.ErrorMessage != null)
this.ErrorMessage(this, args);
}));
}
private void OnStatusMessage(String message)
{
StatusMessageEventArgs args = new StatusMessageEventArgs(message);
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.StatusMessage != null)
this.StatusMessage(this, args);
}));
}
private void OnStateUpdate(TargetState targetState)
{
StateUpdateEventArgs args = new StateUpdateEventArgs(targetState);
if (mLastUpdateMessage == null || !mLastUpdateMessage.Equals(args))
{
mLastUpdateMessage = args;
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.StateUpdate != null)
this.StateUpdate(this, args);
}));
}
}
private void OnStateUpdate(TargetState targetState, LuaValue thread, String file, int line)
{
StateUpdateEventArgs args = new StateUpdateEventArgs(targetState, thread, file, line);
if (mLastUpdateMessage == null || !mLastUpdateMessage.Equals(args))
{
mLastUpdateMessage = args;
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.StateUpdate != null)
this.StateUpdate(this, args);
}));
}
}
void OnCallstackUpdate(CallstackUpdateEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.CallstackUpdate != null)
this.CallstackUpdate(this, args);
}));
}
void OnThreadUpdate(ThreadUpdateEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.ThreadUpdate != null)
this.ThreadUpdate(this, args);
}));
}
void OnVariableUpdate(VariableUpdateEventArgs args)
{
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.VariableUpdate != null)
this.VariableUpdate(this, args);
}));
}
void OnBreakpointUpdate(int bkptid, BreakpointUpdateEventState state)
{
BreakpointUpdateEventArgs args = new BreakpointUpdateEventArgs(bkptid, state);
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.BreakpointUpdate != null)
this.BreakpointUpdate(this, args);
}));
}
void OnValueCached(LuaValue value, string desc)
{
ValueCachedEventArgs args = new ValueCachedEventArgs(value, desc);
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.ValueCached != null)
this.ValueCached(this, args);
}));
}
void OnFileUpload(string fileName, byte [] data)
{
FileUploadEventArgs args = new FileUploadEventArgs(fileName, data);
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.FileUpload != null)
this.FileUpload(this, args);
}));
}
void OnSnippetResult(bool success, string output, string result)
{
SnippetResultEventArgs args = new SnippetResultEventArgs(success, output, result);
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.SnippetResult != null)
this.SnippetResult(this, args);
}));
}
void OnAutocompleteOptions(int seqid, AutocompleteResult [] options, string message)
{
AutocompleteOptionsEventArgs args = new AutocompleteOptionsEventArgs(seqid, options, message);
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.AutocompleteOptions != null)
this.AutocompleteOptions(this, args);
}));
}
void OnExMessage(string command, byte [] data)
{
ExMessageEventArgs args = new ExMessageEventArgs(command, data);
if (mForm != null && mForm.IsHandleCreated)
mForm.BeginInvoke(new MethodInvoker(delegate()
{
if (this.ExMessage != null)
this.ExMessage(this, args);
}));
}
#region Target Members
public HostInfo HostInfo
{
get { return mConnection.HostInfo; }
}
public event DebugPrintEventHandler DebugPrint;
public event ErrorMessageEventHandler ErrorMessage;
public event StatusMessageEventHandler StatusMessage;
public event StateUpdateEventHandler StateUpdate;
public event CallstackUpdateEventHandler CallstackUpdate;
public event ThreadUpdateEventHandler ThreadUpdate;
public event VariableUpdateEventHandler VariableUpdate;
public event BreakpointUpdateEventHandler BreakpointUpdate;
public event ValueCachedEventHandler ValueCached;
public event FileUploadEventHandler FileUpload;
public event SnippetResultEventHandler SnippetResult;
public event AutocompleteOptionsEventHandler AutocompleteOptions;
public event ExMessageEventHandler ExMessage;
private object BlockingInvoke(ReturnDelegate del)
{
// Fire off the asynchronous operation
MessageQueue.BlockingMessage message = new MessageQueue.BlockingMessage(del);
mMessageQueue.Push(message);
mHostEvent.Set();
// Wait for it to finish
message.AsyncWaitHandle.WaitOne();
// Return the result, or re-throw the exception
if (message.Exception != null)
throw (message.Exception);
else
return message.Result;
}
private void AsyncInvoke(VoidDelegate del)
{
MessageQueue.Message message = new MessageQueue.Message(del);
mMessageQueue.Push(message);
mHostEvent.Set();
}
public void Disconnect()
{
AsyncInvoke(delegate()
{
m_shutdown = true;
}
);
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
public void Run(ExecutionMode mode)
{
AsyncInvoke(delegate()
{
CreateMessage_Run(mode);
SendMessages();
System.Diagnostics.Process bProcess = System.Diagnostics.Process.GetProcessById(this.m_callingProcessId);
if (bProcess != null)
{
SetForegroundWindow(bProcess.MainWindowHandle);
}
}
);
}
public void AddBreakpoint(string fileName, int lineNumber, int bkptid)
{
AsyncInvoke(delegate()
{
CreateMessage_AddBreakpoint(fileName, lineNumber, bkptid);
SendMessages();
}
);
}
public void RemoveBreakpoint(int bkptid)
{
AsyncInvoke(delegate()
{
CreateMessage_RemoveBreakpoint(bkptid);
SendMessages();
}
);
}
public void ClearBreakpoints()
{
AsyncInvoke(delegate()
{
throw new Exception("The method or operation is not implemented.");
}
);
}
public void IgnoreError(string fileName, int lineNumber)
{
AsyncInvoke(delegate()
{
CreateMessage_IgnoreError(fileName, lineNumber);
SendMessages();
}
);
}
public void RetrieveStatus(LuaValue thread, int stackFrame)
{
AsyncInvoke(delegate()
{
CreateMessage_RetrieveStatus(thread, stackFrame);
SendMessages();
}
);
}
public void RetrieveThreads()
{
AsyncInvoke(delegate()
{
CreateMessage_RetrieveThreads();
SendMessages();
}
);
}
public void RetrieveLocals(LuaValue thread, int stackFrame)
{
AsyncInvoke(delegate()
{
System.Diagnostics.Debug.Assert(!thread.IsNil());
CreateMessage_RetrieveLocals(thread, stackFrame);
SendMessages();
}
);
}
public void ExpandLocal(LuaValue[] path)
{
AsyncInvoke(delegate()
{
CreateMessage_ExpandLocal(path);
SendMessages();
}
);
}
public void CloseLocal(LuaValue[] path)
{
AsyncInvoke(delegate()
{
CreateMessage_CloseLocal(path);
SendMessages();
}
);
}
public void RetrieveWatches(LuaValue thread, int stackFrame)
{
AsyncInvoke(delegate()
{
System.Diagnostics.Debug.Assert(!thread.IsNil());
CreateMessage_RetrieveWatches(thread, stackFrame);
SendMessages();
}
);
}
public void UpdateWatch(int watchid, LuaValue thread, int stackFrame)
{
AsyncInvoke(delegate()
{
System.Diagnostics.Debug.Assert(!thread.IsNil());
CreateMessage_UpdateWatch(watchid, thread, stackFrame);
SendMessages();
}
);
}
public void AddWatch(string expr, int watchid)
{
AsyncInvoke(delegate()
{
CreateMessage_AddWatch(expr, watchid);
SendMessages();
}
);
}
public void RemoveWatch(int watchid)
{
AsyncInvoke(delegate()
{
CreateMessage_RemoveWatch(watchid);
SendMessages();
}
);
}
public void ExpandWatch(int watchid, LuaValue[] path)
{
AsyncInvoke(delegate()
{
CreateMessage_ExpandWatch(watchid, path);
SendMessages();
}
);
}
public void CloseWatch(int watchid, LuaValue[] path)
{
AsyncInvoke(delegate()
{
CreateMessage_CloseWatch(watchid, path);
SendMessages();
}
);
}
public void ClearWatches()
{
AsyncInvoke(delegate()
{
throw new Exception("The method or operation is not implemented.");
}
);
}
public void RunSnippet(string snippet, LuaValue thread, int stackFrame)
{
AsyncInvoke(delegate()
{
CreateMessage_RunSnippet(snippet, thread, stackFrame);
SendMessages();
}
);
}
public void RetrieveAutocompleteOptions(int seqid, string expression, LuaValue thread, int stackFrame)
{
AsyncInvoke(delegate()
{
CreateMessage_RetrieveAutocompleteOptions(seqid, expression, thread, stackFrame);
SendMessages();
}
);
}
public bool DownloadFile(string fileName)
{
return (bool) BlockingInvoke(delegate()
{
return mConnection.DownloadFile(fileName);
}
);
}
public void ExCommand(string command, byte[] data)
{
AsyncInvoke(delegate()
{
CreateMessage_ExCommand(command, data);
SendMessages();
}
);
}
#endregion
void SendMessages()
{
try
{
if (!m_shutdown)
mConnection.Send(m_writeBuffer.Data, 0, m_writeBuffer.Length);
}
catch (System.Exception ex)
{
Abort(ex.ToString());
}
m_writeBuffer.Length = 0;
}
void CreateMessage_Run(ExecutionMode mode)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.Run);
m_writeBuffer.Write((int)mode);
m_writeBuffer.End();
}
void CreateMessage_AddBreakpoint(string file, int line, int bkptid)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.AddBreakpoint);
m_writeBuffer.Write((int)bkptid);
m_writeBuffer.Write(mDebugManager.FindTargetFile(file));
m_writeBuffer.Write((int)line);
m_writeBuffer.End();
}
void CreateMessage_RemoveBreakpoint(int bkptid)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.RemoveBreakpoint);
m_writeBuffer.Write((int)bkptid);
m_writeBuffer.End();
}
void CreateMessage_IgnoreError(string file, int line)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.IgnoreError);
m_writeBuffer.Write(mDebugManager.FindTargetFile(file));
m_writeBuffer.Write((int)line);
m_writeBuffer.End();
}
private void CreateMessage_RetrieveStatus(LuaValue thread, int stackFrame)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.RetrieveStatus);
m_writeBuffer.WriteObjectID(thread.AsIdentifier());
m_writeBuffer.Write((int)stackFrame);
m_writeBuffer.End();
}
private void CreateMessage_RetrieveThreads()
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.RetrieveThreads);
m_writeBuffer.End();
}
void CreateMessage_RetrieveLocals(LuaValue thread, int stackFrame)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.RetrieveLocals);
m_writeBuffer.WriteObjectID(thread.AsIdentifier());
m_writeBuffer.Write((int)stackFrame);
m_writeBuffer.End();
}
private void CreateMessage_ExpandLocal(LuaValue[] path)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.ExpandLocal);
m_writeBuffer.Write((int)path.Length);
foreach (LuaValue value in path)
{
m_writeBuffer.WriteValue(value);
}
m_writeBuffer.End();
}
private void CreateMessage_CloseLocal(LuaValue[] path)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.CloseLocal);
m_writeBuffer.Write((int)path.Length);
foreach (LuaValue value in path)
{
m_writeBuffer.WriteValue(value);
}
m_writeBuffer.End();
}
private void CreateMessage_RetrieveWatches(LuaValue thread, int stackFrame)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.RetrieveWatches);
m_writeBuffer.WriteObjectID(thread.AsIdentifier());
m_writeBuffer.Write((int)stackFrame);
m_writeBuffer.End();
}
private void CreateMessage_UpdateWatch(int watchid, LuaValue thread, int stackFrame)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.UpdateWatch);
m_writeBuffer.Write((int)watchid);
m_writeBuffer.WriteObjectID(thread.AsIdentifier());
m_writeBuffer.Write((int)stackFrame);
m_writeBuffer.End();
}
private void CreateMessage_AddWatch(string expr, int watchid)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.AddWatch);
m_writeBuffer.Write(expr);
m_writeBuffer.Write(watchid);
m_writeBuffer.End();
}
private void CreateMessage_RemoveWatch(int watchid)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.RemoveWatch);
m_writeBuffer.Write(watchid);
m_writeBuffer.End();
}
private void CreateMessage_ExpandWatch(int watchid, LuaValue[] path)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.ExpandWatch);
m_writeBuffer.Write((int)watchid);
m_writeBuffer.Write((int)path.Length - 1);
for (int index = 1; index < path.Length; ++index)
{
m_writeBuffer.WriteValue(path[index]);
}
m_writeBuffer.End();
}
private void CreateMessage_CloseWatch(int watchid, LuaValue[] path)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.CloseWatch);
m_writeBuffer.Write((int)watchid);
m_writeBuffer.Write((int)path.Length - 1);
for (int index = 1; index < path.Length; ++index)
{
m_writeBuffer.WriteValue(path[index]);
}
m_writeBuffer.End();
}
private void CreateMessage_RunSnippet(string snippet, LuaValue thread, int stackFrame)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.RunSnippet);
m_writeBuffer.WriteObjectID(thread.AsIdentifier());
m_writeBuffer.Write((int)stackFrame);
m_writeBuffer.Write(snippet);
m_writeBuffer.End();
}
private void CreateMessage_RetrieveAutocompleteOptions(int seqid, string expression, LuaValue thread, int stackFrame)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.RetrieveAutocompleteOptions);
m_writeBuffer.Write((int)seqid);
m_writeBuffer.WriteObjectID(thread.AsIdentifier());
m_writeBuffer.Write((int)stackFrame);
m_writeBuffer.Write(expression);
m_writeBuffer.End();
}
private void CreateMessage_ExCommand(string command, byte[] data)
{
m_writeBuffer.Begin();
m_writeBuffer.Write((int)DebuggerMessage.ExCommand);
m_writeBuffer.Write(command);
if (data != null)
m_writeBuffer.Write(data);
m_writeBuffer.End();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Saltarelle.Compiler.JSModel.Statements;
using Saltarelle.Compiler.JSModel.ExtensionMethods;
namespace Saltarelle.Compiler.JSModel.Expressions {
public enum ExpressionNodeType {
ArrayLiteral,
// Binary
LogicalAnd,
LogicalOr,
NotEqual,
LesserOrEqual,
GreaterOrEqual,
Lesser,
Greater,
Equal,
Subtract,
Add,
Modulo,
Divide,
Multiply,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
Same,
NotSame,
LeftShift,
RightShiftSigned,
RightShiftUnsigned,
InstanceOf,
In,
Index,
Assign,
MultiplyAssign,
DivideAssign,
ModuloAssign,
AddAssign,
SubtractAssign,
LeftShiftAssign,
RightShiftSignedAssign,
RightShiftUnsignedAssign,
BitwiseAndAssign,
BitwiseOrAssign,
BitwiseXorAssign,
// /Binary
Comma,
Conditional,
// Constants
Number,
String,
Boolean,
Regexp,
Null,
// /Constants
FunctionDefinition,
Identifier,
Invocation,
MemberAccess,
New,
ObjectLiteral,
// Unary
TypeOf,
LogicalNot,
Negate,
Positive,
PrefixPlusPlus,
PrefixMinusMinus,
PostfixPlusPlus,
PostfixMinusMinus,
Delete,
Void,
BitwiseNot,
// /Unary
This,
// Fake
TypeReference,
Literal,
AssignFirst = Assign,
AssignLast = BitwiseXorAssign,
BinaryFirst = LogicalAnd,
BinaryLast = BitwiseXorAssign,
ConstantFirst = Number,
ConstantLast = Null,
UnaryFirst = TypeOf,
UnaryLast = BitwiseNot
}
[Serializable, DebuggerDisplay("{DebugToString()}")]
public abstract class JsExpression {
[System.Diagnostics.DebuggerStepThrough]
public abstract TReturn Accept<TReturn, TData>(IExpressionVisitor<TReturn, TData> visitor, TData data);
public ExpressionNodeType NodeType { get; private set; }
private string DebugToString() {
return OutputFormatter.Format(this, allowIntermediates: true);
}
public static implicit operator JsStatement(JsExpression expr) {
return JsStatement.Expression(expr);
}
public static implicit operator JsExpressionStatement(JsExpression expr) {
return JsStatement.Expression(expr);
}
protected JsExpression(ExpressionNodeType nodeType) {
NodeType = nodeType;
}
public static JsArrayLiteralExpression ArrayLiteral(IEnumerable<JsExpression> elements) {
return new JsArrayLiteralExpression(elements);
}
public static JsArrayLiteralExpression ArrayLiteral(params JsExpression[] elements) {
return ArrayLiteral((IEnumerable<JsExpression>)elements);
}
public static JsBinaryExpression Binary(ExpressionNodeType nodeType, JsExpression left, JsExpression right) {
return new JsBinaryExpression(nodeType, left, right);
}
public static JsBinaryExpression LogicalAnd(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.LogicalAnd, left, right);
}
public static JsBinaryExpression LogicalOr(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.LogicalOr, left, right);
}
public static JsBinaryExpression NotEqual(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.NotEqual, left, right);
}
public static JsBinaryExpression LesserOrEqual(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.LesserOrEqual, left, right);
}
public static JsBinaryExpression GreaterOrEqual(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.GreaterOrEqual, left, right);
}
public static JsBinaryExpression Lesser(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Lesser, left, right);
}
public static JsBinaryExpression Greater(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Greater, left, right);
}
public static JsBinaryExpression Equal(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Equal, left, right);
}
public static JsBinaryExpression Subtract(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Subtract, left, right);
}
public static JsBinaryExpression Add(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Add, left, right);
}
public static JsBinaryExpression Modulo(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Modulo, left, right);
}
public static JsBinaryExpression Divide(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Divide, left, right);
}
public static JsBinaryExpression Multiply(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Multiply, left, right);
}
public static JsBinaryExpression BitwiseAnd(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.BitwiseAnd, left, right);
}
public static JsBinaryExpression BitwiseOr(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.BitwiseOr, left, right);
}
public static JsBinaryExpression BitwiseXor(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.BitwiseXor, left, right);
}
public static JsBinaryExpression Same(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Same, left, right);
}
public static JsBinaryExpression NotSame(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.NotSame, left, right);
}
public static JsBinaryExpression LeftShift(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.LeftShift, left, right);
}
public static JsBinaryExpression RightShiftSigned(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.RightShiftSigned, left, right);
}
public static JsBinaryExpression RightShiftUnsigned(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.RightShiftUnsigned, left, right);
}
public static JsBinaryExpression InstanceOf(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.InstanceOf, left, right);
}
public static JsBinaryExpression In(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.In, left, right);
}
public static JsBinaryExpression Index(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Index, left, right);
}
public static JsBinaryExpression Assign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.Assign, left, right);
}
public static JsBinaryExpression MultiplyAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.MultiplyAssign, left, right);
}
public static JsBinaryExpression DivideAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.DivideAssign, left, right);
}
public static JsBinaryExpression ModuloAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.ModuloAssign, left, right);
}
public static JsBinaryExpression AddAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.AddAssign, left, right);
}
public static JsBinaryExpression SubtractAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.SubtractAssign, left, right);
}
public static JsBinaryExpression LeftShiftAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.LeftShiftAssign, left, right);
}
public static JsBinaryExpression RightShiftSignedAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.RightShiftSignedAssign, left, right);
}
public static JsBinaryExpression RightShiftUnsignedAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.RightShiftUnsignedAssign, left, right);
}
public static JsBinaryExpression BitwiseAndAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.BitwiseAndAssign, left, right);
}
public static JsBinaryExpression BitwiseOrAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.BitwiseOrAssign, left, right);
}
public static JsBinaryExpression BitwiseXorAssign(JsExpression left, JsExpression right) {
return Binary(ExpressionNodeType.BitwiseXorAssign, left, right);
}
public static JsCommaExpression Comma(IEnumerable<JsExpression> expressions) {
return new JsCommaExpression(expressions);
}
public static JsCommaExpression Comma(params JsExpression[] expressions) {
return Comma((IEnumerable<JsExpression>)expressions);
}
public static JsConditionalExpression Conditional(JsExpression test, JsExpression truePart, JsExpression falsePart) {
return new JsConditionalExpression(test, truePart, falsePart);
}
public static JsConstantExpression Regexp(string pattern, string options = null) {
return new JsConstantExpression(new JsConstantExpression.RegexpData(pattern, options ?? ""));
}
public static JsConstantExpression Number(double value) {
return new JsConstantExpression(value);
}
public static JsConstantExpression String(string value) {
return new JsConstantExpression(value);
}
public static JsConstantExpression Boolean(bool value) {
return value ? True : False;
}
public static JsConstantExpression Null { get { return JsConstantExpression.Null; } }
public static JsConstantExpression True { get { return JsConstantExpression.True; } }
public static JsConstantExpression False { get { return JsConstantExpression.False; } }
public static JsFunctionDefinitionExpression FunctionDefinition(IEnumerable<string> parameterNames, JsStatement body, string name = null) {
return new JsFunctionDefinitionExpression(parameterNames, body, name);
}
public static JsIdentifierExpression Identifier(string name) {
return new JsIdentifierExpression(name);
}
public static JsInvocationExpression Invocation(JsExpression method, IEnumerable<JsExpression> arguments) {
return new JsInvocationExpression(method, arguments);
}
public static JsInvocationExpression Invocation(JsExpression method, params JsExpression[] arguments) {
return Invocation(method, (IEnumerable<JsExpression>)arguments);
}
public static JsMemberAccessExpression MemberAccess(JsExpression target, string member) {
return new JsMemberAccessExpression(target, member);
}
/// <summary>
/// Creates an expression to access a member. If the member is a valid JS identifier, will return target.member, otherwise returns traget["member"].
/// </summary>
public static JsExpression Member(JsExpression target, string member) {
return member.IsValidJavaScriptIdentifier() ? (JsExpression)MemberAccess(target, member) : Index(target, JsExpression.String(member));
}
public static JsNewExpression New(JsExpression constructor, IEnumerable<JsExpression> arguments) {
return new JsNewExpression(constructor, arguments);
}
public static JsNewExpression New(JsExpression constructor, params JsExpression[] arguments) {
return New(constructor, (IEnumerable<JsExpression>)arguments);
}
public static JsObjectLiteralExpression ObjectLiteral(IEnumerable<JsObjectLiteralProperty> values) {
return new JsObjectLiteralExpression(values);
}
public static JsObjectLiteralExpression ObjectLiteral(params JsObjectLiteralProperty[] values) {
return ObjectLiteral((IEnumerable<JsObjectLiteralProperty>)values);
}
public static JsUnaryExpression Unary(ExpressionNodeType nodeType, JsExpression operand) {
return new JsUnaryExpression(nodeType, operand);
}
public static JsUnaryExpression TypeOf(JsExpression operand) {
return Unary(ExpressionNodeType.TypeOf, operand);
}
public static JsUnaryExpression LogicalNot(JsExpression operand) {
return Unary(ExpressionNodeType.LogicalNot, operand);
}
public static JsUnaryExpression Negate(JsExpression operand) {
return Unary(ExpressionNodeType.Negate, operand);
}
public static JsUnaryExpression Positive(JsExpression operand) {
return Unary(ExpressionNodeType.Positive, operand);
}
public static JsUnaryExpression PrefixPlusPlus(JsExpression operand) {
return Unary(ExpressionNodeType.PrefixPlusPlus, operand);
}
public static JsUnaryExpression PrefixMinusMinus(JsExpression operand) {
return Unary(ExpressionNodeType.PrefixMinusMinus, operand);
}
public static JsUnaryExpression PostfixPlusPlus(JsExpression operand) {
return Unary(ExpressionNodeType.PostfixPlusPlus, operand);
}
public static JsUnaryExpression PostfixMinusMinus(JsExpression operand) {
return Unary(ExpressionNodeType.PostfixMinusMinus, operand);
}
public static JsUnaryExpression Delete(JsExpression operand) {
return Unary(ExpressionNodeType.Delete, operand);
}
public static JsUnaryExpression Void(JsExpression operand) {
return Unary(ExpressionNodeType.Void, operand);
}
public static JsUnaryExpression BitwiseNot(JsExpression operand) {
return Unary(ExpressionNodeType.BitwiseNot, operand);
}
public static JsThisExpression This { get { return JsThisExpression.This; } }
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet
* The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangRussianModel.cpp
* and adjusted to language specific support.
*/
namespace UtfUnknown.Core.Models.SingleByte.Russian;
internal class Windows_1251_RussianModel : RussianModel
{
private static readonly byte[] CHAR_TO_ORDER_MAP =
{
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
RET,
CTR,
CTR,
RET,
CTR,
CTR, /* 0X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 1X */
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* 2X */
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* 3X */
SYM,
142,
143,
144,
145,
146,
147,
148,
149,
150,
151,
152,
74,
153,
75,
154, /* 4X */
155,
156,
157,
158,
159,
160,
161,
162,
163,
164,
165,
SYM,
SYM,
SYM,
SYM,
SYM, /* 5X */
SYM,
71,
172,
66,
173,
65,
174,
76,
175,
64,
176,
177,
77,
72,
178,
69, /* 6X */
67,
179,
78,
73,
180,
181,
79,
182,
183,
184,
185,
SYM,
SYM,
SYM,
SYM,
SYM, /* 7X */
191,
192,
193,
194,
195,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206, /* 8X */
207,
208,
209,
210,
211,
212,
213,
214,
ILL,
216,
217,
218,
219,
220,
221,
222, /* 9X */
223,
224,
225,
226,
227,
228,
229,
230,
231,
232,
233,
234,
235,
236,
237,
238, /* AX */
239,
240,
241,
242,
243,
244,
245,
246,
68,
247,
248,
249,
250,
251,
NUM,
SYM, /* BX */
37,
44,
33,
46,
41,
48,
56,
51,
42,
60,
36,
49,
38,
31,
34,
35, /* CX */
45,
32,
40,
52,
53,
55,
58,
50,
57,
63,
70,
62,
61,
47,
59,
43, /* DX */
3,
21,
10,
19,
13,
2,
24,
20,
4,
23,
11,
8,
12,
5,
1,
15, /* EX */
9,
7,
6,
14,
39,
26,
28,
22,
25,
29,
54,
18,
17,
30,
27,
16 /* FX */
};
/*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */
public Windows_1251_RussianModel()
: base(
CHAR_TO_ORDER_MAP,
CodepageName.WINDOWS_1251) { }
}
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Documents;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Lucene.Net.Util.BytesRef;
using CannedTokenStream = Lucene.Net.Analysis.CannedTokenStream;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MultiFields = Lucene.Net.Index.MultiFields;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Term = Lucene.Net.Index.Term;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TextField = TextField;
using Token = Lucene.Net.Analysis.Token;
/// <summary>
/// this class tests the MultiPhraseQuery class.
///
///
/// </summary>
[TestFixture]
public class TestMultiPhraseQuery : LuceneTestCase
{
[Test]
public virtual void TestPhrasePrefix()
{
Directory indexStore = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, indexStore);
Add("blueberry pie", writer);
Add("blueberry strudel", writer);
Add("blueberry pizza", writer);
Add("blueberry chewing gum", writer);
Add("bluebird pizza", writer);
Add("bluebird foobar pizza", writer);
Add("piccadilly circus", writer);
IndexReader reader = writer.GetReader();
IndexSearcher searcher = NewSearcher(reader);
// search for "blueberry pi*":
MultiPhraseQuery query1 = new MultiPhraseQuery();
// search for "strawberry pi*":
MultiPhraseQuery query2 = new MultiPhraseQuery();
query1.Add(new Term("body", "blueberry"));
query2.Add(new Term("body", "strawberry"));
LinkedList<Term> termsWithPrefix = new LinkedList<Term>();
// this TermEnum gives "piccadilly", "pie" and "pizza".
string prefix = "pi";
TermsEnum te = MultiFields.GetFields(reader).GetTerms("body").GetEnumerator();
te.SeekCeil(new BytesRef(prefix));
do
{
string s = te.Term.Utf8ToString();
if (s.StartsWith(prefix, StringComparison.Ordinal))
{
termsWithPrefix.AddLast(new Term("body", s));
}
else
{
break;
}
} while (te.MoveNext());
query1.Add(termsWithPrefix.ToArray(/*new Term[0]*/));
Assert.AreEqual("body:\"blueberry (piccadilly pie pizza)\"", query1.ToString());
query2.Add(termsWithPrefix.ToArray(/*new Term[0]*/));
Assert.AreEqual("body:\"strawberry (piccadilly pie pizza)\"", query2.ToString());
ScoreDoc[] result;
result = searcher.Search(query1, null, 1000).ScoreDocs;
Assert.AreEqual(2, result.Length);
result = searcher.Search(query2, null, 1000).ScoreDocs;
Assert.AreEqual(0, result.Length);
// search for "blue* pizza":
MultiPhraseQuery query3 = new MultiPhraseQuery();
termsWithPrefix.Clear();
prefix = "blue";
te.SeekCeil(new BytesRef(prefix));
do
{
if (te.Term.Utf8ToString().StartsWith(prefix, StringComparison.Ordinal))
{
termsWithPrefix.AddLast(new Term("body", te.Term.Utf8ToString()));
}
} while (te.MoveNext());
query3.Add(termsWithPrefix.ToArray(/*new Term[0]*/));
query3.Add(new Term("body", "pizza"));
result = searcher.Search(query3, null, 1000).ScoreDocs;
Assert.AreEqual(2, result.Length); // blueberry pizza, bluebird pizza
Assert.AreEqual("body:\"(blueberry bluebird) pizza\"", query3.ToString());
// test slop:
query3.Slop = 1;
result = searcher.Search(query3, null, 1000).ScoreDocs;
// just make sure no exc:
searcher.Explain(query3, 0);
Assert.AreEqual(3, result.Length); // blueberry pizza, bluebird pizza, bluebird
// foobar pizza
MultiPhraseQuery query4 = new MultiPhraseQuery();
try
{
query4.Add(new Term("field1", "foo"));
query4.Add(new Term("field2", "foobar"));
Assert.Fail();
}
#pragma warning disable 168
catch (ArgumentException e)
#pragma warning restore 168
{
// okay, all terms must belong to the same field
}
writer.Dispose();
reader.Dispose();
indexStore.Dispose();
}
// LUCENE-2580
[Test]
public virtual void TestTall()
{
Directory indexStore = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, indexStore);
Add("blueberry chocolate pie", writer);
Add("blueberry chocolate tart", writer);
IndexReader r = writer.GetReader();
writer.Dispose();
IndexSearcher searcher = NewSearcher(r);
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(new Term("body", "blueberry"));
q.Add(new Term("body", "chocolate"));
q.Add(new Term[] { new Term("body", "pie"), new Term("body", "tart") });
Assert.AreEqual(2, searcher.Search(q, 1).TotalHits);
r.Dispose();
indexStore.Dispose();
}
//ORIGINAL LINE: @Ignore public void testMultiSloppyWithRepeats() throws java.io.IOException
[Test]
[Ignore("This appears to be a known issue")]
public virtual void TestMultiSloppyWithRepeats() //LUCENE-3821 fixes sloppy phrase scoring, except for this known problem
{
Directory indexStore = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, indexStore);
Add("a b c d e f g h i k", writer);
IndexReader r = writer.GetReader();
writer.Dispose();
IndexSearcher searcher = NewSearcher(r);
MultiPhraseQuery q = new MultiPhraseQuery();
// this will fail, when the scorer would propagate [a] rather than [a,b],
q.Add(new Term[] { new Term("body", "a"), new Term("body", "b") });
q.Add(new Term[] { new Term("body", "a") });
q.Slop = 6;
Assert.AreEqual(1, searcher.Search(q, 1).TotalHits); // should match on "a b"
r.Dispose();
indexStore.Dispose();
}
[Test]
public virtual void TestMultiExactWithRepeats()
{
Directory indexStore = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, indexStore);
Add("a b c d e f g h i k", writer);
IndexReader r = writer.GetReader();
writer.Dispose();
IndexSearcher searcher = NewSearcher(r);
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(new Term[] { new Term("body", "a"), new Term("body", "d") }, 0);
q.Add(new Term[] { new Term("body", "a"), new Term("body", "f") }, 2);
Assert.AreEqual(1, searcher.Search(q, 1).TotalHits); // should match on "a b"
r.Dispose();
indexStore.Dispose();
}
private void Add(string s, RandomIndexWriter writer)
{
Document doc = new Document();
doc.Add(NewTextField("body", s, Field.Store.YES));
writer.AddDocument(doc);
}
[Test]
public virtual void TestBooleanQueryContainingSingleTermPrefixQuery()
{
// this tests against bug 33161 (now fixed)
// In order to cause the bug, the outer query must have more than one term
// and all terms required.
// The contained PhraseMultiQuery must contain exactly one term array.
Directory indexStore = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, indexStore);
Add("blueberry pie", writer);
Add("blueberry chewing gum", writer);
Add("blue raspberry pie", writer);
IndexReader reader = writer.GetReader();
IndexSearcher searcher = NewSearcher(reader);
// this query will be equivalent to +body:pie +body:"blue*"
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("body", "pie")), Occur.MUST);
MultiPhraseQuery trouble = new MultiPhraseQuery();
trouble.Add(new Term[] { new Term("body", "blueberry"), new Term("body", "blue") });
q.Add(trouble, Occur.MUST);
// exception will be thrown here without fix
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length, "Wrong number of hits");
// just make sure no exc:
searcher.Explain(q, 0);
writer.Dispose();
reader.Dispose();
indexStore.Dispose();
}
[Test]
public virtual void TestPhrasePrefixWithBooleanQuery()
{
Directory indexStore = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, indexStore);
Add("this is a test", "object", writer);
Add("a note", "note", writer);
IndexReader reader = writer.GetReader();
IndexSearcher searcher = NewSearcher(reader);
// this query will be equivalent to +type:note +body:"a t*"
BooleanQuery q = new BooleanQuery();
q.Add(new TermQuery(new Term("type", "note")), Occur.MUST);
MultiPhraseQuery trouble = new MultiPhraseQuery();
trouble.Add(new Term("body", "a"));
trouble.Add(new Term[] { new Term("body", "test"), new Term("body", "this") });
q.Add(trouble, Occur.MUST);
// exception will be thrown here without fix for #35626:
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
Assert.AreEqual(0, hits.Length, "Wrong number of hits");
writer.Dispose();
reader.Dispose();
indexStore.Dispose();
}
[Test]
public virtual void TestNoDocs()
{
Directory indexStore = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, indexStore);
Add("a note", "note", writer);
IndexReader reader = writer.GetReader();
IndexSearcher searcher = NewSearcher(reader);
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(new Term("body", "a"));
q.Add(new Term[] { new Term("body", "nope"), new Term("body", "nope") });
Assert.AreEqual(0, searcher.Search(q, null, 1).TotalHits, "Wrong number of hits");
// just make sure no exc:
searcher.Explain(q, 0);
writer.Dispose();
reader.Dispose();
indexStore.Dispose();
}
[Test]
public virtual void TestHashCodeAndEquals()
{
MultiPhraseQuery query1 = new MultiPhraseQuery();
MultiPhraseQuery query2 = new MultiPhraseQuery();
Assert.AreEqual(query1.GetHashCode(), query2.GetHashCode());
Assert.IsTrue(query1.Equals(query2));
Assert.AreEqual(query1, query2);
Term term1 = new Term("someField", "someText");
query1.Add(term1);
query2.Add(term1);
Assert.AreEqual(query1.GetHashCode(), query2.GetHashCode());
Assert.AreEqual(query1, query2);
Term term2 = new Term("someField", "someMoreText");
query1.Add(term2);
Assert.IsFalse(query1.GetHashCode() == query2.GetHashCode());
Assert.IsFalse(query1.Equals(query2));
query2.Add(term2);
Assert.AreEqual(query1.GetHashCode(), query2.GetHashCode());
Assert.AreEqual(query1, query2);
}
private void Add(string s, string type, RandomIndexWriter writer)
{
Document doc = new Document();
doc.Add(NewTextField("body", s, Field.Store.YES));
doc.Add(NewStringField("type", type, Field.Store.NO));
writer.AddDocument(doc);
}
// LUCENE-2526
[Test]
public virtual void TestEmptyToString()
{
(new MultiPhraseQuery()).ToString();
}
[Test]
public virtual void TestCustomIDF()
{
Directory indexStore = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, indexStore);
Add("this is a test", "object", writer);
Add("a note", "note", writer);
IndexReader reader = writer.GetReader();
IndexSearcher searcher = NewSearcher(reader);
searcher.Similarity = new DefaultSimilarityAnonymousInnerClassHelper(this);
MultiPhraseQuery query = new MultiPhraseQuery();
query.Add(new Term[] { new Term("body", "this"), new Term("body", "that") });
query.Add(new Term("body", "is"));
Weight weight = query.CreateWeight(searcher);
Assert.AreEqual(10f * 10f, weight.GetValueForNormalization(), 0.001f);
writer.Dispose();
reader.Dispose();
indexStore.Dispose();
}
private class DefaultSimilarityAnonymousInnerClassHelper : DefaultSimilarity
{
private readonly TestMultiPhraseQuery outerInstance;
public DefaultSimilarityAnonymousInnerClassHelper(TestMultiPhraseQuery outerInstance)
{
this.outerInstance = outerInstance;
}
public override Explanation IdfExplain(CollectionStatistics collectionStats, TermStatistics[] termStats)
{
return new Explanation(10f, "just a test");
}
}
[Test]
public virtual void TestZeroPosIncr()
{
Directory dir = new RAMDirectory();
Token[] tokens = new Token[3];
tokens[0] = new Token();
tokens[0].Append("a");
tokens[0].PositionIncrement = 1;
tokens[1] = new Token();
tokens[1].Append("b");
tokens[1].PositionIncrement = 0;
tokens[2] = new Token();
tokens[2].Append("c");
tokens[2].PositionIncrement = 0;
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
doc.Add(new TextField("field", new CannedTokenStream(tokens)));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new TextField("field", new CannedTokenStream(tokens)));
writer.AddDocument(doc);
IndexReader r = writer.GetReader();
writer.Dispose();
IndexSearcher s = NewSearcher(r);
MultiPhraseQuery mpq = new MultiPhraseQuery();
//mpq.setSlop(1);
// NOTE: not great that if we do the else clause here we
// get different scores! MultiPhraseQuery counts that
// phrase as occurring twice per doc (it should be 1, I
// think?). this is because MultipleTermPositions is able to
// return the same position more than once (0, in this
// case):
if (true)
{
mpq.Add(new Term[] { new Term("field", "b"), new Term("field", "c") }, 0);
mpq.Add(new Term[] { new Term("field", "a") }, 0);
}
else
{
#pragma warning disable 162
mpq.Add(new Term[] { new Term("field", "a") }, 0);
mpq.Add(new Term[] { new Term("field", "b"), new Term("field", "c") }, 0);
#pragma warning restore 162
}
TopDocs hits = s.Search(mpq, 2);
Assert.AreEqual(2, hits.TotalHits);
Assert.AreEqual(hits.ScoreDocs[0].Score, hits.ScoreDocs[1].Score, 1e-5);
/*
for(int hit=0;hit<hits.TotalHits;hit++) {
ScoreDoc sd = hits.ScoreDocs[hit];
System.out.println(" hit doc=" + sd.Doc + " score=" + sd.Score);
}
*/
r.Dispose();
dir.Dispose();
}
private static Token MakeToken(string text, int posIncr)
{
Token t = new Token();
t.Append(text);
t.PositionIncrement = posIncr;
return t;
}
private static readonly Token[] INCR_0_DOC_TOKENS = new Token[] { MakeToken("x", 1), MakeToken("a", 1), MakeToken("1", 0), MakeToken("m", 1), MakeToken("b", 1), MakeToken("1", 0), MakeToken("n", 1), MakeToken("c", 1), MakeToken("y", 1) };
private static readonly Token[] INCR_0_QUERY_TOKENS_AND = new Token[] { MakeToken("a", 1), MakeToken("1", 0), MakeToken("b", 1), MakeToken("1", 0), MakeToken("c", 1) };
private static readonly Token[][] INCR_0_QUERY_TOKENS_AND_OR_MATCH = new Token[][] { new Token[] { MakeToken("a", 1) }, new Token[] { MakeToken("x", 1), MakeToken("1", 0) }, new Token[] { MakeToken("b", 2) }, new Token[] { MakeToken("x", 2), MakeToken("1", 0) }, new Token[] { MakeToken("c", 3) } };
private static readonly Token[][] INCR_0_QUERY_TOKENS_AND_OR_NO_MATCHN = new Token[][] { new Token[] { MakeToken("x", 1) }, new Token[] { MakeToken("a", 1), MakeToken("1", 0) }, new Token[] { MakeToken("x", 2) }, new Token[] { MakeToken("b", 2), MakeToken("1", 0) }, new Token[] { MakeToken("c", 3) } };
/// <summary>
/// using query parser, MPQ will be created, and will not be strict about having all query terms
/// in each position - one of each position is sufficient (OR logic)
/// </summary>
[Test]
public virtual void TestZeroPosIncrSloppyParsedAnd()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(new Term[] { new Term("field", "a"), new Term("field", "1") }, -1);
q.Add(new Term[] { new Term("field", "b"), new Term("field", "1") }, 0);
q.Add(new Term[] { new Term("field", "c") }, 1);
DoTestZeroPosIncrSloppy(q, 0);
q.Slop = 1;
DoTestZeroPosIncrSloppy(q, 0);
q.Slop = 2;
DoTestZeroPosIncrSloppy(q, 1);
}
private void DoTestZeroPosIncrSloppy(Query q, int nExpected)
{
Directory dir = NewDirectory(); // random dir
IndexWriterConfig cfg = NewIndexWriterConfig(TEST_VERSION_CURRENT, null);
IndexWriter writer = new IndexWriter(dir, cfg);
Document doc = new Document();
doc.Add(new TextField("field", new CannedTokenStream(INCR_0_DOC_TOKENS)));
writer.AddDocument(doc);
IndexReader r = DirectoryReader.Open(writer, false);
writer.Dispose();
IndexSearcher s = NewSearcher(r);
if (Verbose)
{
Console.WriteLine("QUERY=" + q);
}
TopDocs hits = s.Search(q, 1);
Assert.AreEqual(nExpected, hits.TotalHits, "wrong number of results");
if (Verbose)
{
for (int hit = 0; hit < hits.TotalHits; hit++)
{
ScoreDoc sd = hits.ScoreDocs[hit];
Console.WriteLine(" hit doc=" + sd.Doc + " score=" + sd.Score);
}
}
r.Dispose();
dir.Dispose();
}
/// <summary>
/// PQ AND Mode - Manually creating a phrase query
/// </summary>
[Test]
public virtual void TestZeroPosIncrSloppyPqAnd()
{
PhraseQuery pq = new PhraseQuery();
int pos = -1;
foreach (Token tap in INCR_0_QUERY_TOKENS_AND)
{
pos += tap.PositionIncrement;
pq.Add(new Term("field", tap.ToString()), pos);
}
DoTestZeroPosIncrSloppy(pq, 0);
pq.Slop = 1;
DoTestZeroPosIncrSloppy(pq, 0);
pq.Slop = 2;
DoTestZeroPosIncrSloppy(pq, 1);
}
/// <summary>
/// MPQ AND Mode - Manually creating a multiple phrase query
/// </summary>
[Test]
public virtual void TestZeroPosIncrSloppyMpqAnd()
{
MultiPhraseQuery mpq = new MultiPhraseQuery();
int pos = -1;
foreach (Token tap in INCR_0_QUERY_TOKENS_AND)
{
pos += tap.PositionIncrement;
mpq.Add(new Term[] { new Term("field", tap.ToString()) }, pos); //AND logic
}
DoTestZeroPosIncrSloppy(mpq, 0);
mpq.Slop = 1;
DoTestZeroPosIncrSloppy(mpq, 0);
mpq.Slop = 2;
DoTestZeroPosIncrSloppy(mpq, 1);
}
/// <summary>
/// MPQ Combined AND OR Mode - Manually creating a multiple phrase query
/// </summary>
[Test]
public virtual void TestZeroPosIncrSloppyMpqAndOrMatch()
{
MultiPhraseQuery mpq = new MultiPhraseQuery();
foreach (Token[] tap in INCR_0_QUERY_TOKENS_AND_OR_MATCH)
{
Term[] terms = TapTerms(tap);
int pos = tap[0].PositionIncrement - 1;
mpq.Add(terms, pos); //AND logic in pos, OR across lines
}
DoTestZeroPosIncrSloppy(mpq, 0);
mpq.Slop = 1;
DoTestZeroPosIncrSloppy(mpq, 0);
mpq.Slop = 2;
DoTestZeroPosIncrSloppy(mpq, 1);
}
/// <summary>
/// MPQ Combined AND OR Mode - Manually creating a multiple phrase query - with no match
/// </summary>
[Test]
public virtual void TestZeroPosIncrSloppyMpqAndOrNoMatch()
{
MultiPhraseQuery mpq = new MultiPhraseQuery();
foreach (Token[] tap in INCR_0_QUERY_TOKENS_AND_OR_NO_MATCHN)
{
Term[] terms = TapTerms(tap);
int pos = tap[0].PositionIncrement - 1;
mpq.Add(terms, pos); //AND logic in pos, OR across lines
}
DoTestZeroPosIncrSloppy(mpq, 0);
mpq.Slop = 2;
DoTestZeroPosIncrSloppy(mpq, 0);
}
private Term[] TapTerms(Token[] tap)
{
Term[] terms = new Term[tap.Length];
for (int i = 0; i < terms.Length; i++)
{
terms[i] = new Term("field", tap[i].ToString());
}
return terms;
}
[Test]
public virtual void TestNegativeSlop()
{
MultiPhraseQuery query = new MultiPhraseQuery();
query.Add(new Term("field", "two"));
query.Add(new Term("field", "one"));
try
{
query.Slop = -2;
Assert.Fail("didn't get expected exception");
}
#pragma warning disable 168
catch (ArgumentException expected)
#pragma warning restore 168
{
// expected exception
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
public class FlowBoxBehaviorControl : FunctionBehavior
{
public float weitTime = 6F;
public float nowWaitTime;
public int maxExec = 1;
public bool addElements = false;
private bool execDecision = false;
public bool putRight = true;
public ElementSensorControl elementSensor;
private Animator animator;
private AudioSource audioSource;
private AudioClip explosionSE;
private AudioClip absorbSE;
private AudioClip outputSE;
private bool isExec = false;
private LogRecodeController logRecCtrl;
// relation parameter.
private List<SaucerBehavior> SaucerList = new List<SaucerBehavior>();
void Start()
{
MakeObjectSensor ();
InitChangeBox (scriptKind);
animator = this.GetComponent<Animator> ();
GameObject controller = GameObject.FindWithTag ("GameController");
logRecCtrl = controller.GetComponent<LogRecodeController> ();
audioSource = controller.GetComponent<AudioSource>();
explosionSE = Resources.Load ("crash28") as AudioClip;
absorbSE = Resources.Load ("open24") as AudioClip;
outputSE = Resources.Load ("open43") as AudioClip;
}
// Initialize Function Box Process.
public void InitChangeBox( SCRIPTTYPE scKind)
{
this.scriptKind = scKind;
switch (scKind)
{
case SCRIPTTYPE.SWAPARRAY:
case SCRIPTTYPE.EQUAL:
case SCRIPTTYPE.LESS:
case SCRIPTTYPE.GREATER:
MakeSaucer( 2);
break;
case SCRIPTTYPE.ADD:
case SCRIPTTYPE.SUB:
case SCRIPTTYPE.DIV:
case SCRIPTTYPE.MUL:
case SCRIPTTYPE.REM:
case SCRIPTTYPE.SUBSTITUTE:
case SCRIPTTYPE.COUNTER:
case SCRIPTTYPE.MINIMUMINDEX:
case SCRIPTTYPE.INCREMET:
case SCRIPTTYPE.INTIALIZE:
MakeSaucer(1);
break;
case SCRIPTTYPE.CAPSEL:
MakeSaucer(1);
break;
}
return;
}
// Update is called once per frame
void Update ()
{
//NoAbsorbBehavior ();
if (!addElements)
return;
nowWaitTime -= Time.deltaTime;
if (nowWaitTime < 0 )
{
if( !execDecision)
{
ExecScript();
}
else
{
PopElement();
}
}
}
// Execute a process from scriptType.
void ExecScript()
{
switch( scriptKind)
{
case SCRIPTTYPE.SWAPFIRST:
SwapFirst();
break;
case SCRIPTTYPE.SWAPEND:
SwapEnd();
break;
case SCRIPTTYPE.SWAPMIDDLE:
SwapMiddle();
break;
case SCRIPTTYPE.STACK:
ExecStack();
break;
case SCRIPTTYPE.ADD:
Add(SaucerList [0].onElement);
break;
case SCRIPTTYPE.SUB:
Sub(SaucerList [0].onElement);
break;
case SCRIPTTYPE.MUL:
Mul(SaucerList [0].onElement);
break;
case SCRIPTTYPE.DIV:
Div(SaucerList [0].onElement);
break;
case SCRIPTTYPE.REM:
Rem(SaucerList [0].onElement);
break;
case SCRIPTTYPE.SWAPARRAY:
SwapArray(SaucerList [0].onElement, SaucerList [1].onElement);
break;
case SCRIPTTYPE.SUBSTITUTE:
Substitute(SaucerList [0].onElement);
break;
case SCRIPTTYPE.COUNTER:
Counter(SaucerList [0].onElement);
break;
case SCRIPTTYPE.MINIMUMINDEX:
FindMinimumIndex(SaucerList [0].onElement);
break;
case SCRIPTTYPE.LESS:
Less( SaucerList [0].onElement, SaucerList [1].onElement);
break;
case SCRIPTTYPE.GREATER:
Greater( SaucerList [0].onElement, SaucerList [1].onElement);
break;
case SCRIPTTYPE.EQUAL:
Equal( SaucerList [0].onElement, SaucerList [1].onElement);
break;
case SCRIPTTYPE.INCREMET:
Increment( SaucerList [0].onElement);
break;
case SCRIPTTYPE.INTIALIZE:
Initialize( SaucerList [0].onElement);
break;
}
if (error)
{
// Detect error. To be terminated.
ErrorProc();
}
else
{
logRecCtrl.RecordDataWithPos ( "8, Box Execute successuful : " + scriptKind.ToString() + ", " + ((int)scriptKind).ToString(), this.transform.position);
execDecision = true;
}
return;
}
void ErrorProc()
{
this.enabled = false;
logRecCtrl.RecordDataWithPos ( "9, Box Error : " + scriptKind.ToString() + ", " + ((int)scriptKind).ToString() , this.transform.position);
audioSource.PlayOneShot(explosionSE);
animator.SetBool( "isError", true);
}
void PopElement()
{
if( nowWaitTime < -1 && ElementsList.Count != 0 && !IsExistSideElement())
{
nowWaitTime = 0F;
switch( scriptKind)
{
case SCRIPTTYPE.GOTOBLUE:
GoToFlag( SCRIPTTYPE.FLAGBLUE);
nowWaitTime = 3F; // slow..
break;
case SCRIPTTYPE.GOTOGREEN:
GoToFlag( SCRIPTTYPE.FLAGGREEN);
nowWaitTime = 3F; // slow..
break;
case SCRIPTTYPE.PRINT: // Opeariton of PRINTs ...
Print ();
PutElement( ElementsList[0], putRight);
break;
case SCRIPTTYPE.SUBSTITUTE:
GameObject clone = Instantiate (SaucerList [0].onElement) as GameObject;
clone.transform.parent = GameObject.Find ("Elements").transform;
PutElement( clone, putRight);
break;
case SCRIPTTYPE.EQUAL:
case SCRIPTTYPE.GREATER:
case SCRIPTTYPE.LESS:
PutElementUp( ElementsList[0], flag1);
break;
default:
PutElement( ElementsList[0], putRight);
break;
}
animator.SetTrigger("inElement");
audioSource.PlayOneShot(outputSE);
ElementsList.RemoveAt(0);
CheckDestroyBox();
}
}
void PutElementUp( GameObject obj, bool istrue)
{
if( istrue)
{
obj.SendMessage( "PopElement", this.transform.position + Vector3.right * 3F);
}
else
{
obj.SendMessage( "PopElement", this.transform.position + Vector3.down * 3F);
}
}
void PutElement( GameObject obj, bool isRight)
{
if( isRight)
{
obj.SendMessage( "PopElement", this.transform.position + Vector3.right * 3F);
}
else
{
obj.SendMessage( "PopElement",this.transform.position + Vector3.left * 3F);
}
}
void NoAbsorbBehavior()
{
if ( isExec)
{
return;
}
if (scriptKind == SCRIPTTYPE.SWITCHRED)
{
SendMesseageForButtons("PushRed");
this.GetComponent<Image>().enabled = false;
isExec = true;
}
else if( scriptKind == SCRIPTTYPE.SWITCHBLUE)
{
SendMesseageForButtons("PushBlue");
this.GetComponent<Image>().enabled = false;
isExec = true;
}
else if( scriptKind == SCRIPTTYPE.SWITCHRESET)
{
SendMesseageForButtons("PushReset");
this.GetComponent<Image>().enabled = false;
isExec = true;
}
}
void CheckDestroyBox()
{
if( ElementsList.Count == 0)
{
maxExec--;
if( maxExec <= 0)
{
audioSource.PlayOneShot(explosionSE);
this.gameObject.SetActive(false);
}
}
return;
}
void GoToFlag( SCRIPTTYPE flag)
{
// Find an aiming object. if nothing, return null.
GameObject aimObj = GameObject.FindGameObjectsWithTag ("Function")
.Where (go => go.GetComponent<FlowBoxBehaviorControl> ().scriptKind == flag)
.FirstOrDefault();
// Output a top element.
ElementsList[0].SendMessage( "PopElement", this.transform.position + Vector3.up * 3F);
// Get rigidbody from the outputed element.
Rigidbody2D objRigid = ElementsList[0].GetComponent<Rigidbody2D>();
objRigid.Sleep();
objRigid.AddForce( new Vector2( 0F, 15F), ForceMode2D.Impulse);
// If set an aiming flag, flay away to the flag!
if( aimObj != null)
{
float dump = 0.3F;
Vector3 aimPos = aimObj.transform.position;
ElementsList[0].SendMessage( "SetAimPosition", aimPos);
Vector3 vec = aimPos - this.transform.position;
objRigid.AddForce( vec * dump, ForceMode2D.Impulse);
}
return;
}
bool IsExistSideElement()
{
if (scriptKind == SCRIPTTYPE.BLACKHOLE)
{
return true;
}
return elementSensor.elementCount > 0;
}
public void MakeSaucer( int param)
{
for (int i = 1; i <= param; i++)
{
Vector3 pos = this.transform.position + Vector3.up * 2.1F + Vector3.right * (i*2 - param) * 1.1F + Vector3.left * 1.3F;
GameObject clone = Instantiate( Resources.Load("Prefab/Saucer"), pos,Quaternion.identity) as GameObject;
SaucerList.Add(clone.GetComponent<SaucerBehavior>());
clone.transform.parent = this.transform;
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if( collision.gameObject.CompareTag("Element") || collision.gameObject.CompareTag("Card"))
{
if( IsNoAbsorbScriptType())
{
ElemetsBehavior eleBhv = collision.GetComponent<ElemetsBehavior>();
if( eleBhv.existAimPos)
{
return;
}
eleBhv.HideElement();
ElementsList.Add(collision.gameObject);
// These is executed soon.
if( scriptKind == SCRIPTTYPE.ADD || scriptKind == SCRIPTTYPE.SUBSTITUTE || scriptKind == SCRIPTTYPE.BLACKHOLE)
{
nowWaitTime = 0;
}
else
{
nowWaitTime = weitTime;
}
addElements = true;
execDecision = false;
animator.SetTrigger("inElement");
audioSource.PlayOneShot(absorbSE);
}
else
{
NoAbsorbBehavior();
}
}
}
new void PlayOutPutSE()
{
audioSource.PlayOneShot(outputSE);
}
private bool IsNoAbsorbScriptType()
{
return 0 <= (int)scriptKind;
}
protected void PushRed()
{
if (scriptKind == SCRIPTTYPE.CAPSEL)
{
if( SaucerList [0].onElement == null)
{
ErrorProc();
return;
}
GameObject clone = Instantiate (SaucerList [0].onElement) as GameObject;
clone.transform.parent = GameObject.Find ("Elements").transform;
PutElement( clone, putRight);
}
if (scriptKind == SCRIPTTYPE.SWITCHRESET)
{
this.GetComponent<Image>().enabled = true;
isExec = false;
}
}
protected void PushReset()
{
if (scriptKind == SCRIPTTYPE.SWITCHBLUE || scriptKind == SCRIPTTYPE.SWITCHRED)
{
this.GetComponent<Image>().enabled = true;
isExec = false;
}
if (scriptKind == SCRIPTTYPE.STOPSIGN)
{
this.GetComponent<Image>().sprite = Resources.Load<Sprite>( "Element/stopSign");
this.GetComponent<BoxCollider2D>().enabled = true;
}
}
private void MakeObjectSensor()
{
if (elementSensor != null)
{
return;
}
// If no exist sensor.
Vector3 pos = this.transform.position + new Vector3( 3F, 0, 0);
GameObject clone = Instantiate( Resources.Load("Prefab/ObjectSensor"), pos, Quaternion.identity) as GameObject;
clone.GetComponent<RectTransform> ().SetParent ( this.transform);
elementSensor = clone.GetComponent<ElementSensorControl> ();
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.ServiceBus.UnitTests
{
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus.Core;
using Xunit;
public class ExpectedMessagingExceptionTests
{
[Fact]
[LiveTest]
public async Task MessageLockLostExceptionTest()
{
await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName =>
{
const int messageCount = 2;
var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.PeekLock);
try
{
await TestUtility.SendMessagesAsync(sender, messageCount);
var receivedMessages = await TestUtility.ReceiveMessagesAsync(receiver, messageCount);
Assert.True(receivedMessages.Count == messageCount);
// Let the messages expire
await Task.Delay(TimeSpan.FromMinutes(1));
// Complete should throw
await
Assert.ThrowsAsync<MessageLockLostException>(
async () => await TestUtility.CompleteMessagesAsync(receiver, receivedMessages));
receivedMessages = await TestUtility.ReceiveMessagesAsync(receiver, messageCount);
Assert.True(receivedMessages.Count == messageCount);
await TestUtility.CompleteMessagesAsync(receiver, receivedMessages);
}
finally
{
await sender.CloseAsync();
await receiver.CloseAsync();
}
});
}
[Fact]
[LiveTest]
public async Task CompleteOnPeekedMessagesShouldThrowTest()
{
await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName =>
{
var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete);
try
{
await TestUtility.SendMessagesAsync(sender, 1);
var message = await receiver.PeekAsync();
Assert.NotNull(message);
await
Assert.ThrowsAsync<InvalidOperationException>(
async () => await receiver.CompleteAsync(message.SystemProperties.LockToken));
message = await receiver.ReceiveAsync();
Assert.NotNull(message);
}
finally
{
await sender.CloseAsync();
await receiver.CloseAsync();
}
});
}
[Fact]
[LiveTest]
public async Task SessionLockLostExceptionTest()
{
await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, async queueName =>
{
var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName);
try
{
var messageId = "test-message1";
var sessionId = Guid.NewGuid().ToString();
await sender.SendAsync(new Message { MessageId = messageId, SessionId = sessionId });
TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}");
var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);
Assert.NotNull(sessionReceiver);
TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}");
var message = await sessionReceiver.ReceiveAsync();
Assert.True(message.MessageId == messageId);
TestUtility.Log($"Received Message: MessageId: {message.MessageId}");
// Let the Session expire with some buffer time
TestUtility.Log($"Waiting for session lock to time out...");
await Task.Delay((sessionReceiver.LockedUntilUtc - DateTime.UtcNow) + TimeSpan.FromSeconds(10));
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.ReceiveAsync());
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.RenewSessionLockAsync());
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.GetStateAsync());
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.SetStateAsync(null));
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken));
await sessionReceiver.CloseAsync();
TestUtility.Log($"Closed Session Receiver...");
//Accept a new Session and Complete the message
sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);
Assert.NotNull(sessionReceiver);
TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}");
message = await sessionReceiver.ReceiveAsync();
TestUtility.Log($"Received Message: MessageId: {message.MessageId}");
await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken);
await sessionReceiver.CloseAsync();
}
finally
{
await sender.CloseAsync();
await sessionClient.CloseAsync();
}
});
}
[Fact]
[LiveTest]
public async Task OperationsOnMessageSenderReceiverAfterCloseShouldThrowObjectDisposedExceptionTest()
{
await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName =>
{
var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete);
await sender.CloseAsync();
await receiver.CloseAsync();
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await sender.SendAsync(new Message(Encoding.UTF8.GetBytes("test"))));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await receiver.ReceiveAsync());
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await receiver.CompleteAsync("blah"));
});
}
[Fact]
[LiveTest]
public async Task OperationsOnMessageSessionAfterCloseShouldThrowObjectDisposedExceptionTest()
{
await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, async queueName =>
{
var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName);
IMessageSession sessionReceiver = null;
try
{
var messageId = "test-message1";
var sessionId = Guid.NewGuid().ToString();
await sender.SendAsync(new Message { MessageId = messageId, SessionId = sessionId });
TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}");
sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);
Assert.NotNull(sessionReceiver);
TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}");
await sessionReceiver.CloseAsync();
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await sessionReceiver.ReceiveAsync());
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await sessionReceiver.GetStateAsync());
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await sessionReceiver.SetStateAsync(null));
sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);
Assert.NotNull(sessionReceiver);
TestUtility.Log($"Reaccept Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}");
var message = await sessionReceiver.ReceiveAsync();
Assert.True(message.MessageId == messageId);
TestUtility.Log($"Received Message: MessageId: {message.MessageId}");
await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken);
await sessionReceiver.CloseAsync();
}
finally
{
await sender.CloseAsync();
await sessionClient.CloseAsync();
}
});
}
[Fact]
[LiveTest]
public async Task CreatingLinkToNonExistingEntityShouldThrowEntityNotFoundException()
{
var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, "nonExistingEntity"); // Covers queue and topic
await Assert.ThrowsAsync<MessagingEntityNotFoundException>(async () => await receiver.ReceiveAsync());
await ServiceBusScope.UsingTopicAsync(partitioned: false, sessionEnabled: false, async (topicName, subscriptionName) =>
{
receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, EntityNameHelper.FormatSubscriptionPath(topicName, "nonexistingsub"));
await Assert.ThrowsAsync<MessagingEntityNotFoundException>(async () => await receiver.ReceiveAsync());
});
}
}
}
| |
//
// Mono.System.Xml.Serialization.XmlSchemaExporter
//
// Author:
// Tim Coleman (tim@timcoleman.com)
// Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
//
//
// 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 Mono.System.Xml;
using Mono.System.Xml.Schema;
using System.Collections;
namespace Mono.System.Xml.Serialization {
public class XmlSchemaExporter {
#region Fields
XmlSchemas schemas;
Hashtable exportedMaps = new Hashtable();
Hashtable exportedElements = new Hashtable();
bool encodedFormat = false;
XmlDocument xmlDoc;
#endregion
#region Constructors
public XmlSchemaExporter (XmlSchemas schemas)
{
this.schemas = schemas;
}
internal XmlSchemaExporter (XmlSchemas schemas, bool encodedFormat)
{
this.encodedFormat = encodedFormat;
this.schemas = schemas;
}
#endregion // Constructors
#region Methods
[MonoTODO]
public string ExportAnyType (string ns)
{
throw new NotImplementedException ();
}
#if NET_2_0
[MonoNotSupported("")]
public string ExportAnyType (XmlMembersMapping members)
{
throw new NotImplementedException ();
}
#endif
public void ExportMembersMapping (XmlMembersMapping xmlMembersMapping)
{
ExportMembersMapping (xmlMembersMapping, true);
}
#if NET_2_0
public
#else
internal
#endif
void ExportMembersMapping (XmlMembersMapping xmlMembersMapping, bool exportEnclosingType)
{
ClassMap cmap = (ClassMap) xmlMembersMapping.ObjectMap;
if (xmlMembersMapping.HasWrapperElement && exportEnclosingType)
{
XmlSchema schema = GetSchema (xmlMembersMapping.Namespace);
XmlSchemaComplexType stype = new XmlSchemaComplexType ();
XmlSchemaSequence particle;
XmlSchemaAnyAttribute anyAttribute;
ExportMembersMapSchema (schema, cmap, null, stype.Attributes, out particle, out anyAttribute);
stype.Particle = particle;
stype.AnyAttribute = anyAttribute;
if (encodedFormat)
{
stype.Name = xmlMembersMapping.ElementName;
schema.Items.Add (stype);
}
else
{
XmlSchemaElement selem = new XmlSchemaElement ();
selem.Name = xmlMembersMapping.ElementName;
selem.SchemaType = stype;
schema.Items.Add (selem);
}
}
else
{
ICollection members = cmap.ElementMembers;
if (members != null)
{
foreach (XmlTypeMapMemberElement member in members)
{
if (member is XmlTypeMapMemberAnyElement && member.TypeData.IsListType)
{
XmlSchema mschema = GetSchema (xmlMembersMapping.Namespace);
XmlSchemaParticle par = GetSchemaArrayElement (mschema, member.ElementInfo);
if (par is XmlSchemaAny)
{
XmlSchemaComplexType ct = FindComplexType (mschema.Items, "any");
if (ct != null) continue;
ct = new XmlSchemaComplexType ();
ct.Name = "any";
ct.IsMixed = true;
XmlSchemaSequence seq = new XmlSchemaSequence ();
ct.Particle = seq;
seq.Items.Add (par);
mschema.Items.Add (ct);
continue;
}
}
XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo) member.ElementInfo [0];
XmlSchema schema;
if (encodedFormat)
{
schema = GetSchema (xmlMembersMapping.Namespace);
ImportNamespace (schema, XmlSerializer.EncodingNamespace);
}
else
schema = GetSchema (einfo.Namespace);
XmlSchemaElement exe = FindElement (schema.Items, einfo.ElementName);
XmlSchemaElement elem;
XmlSchemaObjectContainer container = null;
// In encoded format, the schema elements are not needed
if (!encodedFormat)
container = new XmlSchemaObjectContainer (schema);
Type memType = member.GetType();
if (member is XmlTypeMapMemberFlatList)
throw new InvalidOperationException ("Unwrapped arrays not supported as parameters");
else if (memType == typeof(XmlTypeMapMemberElement))
elem = (XmlSchemaElement) GetSchemaElement (schema,
einfo, member.DefaultValue, false, container);
else
elem = (XmlSchemaElement) GetSchemaElement (schema,
einfo, false, container);
if (exe != null)
{
if (exe.SchemaTypeName.Equals (elem.SchemaTypeName))
schema.Items.Remove (elem);
else
{
string s = "The XML element named '" + einfo.ElementName + "' ";
s += "from namespace '" + schema.TargetNamespace + "' references distinct types " + elem.SchemaTypeName.Name + " and " + exe.SchemaTypeName.Name + ". ";
s += "Use XML attributes to specify another XML name or namespace for the element or types.";
throw new InvalidOperationException (s);
}
}
}
}
}
CompileSchemas ();
}
[MonoTODO]
public XmlQualifiedName ExportTypeMapping (XmlMembersMapping xmlMembersMapping)
{
throw new NotImplementedException ();
}
public void ExportTypeMapping (XmlTypeMapping xmlTypeMapping)
{
if (!xmlTypeMapping.IncludeInSchema) return;
if (IsElementExported (xmlTypeMapping)) return;
if (encodedFormat)
{
ExportClassSchema (xmlTypeMapping);
XmlSchema schema = GetSchema (xmlTypeMapping.XmlTypeNamespace);
ImportNamespace (schema, XmlSerializer.EncodingNamespace);
}
else
{
XmlSchema schema = GetSchema (xmlTypeMapping.Namespace);
XmlTypeMapElementInfo einfo = new XmlTypeMapElementInfo (null, xmlTypeMapping.TypeData);
einfo.Namespace = xmlTypeMapping.Namespace;
einfo.ElementName = xmlTypeMapping.ElementName;
if (xmlTypeMapping.TypeData.IsComplexType)
einfo.MappedType = xmlTypeMapping;
einfo.IsNullable = xmlTypeMapping.IsNullable;
GetSchemaElement (schema, einfo, false, new XmlSchemaObjectContainer (schema));
SetElementExported (xmlTypeMapping);
}
CompileSchemas ();
}
void ExportXmlSerializableSchema (XmlSchema currentSchema, XmlSerializableMapping map)
{
if (IsMapExported (map)) return;
SetMapExported (map);
if (map.Schema == null) return;
string targetNs = map.Schema.TargetNamespace;
XmlSchema existingSchema = schemas [targetNs];
if (existingSchema == null)
{
schemas.Add (map.Schema);
ImportNamespace (currentSchema, targetNs);
}
else if (existingSchema != map.Schema && !CanBeDuplicated (existingSchema, map.Schema))
{
throw new InvalidOperationException("The namespace '" + targetNs +"' defined by the class '" + map.TypeFullName + "' is a duplicate.");
}
}
private static bool CanBeDuplicated (XmlSchema existingSchema, XmlSchema schema)
{
if(XmlSchemas.IsDataSet (existingSchema) && XmlSchemas.IsDataSet (schema)
&& existingSchema.Id == schema.Id)
return true;
return false;
}
void ExportClassSchema (XmlTypeMapping map)
{
if (IsMapExported (map)) return;
SetMapExported (map);
if (map.TypeData.Type == typeof(object))
{
foreach (XmlTypeMapping dmap in map.DerivedTypes)
if (dmap.TypeData.SchemaType == SchemaTypes.Class) ExportClassSchema (dmap);
return;
}
XmlSchema schema = GetSchema (map.XmlTypeNamespace);
XmlSchemaComplexType stype = new XmlSchemaComplexType ();
stype.Name = map.XmlType;
schema.Items.Add (stype);
ClassMap cmap = (ClassMap)map.ObjectMap;
if (cmap.HasSimpleContent)
{
XmlSchemaSimpleContent simple = new XmlSchemaSimpleContent ();
stype.ContentModel = simple;
XmlSchemaSimpleContentExtension ext = new XmlSchemaSimpleContentExtension ();
simple.Content = ext;
XmlSchemaSequence particle;
XmlSchemaAnyAttribute anyAttribute;
ExportMembersMapSchema (schema, cmap, map.BaseMap, ext.Attributes, out particle, out anyAttribute);
ext.AnyAttribute = anyAttribute;
if (map.BaseMap == null)
ext.BaseTypeName = cmap.SimpleContentBaseType;
else {
ext.BaseTypeName = new XmlQualifiedName (map.BaseMap.XmlType, map.BaseMap.XmlTypeNamespace);
ImportNamespace (schema, map.BaseMap.XmlTypeNamespace);
ExportClassSchema (map.BaseMap);
}
}
else if (map.BaseMap != null && map.BaseMap.IncludeInSchema)
{
XmlSchemaComplexContent cstype = new XmlSchemaComplexContent ();
XmlSchemaComplexContentExtension ext = new XmlSchemaComplexContentExtension ();
ext.BaseTypeName = new XmlQualifiedName (map.BaseMap.XmlType, map.BaseMap.XmlTypeNamespace);
cstype.Content = ext;
stype.ContentModel = cstype;
XmlSchemaSequence particle;
XmlSchemaAnyAttribute anyAttribute;
ExportMembersMapSchema (schema, cmap, map.BaseMap, ext.Attributes, out particle, out anyAttribute);
ext.Particle = particle;
ext.AnyAttribute = anyAttribute;
stype.IsMixed = HasMixedContent (map);
cstype.IsMixed = BaseHasMixedContent (map);
ImportNamespace (schema, map.BaseMap.XmlTypeNamespace);
ExportClassSchema (map.BaseMap);
}
else
{
XmlSchemaSequence particle;
XmlSchemaAnyAttribute anyAttribute;
ExportMembersMapSchema (schema, cmap, map.BaseMap, stype.Attributes, out particle, out anyAttribute);
stype.Particle = particle;
stype.AnyAttribute = anyAttribute;
stype.IsMixed = cmap.XmlTextCollector != null;
}
foreach (XmlTypeMapping dmap in map.DerivedTypes)
if (dmap.TypeData.SchemaType == SchemaTypes.Class) ExportClassSchema (dmap);
}
bool BaseHasMixedContent (XmlTypeMapping map)
{
ClassMap cmap = (ClassMap)map.ObjectMap;
return (cmap.XmlTextCollector != null && (map.BaseMap != null && DefinedInBaseMap (map.BaseMap, cmap.XmlTextCollector)));
}
bool HasMixedContent (XmlTypeMapping map)
{
ClassMap cmap = (ClassMap)map.ObjectMap;
return (cmap.XmlTextCollector != null && (map.BaseMap == null || !DefinedInBaseMap (map.BaseMap, cmap.XmlTextCollector)));
}
void ExportMembersMapSchema (XmlSchema schema, ClassMap map, XmlTypeMapping baseMap, XmlSchemaObjectCollection outAttributes, out XmlSchemaSequence particle, out XmlSchemaAnyAttribute anyAttribute)
{
particle = null;
XmlSchemaSequence seq = new XmlSchemaSequence ();
ICollection members = map.ElementMembers;
if (members != null && !map.HasSimpleContent)
{
foreach (XmlTypeMapMemberElement member in members)
{
if (baseMap != null && DefinedInBaseMap (baseMap, member)) continue;
Type memType = member.GetType();
if (memType == typeof(XmlTypeMapMemberFlatList))
{
XmlSchemaParticle part = GetSchemaArrayElement (schema, member.ElementInfo);
if (part != null) seq.Items.Add (part);
}
else if (memType == typeof(XmlTypeMapMemberAnyElement))
{
seq.Items.Add (GetSchemaArrayElement (schema, member.ElementInfo));
}
else if (memType == typeof(XmlTypeMapMemberElement))
{
GetSchemaElement (schema, (XmlTypeMapElementInfo) member.ElementInfo [0],
member.DefaultValue, true, new XmlSchemaObjectContainer (seq));
}
else
{
GetSchemaElement (schema, (XmlTypeMapElementInfo) member.ElementInfo[0],
true, new XmlSchemaObjectContainer (seq));
}
}
}
if (seq.Items.Count > 0)
particle = seq;
// Write attributes
ICollection attributes = map.AttributeMembers;
if (attributes != null)
{
foreach (XmlTypeMapMemberAttribute attr in attributes) {
if (baseMap != null && DefinedInBaseMap (baseMap, attr)) continue;
outAttributes.Add (GetSchemaAttribute (schema, attr, true));
}
}
XmlTypeMapMember anyAttrMember = map.DefaultAnyAttributeMember;
if (anyAttrMember != null)
anyAttribute = new XmlSchemaAnyAttribute ();
else
anyAttribute = null;
}
XmlSchemaElement FindElement (XmlSchemaObjectCollection col, string name)
{
foreach (XmlSchemaObject ob in col)
{
XmlSchemaElement elem = ob as XmlSchemaElement;
if (elem != null && elem.Name == name) return elem;
}
return null;
}
XmlSchemaComplexType FindComplexType (XmlSchemaObjectCollection col, string name)
{
foreach (XmlSchemaObject ob in col)
{
XmlSchemaComplexType ctype = ob as XmlSchemaComplexType;
if (ctype != null && ctype.Name == name) return ctype;
}
return null;
}
XmlSchemaAttribute GetSchemaAttribute (XmlSchema currentSchema, XmlTypeMapMemberAttribute attinfo, bool isTypeMember)
{
XmlSchemaAttribute sat = new XmlSchemaAttribute ();
if (attinfo.DefaultValue != global::System.DBNull.Value) {
sat.DefaultValue = ExportDefaultValue (attinfo.TypeData,
attinfo.MappedType, attinfo.DefaultValue);
} else {
if (!attinfo.IsOptionalValueType && attinfo.TypeData.IsValueType)
sat.Use = XmlSchemaUse.Required;
}
ImportNamespace (currentSchema, attinfo.Namespace);
XmlSchema memberSchema;
if (attinfo.Namespace.Length == 0 && attinfo.Form != XmlSchemaForm.Qualified)
memberSchema = currentSchema;
else
memberSchema = GetSchema (attinfo.Namespace);
if (currentSchema == memberSchema || encodedFormat)
{
sat.Name = attinfo.AttributeName;
if (isTypeMember) sat.Form = attinfo.Form;
if (attinfo.TypeData.SchemaType == SchemaTypes.Enum)
{
ImportNamespace (currentSchema, attinfo.DataTypeNamespace);
ExportEnumSchema (attinfo.MappedType);
sat.SchemaTypeName = new XmlQualifiedName (attinfo.TypeData.XmlType, attinfo.DataTypeNamespace);
}
else if (attinfo.TypeData.SchemaType == SchemaTypes.Array && TypeTranslator.IsPrimitive (attinfo.TypeData.ListItemType))
{
sat.SchemaType = GetSchemaSimpleListType (attinfo.TypeData);
}
else
sat.SchemaTypeName = new XmlQualifiedName (attinfo.TypeData.XmlType, attinfo.DataTypeNamespace);;
}
else
{
sat.RefName = new XmlQualifiedName (attinfo.AttributeName, attinfo.Namespace);
foreach (XmlSchemaObject ob in memberSchema.Items)
if (ob is XmlSchemaAttribute && ((XmlSchemaAttribute)ob).Name == attinfo.AttributeName)
return sat;
memberSchema.Items.Add (GetSchemaAttribute (memberSchema, attinfo, false));
}
return sat;
}
XmlSchemaParticle GetSchemaElement (XmlSchema currentSchema, XmlTypeMapElementInfo einfo, bool isTypeMember)
{
return GetSchemaElement (currentSchema, einfo, global::System.DBNull.Value,
isTypeMember, (XmlSchemaObjectContainer) null);
}
XmlSchemaParticle GetSchemaElement (XmlSchema currentSchema, XmlTypeMapElementInfo einfo, bool isTypeMember, XmlSchemaObjectContainer container)
{
return GetSchemaElement (currentSchema, einfo, global::System.DBNull.Value, isTypeMember, container);
}
XmlSchemaParticle GetSchemaElement (XmlSchema currentSchema, XmlTypeMapElementInfo einfo, object defaultValue, bool isTypeMember, XmlSchemaObjectContainer container)
{
if (einfo.IsTextElement) return null;
if (einfo.IsUnnamedAnyElement)
{
XmlSchemaAny any = new XmlSchemaAny ();
any.MinOccurs = 0;
any.MaxOccurs = 1;
if (container != null)
container.Items.Add (any);
return any;
}
XmlSchemaElement selem = new XmlSchemaElement ();
selem.IsNillable = einfo.IsNullable;
if (container != null)
container.Items.Add (selem);
if (isTypeMember)
{
selem.MaxOccurs = 1;
selem.MinOccurs = einfo.IsNullable ? 1 : 0;
if ((defaultValue == DBNull.Value && einfo.TypeData.IsValueType && einfo.Member != null && !einfo.Member.IsOptionalValueType) || encodedFormat)
selem.MinOccurs = 1;
}
XmlSchema memberSchema = null;
if (!encodedFormat)
{
memberSchema = GetSchema (einfo.Namespace);
ImportNamespace (currentSchema, einfo.Namespace);
}
if (currentSchema == memberSchema || encodedFormat || !isTypeMember)
{
if (isTypeMember) selem.IsNillable = einfo.IsNullable;
selem.Name = einfo.ElementName;
if (defaultValue != global::System.DBNull.Value)
selem.DefaultValue = ExportDefaultValue (einfo.TypeData,
einfo.MappedType, defaultValue);
if (einfo.Form != XmlSchemaForm.Qualified)
selem.Form = einfo.Form;
switch (einfo.TypeData.SchemaType)
{
case SchemaTypes.XmlNode:
selem.SchemaType = GetSchemaXmlNodeType ();
break;
case SchemaTypes.XmlSerializable:
SetSchemaXmlSerializableType (einfo.MappedType as XmlSerializableMapping, selem);
ExportXmlSerializableSchema (currentSchema, einfo.MappedType as XmlSerializableMapping);
break;
case SchemaTypes.Enum:
selem.SchemaTypeName = new XmlQualifiedName (einfo.MappedType.XmlType, einfo.MappedType.XmlTypeNamespace);
ImportNamespace (currentSchema, einfo.MappedType.XmlTypeNamespace);
ExportEnumSchema (einfo.MappedType);
break;
case SchemaTypes.Array:
XmlQualifiedName atypeName = ExportArraySchema (einfo.MappedType, currentSchema.TargetNamespace);
selem.SchemaTypeName = atypeName;
ImportNamespace (currentSchema, atypeName.Namespace);
break;
case SchemaTypes.Class:
if (einfo.MappedType.TypeData.Type != typeof(object)) {
selem.SchemaTypeName = new XmlQualifiedName (einfo.MappedType.XmlType, einfo.MappedType.XmlTypeNamespace);
ImportNamespace (currentSchema, einfo.MappedType.XmlTypeNamespace);
}
else if (encodedFormat)
selem.SchemaTypeName = new XmlQualifiedName (einfo.MappedType.XmlType, einfo.MappedType.XmlTypeNamespace);
ExportClassSchema (einfo.MappedType);
break;
case SchemaTypes.Primitive:
selem.SchemaTypeName = new XmlQualifiedName (einfo.TypeData.XmlType, einfo.DataTypeNamespace);
if (!einfo.TypeData.IsXsdType) {
ImportNamespace (currentSchema, einfo.MappedType.XmlTypeNamespace);
ExportDerivedSchema (einfo.MappedType);
}
break;
}
}
else
{
selem.RefName = new XmlQualifiedName (einfo.ElementName, einfo.Namespace);
foreach (XmlSchemaObject ob in memberSchema.Items)
if (ob is XmlSchemaElement && ((XmlSchemaElement)ob).Name == einfo.ElementName)
return selem;
GetSchemaElement (memberSchema, einfo, defaultValue, false,
new XmlSchemaObjectContainer (memberSchema));
}
return selem;
}
void ImportNamespace (XmlSchema schema, string ns)
{
if (ns == null || ns.Length == 0 ||
ns == schema.TargetNamespace || ns == XmlSchema.Namespace) return;
foreach (XmlSchemaObject sob in schema.Includes)
if ((sob is XmlSchemaImport) && ((XmlSchemaImport)sob).Namespace == ns) return;
XmlSchemaImport imp = new XmlSchemaImport ();
imp.Namespace = ns;
schema.Includes.Add (imp);
}
bool DefinedInBaseMap (XmlTypeMapping map, XmlTypeMapMember member)
{
if (((ClassMap)map.ObjectMap).FindMember (member.Name) != null)
return true;
else if (map.BaseMap != null)
return DefinedInBaseMap (map.BaseMap, member);
else
return false;
}
XmlSchemaType GetSchemaXmlNodeType ()
{
XmlSchemaComplexType stype = new XmlSchemaComplexType ();
stype.IsMixed = true;
XmlSchemaSequence seq = new XmlSchemaSequence ();
seq.Items.Add (new XmlSchemaAny ());
stype.Particle = seq;
return stype;
}
void SetSchemaXmlSerializableType (XmlSerializableMapping map, XmlSchemaElement elem)
{
#if NET_2_0
if (map.SchemaType != null && map.Schema != null) {
elem.SchemaType = map.SchemaType;
return;
}
if (map.SchemaType == null && map.SchemaTypeName != null) {
elem.SchemaTypeName = map.SchemaTypeName;
elem.Name = map.SchemaTypeName.Name;
return;
}
#endif
XmlSchemaComplexType stype = new XmlSchemaComplexType ();
XmlSchemaSequence seq = new XmlSchemaSequence ();
if (map.Schema == null) {
XmlSchemaElement selem = new XmlSchemaElement ();
selem.RefName = new XmlQualifiedName ("schema",XmlSchema.Namespace);
seq.Items.Add (selem);
seq.Items.Add (new XmlSchemaAny ());
} else {
XmlSchemaAny any = new XmlSchemaAny ();
any.Namespace = map.Schema.TargetNamespace;
seq.Items.Add (any);
}
stype.Particle = seq;
elem.SchemaType = stype;
}
XmlSchemaSimpleType GetSchemaSimpleListType (TypeData typeData)
{
XmlSchemaSimpleType stype = new XmlSchemaSimpleType ();
XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList ();
TypeData itemTypeData = TypeTranslator.GetTypeData (typeData.ListItemType);
list.ItemTypeName = new XmlQualifiedName (itemTypeData.XmlType, XmlSchema.Namespace);
stype.Content = list;
return stype;
}
XmlSchemaParticle GetSchemaArrayElement (XmlSchema currentSchema, XmlTypeMapElementInfoList infos)
{
int numInfos = infos.Count;
if (numInfos > 0 && ((XmlTypeMapElementInfo)infos[0]).IsTextElement) numInfos--;
if (numInfos == 0) return null;
if (numInfos == 1)
{
XmlSchemaParticle selem = GetSchemaElement (currentSchema, (XmlTypeMapElementInfo) infos[infos.Count-1], true);
selem.MinOccursString = "0";
selem.MaxOccursString = "unbounded";
return selem;
}
else
{
XmlSchemaChoice schoice = new XmlSchemaChoice ();
schoice.MinOccursString = "0";
schoice.MaxOccursString = "unbounded";
foreach (XmlTypeMapElementInfo einfo in infos)
{
if (einfo.IsTextElement) continue;
schoice.Items.Add (GetSchemaElement (currentSchema, einfo, true));
}
return schoice;
}
}
string ExportDefaultValue (TypeData typeData, XmlTypeMapping map, object defaultValue)
{
if (typeData.SchemaType == SchemaTypes.Enum) {
EnumMap enumMap = (EnumMap) map.ObjectMap;
// get corresponding xml name
return enumMap.GetXmlName (map.TypeFullName, defaultValue);
}
return XmlCustomFormatter.ToXmlString (typeData, defaultValue);
}
void ExportDerivedSchema(XmlTypeMapping map) {
if (IsMapExported (map)) return;
SetMapExported (map);
XmlSchema schema = GetSchema (map.XmlTypeNamespace);
for (int i = 0; i < schema.Items.Count; i++) {
XmlSchemaSimpleType item = schema.Items [i] as XmlSchemaSimpleType;
if (item != null && item.Name == map.ElementName)
return;
}
XmlSchemaSimpleType stype = new XmlSchemaSimpleType ();
stype.Name = map.ElementName;
schema.Items.Add (stype);
XmlSchemaSimpleTypeRestriction rest = new XmlSchemaSimpleTypeRestriction ();
rest.BaseTypeName = new XmlQualifiedName (map.TypeData.MappedType.XmlType, XmlSchema.Namespace);
XmlSchemaPatternFacet facet = map.TypeData.XmlSchemaPatternFacet;
if (facet != null)
rest.Facets.Add(facet);
stype.Content = rest;
}
void ExportEnumSchema (XmlTypeMapping map)
{
if (IsMapExported (map)) return;
SetMapExported (map);
XmlSchema schema = GetSchema (map.XmlTypeNamespace);
XmlSchemaSimpleType stype = new XmlSchemaSimpleType ();
stype.Name = map.ElementName;
schema.Items.Add (stype);
XmlSchemaSimpleTypeRestriction rest = new XmlSchemaSimpleTypeRestriction ();
rest.BaseTypeName = new XmlQualifiedName ("string",XmlSchema.Namespace);
EnumMap emap = (EnumMap) map.ObjectMap;
foreach (EnumMap.EnumMapMember emem in emap.Members)
{
XmlSchemaEnumerationFacet ef = new XmlSchemaEnumerationFacet ();
ef.Value = emem.XmlName;
rest.Facets.Add (ef);
}
if (emap.IsFlags) {
XmlSchemaSimpleTypeList slist = new XmlSchemaSimpleTypeList ();
XmlSchemaSimpleType restrictionType = new XmlSchemaSimpleType ();
restrictionType.Content = rest;
slist.ItemType = restrictionType;
stype.Content = slist;
} else {
stype.Content = rest;
}
}
XmlQualifiedName ExportArraySchema (XmlTypeMapping map, string defaultNamespace)
{
ListMap lmap = (ListMap) map.ObjectMap;
if (encodedFormat)
{
string name, ns, schemaNs;
lmap.GetArrayType (-1, out name, out ns);
if (ns == XmlSchema.Namespace) schemaNs = defaultNamespace;
else schemaNs = ns;
if (IsMapExported (map)) return new XmlQualifiedName (lmap.GetSchemaArrayName (), schemaNs);
SetMapExported (map);
XmlSchema schema = GetSchema (schemaNs);
XmlSchemaComplexType stype = new XmlSchemaComplexType ();
stype.Name = lmap.GetSchemaArrayName ();
schema.Items.Add (stype);
XmlSchemaComplexContent content = new XmlSchemaComplexContent();
content.IsMixed = false;
stype.ContentModel = content;
XmlSchemaComplexContentRestriction rest = new XmlSchemaComplexContentRestriction ();
content.Content = rest;
rest.BaseTypeName = new XmlQualifiedName ("Array", XmlSerializer.EncodingNamespace);
XmlSchemaAttribute at = new XmlSchemaAttribute ();
rest.Attributes.Add (at);
at.RefName = new XmlQualifiedName ("arrayType", XmlSerializer.EncodingNamespace);
XmlAttribute arrayType = Document.CreateAttribute ("arrayType", XmlSerializer.WsdlNamespace);
arrayType.Value = ns + (ns != "" ? ":" : "") + name;
at.UnhandledAttributes = new XmlAttribute [] { arrayType };
ImportNamespace (schema, XmlSerializer.WsdlNamespace);
XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo) lmap.ItemInfo[0];
if (einfo.MappedType != null)
{
switch (einfo.TypeData.SchemaType)
{
case SchemaTypes.Enum:
ExportEnumSchema (einfo.MappedType);
break;
case SchemaTypes.Array:
ExportArraySchema (einfo.MappedType, schemaNs);
break;
case SchemaTypes.Class:
ExportClassSchema (einfo.MappedType);
break;
}
}
return new XmlQualifiedName (lmap.GetSchemaArrayName (), schemaNs);
}
else
{
if (IsMapExported (map)) return new XmlQualifiedName (map.XmlType, map.XmlTypeNamespace);
SetMapExported (map);
XmlSchema schema = GetSchema (map.XmlTypeNamespace);
XmlSchemaComplexType stype = new XmlSchemaComplexType ();
stype.Name = map.ElementName;
schema.Items.Add (stype);
XmlSchemaParticle spart = GetSchemaArrayElement (schema, lmap.ItemInfo);
if (spart is XmlSchemaChoice)
stype.Particle = spart;
else
{
XmlSchemaSequence seq = new XmlSchemaSequence ();
seq.Items.Add (spart);
stype.Particle = seq;
}
return new XmlQualifiedName (map.XmlType, map.XmlTypeNamespace);
}
}
XmlDocument Document
{
get
{
if (xmlDoc == null) xmlDoc = new XmlDocument ();
return xmlDoc;
}
}
bool IsMapExported (XmlTypeMapping map)
{
if (exportedMaps.ContainsKey (GetMapKey(map))) return true;
return false;
}
void SetMapExported (XmlTypeMapping map)
{
exportedMaps [GetMapKey(map)] = map;
}
bool IsElementExported (XmlTypeMapping map)
{
if (exportedElements.ContainsKey (GetMapKey(map))) return true;
if (map.TypeData.Type == typeof(object)) return true;
return false;
}
void SetElementExported (XmlTypeMapping map)
{
exportedElements [GetMapKey(map)] = map;
}
string GetMapKey (XmlTypeMapping map)
{
// Don't use type name for array types, since we can have different
// classes that represent the same array type (for example
// StringCollection and string[]).
if (map.TypeData.IsListType)
return GetArrayKeyName (map.TypeData) + " " + map.XmlType + " " + map.XmlTypeNamespace;
else
return map.TypeData.FullTypeName + " " + map.XmlType + " " + map.XmlTypeNamespace;
}
string GetArrayKeyName (TypeData td)
{
TypeData etd = td.ListItemTypeData;
return "*arrayof*" + (etd.IsListType ? GetArrayKeyName (etd) : etd.FullTypeName);
}
void CompileSchemas ()
{
// foreach (XmlSchema sc in schemas)
// sc.Compile (null);
}
XmlSchema GetSchema (string ns)
{
XmlSchema schema = schemas [ns];
if (schema == null)
{
schema = new XmlSchema ();
if (ns != null && ns.Length > 0)
schema.TargetNamespace = ns;
if (!encodedFormat)
schema.ElementFormDefault = XmlSchemaForm.Qualified;
schemas.Add (schema);
}
return schema;
}
#endregion // Methods
private class XmlSchemaObjectContainer
{
private readonly XmlSchemaObject _xmlSchemaObject;
public XmlSchemaObjectContainer (XmlSchema schema)
{
_xmlSchemaObject = schema;
}
public XmlSchemaObjectContainer (XmlSchemaGroupBase group)
{
_xmlSchemaObject = group;
}
public XmlSchemaObjectCollection Items {
get {
if (_xmlSchemaObject is XmlSchema) {
return ((XmlSchema) _xmlSchemaObject).Items;
} else {
return ((XmlSchemaGroupBase) _xmlSchemaObject).Items;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation connections. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
internal partial class ConnectionOperations : IServiceOperations<AutomationManagementClient>, IConnectionOperations
{
/// <summary>
/// Initializes a new instance of the ConnectionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ConnectionOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a connection. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create or update
/// connection operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create or update connection operation.
/// </returns>
public async Task<ConnectionCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, ConnectionCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.ConnectionType == null)
{
throw new ArgumentNullException("parameters.Properties.ConnectionType");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/connections/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject connectionCreateOrUpdateParametersValue = new JObject();
requestDoc = connectionCreateOrUpdateParametersValue;
connectionCreateOrUpdateParametersValue["name"] = parameters.Name;
JObject propertiesValue = new JObject();
connectionCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
JObject connectionTypeValue = new JObject();
propertiesValue["connectionType"] = connectionTypeValue;
if (parameters.Properties.ConnectionType.Name != null)
{
connectionTypeValue["name"] = parameters.Properties.ConnectionType.Name;
}
if (parameters.Properties.FieldDefinitionValues != null)
{
if (parameters.Properties.FieldDefinitionValues is ILazyCollection == false || ((ILazyCollection)parameters.Properties.FieldDefinitionValues).IsInitialized)
{
JObject fieldDefinitionValuesDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Properties.FieldDefinitionValues)
{
string fieldDefinitionValuesKey = pair.Key;
string fieldDefinitionValuesValue = pair.Value;
fieldDefinitionValuesDictionary[fieldDefinitionValuesKey] = fieldDefinitionValuesValue;
}
propertiesValue["fieldDefinitionValues"] = fieldDefinitionValuesDictionary;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ConnectionCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ConnectionCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Connection connectionInstance = new Connection();
result.Connection = connectionInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
connectionInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
ConnectionProperties propertiesInstance = new ConnectionProperties();
connectionInstance.Properties = propertiesInstance;
JToken connectionTypeValue2 = propertiesValue2["connectionType"];
if (connectionTypeValue2 != null && connectionTypeValue2.Type != JTokenType.Null)
{
ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty();
propertiesInstance.ConnectionType = connectionTypeInstance;
JToken nameValue2 = connectionTypeValue2["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
connectionTypeInstance.Name = nameInstance2;
}
}
JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue2["fieldDefinitionValues"]);
if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in fieldDefinitionValuesSequenceElement)
{
string fieldDefinitionValuesKey2 = ((string)property.Name);
string fieldDefinitionValuesValue2 = ((string)property.Value);
propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey2, fieldDefinitionValuesValue2);
}
}
JToken creationTimeValue = propertiesValue2["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue2["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete the connection. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionName'>
/// Required. The name of connection.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string connectionName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (connectionName == null)
{
throw new ArgumentNullException("connectionName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("connectionName", connectionName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/connections/";
url = url + Uri.EscapeDataString(connectionName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the connection identified by connection name. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionName'>
/// Required. The name of connection.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get connection operation.
/// </returns>
public async Task<ConnectionGetResponse> GetAsync(string resourceGroupName, string automationAccount, string connectionName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (connectionName == null)
{
throw new ArgumentNullException("connectionName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("connectionName", connectionName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/connections/";
url = url + Uri.EscapeDataString(connectionName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ConnectionGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ConnectionGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Connection connectionInstance = new Connection();
result.Connection = connectionInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
connectionInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ConnectionProperties propertiesInstance = new ConnectionProperties();
connectionInstance.Properties = propertiesInstance;
JToken connectionTypeValue = propertiesValue["connectionType"];
if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null)
{
ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty();
propertiesInstance.ConnectionType = connectionTypeInstance;
JToken nameValue2 = connectionTypeValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
connectionTypeInstance.Name = nameInstance2;
}
}
JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]);
if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in fieldDefinitionValuesSequenceElement)
{
string fieldDefinitionValuesKey = ((string)property.Name);
string fieldDefinitionValuesValue = ((string)property.Value);
propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue);
}
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of connections. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list connection operation.
/// </returns>
public async Task<ConnectionListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/connections";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ConnectionListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ConnectionListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Connection connectionInstance = new Connection();
result.Connection.Add(connectionInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
connectionInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ConnectionProperties propertiesInstance = new ConnectionProperties();
connectionInstance.Properties = propertiesInstance;
JToken connectionTypeValue = propertiesValue["connectionType"];
if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null)
{
ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty();
propertiesInstance.ConnectionType = connectionTypeInstance;
JToken nameValue2 = connectionTypeValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
connectionTypeInstance.Name = nameInstance2;
}
}
JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]);
if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in fieldDefinitionValuesSequenceElement)
{
string fieldDefinitionValuesKey = ((string)property.Name);
string fieldDefinitionValuesValue = ((string)property.Value);
propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue);
}
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of connections. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list connection operation.
/// </returns>
public async Task<ConnectionListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ConnectionListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ConnectionListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Connection connectionInstance = new Connection();
result.Connection.Add(connectionInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
connectionInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ConnectionProperties propertiesInstance = new ConnectionProperties();
connectionInstance.Properties = propertiesInstance;
JToken connectionTypeValue = propertiesValue["connectionType"];
if (connectionTypeValue != null && connectionTypeValue.Type != JTokenType.Null)
{
ConnectionTypeAssociationProperty connectionTypeInstance = new ConnectionTypeAssociationProperty();
propertiesInstance.ConnectionType = connectionTypeInstance;
JToken nameValue2 = connectionTypeValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
connectionTypeInstance.Name = nameInstance2;
}
}
JToken fieldDefinitionValuesSequenceElement = ((JToken)propertiesValue["fieldDefinitionValues"]);
if (fieldDefinitionValuesSequenceElement != null && fieldDefinitionValuesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in fieldDefinitionValuesSequenceElement)
{
string fieldDefinitionValuesKey = ((string)property.Name);
string fieldDefinitionValuesValue = ((string)property.Value);
propertiesInstance.FieldDefinitionValues.Add(fieldDefinitionValuesKey, fieldDefinitionValuesValue);
}
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update a connection. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the patch a connection
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> PatchAsync(string resourceGroupName, string automationAccount, ConnectionPatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/connections/";
if (parameters.Name != null)
{
url = url + Uri.EscapeDataString(parameters.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject connectionPatchParametersValue = new JObject();
requestDoc = connectionPatchParametersValue;
if (parameters.Name != null)
{
connectionPatchParametersValue["name"] = parameters.Name;
}
JObject propertiesValue = new JObject();
connectionPatchParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
if (parameters.Properties.FieldDefinitionValues != null)
{
if (parameters.Properties.FieldDefinitionValues is ILazyCollection == false || ((ILazyCollection)parameters.Properties.FieldDefinitionValues).IsInitialized)
{
JObject fieldDefinitionValuesDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Properties.FieldDefinitionValues)
{
string fieldDefinitionValuesKey = pair.Key;
string fieldDefinitionValuesValue = pair.Value;
fieldDefinitionValuesDictionary[fieldDefinitionValuesKey] = fieldDefinitionValuesValue;
}
propertiesValue["fieldDefinitionValues"] = fieldDefinitionValuesDictionary;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Serialization;
using Windows.Networking.Proximity;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
using Microsoft.Phone.Tasks;
using BluetoothConnectionManager;
using Windows.Networking;
using System.Text;
using System.Threading;
public class BluetoothSerial : BaseCommand
{
private ConnectionManager connectionManager;
private string token; // normally a char like \n TODO rename to delimiter
private string connectionCallbackId;
private string rawDataCallbackId;
private string subscribeCallbackId;
// TODO maybe use one buffer if delimiter is a char and not a string
private StringBuilder buffer = new StringBuilder("");
private List<byte> byteBuffer = new List<byte>();
private Timer timer;
private int MIN_RAW_DATA_COUNT = 6; // queue data until it reaches this count
private int RAW_DATA_FLUSH_TIMER_MILLIS = 200;
private Boolean connected = false;
public async void list(string args)
{
Debug.WriteLine("Listing Paired Bluetooth Devices");
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
try
{
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
Debug.WriteLine("No paired devices were found.");
}
// return serializable device info
var pairedDeviceList = new List<PairedDeviceInfo>(pairedDevices.Select(x => new PairedDeviceInfo(x)));
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, pairedDeviceList));
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Bluetooth is disabled"));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message));
}
}
}
public void connect(string args)
{
string[] javascriptArgs = JsonHelper.Deserialize<string[]>(args);
string macAddress = javascriptArgs[0];
connectionCallbackId = javascriptArgs[1];
connectionManager = new ConnectionManager();
connectionManager.Initialize(); // TODO can't we put this in the constructor?
connectionManager.ByteReceived += connectionManager_ByteReceived;
connectionManager.ConnectionSuccess += connectionManager_ConnectionSuccess;
connectionManager.ConnectionFailure += connectionManager_ConnectionFailure;
try
{
HostName deviceHostName = new HostName(macAddress);
connectionManager.Connect(deviceHostName);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
connectionManager_ConnectionFailure("Invalid Hostname");
}
}
public void disconnect(string args)
{
if (connectionManager != null)
{
connectionCallbackId = null;
connectionManager.Terminate();
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void subscribe(string args)
{
var arguments = JsonHelper.Deserialize<string[]>(args);
token = arguments[0];
subscribeCallbackId = arguments[1];
}
public void unsubscribe(string args)
{
token = null;
subscribeCallbackId = null;
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
// TODO rename subscribeRawData (across all platforms)
public void subscribeRaw(string args)
{
rawDataCallbackId = JsonHelper.Deserialize<string[]>(args)[0];
timer = new Timer(new TimerCallback(FlushByteBuffer));
}
// TODO rename unsubscribeRawData
public void unsubscribeRaw(string args)
{
rawDataCallbackId = null;
if (timer != null)
{
timer.Dispose();
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public async void write(string args)
{
string[] javascriptArgs = JsonHelper.Deserialize<string[]>(args);
string encodedMessageBytes = javascriptArgs[0];
string writeCallbackId = javascriptArgs[1];
byte[] data = Convert.FromBase64String(encodedMessageBytes);
var success = await connectionManager.WriteData(data);
if (success)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), writeCallbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), writeCallbackId);
}
}
public void available(string args) {
string callbackId = JsonHelper.Deserialize<string[]>(args)[0];
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, buffer.Length), callbackId);
}
public void read(string args) {
int length = buffer.Length; // can the size of the buffer change in this method?
string message = buffer.ToString(0, length);
buffer.Remove(0, length);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, message));
}
public void readUntil(string args) {
string delimiter = JsonHelper.Deserialize<string[]>(args)[0];
int index = buffer.ToString().IndexOf(delimiter);
string message = buffer.ToString(0, index + delimiter.Length);
buffer.Remove(0, index + delimiter.Length);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, message));
}
public void clear(string args) {
buffer.Clear();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void isConnected(string args)
{
if (connected)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR));
}
}
public async void isEnabled(string args)
{
string callbackId = JsonHelper.Deserialize<string[]>(args)[0];
// This is a bad way to do this, improve later
// See if we can determine in the Connection Manager
// https://msdn.microsoft.com/library/windows/apps/jj207007(v=vs.105).aspx
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
try
{
var peers = await PeerFinder.FindAllPeersAsync();
// Handle the result of the FindAllPeersAsync call
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message), callbackId);
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
public void showBluetoothSettings(string args)
{
ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
connectionSettingsTask.Show();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
private void connectionManager_ConnectionSuccess()
{
if (connectionCallbackId != null)
{
PluginResult result = new PluginResult(PluginResult.Status.OK);
result.KeepCallback = true;
DispatchCommandResult(result, connectionCallbackId);
}
connected = true;
}
private void connectionManager_ConnectionFailure(string reason)
{
if (connectionCallbackId != null)
{
PluginResult result = new PluginResult(PluginResult.Status.ERROR, reason);
result.KeepCallback = true;
DispatchCommandResult(result, connectionCallbackId);
}
connected = false;
}
private void connectionManager_ByteReceived(byte data)
{
char dataAsChar = Convert.ToChar(data);
buffer.Append(dataAsChar);
byteBuffer.Add(data);
Debug.WriteLine(data + " " + dataAsChar);
if (rawDataCallbackId != null)
{
MaybeSendRawData();
}
if (subscribeCallbackId != null)
{
sendDataToSubscriber();
}
}
// This method is called by the timer delegate.
private void FlushByteBuffer(Object stateInfo)
{
SendRawDataToSubscriber();
}
private void SendRawDataToSubscriber()
{
if (byteBuffer.Count > 0)
{
// NOTE an array of 1 gets flattened to an int, we fix in JavaScript
PluginResult result = new PluginResult(PluginResult.Status.OK, byteBuffer);
result.KeepCallback = true;
DispatchCommandResult(result, rawDataCallbackId);
byteBuffer.Clear();
}
}
private void MaybeSendRawData() // TODO rename "fill raw data buffer and maybe send to subscribers"
{
if (byteBuffer.Count >= MIN_RAW_DATA_COUNT)
{
SendRawDataToSubscriber();
}
else if (byteBuffer.Count == 0)
{
Debug.WriteLine("Empty");
}
else
{
Debug.WriteLine("Not enough data");
timer.Change(RAW_DATA_FLUSH_TIMER_MILLIS, Timeout.Infinite); // reset the timer
}
}
private void sendDataToSubscriber()
{
string delimiter = token;
int index = buffer.ToString().IndexOf(delimiter);
if (index > -1)
{
string message = buffer.ToString(0, index + delimiter.Length);
buffer.Remove(0, index + delimiter.Length);
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
result.KeepCallback = true;
DispatchCommandResult(result, subscribeCallbackId);
// call again in case the delimiter occurs multiple times
sendDataToSubscriber();
}
}
[DataContract]
public class PairedDeviceInfo
{
public PairedDeviceInfo(PeerInformation peerInformation)
{
id = peerInformation.HostName.ToString();
name = peerInformation.DisplayName;
}
[DataMember]
public String id { get; set; }
[DataMember]
public String name { get; set; }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.NetCore.Analyzers.Security
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class PotentialReferenceCycleInDeserializedObjectGraph : DiagnosticAnalyzer
{
internal const string DiagnosticId = "CA5362";
private static readonly LocalizableString s_Title = new LocalizableResourceString(
nameof(MicrosoftNetCoreAnalyzersResources.PotentialReferenceCycleInDeserializedObjectGraphTitle),
MicrosoftNetCoreAnalyzersResources.ResourceManager,
typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_Message = new LocalizableResourceString(
nameof(MicrosoftNetCoreAnalyzersResources.PotentialReferenceCycleInDeserializedObjectGraphMessage),
MicrosoftNetCoreAnalyzersResources.ResourceManager,
typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_Description = new LocalizableResourceString(
nameof(MicrosoftNetCoreAnalyzersResources.PotentialReferenceCycleInDeserializedObjectGraphDescription),
MicrosoftNetCoreAnalyzersResources.ResourceManager,
typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(
DiagnosticId,
s_Title,
s_Message,
DiagnosticCategory.Security,
RuleLevel.Disabled,
description: s_Description,
isPortedFxCopRule: false,
isDataflowRule: false,
isEnabledByDefaultInFxCopAnalyzers: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public sealed override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
// Security analyzer - analyze and report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterCompilationStartAction(
(CompilationStartAnalysisContext compilationStartAnalysisContext) =>
{
var compilation = compilationStartAnalysisContext.Compilation;
var serializableAttributeTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute);
if (serializableAttributeTypeSymbol == null)
{
return;
}
var nonSerializedAttribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute);
if (nonSerializedAttribute == null)
{
return;
}
ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>> forwardGraph = new ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>>();
ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>> invertedGraph = new ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>>();
// It keeps the out Degree of every vertex in the invertedGraph, which is corresponding to the in Degree of the vertex in forwardGraph.
ConcurrentDictionary<ISymbol, int> inDegree = new ConcurrentDictionary<ISymbol, int>();
// It Keeps the out degree of every vertex in the forwardGraph, which is corresponding to the in Degree of the vertex in invertedGraph.
ConcurrentDictionary<ISymbol, int> outDegree = new ConcurrentDictionary<ISymbol, int>();
compilationStartAnalysisContext.RegisterSymbolAction(
(SymbolAnalysisContext symbolAnalysisContext) =>
{
DrawGraph((INamedTypeSymbol)symbolAnalysisContext.Symbol);
}, SymbolKind.NamedType);
compilationStartAnalysisContext.RegisterCompilationEndAction(
(CompilationAnalysisContext compilationAnalysisContext) =>
{
ModifyDegree(inDegree, forwardGraph);
ModifyDegree(outDegree, invertedGraph);
// If the degree of a vertex is greater than 0 both in the forward graph and inverted graph after topological sorting,
// the vertex must belong to a loop.
var leftVertices = inDegree.Where(s => s.Value > 0).Select(s => s.Key).ToImmutableHashSet();
var invertedLeftVertices = outDegree.Where(s => s.Value > 0).Select(s => s.Key).ToImmutableHashSet();
var verticesInLoop = leftVertices.Intersect(invertedLeftVertices);
foreach (var vertex in verticesInLoop)
{
if (vertex is IFieldSymbol fieldInLoop)
{
var associatedSymbol = fieldInLoop.AssociatedSymbol;
compilationAnalysisContext.ReportDiagnostic(
fieldInLoop.CreateDiagnostic(
Rule,
associatedSymbol == null ? vertex.Name : associatedSymbol.Name));
}
}
});
// Traverse from point to its descendants, save the information into a directed graph.
//
// point: The initial point
void DrawGraph(ITypeSymbol point)
{
// If the point has been visited, return;
// otherwise, add it to the graph and mark it as visited.
if (!AddPointToBothGraphs(point))
{
return;
}
foreach (var associatedTypePoint in GetAssociatedTypes(point))
{
if (associatedTypePoint == null ||
associatedTypePoint.Equals(point))
{
continue;
}
AddLineToBothGraphs(point, associatedTypePoint);
DrawGraph(associatedTypePoint);
}
if (point.IsInSource() &&
point.HasAttribute(serializableAttributeTypeSymbol))
{
var fieldPoints = point.GetMembers().OfType<IFieldSymbol>().Where(s => !s.HasAttribute(nonSerializedAttribute) &&
!s.IsStatic);
foreach (var fieldPoint in fieldPoints)
{
var fieldTypePoint = fieldPoint.Type;
AddLineToBothGraphs(point, fieldPoint);
AddLineToBothGraphs(fieldPoint, fieldTypePoint);
DrawGraph(fieldTypePoint);
}
}
}
static HashSet<ITypeSymbol> GetAssociatedTypes(ITypeSymbol type)
{
var result = new HashSet<ITypeSymbol>();
if (type is INamedTypeSymbol namedTypeSymbol)
{
// 1. Type arguments of generic type.
if (namedTypeSymbol.IsGenericType)
{
foreach (var arg in namedTypeSymbol.TypeArguments)
{
result.Add(arg);
}
}
// 2. The type it constructed from.
var constructedFrom = namedTypeSymbol.ConstructedFrom;
result.Add(constructedFrom);
}
else if (type is IArrayTypeSymbol arrayTypeSymbol)
{
// 3. Element type of the array.
result.Add(arrayTypeSymbol.ElementType);
}
// 4. Base type.
result.Add(type.BaseType);
return result;
}
// Add a line to the graph.
//
// from: The start point of the line
// to: The end point of the line
// degree: The out degree of all vertices in the graph
// graph: The graph
void AddLine(ISymbol from, ISymbol to, ConcurrentDictionary<ISymbol, int> degree, ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>> graph)
{
graph.AddOrUpdate(from, new ConcurrentDictionary<ISymbol, bool> { [to] = true }, (k, v) => { v[to] = true; return v; });
degree.AddOrUpdate(from, 1, (k, v) => v + 1);
}
// Add a point to the graph.
//
// point: The point to be added
// degree: The out degree of all vertices in the graph
// graph: The graph
static bool AddPoint(ISymbol point, ConcurrentDictionary<ISymbol, int> degree, ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>> graph)
{
degree.TryAdd(point, 0);
return graph.TryAdd(point, new ConcurrentDictionary<ISymbol, bool>());
}
// Add a line to the forward graph and inverted graph unconditionally.
//
// from: The start point of the line
// to: The end point of the line
void AddLineToBothGraphs(ISymbol from, ISymbol to)
{
AddLine(from, to, outDegree, forwardGraph);
AddLine(to, from, inDegree, invertedGraph);
}
// Add a point to the forward graph and inverted graph unconditionally.
//
// point: The point to be added
// return: `true` if `point` is added to the forward graph successfully; otherwise `false`.
bool AddPointToBothGraphs(ISymbol point)
{
AddPoint(point, inDegree, invertedGraph);
return AddPoint(point, outDegree, forwardGraph);
}
// According to topological sorting, modify the degree of every vertex in the graph.
//
// degree: The in degree of all vertices in the graph
// graph: The graph
static void ModifyDegree(ConcurrentDictionary<ISymbol, int> degree, ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>> graph)
{
var stack = new Stack<ISymbol>(degree.Where(s => s.Value == 0).Select(s => s.Key));
while (stack.Count != 0)
{
var start = stack.Pop();
degree.AddOrUpdate(start, -1, (k, v) => v - 1);
foreach (var vertex in graph[start].Keys)
{
degree.AddOrUpdate(vertex, -1, (k, v) => v - 1);
if (degree[vertex] == 0)
{
stack.Push(vertex);
}
}
}
}
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
namespace System.Xml
{
internal class XmlElementList : XmlNodeList
{
private readonly string _asterisk;
private int _changeCount; //recording the total number that the dom tree has been changed ( insertion and deletion )
//the member vars below are saved for further reconstruction
private readonly string _name; //only one of 2 string groups will be initialized depends on which constructor is called.
private string _localName;
private string _namespaceURI;
private readonly XmlNode _rootNode;
// the member vars below serves the optimization of accessing of the elements in the list
private int _curInd; // -1 means the starting point for a new search round
private XmlNode _curElem; // if sets to rootNode, means the starting point for a new search round
private bool _empty; // whether the list is empty
private bool _atomized; //whether the localname and namespaceuri are atomized
private int _matchCount; // cached list count. -1 means it needs reconstruction
private WeakReference _listener; // XmlElementListListener
private XmlElementList(XmlNode parent)
{
Debug.Assert(parent != null);
Debug.Assert(parent.NodeType == XmlNodeType.Element || parent.NodeType == XmlNodeType.Document);
_rootNode = parent;
Debug.Assert(parent.Document != null);
_curInd = -1;
_curElem = _rootNode;
_changeCount = 0;
_empty = false;
_atomized = true;
_matchCount = -1;
// This can be a regular reference, but it would cause some kind of loop inside the GC
_listener = new WeakReference(new XmlElementListListener(parent.Document, this));
}
~XmlElementList()
{
Dispose(false);
}
internal void ConcurrencyCheck(XmlNodeChangedEventArgs args)
{
if (_atomized == false)
{
XmlNameTable nameTable = _rootNode.Document.NameTable;
_localName = nameTable.Add(_localName);
_namespaceURI = nameTable.Add(_namespaceURI);
_atomized = true;
}
if (IsMatch(args.Node))
{
_changeCount++;
_curInd = -1;
_curElem = _rootNode;
if (args.Action == XmlNodeChangedAction.Insert)
_empty = false;
}
_matchCount = -1;
}
internal XmlElementList(XmlNode parent, string name) : this(parent)
{
Debug.Assert(parent.Document != null);
XmlNameTable nt = parent.Document.NameTable;
Debug.Assert(nt != null);
_asterisk = nt.Add("*");
_name = nt.Add(name);
_localName = null;
_namespaceURI = null;
}
internal XmlElementList(XmlNode parent, string localName, string namespaceURI) : this(parent)
{
Debug.Assert(parent.Document != null);
XmlNameTable nt = parent.Document.NameTable;
Debug.Assert(nt != null);
_asterisk = nt.Add("*");
_localName = nt.Get(localName);
_namespaceURI = nt.Get(namespaceURI);
if ((_localName == null) || (_namespaceURI == null))
{
_empty = true;
_atomized = false;
_localName = localName;
_namespaceURI = namespaceURI;
}
_name = null;
}
internal int ChangeCount
{
get { return _changeCount; }
}
// return the next element node that is in PreOrder
private XmlNode NextElemInPreOrder(XmlNode curNode)
{
Debug.Assert(curNode != null);
//For preorder walking, first try its child
XmlNode retNode = curNode.FirstChild;
if (retNode == null)
{
//if no child, the next node forward will the be the NextSibling of the first ancestor which has NextSibling
//so, first while-loop find out such an ancestor (until no more ancestor or the ancestor is the rootNode
retNode = curNode;
while (retNode != null
&& retNode != _rootNode
&& retNode.NextSibling == null)
{
retNode = retNode.ParentNode;
}
//then if such ancestor exists, set the retNode to its NextSibling
if (retNode != null && retNode != _rootNode)
retNode = retNode.NextSibling;
}
if (retNode == _rootNode)
//if reach the rootNode, consider having walked through the whole tree and no more element after the curNode
retNode = null;
return retNode;
}
// return the previous element node that is in PreOrder
private XmlNode PrevElemInPreOrder(XmlNode curNode)
{
Debug.Assert(curNode != null);
//For preorder walking, the previous node will be the right-most node in the tree of PreviousSibling of the curNode
XmlNode retNode = curNode.PreviousSibling;
// so if the PreviousSibling is not null, going through the tree down to find the right-most node
while (retNode != null)
{
if (retNode.LastChild == null)
break;
retNode = retNode.LastChild;
}
// if no PreviousSibling, the previous node will be the curNode's parentNode
if (retNode == null)
retNode = curNode.ParentNode;
// if the final retNode is rootNode, consider having walked through the tree and no more previous node
if (retNode == _rootNode)
retNode = null;
return retNode;
}
// if the current node a matching element node
private bool IsMatch(XmlNode curNode)
{
if (curNode.NodeType == XmlNodeType.Element)
{
if (_name != null)
{
if (Ref.Equal(_name, _asterisk) || Ref.Equal(curNode.Name, _name))
return true;
}
else
{
if (
(Ref.Equal(_localName, _asterisk) || Ref.Equal(curNode.LocalName, _localName)) &&
(Ref.Equal(_namespaceURI, _asterisk) || curNode.NamespaceURI == _namespaceURI)
)
{
return true;
}
}
}
return false;
}
private XmlNode GetMatchingNode(XmlNode n, bool bNext)
{
Debug.Assert(n != null);
XmlNode node = n;
do
{
if (bNext)
node = NextElemInPreOrder(node);
else
node = PrevElemInPreOrder(node);
} while (node != null && !IsMatch(node));
return node;
}
private XmlNode GetNthMatchingNode(XmlNode n, bool bNext, int nCount)
{
Debug.Assert(n != null);
XmlNode node = n;
for (int ind = 0; ind < nCount; ind++)
{
node = GetMatchingNode(node, bNext);
if (node == null)
return null;
}
return node;
}
//the function is for the enumerator to find out the next available matching element node
public XmlNode GetNextNode(XmlNode n)
{
if (_empty == true)
return null;
XmlNode node = (n == null) ? _rootNode : n;
return GetMatchingNode(node, true);
}
public override XmlNode Item(int index)
{
if (_rootNode == null || index < 0)
return null;
if (_empty == true)
return null;
if (_curInd == index)
return _curElem;
int nDiff = index - _curInd;
bool bForward = (nDiff > 0);
if (nDiff < 0)
nDiff = -nDiff;
XmlNode node;
if ((node = GetNthMatchingNode(_curElem, bForward, nDiff)) != null)
{
_curInd = index;
_curElem = node;
return _curElem;
}
return null;
}
public override int Count
{
get
{
if (_empty == true)
return 0;
if (_matchCount < 0)
{
int currMatchCount = 0;
int currChangeCount = _changeCount;
XmlNode node = _rootNode;
while ((node = GetMatchingNode(node, true)) != null)
{
currMatchCount++;
}
if (currChangeCount != _changeCount)
{
return currMatchCount;
}
_matchCount = currMatchCount;
}
return _matchCount;
}
}
public override IEnumerator GetEnumerator()
{
if (_empty == true)
return new XmlEmptyElementListEnumerator(this); ;
return new XmlElementListEnumerator(this);
}
protected override void PrivateDisposeNodeList()
{
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_listener != null)
{
XmlElementListListener listener = (XmlElementListListener)_listener.Target;
if (listener != null)
{
listener.Unregister();
}
_listener = null;
}
}
}
internal class XmlElementListEnumerator : IEnumerator
{
private readonly XmlElementList _list;
private XmlNode _curElem;
private int _changeCount; //save the total number that the dom tree has been changed ( insertion and deletion ) when this enumerator is created
public XmlElementListEnumerator(XmlElementList list)
{
_list = list;
_curElem = null;
_changeCount = list.ChangeCount;
}
public bool MoveNext()
{
if (_list.ChangeCount != _changeCount)
{
//the number mismatch, there is new change(s) happened since last MoveNext() is called.
throw new InvalidOperationException(SR.Xdom_Enum_ElementList);
}
else
{
_curElem = _list.GetNextNode(_curElem);
}
return _curElem != null;
}
public void Reset()
{
_curElem = null;
//reset the number of changes to be synced with current dom tree as well
_changeCount = _list.ChangeCount;
}
public object Current
{
get { return _curElem; }
}
}
internal class XmlEmptyElementListEnumerator : IEnumerator
{
public XmlEmptyElementListEnumerator(XmlElementList list)
{
}
public bool MoveNext()
{
return false;
}
public void Reset()
{
}
public object Current
{
get { return null; }
}
}
internal class XmlElementListListener
{
private WeakReference _elemList;
private readonly XmlDocument _doc;
private readonly XmlNodeChangedEventHandler _nodeChangeHandler = null;
internal XmlElementListListener(XmlDocument doc, XmlElementList elemList)
{
_doc = doc;
_elemList = new WeakReference(elemList);
_nodeChangeHandler = new XmlNodeChangedEventHandler(this.OnListChanged);
doc.NodeInserted += _nodeChangeHandler;
doc.NodeRemoved += _nodeChangeHandler;
}
private void OnListChanged(object sender, XmlNodeChangedEventArgs args)
{
lock (this)
{
if (_elemList != null)
{
XmlElementList el = (XmlElementList)_elemList.Target;
if (null != el)
{
el.ConcurrencyCheck(args);
}
else
{
_doc.NodeInserted -= _nodeChangeHandler;
_doc.NodeRemoved -= _nodeChangeHandler;
_elemList = null;
}
}
}
}
// This method is called from the finalizer of XmlElementList
internal void Unregister()
{
lock (this)
{
if (_elemList != null)
{
_doc.NodeInserted -= _nodeChangeHandler;
_doc.NodeRemoved -= _nodeChangeHandler;
_elemList = null;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.