context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using Google.Apis.Auth.OAuth2;
using System;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Storage.V1
{
/// <summary>
/// Class which helps create signed URLs which can be used to provide limited access to specific buckets and objects
/// to anyone in possession of the URL, regardless of whether they have a Google account.
/// </summary>
/// <remarks>
/// See https://cloud.google.com/storage/docs/access-control/signed-urls for more information on signed URLs.
/// </remarks>
public sealed partial class UrlSigner
{
private const string StorageHost = "storage.googleapis.com";
private static readonly ISigner s_v2Signer = new V2Signer();
private static readonly ISigner s_v4Signer = new V4Signer();
private const string GoogHeaderPrefix = "x-goog-";
/// <summary>
/// Gets a special HTTP method which can be used to create a signed URL for initiating a resumable upload.
/// See https://cloud.google.com/storage/docs/access-control/signed-urls#signing-resumable for more information.
/// </summary>
/// <remarks>
/// Note: When using the RESUMABLE method to create a signed URL, a URL will actually be signed for the POST method with a header of
/// 'x-goog-resumable:start'. The caller must perform a POST request with this URL and specify the 'x-goog-resumable:start' header as
/// well or signature validation will fail.
/// </remarks>
public static HttpMethod ResumableHttpMethod { get; } = new HttpMethod("RESUMABLE");
private static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeSpan.Zero);
private readonly IBlobSigner _blobSigner;
private readonly IClock _clock;
private UrlSigner(IBlobSigner blobSigner, IClock clock)
{
_blobSigner = blobSigner;
_clock = clock;
}
/// <summary>
/// Creates a new <see cref="UrlSigner"/> instance for a service account.
/// </summary>
/// <param name="credentialFilePath">The path to the JSON key file for a service account. Must not be null.</param>
/// <exception cref="InvalidOperationException">
/// The <paramref name="credentialFilePath"/> does not refer to a valid JSON service account key file.
/// </exception>
public static UrlSigner FromServiceAccountPath(string credentialFilePath)
{
GaxPreconditions.CheckNotNull(credentialFilePath, nameof(credentialFilePath));
using (var credentialData = File.OpenRead(credentialFilePath))
{
return FromServiceAccountData(credentialData);
}
}
/// <summary>
/// Creates a new <see cref="UrlSigner"/> instance for a service account.
/// </summary>
/// <param name="credentialData">The stream from which to read the JSON key data for a service account. Must not be null.</param>
/// <exception cref="InvalidOperationException">
/// The <paramref name="credentialData"/> does not contain valid JSON service account key data.
/// </exception>
public static UrlSigner FromServiceAccountData(Stream credentialData)
{
GaxPreconditions.CheckNotNull(credentialData, nameof(credentialData));
return UrlSigner.FromServiceAccountCredential(ServiceAccountCredential.FromServiceAccountData(credentialData));
}
/// <summary>
/// Creates a new <see cref="UrlSigner"/> instance for a service account.
/// </summary>
/// <param name="credential">The credential for the a service account. Must not be null.</param>
public static UrlSigner FromServiceAccountCredential(ServiceAccountCredential credential)
{
GaxPreconditions.CheckNotNull(credential, nameof(credential));
return new UrlSigner(new ServiceAccountCredentialBlobSigner(credential), SystemClock.Instance);
}
/// <summary>
/// Creates a new <see cref="UrlSigner"/> instance for a custom blob signer.
/// </summary>
/// <remarks>
/// This method is typically used when a service account credential file isn't available, either
/// for testing or to use the IAM service's blob signing capabilities.
/// </remarks>
/// <param name="signer">The blob signer to use. Must not be null.</param>
/// <returns>A new <see cref="UrlSigner"/> using the specified blob signer.</returns>
public static UrlSigner FromBlobSigner(IBlobSigner signer)
{
GaxPreconditions.CheckNotNull(signer, nameof(signer));
return new UrlSigner(signer, SystemClock.Instance);
}
/// <summary>
/// Only available for testing purposes, this allows the clock used for signature generation to be replaced.
/// </summary>
internal UrlSigner WithClock(IClock clock) => new UrlSigner(_blobSigner, clock);
/// <summary>
/// Creates a signed URL which can be used to provide limited access to specific buckets and objects to anyone
/// in possession of the URL, regardless of whether they have a Google account.
/// </summary>
/// <remarks>
/// <para>
/// When a <see cref="UrlSigner"/> is created with a service account credential, the signing can be performed
/// with no network access. When it is created with an implementation of <see cref="IBlobSigner"/>, that may require
/// network access or other IO. In that case, one of the asynchronous methods should be used when the caller is
/// in a context that should not block.
/// </para>
/// <para>
/// See https://cloud.google.com/storage/docs/access-control/signed-urls for more information on signed URLs.
/// </para>
/// <para>
/// Note that when GET is specified as the <paramref name="httpMethod"/> (or it is null, in which case GET is
/// used), both GET and HEAD requests can be made with the created signed URL.
/// </para>
/// </remarks>
/// <param name="bucket">The name of the bucket. Must not be null.</param>
/// <param name="objectName">The name of the object within the bucket. May be null, in which case the signed URL
/// will refer to the bucket instead of an object.</param>
/// <param name="duration">The length of time for which the signed URL should remain usable.</param>
/// <param name="httpMethod">The HTTP request method for which the signed URL is allowed to be used. May be null,
/// in which case GET will be used.</param>
/// <param name="signingVersion">The signing version to use to generate the signed URL. May be null, in which case
/// <see cref="SigningVersion.Default"/> will be used.</param>
/// <returns>The signed URL which can be used to provide access to a bucket or object for a limited amount of time.</returns>
public string Sign(string bucket, string objectName, TimeSpan duration, HttpMethod httpMethod = null, SigningVersion? signingVersion = null)
{
var template = RequestTemplate
.FromBucket(bucket)
.WithObjectName(objectName)
.WithHttpMethod(httpMethod);
var options = Options.FromDuration(duration);
if (signingVersion.HasValue)
{
options = options.WithSigningVersion(signingVersion.Value);
}
return Sign(template, options);
}
/// <summary>
/// Creates a signed URL which can be used to provide limited access to specific buckets and objects to anyone
/// in possession of the URL, regardless of whether they have a Google account.
/// </summary>
/// <remarks>
/// <para>
/// When a <see cref="UrlSigner"/> is created with a service account credential, the signing can be performed
/// with no network access. When it is created with an implementation of <see cref="IBlobSigner"/>, that may require
/// network access or other IO. In that case, one of the asynchronous methods should be used when the caller is
/// in a context that should not block.
/// </para>
/// <para>
/// See https://cloud.google.com/storage/docs/access-control/signed-urls for more information on signed URLs.
/// </para>
/// </remarks>
/// <param name="requestTemplate">The request template that will be used to generate the signed URL for. Must not be null.</param>
/// <param name="options">The options used to generate the signed URL. Must not be null.</param>
/// <returns>
/// The signed URL which can be used to provide access to a bucket or object for a limited amount of time.
/// </returns>
public string Sign(RequestTemplate requestTemplate, Options options) =>
GetEffectiveSigner(GaxPreconditions.CheckNotNull(options, nameof(options)).SigningVersion).Sign(
GaxPreconditions.CheckNotNull(requestTemplate, nameof(requestTemplate)), options, _blobSigner, _clock);
/// <summary>
/// Signs the given post policy. The result can be used to make form posting requests matching the conditions
/// set in the post policy.
/// </summary>
/// <remarks>
/// <para>
/// Signing post policies is not supported by <see cref="SigningVersion.V2"/>. A <see cref="NotSupportedException"/>
/// will be thrown if an attempt is made to sign a post policy using <see cref="SigningVersion.V2"/>.
/// </para>
/// <para>
/// When a <see cref="UrlSigner"/> is created with a service account credential, the signing can be performed
/// with no network access. When it is created with an implementation of <see cref="IBlobSigner"/>, that may require
/// network access or other IO. In that case, one of the asynchronous methods should be used when the caller is
/// in a context that should not block.
/// </para>
/// <para>
/// See https://cloud.google.com/storage/docs/xml-api/post-object for more information on signed post policies.
/// </para>
/// </remarks>
/// <param name="postPolicy">The post policy to signed and that will be enforced when making the post request.
/// Must not be null.</param>
/// <param name="options">The options used to generate the signed post policy. Must not be null.</param>
/// <returns>The signed post policy, which contains all the fields that should be including in the form to post.</returns>
public SignedPostPolicy Sign(PostPolicy postPolicy, Options options) =>
GetEffectiveSigner(GaxPreconditions.CheckNotNull(options, nameof(options)).SigningVersion).Sign(
GaxPreconditions.CheckNotNull(postPolicy, nameof(postPolicy)), options, _blobSigner, _clock);
/// <summary>
/// Creates a signed URL which can be used to provide limited access to specific buckets and objects to anyone
/// in possession of the URL, regardless of whether they have a Google account.
/// </summary>
/// <remarks>
/// <para>
/// When a <see cref="UrlSigner"/> is created with a service account credential, the signing can be performed
/// with no network access. When it is created with an implementation of <see cref="IBlobSigner"/>, that may require
/// network access or other IO. In that case, one of the asynchronous methods should be used when the caller is
/// in a context that should not block.
/// </para>
/// <para>
/// See https://cloud.google.com/storage/docs/access-control/signed-urls for more information on signed URLs.
/// </para>
/// <para>
/// Note that when GET is specified as the <paramref name="httpMethod"/> (or it is null, in which case GET is
/// used), both GET and HEAD requests can be made with the created signed URL.
/// </para>
/// </remarks>
/// <param name="bucket">The name of the bucket. Must not be null.</param>
/// <param name="objectName">The name of the object within the bucket. May be null, in which case the signed URL
/// will refer to the bucket instead of an object.</param>
/// <param name="duration">The length of time for which the signed URL should remain usable.</param>
/// <param name="httpMethod">The HTTP request method for which the signed URL is allowed to be used. May be null,
/// in which case GET will be used.</param>
/// <param name="signingVersion">The signing version to use to generate the signed URL. May be null, in which case
/// <see cref="SigningVersion.Default"/> will be used.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns> A task representing the asynchronous operation, with a result returning the
/// signed URL which can be used to provide access to a bucket or object for a limited amount of time.</returns>
public async Task<string> SignAsync(string bucket, string objectName, TimeSpan duration, HttpMethod httpMethod = null, SigningVersion? signingVersion = null, CancellationToken cancellationToken = default)
{
var template = RequestTemplate
.FromBucket(bucket)
.WithObjectName(objectName)
.WithHttpMethod(httpMethod);
var options = Options.FromDuration(duration);
if (signingVersion.HasValue)
{
options = options.WithSigningVersion(signingVersion.Value);
}
return await SignAsync(template, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously creates a signed URL which can be used to provide limited access to specific buckets and objects to anyone
/// in possession of the URL, regardless of whether they have a Google account.
/// </summary>
/// <remarks>
/// <para>
/// When a <see cref="UrlSigner"/> is created with a service account credential, the signing can be performed
/// with no network access. When it is created with an implementation of <see cref="IBlobSigner"/>, that may require
/// network access or other IO. In that case, one of the asynchronous methods should be used when the caller is
/// in a context that should not block.
/// </para>
/// <para>
/// See https://cloud.google.com/storage/docs/access-control/signed-urls for more information on signed URLs.
/// </para>
/// </remarks>
/// <param name="requestTemplate">The request template that will be used to generate the signed URL for. Must not be null.</param>
/// <param name="options">The options used to generate the signed URL. Must not be null.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>
/// A task representing the asynchronous operation, with a result returning the
/// signed URL which can be used to provide access to a bucket or object for a limited amount of time.
/// </returns>
public Task<string> SignAsync(RequestTemplate requestTemplate, Options options, CancellationToken cancellationToken = default) =>
GetEffectiveSigner(GaxPreconditions.CheckNotNull(options, nameof(options)).SigningVersion).SignAsync(
GaxPreconditions.CheckNotNull(requestTemplate, nameof(requestTemplate)), options, _blobSigner, _clock, cancellationToken);
/// <summary>
/// Signs the given post policy. The result can be used to make form posting requests matching the conditions
/// set in the post policy.
/// </summary>
/// <remarks>
/// <para>
/// Signing post policies is not supported by <see cref="SigningVersion.V2"/>. A <see cref="NotSupportedException"/>
/// will be thrown if an attempt is made to sign a post policy using <see cref="SigningVersion.V2"/>.
/// </para>
/// <para>
/// When a <see cref="UrlSigner"/> is created with a service account credential, the signing can be performed
/// with no network access. When it is created with an implementation of <see cref="IBlobSigner"/>, that may require
/// network access or other IO. In that case, one of the asynchronous methods should be used when the caller is
/// in a context that should not block.
/// </para>
/// <para>
/// See https://cloud.google.com/storage/docs/xml-api/post-object for more information on signed post policies.
/// </para>
/// </remarks>
/// <param name="postPolicy">The post policy to signed and that will be enforced when making the post request.
/// Most not be null.</param>
/// <param name="options">The options used to generate the signed post policy. Must not be null.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The signed post policy, which contains all the fields that should be including in the form to post.</returns>
public Task<SignedPostPolicy> SignAsync(PostPolicy postPolicy, Options options, CancellationToken cancellationToken = default) =>
GetEffectiveSigner(GaxPreconditions.CheckNotNull(options, nameof(options)).SigningVersion).SignAsync(
GaxPreconditions.CheckNotNull(postPolicy, nameof(postPolicy)), options, _blobSigner, _clock, cancellationToken);
private ISigner GetEffectiveSigner(SigningVersion signingVersion) =>
signingVersion switch
{
SigningVersion.Default => s_v4Signer,
SigningVersion.V2 => s_v2Signer,
SigningVersion.V4 => s_v4Signer,
// We really shouldn't get here, as we validate any user-specified signing version.
_ => throw new InvalidOperationException($"Invalid signing version: {signingVersion}")
};
private static readonly Regex s_newlineRegex = new Regex(@"\r?\n", RegexOptions.Compiled);
private static readonly Regex s_tabRegex = new Regex(@"\t+", RegexOptions.Compiled);
private static readonly Regex s_whitespaceRegex = new Regex(@"\s+", RegexOptions.Compiled);
/// <summary>
/// Prepares a header value for signing, trimming both ends and collapsing internal whitespace.
/// </summary>
internal static string PrepareHeaderValue(string value, bool collapseTabs)
{
// Remove leading/trailing whitespace
value = value.Trim();
if (collapseTabs)
{
// Replaces all consecutive tabs by a space.
// If consecutive spaces result out of this, then the next line will
// collapse all the spaces.
value = s_tabRegex.Replace(value, " ");
}
// Collapse whitespace runs: only keep the last character
value = s_whitespaceRegex.Replace(value, match => match.Value[match.Value.Length - 1].ToString());
// Remove newlines
value = s_newlineRegex.Replace(value, "");
return value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Es.ToolsCommon;
using Newtonsoft.Json.Linq;
namespace Es.DnsProxy
{
internal sealed class DnsProxyServer
{
private const int DnsPort = 53;
private const int DnsIamPort = 453;
private static readonly char[] DotSeparator = {'.'};
private readonly Dictionary<ulong, CacheEntry> _cacheEntries = new Dictionary<ulong, CacheEntry>();
private readonly TimeSpan _cacheTimeout = TimeSpan.FromMinutes(5);
private readonly List<HostOverride> _hostOverrides = new List<HostOverride>();
private readonly Action<string> _onError;
private readonly Action<string> _onLog;
private readonly Dictionary<ushort, ulong> _outstandingQueries = new Dictionary<ushort, ulong>();
private readonly IPEndPoint _primaryDnsAddress;
private static readonly DateTime EndOfTime = DateTime.MaxValue.Subtract(TimeSpan.FromDays(1));
public DnsProxyServer(string dir, Action<object> onError, Action<object> onLog)
{
_onError = onError;
_onLog = onLog;
var configFilename = Path.Combine(dir, "dnsproxy.json");
if (!File.Exists(configFilename))
{
_onError($"No config file at {configFilename}");
return;
}
var config = JObject.Parse(File.ReadAllText(configFilename));
var hostMaps = config.GetValue("hosts").ToObject<string[][]>();
if (hostMaps != null)
{
SetupHostsEntries(hostMaps);
}
_primaryDnsAddress = new IPEndPoint(IPAddress.Parse(config.GetValue("servers").First.ToObject<string>()),
DnsPort);
}
private void SetupHostsEntries(string[][] hostMaps)
{
foreach (var hostMap in hostMaps)
{
if (hostMap.Length < 2)
{
_onError?.Invoke($"didn't understand hosts entry ${string.Join(",", hostMap)}");
continue;
}
// for now only support 1 IP override.
var hostname = hostMap[0];
var hostip = hostMap[1];
var ip = IPAddress.Parse(hostip).GetAddressBytes();
var ho = CreateHostOverride(hostname, ip);
_hostOverrides.Add(ho);
_onLog?.Invoke(
$"hostmap for {hostname} {hostip}\n\t{string.Join(" ", ho.hostPostfix.Select(b => b.ToString("X2")))}\n\t{string.Join(" ", ho.ipAddr.Select(b => b.ToString("X2")))}");
}
}
private static HostOverride CreateHostOverride(string hostname, byte[] ip)
{
var ho = new HostOverride {hostname = hostname};
var hostBits = hostname.Split(DotSeparator, StringSplitOptions.RemoveEmptyEntries);
var n = 0;
var buffer = new byte[512];
foreach (var bit in hostBits)
{
buffer[n++] = (byte) bit.Length;
var utf8Bytes = Encoding.UTF8.GetBytes(bit);
foreach (var b in utf8Bytes)
{
buffer[n++] = b;
}
}
ho.hostPostfix = buffer.Take(n).ToArray();
ho.ipAddr = ip;
return ho;
}
public void DumpBuffer(byte[] buffer, int n)
{
const int perLine = 16;
for (var i = 0; i < n; i += perLine)
{
var t = i + perLine > n ? n - i : perLine;
_onLog?.Invoke(string.Join(" ", buffer.Skip(i).Take(t).Select(b => b.ToString("X2"))));
}
}
public async Task Run(CancellationToken token)
{
try
{
var sIam = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
IgnoreConnReset(sIam);
sIam.Bind(new IPEndPoint(IPAddress.Any, DnsIamPort));
var sDns = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
IgnoreConnReset(sDns);
sDns.Bind(new IPEndPoint(IPAddress.Any, DnsPort));
var bufferDns = new byte[512];
var bufferIam = new byte[512];
var rftDns = ReceiveFrom(sDns, bufferDns);
var rftIam = ReceiveFrom(sIam, bufferIam);
var ts = new Task<RecvResult>[2];
ts[0] = rftDns;
ts[1] = rftIam;
while (!token.IsCancellationRequested)
{
rftDns = ts[0];
rftIam = ts[1];
var tr = await Task.WhenAny(ts);
if (tr.IsCanceled)
break;
var rf = tr.Result;
if (rf==null)
continue;
var n = rf.N;
var remoteEp = rf.RemoteEp;
_onLog($"RecvFrom {remoteEp}");
if (tr == rftDns)
{
DumpBuffer(bufferDns, n);
if (remoteEp.Equals(_primaryDnsAddress))
{
await HandleReplyFromPrimaryDnsServer(bufferDns, n, sDns);
_onLog($"# outstanding {_cacheEntries.Sum(x=>x.Value.Requests.Count)}");
}
else
{
await HandleRequestFromClient(bufferDns, n, remoteEp, sDns);
}
ts[0] = ReceiveFrom(sDns, bufferDns);
}
else if (tr == rftIam)
{
do
{
DumpBuffer(bufferIam, n);
if (n < 5)
{
_onLog($"IAM {remoteEp} send {n} bytes, too small to parse");
break;
}
if (bufferIam[0] != 0)
{
_onLog($"IAM {remoteEp} send unsupported version tag {bufferIam[0]}");
break;
}
var cmd = bufferIam[1];
if (cmd == 0 || cmd == 1)
{
byte[] ip = null;
if (cmd == 0) // use remoteIp
{
// register
var ipEndPoint = remoteEp as IPEndPoint;
if (ipEndPoint == null)
{
_onLog($"IAM {remoteEp} not an ipEndpoint??");
break;
}
ip = ipEndPoint.Address.GetAddressBytes();
if (ip.Length != 4)
{
_onLog($"IAM {remoteEp} not ipv4");
break;
}
}
var nl = bufferIam[2];
if (nl > n - 3)
{
_onLog($"IAM {remoteEp} send name length that exceeds packet length");
break;
}
var hostname = Encoding.ASCII.GetString(bufferIam, 3, nl);
if (cmd == 1) // use providedIp
{
ip = new[]
{
bufferIam[3 + nl],
bufferIam[4 + nl],
bufferIam[5 + nl],
bufferIam[6 + nl],
};
}
if (ip == null)
{
_onLog($"IAM {remoteEp} ip is still null, how?");
break;
}
var toReplase = _hostOverrides.Find(x => x.hostname == hostname);
if (toReplase != null)
{
toReplase.ipAddr = ip;
}
else
{
_hostOverrides.Add(CreateHostOverride(hostname, ip));
}
_cacheEntries.Clear();
if (cmd == 1)
{
bufferIam[3 + nl] = ip[0];
bufferIam[4 + nl] = ip[1];
bufferIam[5 + nl] = ip[2];
bufferIam[6 + nl] = ip[3];
n += 4;
}
bufferIam[1] |= 0x80;
_onLog(
$"IAM {remoteEp} set {hostname} to {string.Join(".", ip.Select(x => x.ToString()))}");
await SendTo(sIam, bufferIam, n, remoteEp);
break;
}
_onLog($"IAM {remoteEp} send unsupported cmd {cmd}");
} while (false);
ts[1] = ReceiveFrom(sIam, bufferIam);
}
}
}
catch (Exception ex)
{
_onError(ex.ToString());
}
}
private static void IgnoreConnReset(Socket s)
{
const uint IOC_IN = 0x80000000;
const uint IOC_VENDOR = 0x18000000;
const uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
unchecked
{
s.IOControl((int) SIO_UDP_CONNRESET, new byte[] {0}, null);
}
}
private async Task HandleRequestFromClient(byte[] buffer, int n, EndPoint remoteEp, Socket s)
{
// request from a client
// skip qID for hash
var hash = buffer.Hash(2, n - 2);
//_onLog($"{n} {hash}");
CacheEntry ce;
_cacheEntries.TryGetValue(hash, out ce);
if (ce == null)
{
ce = HandleOverrides(buffer, n, hash);
if (ce != null)
{
_cacheEntries[hash] = ce;
}
}
var repliedAlready = false;
if (ce?.Response != null)
{
// copy over qId
ce.Response[0] = buffer[0];
ce.Response[1] = buffer[1];
_onLog($"CACHED SendTo {remoteEp}");
DumpBuffer(ce.Response, ce.Response.Length);
await SendTo(s, ce.Response, ce.Response.Length, remoteEp);
// send again
await Task.Delay(1);
await SendTo(s, ce.Response, ce.Response.Length, remoteEp);
repliedAlready = true;
var now = DateTime.Now;
var timeSpan = now.Subtract(ce.LastUpdated);
if (timeSpan < _cacheTimeout)
{
_onLog($"Skipped relookup, cache entry only {timeSpan.TotalSeconds}s old");
return;
}
}
if (ce == null)
{
ce = new CacheEntry(hash);
}
var queryId = (ushort)hash;
if (!repliedAlready)
{
_outstandingQueries[queryId] = hash;
var originalQueryId = (ushort)((buffer[0] << 8) | buffer[1]);
ce.Requests.Add(new Request(originalQueryId, remoteEp));
_cacheEntries[hash] = ce;
}
// try to resolve it
buffer[0] = (byte) (queryId >> 8);
buffer[1] = (byte) (queryId & 0xff);
_onLog($"SendTo {_primaryDnsAddress}");
DumpBuffer(buffer, n);
await SendTo(s, buffer, n, _primaryDnsAddress);
}
private CacheEntry HandleOverrides(byte[] buffer, int n, ulong hash)
{
if (!(buffer[2] == 1
&& buffer[3] == 0
&& buffer[4] == 0
&& buffer[5] == 1
&& buffer[n - 1] == 1
&& buffer[n - 2] == 0
&& buffer[n - 3] == 1
&& buffer[n - 4] == 0
)) // single question, normal flags, A, IN
{
return null;
}
var maxLen = n - 16; // offset 12 to n-4
DumpSingleARequest(buffer, n);
foreach (var ho in _hostOverrides)
{
if (ho.hostPostfix.Length > maxLen)
continue;
var nk = n - 5 - ho.hostPostfix.Length;
if (!ho.hostPostfix.All(t => buffer[nk++] == t))
continue;
// postfix matches, create cache entry with pre-populated response.
var ce = new CacheEntry(hash, EndOfTime); // never expire
buffer[2] = 0x81; // response
buffer[3] = 0x80; // rescursion abailable
buffer[7] = 0x01; // one reply
buffer[n++] = 0xc0; // ref
buffer[n++] = 0x0c; // offset 12
buffer[n++] = 0; // A
buffer[n++] = 1; // A
buffer[n++] = 0; // IN
buffer[n++] = 1; // IN
buffer[n++] = 0; // ttl
buffer[n++] = 0; // ttl
buffer[n++] = 0; // ttl
buffer[n++] = 1; // ttl (super short)
buffer[n++] = 0; // count
buffer[n++] = 4; // 4 bytes to follow
buffer[n++] = ho.ipAddr[0];
buffer[n++] = ho.ipAddr[1];
buffer[n++] = ho.ipAddr[2];
buffer[n++] = ho.ipAddr[3];
ce.Response = buffer.Take(n).ToArray();
return ce;
}
return null;
}
private void DumpSingleARequest(byte[] buffer, int n)
{
var p = new List<string>();
for (var j = 11; j < n - 4;)
{
var l = (int) buffer[++j];
if (l == 0)
break;
var s = "";
for (var k = 0; k < l; ++k)
{
s += (char) buffer[++j];
}
p.Add(s);
}
var host = string.Join(".", p);
_onLog($"A {host}");
}
private async Task HandleReplyFromPrimaryDnsServer(byte[] buffer, int n, Socket s)
{
// reply from primary dns server
var originalQueryId = (ushort) ((buffer[0] << 8) | buffer[1]);
ulong hash;
if (!_outstandingQueries.TryGetValue(originalQueryId, out hash))
return;
_outstandingQueries.Remove(originalQueryId);
CacheEntry ce;
if (!_cacheEntries.TryGetValue(hash, out ce))
return;
DumpSingleARequest(buffer, n);
foreach (var r in ce.Requests)
{
var queryId = r.Qid;
var requestedEp = r.Asker;
r.Stopwatch.Stop();
buffer[0] = (byte) (queryId >> 8);
buffer[1] = (byte) queryId;
_onLog($"SendTo {requestedEp} {r.Stopwatch.ElapsedMilliseconds}ms");
await SendTo(s, buffer, n, requestedEp);
}
ce.Requests.Clear();
ce.Response = buffer.Take(n).ToArray();
}
private async Task SendTo(Socket s, byte[] buffer, int length, EndPoint remoteEp)
{
try
{
var tcs = new TaskCompletionSource<int>(s);
s.BeginSendTo(buffer, 0, length, SocketFlags.None, remoteEp,
iar => { tcs.SetResult(s.EndSendTo(iar)); },
tcs);
await tcs.Task;
}
catch (Exception ex)
{
_onLog($"{ex}");
}
}
private async Task<RecvResult> ReceiveFrom(Socket s, byte[] buffer)
{
try
{
EndPoint remoteEp = new IPEndPoint(IPAddress.Any, DnsPort);
var tcs = new TaskCompletionSource<int>(s);
s.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEp,
iar => { tcs.SetResult(s.EndReceiveFrom(iar, ref remoteEp)); }, tcs);
var n = await tcs.Task;
return new RecvResult {N = n, RemoteEp = remoteEp};
}
catch (Exception ex)
{
_onLog($"{ex}");
}
return null;
}
private sealed class Request
{
public readonly ushort Qid;
public readonly EndPoint Asker;
public readonly Stopwatch Stopwatch;
public Request(ushort originalQueryId, EndPoint remoteEp)
{
Qid = originalQueryId;
Asker = remoteEp;
Stopwatch = Stopwatch.StartNew();
}
}
private sealed class CacheEntry
{
public readonly ulong Hash;
public readonly DateTime LastUpdated;
public readonly List<Request> Requests = new List<Request>();
public byte[] Response;
public CacheEntry(ulong hash)
{
Hash = hash;
LastUpdated = DateTime.Now;
Response = null;
}
public CacheEntry(ulong hash, DateTime lastUpdated)
{
Hash = hash;
LastUpdated = lastUpdated;
Response = null;
}
}
private sealed class RecvResult
{
public int N;
public EndPoint RemoteEp;
}
private sealed class HostOverride
{
public string hostname;
public byte[] hostPostfix;
public byte[] ipAddr;
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="Conversation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the Conversation class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
/// <summary>
/// Represents a collection of Conversation related properties.
/// Properties available on this object are defined in the ConversationSchema class.
/// </summary>
[ServiceObjectDefinition(XmlElementNames.Conversation)]
public class Conversation : ServiceObject
{
/// <summary>
/// Initializes an unsaved local instance of <see cref="Conversation"/>.
/// </summary>
/// <param name="service">The ExchangeService object to which the item will be bound.</param>
internal Conversation(ExchangeService service)
: base(service)
{
}
/// <summary>
/// Internal method to return the schema associated with this type of object.
/// </summary>
/// <returns>The schema associated with this type of object.</returns>
internal override ServiceObjectSchema GetSchema()
{
return ConversationSchema.Instance;
}
/// <summary>
/// Gets the minimum required server version.
/// </summary>
/// <returns>Earliest Exchange version in which this service object type is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2010_SP1;
}
/// <summary>
/// The property definition for the Id of this object.
/// </summary>
/// <returns>A PropertyDefinition instance.</returns>
internal override PropertyDefinition GetIdPropertyDefinition()
{
return ConversationSchema.Id;
}
#region Not Supported Methods or properties
/// <summary>
/// This method is not supported in this object.
/// Loads the specified set of properties on the object.
/// </summary>
/// <param name="propertySet">The properties to load.</param>
internal override void InternalLoad(PropertySet propertySet)
{
throw new NotSupportedException();
}
/// <summary>
/// This is not supported in this object.
/// Deletes the object.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
/// <param name="sendCancellationsMode">Indicates whether meeting cancellation messages should be sent.</param>
/// <param name="affectedTaskOccurrences">Indicate which occurrence of a recurring task should be deleted.</param>
internal override void InternalDelete(DeleteMode deleteMode, SendCancellationsMode? sendCancellationsMode, AffectedTaskOccurrence? affectedTaskOccurrences)
{
throw new NotSupportedException();
}
/// <summary>
/// This method is not supported in this object.
/// Gets the name of the change XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal override string GetChangeXmlElementName()
{
throw new NotSupportedException();
}
/// <summary>
/// This method is not supported in this object.
/// Gets the name of the delete field XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal override string GetDeleteFieldXmlElementName()
{
throw new NotSupportedException();
}
/// <summary>
/// This method is not supported in this object.
/// Gets the name of the set field XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal override string GetSetFieldXmlElementName()
{
throw new NotSupportedException();
}
/// <summary>
/// This method is not supported in this object.
/// Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem
/// or UpdateItem request so this item can be property saved or updated.
/// </summary>
/// <param name="isUpdateOperation">Indicates whether the operation being petrformed is an update operation.</param>
/// <returns><c>true</c> if a time zone SOAP header should be emitted; otherwise, <c>false</c>.</returns>
internal override bool GetIsTimeZoneHeaderRequired(bool isUpdateOperation)
{
throw new NotSupportedException();
}
/// <summary>
/// This method is not supported in this object.
/// Gets the extended properties collection.
/// </summary>
/// <returns>Extended properties collection.</returns>
internal override ExtendedPropertyCollection GetExtendedProperties()
{
throw new NotSupportedException();
}
#endregion
#region Conversation Action Methods
/// <summary>
/// Sets up a conversation so that any item received within that conversation is always categorized.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="categories">The categories that should be stamped on items in the conversation.</param>
/// <param name="processSynchronously">Indicates whether the method should return only once enabling this rule and stamping existing items
/// in the conversation is completely done. If processSynchronously is false, the method returns immediately.
/// </param>
public void EnableAlwaysCategorizeItems(IEnumerable<string> categories, bool processSynchronously)
{
this.Service.EnableAlwaysCategorizeItemsInConversations(
new ConversationId[] { this.Id },
categories,
processSynchronously)[0].ThrowIfNecessary();
}
/// <summary>
/// Sets up a conversation so that any item received within that conversation is no longer categorized.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="processSynchronously">Indicates whether the method should return only once disabling this rule and removing the categories from existing items
/// in the conversation is completely done. If processSynchronously is false, the method returns immediately.
/// </param>
public void DisableAlwaysCategorizeItems(bool processSynchronously)
{
this.Service.DisableAlwaysCategorizeItemsInConversations(
new ConversationId[] { this.Id },
processSynchronously)[0].ThrowIfNecessary();
}
/// <summary>
/// Sets up a conversation so that any item received within that conversation is always moved to Deleted Items folder.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="processSynchronously">Indicates whether the method should return only once enabling this rule and deleting existing items
/// in the conversation is completely done. If processSynchronously is false, the method returns immediately.
/// </param>
public void EnableAlwaysDeleteItems(bool processSynchronously)
{
this.Service.EnableAlwaysDeleteItemsInConversations(
new ConversationId[] { this.Id },
processSynchronously)[0].ThrowIfNecessary();
}
/// <summary>
/// Sets up a conversation so that any item received within that conversation is no longer moved to Deleted Items folder.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="processSynchronously">Indicates whether the method should return only once disabling this rule and restoring the items
/// in the conversation is completely done. If processSynchronously is false, the method returns immediately.
/// </param>
public void DisableAlwaysDeleteItems(bool processSynchronously)
{
this.Service.DisableAlwaysDeleteItemsInConversations(
new ConversationId[] { this.Id },
processSynchronously)[0].ThrowIfNecessary();
}
/// <summary>
/// Sets up a conversation so that any item received within that conversation is always moved to a specific folder.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="destinationFolderId">The Id of the folder to which conversation items should be moved.</param>
/// <param name="processSynchronously">Indicates whether the method should return only once enabling this rule
/// and moving existing items in the conversation is completely done. If processSynchronously is false, the method
/// returns immediately.
/// </param>
public void EnableAlwaysMoveItems(FolderId destinationFolderId, bool processSynchronously)
{
this.Service.EnableAlwaysMoveItemsInConversations(
new ConversationId[] { this.Id },
destinationFolderId,
processSynchronously)[0].ThrowIfNecessary();
}
/// <summary>
/// Sets up a conversation so that any item received within that conversation is no longer moved to a specific
/// folder. Calling this method results in a call to EWS.
/// </summary>
/// <param name="processSynchronously">Indicates whether the method should return only once disabling this
/// rule is completely done. If processSynchronously is false, the method returns immediately.
/// </param>
public void DisableAlwaysMoveItemsInConversation(bool processSynchronously)
{
this.Service.DisableAlwaysMoveItemsInConversations(
new ConversationId[] { this.Id },
processSynchronously)[0].ThrowIfNecessary();
}
/// <summary>
/// Deletes items in the specified conversation.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order to be deleted. If contextFolderId is
/// null, items across the entire mailbox are deleted.</param>
/// <param name="deleteMode">The deletion mode.</param>
public void DeleteItems(
FolderId contextFolderId,
DeleteMode deleteMode)
{
this.Service.DeleteItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
deleteMode)[0].ThrowIfNecessary();
}
/// <summary>
/// Moves items in the specified conversation to a specific folder.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order to be moved. If contextFolderId is null,
/// items across the entire mailbox are moved.</param>
/// <param name="destinationFolderId">The Id of the destination folder.</param>
public void MoveItemsInConversation(
FolderId contextFolderId,
FolderId destinationFolderId)
{
this.Service.MoveItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
destinationFolderId)[0].ThrowIfNecessary();
}
/// <summary>
/// Copies items in the specified conversation to a specific folder. Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order to be copied. If contextFolderId
/// is null, items across the entire mailbox are copied.</param>
/// <param name="destinationFolderId">The Id of the destination folder.</param>
public void CopyItemsInConversation(
FolderId contextFolderId,
FolderId destinationFolderId)
{
this.Service.CopyItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
destinationFolderId)[0].ThrowIfNecessary();
}
/// <summary>
/// Sets the read state of items in the specified conversation. Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order for their read state to
/// be set. If contextFolderId is null, the read states of items across the entire mailbox are set.</param>
/// <param name="isRead">if set to <c>true</c>, conversation items are marked as read; otherwise they are
/// marked as unread.</param>
public void SetReadStateForItemsInConversation(
FolderId contextFolderId,
bool isRead)
{
this.Service.SetReadStateForItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
isRead)[0].ThrowIfNecessary();
}
/// <summary>
/// Sets the read state of items in the specified conversation. Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order for their read state to
/// be set. If contextFolderId is null, the read states of items across the entire mailbox are set.</param>
/// <param name="isRead">if set to <c>true</c>, conversation items are marked as read; otherwise they are
/// marked as unread.</param>
/// <param name="suppressReadReceipts">if set to <c>true</c> read receipts are suppressed.</param>
public void SetReadStateForItemsInConversation(
FolderId contextFolderId,
bool isRead,
bool suppressReadReceipts)
{
this.Service.SetReadStateForItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
isRead,
suppressReadReceipts)[0].ThrowIfNecessary();
}
/// <summary>
/// Sets the retention policy of items in the specified conversation. Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order for their retention policy to
/// be set. If contextFolderId is null, the retention policy of items across the entire mailbox are set.</param>
/// <param name="retentionPolicyType">Retention policy type.</param>
/// <param name="retentionPolicyTagId">Retention policy tag id. Null will clear the policy.</param>
public void SetRetentionPolicyForItemsInConversation(
FolderId contextFolderId,
RetentionType retentionPolicyType,
Guid? retentionPolicyTagId)
{
this.Service.SetRetentionPolicyForItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
retentionPolicyType,
retentionPolicyTagId)[0].ThrowIfNecessary();
}
/// <summary>
/// Flag conversation items as complete. Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order to be flagged as complete. If contextFolderId is
/// null, items in conversation across the entire mailbox are marked as complete.</param>
/// <param name="completeDate">The complete date (can be null).</param>
public void FlagItemsComplete(
FolderId contextFolderId,
DateTime? completeDate)
{
Flag flag = new Flag() { FlagStatus = ItemFlagStatus.Complete };
if (completeDate.HasValue)
{
flag.CompleteDate = completeDate.Value;
}
this.Service.SetFlagStatusForItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
flag)[0].ThrowIfNecessary();
}
/// <summary>
/// Clear flags for conversation items. Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order to be unflagged. If contextFolderId is
/// null, flags for items in conversation across the entire mailbox are cleared.</param>
public void ClearItemFlags(FolderId contextFolderId)
{
Flag flag = new Flag() { FlagStatus = ItemFlagStatus.NotFlagged };
this.Service.SetFlagStatusForItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
flag)[0].ThrowIfNecessary();
}
/// <summary>
/// Flags conversation items. Calling this method results in a call to EWS.
/// </summary>
/// <param name="contextFolderId">The Id of the folder items must belong to in order to be flagged. If contextFolderId is
/// null, items in conversation across the entire mailbox are flagged.</param>
/// <param name="startDate">The start date (can be null).</param>
/// <param name="dueDate">The due date (can be null).</param>
public void FlagItems(
FolderId contextFolderId,
DateTime? startDate,
DateTime? dueDate)
{
Flag flag = new Flag() { FlagStatus = ItemFlagStatus.Flagged };
if (startDate.HasValue)
{
flag.StartDate = startDate.Value;
}
if (dueDate.HasValue)
{
flag.DueDate = dueDate.Value;
}
this.Service.SetFlagStatusForItemsInConversations(
new KeyValuePair<ConversationId, DateTime?>[]
{
new KeyValuePair<ConversationId, DateTime?>(
this.Id,
this.GlobalLastDeliveryTime)
},
contextFolderId,
flag)[0].ThrowIfNecessary();
}
#endregion
#region Properties
/// <summary>
/// Gets the Id of this Conversation.
/// </summary>
public ConversationId Id
{
get { return (ConversationId)this.PropertyBag[this.GetIdPropertyDefinition()]; }
}
/// <summary>
/// Gets the topic of this Conversation.
/// </summary>
public String Topic
{
get
{
String returnValue = String.Empty;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.Topic))
{
this.PropertyBag.TryGetProperty<string>(
ConversationSchema.Topic,
out returnValue);
}
return returnValue;
}
}
/// <summary>
/// Gets a list of all the people who have received messages in this conversation in the current folder only.
/// </summary>
public StringList UniqueRecipients
{
get { return (StringList)this.PropertyBag[ConversationSchema.UniqueRecipients]; }
}
/// <summary>
/// Gets a list of all the people who have received messages in this conversation across all folders in the mailbox.
/// </summary>
public StringList GlobalUniqueRecipients
{
get { return (StringList)this.PropertyBag[ConversationSchema.GlobalUniqueRecipients]; }
}
/// <summary>
/// Gets a list of all the people who have sent messages that are currently unread in this conversation in the current folder only.
/// </summary>
public StringList UniqueUnreadSenders
{
get
{
StringList unreadSenders = null;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.UniqueUnreadSenders))
{
this.PropertyBag.TryGetProperty<StringList>(
ConversationSchema.UniqueUnreadSenders,
out unreadSenders);
}
return unreadSenders;
}
}
/// <summary>
/// Gets a list of all the people who have sent messages that are currently unread in this conversation across all folders in the mailbox.
/// </summary>
public StringList GlobalUniqueUnreadSenders
{
get
{
StringList unreadSenders = null;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.GlobalUniqueUnreadSenders))
{
this.PropertyBag.TryGetProperty<StringList>(
ConversationSchema.GlobalUniqueUnreadSenders,
out unreadSenders);
}
return unreadSenders;
}
}
/// <summary>
/// Gets a list of all the people who have sent messages in this conversation in the current folder only.
/// </summary>
public StringList UniqueSenders
{
get { return (StringList)this.PropertyBag[ConversationSchema.UniqueSenders]; }
}
/// <summary>
/// Gets a list of all the people who have sent messages in this conversation across all folders in the mailbox.
/// </summary>
public StringList GlobalUniqueSenders
{
get { return (StringList)this.PropertyBag[ConversationSchema.GlobalUniqueSenders]; }
}
/// <summary>
/// Gets the delivery time of the message that was last received in this conversation in the current folder only.
/// </summary>
public DateTime LastDeliveryTime
{
get { return (DateTime)this.PropertyBag[ConversationSchema.LastDeliveryTime]; }
}
/// <summary>
/// Gets the delivery time of the message that was last received in this conversation across all folders in the mailbox.
/// </summary>
public DateTime GlobalLastDeliveryTime
{
get { return (DateTime)this.PropertyBag[ConversationSchema.GlobalLastDeliveryTime]; }
}
/// <summary>
/// Gets a list summarizing the categories stamped on messages in this conversation, in the current folder only.
/// </summary>
public StringList Categories
{
get
{
StringList returnValue = null;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.Categories))
{
this.PropertyBag.TryGetProperty<StringList>(
ConversationSchema.Categories,
out returnValue);
}
return returnValue;
}
}
/// <summary>
/// Gets a list summarizing the categories stamped on messages in this conversation, across all folders in the mailbox.
/// </summary>
public StringList GlobalCategories
{
get
{
StringList returnValue = null;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.GlobalCategories))
{
this.PropertyBag.TryGetProperty<StringList>(
ConversationSchema.GlobalCategories,
out returnValue);
}
return returnValue;
}
}
/// <summary>
/// Gets the flag status for this conversation, calculated by aggregating individual messages flag status in the current folder.
/// </summary>
public ConversationFlagStatus FlagStatus
{
get
{
ConversationFlagStatus returnValue = ConversationFlagStatus.NotFlagged;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.FlagStatus))
{
this.PropertyBag.TryGetProperty<ConversationFlagStatus>(ConversationSchema.FlagStatus, out returnValue);
}
return returnValue;
}
}
/// <summary>
/// Gets the flag status for this conversation, calculated by aggregating individual messages flag status across all folders in the mailbox.
/// </summary>
public ConversationFlagStatus GlobalFlagStatus
{
get
{
ConversationFlagStatus returnValue = ConversationFlagStatus.NotFlagged;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.GlobalFlagStatus))
{
this.PropertyBag.TryGetProperty<ConversationFlagStatus>(
ConversationSchema.GlobalFlagStatus,
out returnValue);
}
return returnValue;
}
}
/// <summary>
/// Gets a value indicating if at least one message in this conversation, in the current folder only, has an attachment.
/// </summary>
public bool HasAttachments
{
get { return (bool)this.PropertyBag[ConversationSchema.HasAttachments]; }
}
/// <summary>
/// Gets a value indicating if at least one message in this conversation, across all folders in the mailbox, has an attachment.
/// </summary>
public bool GlobalHasAttachments
{
get { return (bool)this.PropertyBag[ConversationSchema.GlobalHasAttachments]; }
}
/// <summary>
/// Gets the total number of messages in this conversation in the current folder only.
/// </summary>
public int MessageCount
{
get { return (int)this.PropertyBag[ConversationSchema.MessageCount]; }
}
/// <summary>
/// Gets the total number of messages in this conversation across all folders in the mailbox.
/// </summary>
public int GlobalMessageCount
{
get { return (int)this.PropertyBag[ConversationSchema.GlobalMessageCount]; }
}
/// <summary>
/// Gets the total number of unread messages in this conversation in the current folder only.
/// </summary>
public int UnreadCount
{
get
{
int returnValue = 0;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.UnreadCount))
{
this.PropertyBag.TryGetProperty<int>(
ConversationSchema.UnreadCount,
out returnValue);
}
return returnValue;
}
}
/// <summary>
/// Gets the total number of unread messages in this conversation across all folders in the mailbox.
/// </summary>
public int GlobalUnreadCount
{
get
{
int returnValue = 0;
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(ConversationSchema.GlobalUnreadCount))
{
this.PropertyBag.TryGetProperty<int>(
ConversationSchema.GlobalUnreadCount,
out returnValue);
}
return returnValue;
}
}
/// <summary>
/// Gets the size of this conversation, calculated by adding the sizes of all messages in the conversation in the current folder only.
/// </summary>
public int Size
{
get { return (int)this.PropertyBag[ConversationSchema.Size]; }
}
/// <summary>
/// Gets the size of this conversation, calculated by adding the sizes of all messages in the conversation across all folders in the mailbox.
/// </summary>
public int GlobalSize
{
get { return (int)this.PropertyBag[ConversationSchema.GlobalSize]; }
}
/// <summary>
/// Gets a list summarizing the classes of the items in this conversation, in the current folder only.
/// </summary>
public StringList ItemClasses
{
get { return (StringList)this.PropertyBag[ConversationSchema.ItemClasses]; }
}
/// <summary>
/// Gets a list summarizing the classes of the items in this conversation, across all folders in the mailbox.
/// </summary>
public StringList GlobalItemClasses
{
get { return (StringList)this.PropertyBag[ConversationSchema.GlobalItemClasses]; }
}
/// <summary>
/// Gets the importance of this conversation, calculated by aggregating individual messages importance in the current folder only.
/// </summary>
public Importance Importance
{
get { return (Importance)this.PropertyBag[ConversationSchema.Importance]; }
}
/// <summary>
/// Gets the importance of this conversation, calculated by aggregating individual messages importance across all folders in the mailbox.
/// </summary>
public Importance GlobalImportance
{
get { return (Importance)this.PropertyBag[ConversationSchema.GlobalImportance]; }
}
/// <summary>
/// Gets the Ids of the messages in this conversation, in the current folder only.
/// </summary>
public ItemIdCollection ItemIds
{
get { return (ItemIdCollection)this.PropertyBag[ConversationSchema.ItemIds]; }
}
/// <summary>
/// Gets the Ids of the messages in this conversation, across all folders in the mailbox.
/// </summary>
public ItemIdCollection GlobalItemIds
{
get { return (ItemIdCollection)this.PropertyBag[ConversationSchema.GlobalItemIds]; }
}
/// <summary>
/// Gets the date and time this conversation was last modified.
/// </summary>
public DateTime LastModifiedTime
{
get { return (DateTime)this.PropertyBag[ConversationSchema.LastModifiedTime]; }
}
/// <summary>
/// Gets the conversation instance key.
/// </summary>
public byte[] InstanceKey
{
get { return (byte[])this.PropertyBag[ConversationSchema.InstanceKey]; }
}
/// <summary>
/// Gets the conversation Preview.
/// </summary>
public string Preview
{
get { return (string)this.PropertyBag[ConversationSchema.Preview]; }
}
/// <summary>
/// Gets the conversation IconIndex.
/// </summary>
public IconIndex IconIndex
{
get { return (IconIndex)this.PropertyBag[ConversationSchema.IconIndex]; }
}
/// <summary>
/// Gets the conversation global IconIndex.
/// </summary>
public IconIndex GlobalIconIndex
{
get { return (IconIndex)this.PropertyBag[ConversationSchema.GlobalIconIndex]; }
}
/// <summary>
/// Gets the draft item ids.
/// </summary>
public ItemIdCollection DraftItemIds
{
get { return (ItemIdCollection)this.PropertyBag[ConversationSchema.DraftItemIds]; }
}
/// <summary>
/// Gets a value indicating if at least one message in this conversation, in the current folder only, is an IRM.
/// </summary>
public bool HasIrm
{
get { return (bool)this.PropertyBag[ConversationSchema.HasIrm]; }
}
/// <summary>
/// Gets a value indicating if at least one message in this conversation, across all folders in the mailbox, is an IRM.
/// </summary>
public bool GlobalHasIrm
{
get { return (bool)this.PropertyBag[ConversationSchema.GlobalHasIrm]; }
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2012 Charlie Poole
//
// 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.
// ***********************************************************************
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif
using System.Reflection;
using NUnit.Framework.Api;
using NUnit.Framework.Internal.Commands;
using NUnit.Framework.Internal.WorkItems;
namespace NUnit.Framework.Internal
{
/// <summary>
/// The TestMethod class represents a Test implemented as a method.
/// Because of how exceptions are handled internally, this class
/// must incorporate processing of expected exceptions. A change to
/// the Test interface might make it easier to process exceptions
/// in an object that aggregates a TestMethod in the future.
/// </summary>
public class TestMethod : Test
{
#region Fields
/// <summary>
/// The test method
/// </summary>
internal MethodInfo method;
/// <summary>
/// A list of all decorators applied to the test by attributes or parameterset arguments
/// </summary>
#if CLR_2_0 || CLR_4_0
private List<ICommandDecorator> decorators = new List<ICommandDecorator>();
#else
private System.Collections.ArrayList decorators = new System.Collections.ArrayList();
#endif
/// <summary>
/// The ParameterSet used to create this test method
/// </summary>
internal ParameterSet parms;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="TestMethod"/> class.
/// </summary>
/// <param name="method">The method to be used as a test.</param>
/// <param name="parentSuite">The suite or fixture to which the new test will be added</param>
public TestMethod(MethodInfo method, Test parentSuite)
: base( method.ReflectedType )
{
this.Name = method.Name;
this.FullName += "." + this.Name;
// Disambiguate call to base class methods
// TODO: This should not be here - it's a presentation issue
if( method.DeclaringType != method.ReflectedType)
this.Name = method.DeclaringType.Name + "." + method.Name;
// Needed to give proper fullname to test in a parameterized fixture.
// Without this, the arguments to the fixture are not included.
string prefix = method.ReflectedType.FullName;
if (parentSuite != null)
{
prefix = parentSuite.FullName;
this.FullName = prefix + "." + this.Name;
}
this.method = method;
}
#endregion
#region Properties
/// <summary>
/// Gets the method.
/// </summary>
/// <value>The method that performs the test.</value>
public MethodInfo Method
{
get { return method; }
}
/// <summary>
/// Gets a list of custom decorators for this test.
/// </summary>
#if CLR_2_0 || CLR_4_0
public IList<ICommandDecorator> CustomDecorators
#else
public System.Collections.IList CustomDecorators
#endif
{
get { return decorators; }
}
internal bool HasExpectedResult
{
get { return parms != null && parms.HasExpectedResult; }
}
internal object ExpectedResult
{
get { return parms != null ? parms.ExpectedResult : null; }
}
internal object[] Arguments
{
get { return parms != null ? parms.Arguments : null; }
}
internal bool IsAsync
{
get
{
#if NET_4_5
return method.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute), false);
#else
return false;
#endif
}
}
#endregion
#region Test Overrides
/// <summary>
/// Overridden to return a TestCaseResult.
/// </summary>
/// <returns>A TestResult for this test.</returns>
public override TestResult MakeTestResult()
{
return new TestCaseResult(this);
}
/// <summary>
/// Gets a bool indicating whether the current test
/// has any descendant tests.
/// </summary>
public override bool HasChildren
{
get { return false; }
}
/// <summary>
/// Returns an XmlNode representing the current result after
/// adding it as a child of the supplied parent node.
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="recursive">If true, descendant results are included</param>
/// <returns></returns>
public override XmlNode AddToXml(XmlNode parentNode, bool recursive)
{
XmlNode thisNode = parentNode.AddElement(XmlElementName);
PopulateTestNode(thisNode, recursive);
return thisNode;
}
/// <summary>
/// Gets this test's child tests
/// </summary>
/// <value>A list of child tests</value>
#if CLR_2_0 || CLR_4_0
public override IList<ITest> Tests
#else
public override System.Collections.IList Tests
#endif
{
get { return new ITest[0]; }
}
/// <summary>
/// Gets the name used for the top-level element in the
/// XML representation of this test
/// </summary>
public override string XmlElementName
{
get { return "test-case"; }
}
/// <summary>
/// Creates a test command for use in running this test.
/// </summary>
/// <returns></returns>
public virtual TestCommand GetTestCommand()
{
TestCommand command = new TestMethodCommand(this);
command = ApplyDecoratorsToCommand(command);
IApplyToContext[] changes = (IApplyToContext[])this.Method.GetCustomAttributes(typeof(IApplyToContext), true);
if (changes.Length > 0)
command = new ApplyChangesToContextCommand(command, changes);
return command;
}
#endregion
#region Helper Methods
private TestCommand ApplyDecoratorsToCommand(TestCommand command)
{
CommandDecoratorList decorators = new CommandDecoratorList();
// Add Standard stuff
decorators.Add(new SetUpTearDownDecorator());
// Add Decorators supplied by attributes and parameter sets
foreach (ICommandDecorator decorator in CustomDecorators)
decorators.Add(decorator);
decorators.OrderByStage();
foreach (ICommandDecorator decorator in decorators)
{
command = decorator.Decorate(command);
}
return command;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Security;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Linq.Expressions;
using System.Dynamic;
using System.Collections.Generic;
using System.Collections;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Runtime.Versioning;
using Microsoft.Dnx.Compilation;
using Microsoft.Dnx.Compilation.Caching;
using Microsoft.Dnx.Runtime;
using Microsoft.Dnx.Runtime.Loader;
using Microsoft.Extensions.PlatformAbstractions;
[StructLayout(LayoutKind.Sequential)]
// ReSharper disable once CheckNamespace
public struct V8ObjectData
{
public int propertiesCount;
public IntPtr propertyTypes;
public IntPtr propertyNames;
public IntPtr propertyValues;
}
[StructLayout(LayoutKind.Sequential)]
public struct V8ArrayData
{
public int arrayLength;
public IntPtr itemTypes;
public IntPtr itemValues;
}
[StructLayout(LayoutKind.Sequential)]
public struct V8BufferData
{
public int bufferLength;
public IntPtr buffer;
}
public enum V8Type
{
Function = 1,
Buffer = 2,
Array = 3,
Date = 4,
Object = 5,
String = 6,
Boolean = 7,
Int32 = 8,
UInt32 = 9,
Number = 10,
Null = 11,
Task = 12,
Exception = 13
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct EdgeBootstrapperContext
{
[MarshalAs(UnmanagedType.LPStr)]
public string OperatingSystem;
[MarshalAs(UnmanagedType.LPStr)]
public string OperatingSystemVersion;
[MarshalAs(UnmanagedType.LPStr)]
public string Architecture;
[MarshalAs(UnmanagedType.LPStr)]
public string RuntimeDirectory;
[MarshalAs(UnmanagedType.LPStr)]
public string ApplicationDirectory;
[MarshalAs(UnmanagedType.LPStr)]
public string EdgeNodePath;
}
public delegate void CallV8FunctionDelegate(IntPtr payload, int payloadType, IntPtr v8FunctionContext, IntPtr callbackContext, IntPtr callbackDelegate);
public delegate void TaskCompleteDelegate(IntPtr result, int resultType, int taskState, IntPtr context);
[SecurityCritical]
public class CoreCLREmbedding
{
private class TaskState
{
public readonly TaskCompleteDelegate Callback;
public readonly IntPtr Context;
public TaskState(TaskCompleteDelegate callback, IntPtr context)
{
Callback = callback;
Context = context;
}
}
private class EdgeServiceProviderLocator : IServiceProviderLocator
{
public IServiceProvider ServiceProvider
{
get;
set;
}
}
private class EdgeServiceProvider : IServiceProvider
{
private readonly Dictionary<Type, object> _entries = new Dictionary<Type, object>();
public EdgeServiceProvider()
{
Add(typeof(IServiceProvider), this);
}
public void Add(Type type, object instance)
{
_entries[type] = instance;
}
public bool TryAdd(Type type, object instance)
{
if (GetService(type) == null)
{
Add(type, instance);
return true;
}
return false;
}
public object GetService(Type serviceType)
{
return _entries[serviceType];
}
}
private class EdgeRuntimeEnvironment : IRuntimeEnvironment
{
public EdgeRuntimeEnvironment(EdgeBootstrapperContext bootstrapperContext)
{
OperatingSystem = bootstrapperContext.OperatingSystem;
OperatingSystemVersion = bootstrapperContext.OperatingSystemVersion;
RuntimeArchitecture = bootstrapperContext.Architecture;
ApplicationDirectory = bootstrapperContext.ApplicationDirectory;
RuntimeVersion = typeof(object).GetTypeInfo().Assembly.GetName().Version.ToString();
RuntimePath = bootstrapperContext.RuntimeDirectory;
EdgeNodePath = bootstrapperContext.EdgeNodePath;
}
public string OperatingSystem
{
get;
}
public string OperatingSystemVersion
{
get;
}
public string RuntimeType => "CoreCLR";
public string RuntimeArchitecture
{
get;
}
public string RuntimeVersion
{
get;
}
public string RuntimePath
{
get;
}
public string ApplicationDirectory
{
get;
}
public string EdgeNodePath
{
get;
}
}
private class EdgeAssemblyLoadContextAccessor : IAssemblyLoadContextAccessor
{
private readonly Lazy<EdgeAssemblyLoadContext> _context;
public EdgeAssemblyLoadContextAccessor()
{
_context = new Lazy<EdgeAssemblyLoadContext>(() => new EdgeAssemblyLoadContext(this));
}
public IAssemblyLoadContext GetLoadContext(Assembly assembly)
{
return (IAssemblyLoadContext) AssemblyLoadContext.GetLoadContext(assembly);
}
public IAssemblyLoadContext Default => _context.Value;
public EdgeAssemblyLoadContext TypedDefault => _context.Value;
}
private class EdgeAssemblyLoadContext : AssemblyLoadContext, IAssemblyLoadContext
{
internal readonly Dictionary<string, string> CompileAssemblies = new Dictionary<string, string>();
private readonly List<IAssemblyLoader> _loaders = new List<IAssemblyLoader>();
private readonly bool _noProjectJsonFile;
private readonly EdgeAssemblyLoadContextAccessor _loadContextAccessor;
private readonly Dictionary<string, Assembly> _loadedAssemblies = new Dictionary<string, Assembly>();
public EdgeAssemblyLoadContext(EdgeAssemblyLoadContextAccessor loadContextAccessor)
{
DebugMessage("EdgeAssemblyLoadContext::ctor (CLR) - Starting");
DebugMessage("EdgeAssemblyLoadContext::ctor (CLR) - Application root is {0}", RuntimeEnvironment.ApplicationDirectory);
_loadContextAccessor = loadContextAccessor;
if (File.Exists(Path.Combine(RuntimeEnvironment.ApplicationDirectory, "project.lock.json")))
{
IList<LibraryDescription> libraries = ApplicationHostContext.GetRuntimeLibraries(ApplicationHostContext);
Dictionary<string, ProjectDescription> projects = libraries.Where(p => p.Type == LibraryTypes.Project).ToDictionary(p => p.Identity.Name, p => (ProjectDescription)p);
Dictionary<AssemblyName, string> assemblies = PackageDependencyProvider.ResolvePackageAssemblyPaths(libraries);
CompilationEngineContext compilationContext = new CompilationEngineContext(ApplicationEnvironment, RuntimeEnvironment, this, new CompilationCache());
CompilationEngine compilationEngine = new CompilationEngine(compilationContext);
AddCompileAssemblies(libraries);
_loaders.Add(new ProjectAssemblyLoader(_loadContextAccessor, compilationEngine, projects.Values));
_loaders.Add(new PackageAssemblyLoader(_loadContextAccessor, assemblies, libraries));
}
else
{
_noProjectJsonFile = true;
if (File.Exists(Path.Combine(RuntimeEnvironment.EdgeNodePath, "project.lock.json")))
{
ApplicationHostContext stockHostContext = new ApplicationHostContext
{
ProjectDirectory = RuntimeEnvironment.EdgeNodePath,
TargetFramework = TargetFrameworkName
};
IList<LibraryDescription> libraries = ApplicationHostContext.GetRuntimeLibraries(stockHostContext);
Dictionary<AssemblyName, string> assemblies = PackageDependencyProvider.ResolvePackageAssemblyPaths(libraries);
AddCompileAssemblies(libraries);
_loaders.Add(new PackageAssemblyLoader(_loadContextAccessor, assemblies, libraries));
}
}
DebugMessage("EdgeAssemblyLoadContext::ctor (CLR) - Created the dependency providers for the application");
}
protected void AddCompileAssemblies(IList<LibraryDescription> libraries)
{
foreach (LibraryDescription libraryDescription in libraries.Where(l => l.Type == LibraryTypes.Package))
{
if (CompileAssemblies.ContainsKey(libraryDescription.Identity.Name))
{
continue;
}
PackageDescription packageDescription = (PackageDescription)libraryDescription;
if (packageDescription.Target.CompileTimeAssemblies != null && packageDescription.Target.CompileTimeAssemblies.Count > 0)
{
CompileAssemblies[libraryDescription.Identity.Name] = Path.Combine(packageDescription.Path, packageDescription.Target.CompileTimeAssemblies[0].Path);
}
else if (packageDescription.Target.RuntimeAssemblies != null && packageDescription.Target.RuntimeAssemblies.Count > 0)
{
CompileAssemblies[libraryDescription.Identity.Name] = Path.Combine(packageDescription.Path, packageDescription.Target.RuntimeAssemblies[0].Path);
}
}
}
internal void AddCompiler(string compilerDirectory)
{
DebugMessage("EdgeAssemblyLoadContext::AddCompiler (CLR) - Adding the compiler in {0}", compilerDirectory);
ApplicationHostContext compilerHostContext = new ApplicationHostContext
{
ProjectDirectory = compilerDirectory,
TargetFramework = TargetFrameworkName
};
IList<LibraryDescription> libraries = ApplicationHostContext.GetRuntimeLibraries(compilerHostContext);
Dictionary<AssemblyName, string> assemblies = PackageDependencyProvider.ResolvePackageAssemblyPaths(libraries);
AddCompileAssemblies(libraries);
_loaders.Add(new PackageAssemblyLoader(_loadContextAccessor, assemblies, libraries));
DebugMessage("EdgeAssemblyLoadContext::AddCompiler (CLR) - Finished");
}
[SecuritySafeCritical]
protected override Assembly Load(AssemblyName assemblyName)
{
DebugMessage("EdgeAssemblyLoadContext::Load (CLR) - Trying to load {0}", assemblyName.Name);
if (_loadedAssemblies.ContainsKey(assemblyName.Name))
{
DebugMessage("EdgeAssemblyLoadContext::Load (CLR) - Returning previously loaded assembly");
return _loadedAssemblies[assemblyName.Name];
}
foreach (IAssemblyLoader loader in _loaders)
{
try
{
Assembly assembly = loader.Load(assemblyName);
if (assembly != null)
{
DebugMessage("EdgeAssemblyLoadContext::Load (CLR) - Successfully resolved assembly with {0}", loader.GetType().Name);
_loadedAssemblies[assemblyName.Name] = assembly;
return assembly;
}
}
catch (Exception e)
{
DebugMessage("EdgeAssemblyLoadContext::Load (CLR) - Error trying to load {0} with {1}: {2}{3}{4}", assemblyName.Name, loader.GetType().Name, e.Message, Environment.NewLine, e.StackTrace);
throw;
}
}
DebugMessage("EdgeAssemblyLoadContext::Load (CLR) - Unable to resolve assembly with any of the loaders");
try
{
return Assembly.Load(assemblyName);
}
catch (Exception e)
{
if (_noProjectJsonFile)
{
throw new Exception(
String.Format(
"Could not load assembly '{0}'. Please ensure that a project.json file specifying the dependencies for this application exists either in the current directory or in a .NET project directory specified using the EDGE_APP_ROOT environment variable and that the 'dnu restore' command has been run for this project.json file.",
assemblyName.Name), e);
}
throw;
}
}
public Assembly LoadFile(string assemblyPath)
{
if (!Path.IsPathRooted(assemblyPath))
{
assemblyPath = Path.Combine(RuntimeEnvironment.ApplicationDirectory, assemblyPath);
}
if (!File.Exists(assemblyPath))
{
throw new FileNotFoundException("Assembly file not found.", assemblyPath);
}
return LoadFromAssemblyPath(assemblyPath);
}
public Assembly LoadStream(Stream assemblyStream, Stream assemblySymbols)
{
return LoadFromStream(assemblyStream);
}
public IntPtr LoadUnmanagedLibrary(string name)
{
return LoadUnmanagedDll(name);
}
public IntPtr LoadUnmanagedLibraryFromPath(string path)
{
return LoadUnmanagedDllFromPath(path);
}
public void Dispose()
{
}
Assembly IAssemblyLoadContext.Load(AssemblyName assemblyName)
{
return Load(assemblyName);
}
}
// ReSharper disable InconsistentNaming
private static EdgeAssemblyLoadContextAccessor LoadContextAccessor;
private static ApplicationHostContext ApplicationHostContext;
private static ApplicationEnvironment ApplicationEnvironment;
private static EdgeRuntimeEnvironment RuntimeEnvironment;
// ReSharper enable InconsistentNaming
private static readonly bool DebugMode = Environment.GetEnvironmentVariable("EDGE_DEBUG") == "1";
private static readonly FrameworkName TargetFrameworkName = new FrameworkName("DNXCore,Version=v5.0");
private static readonly long MinDateTimeTicks = 621355968000000000;
private static readonly Dictionary<Type, List<Tuple<string, Func<object, object>>>> TypePropertyAccessors = new Dictionary<Type, List<Tuple<string, Func<object, object>>>>();
private static readonly int PointerSize = Marshal.SizeOf<IntPtr>();
private static readonly int V8BufferDataSize = Marshal.SizeOf<V8BufferData>();
private static readonly int V8ObjectDataSize = Marshal.SizeOf<V8ObjectData>();
private static readonly int V8ArrayDataSize = Marshal.SizeOf<V8ArrayData>();
private static readonly Dictionary<string, Tuple<Type, MethodInfo>> Compilers = new Dictionary<string, Tuple<Type, MethodInfo>>();
public static void Initialize(IntPtr context, IntPtr exception)
{
try
{
DebugMessage("CoreCLREmbedding::Initialize (CLR) - Starting");
RuntimeEnvironment = new EdgeRuntimeEnvironment(Marshal.PtrToStructure<EdgeBootstrapperContext>(context));
Project project;
Project.TryGetProject(RuntimeEnvironment.ApplicationDirectory, out project);
ApplicationHostContext = new ApplicationHostContext
{
ProjectDirectory = RuntimeEnvironment.ApplicationDirectory,
TargetFramework = TargetFrameworkName,
Project = project
};
ApplicationEnvironment = new ApplicationEnvironment(ApplicationHostContext.Project, TargetFrameworkName, "Release", null);
LoadContextAccessor = new EdgeAssemblyLoadContextAccessor();
EdgeServiceProvider serviceProvider = new EdgeServiceProvider();
serviceProvider.Add(typeof(IRuntimeEnvironment), RuntimeEnvironment);
serviceProvider.Add(typeof(IApplicationEnvironment), ApplicationEnvironment);
serviceProvider.Add(typeof(IAssemblyLoadContextAccessor), LoadContextAccessor);
CallContextServiceLocator.Locator = new EdgeServiceProviderLocator
{
ServiceProvider = serviceProvider
};
PlatformServices.SetDefault(PlatformServices.Create(null, ApplicationEnvironment, RuntimeEnvironment, null, LoadContextAccessor, null));
DebugMessage("CoreCLREmbedding::Initialize (CLR) - Complete");
}
catch (Exception e)
{
DebugMessage("CoreCLREmbedding::Initialize (CLR) - Exception was thrown: {0}", e.Message);
V8Type v8Type;
Marshal.WriteIntPtr(exception, MarshalCLRToV8(e, out v8Type));
}
}
[SecurityCritical]
public static IntPtr GetFunc(string assemblyFile, string typeName, string methodName, IntPtr exception)
{
try
{
Marshal.WriteIntPtr(exception, IntPtr.Zero);
Assembly assembly;
if (assemblyFile.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || assemblyFile.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
if (!Path.IsPathRooted(assemblyFile))
{
assemblyFile = Path.Combine(Directory.GetCurrentDirectory(), assemblyFile);
}
assembly = LoadContextAccessor.Default.LoadFile(assemblyFile);
}
else
{
assembly = LoadContextAccessor.Default.Load(new AssemblyName(assemblyFile));
}
DebugMessage("CoreCLREmbedding::GetFunc (CLR) - Assembly {0} loaded successfully", assemblyFile);
ClrFuncReflectionWrap wrapper = ClrFuncReflectionWrap.Create(assembly, typeName, methodName);
DebugMessage("CoreCLREmbedding::GetFunc (CLR) - Method {0}.{1}() loaded successfully", typeName, methodName);
Func<object, Task<object>> wrapperFunc = wrapper.Call;
GCHandle wrapperHandle = GCHandle.Alloc(wrapperFunc);
return GCHandle.ToIntPtr(wrapperHandle);
}
catch (Exception e)
{
DebugMessage("CoreCLREmbedding::GetFunc (CLR) - Exception was thrown: {0}", e.Message);
V8Type v8Type;
Marshal.WriteIntPtr(exception, MarshalCLRToV8(e, out v8Type));
return IntPtr.Zero;
}
}
[SecurityCritical]
public static IntPtr CompileFunc(IntPtr v8Options, int payloadType, IntPtr exception)
{
try
{
Marshal.WriteIntPtr(exception, IntPtr.Zero);
IDictionary<string, object> options = (IDictionary<string, object>)MarshalV8ToCLR(v8Options, (V8Type)payloadType);
string compiler = (string)options["compiler"];
if (!Path.IsPathRooted(compiler))
{
compiler = Path.Combine(Directory.GetCurrentDirectory(), compiler);
}
MethodInfo compileMethod;
Type compilerType;
if (!Compilers.ContainsKey(compiler))
{
LoadContextAccessor.TypedDefault.AddCompiler(Directory.GetParent(compiler).FullName);
Assembly compilerAssembly = LoadContextAccessor.Default.LoadFile(compiler);
DebugMessage("CoreCLREmbedding::CompileFunc (CLR) - Compiler assembly {0} loaded successfully", compiler);
compilerType = compilerAssembly.GetType("EdgeCompiler");
if (compilerType == null)
{
throw new TypeLoadException("Could not load type 'EdgeCompiler'");
}
compileMethod = compilerType.GetMethod("CompileFunc", BindingFlags.Instance | BindingFlags.Public);
if (compileMethod == null)
{
throw new Exception("Unable to find the CompileFunc() method on " + compilerType.FullName + ".");
}
MethodInfo setAssemblyLoader = compilerType.GetMethod("SetAssemblyLoader", BindingFlags.Static | BindingFlags.Public);
setAssemblyLoader?.Invoke(null, new object[]
{
new Func<Stream, Assembly>(assemblyStream => LoadContextAccessor.Default.LoadStream(assemblyStream, null))
});
Compilers[compiler] = new Tuple<Type, MethodInfo>(compilerType, compileMethod);
}
else
{
compilerType = Compilers[compiler].Item1;
compileMethod = Compilers[compiler].Item2;
}
object compilerInstance = Activator.CreateInstance(compilerType);
DebugMessage("CoreCLREmbedding::CompileFunc (CLR) - Starting compilation");
Func<object, Task<object>> compiledFunction = (Func<object, Task<object>>)compileMethod.Invoke(compilerInstance, new object[]
{
options,
LoadContextAccessor.TypedDefault.CompileAssemblies
});
DebugMessage("CoreCLREmbedding::CompileFunc (CLR) - Compilation complete");
GCHandle handle = GCHandle.Alloc(compiledFunction);
return GCHandle.ToIntPtr(handle);
}
catch (TargetInvocationException e)
{
DebugMessage("CoreCLREmbedding::CompileFunc (CLR) - Exception was thrown: {0}\n{1}", e.InnerException.Message, e.InnerException.StackTrace);
V8Type v8Type;
Marshal.WriteIntPtr(exception, MarshalCLRToV8(e, out v8Type));
return IntPtr.Zero;
}
catch (Exception e)
{
DebugMessage("CoreCLREmbedding::CompileFunc (CLR) - Exception was thrown: {0}\n{1}", e.Message, e.StackTrace);
V8Type v8Type;
Marshal.WriteIntPtr(exception, MarshalCLRToV8(e, out v8Type));
return IntPtr.Zero;
}
}
[SecurityCritical]
public static void FreeHandle(IntPtr gcHandle)
{
GCHandle actualHandle = GCHandle.FromIntPtr(gcHandle);
actualHandle.Free();
}
[SecurityCritical]
public static void CallFunc(IntPtr function, IntPtr payload, int payloadType, IntPtr taskState, IntPtr result, IntPtr resultType)
{
try
{
DebugMessage("CoreCLREmbedding::CallFunc (CLR) - Starting");
GCHandle wrapperHandle = GCHandle.FromIntPtr(function);
Func<object, Task<object>> wrapperFunc = (Func<object, Task<object>>)wrapperHandle.Target;
DebugMessage("CoreCLREmbedding::CallFunc (CLR) - Marshalling data of type {0} and calling the .NET method", ((V8Type)payloadType).ToString("G"));
Task<Object> functionTask = wrapperFunc(MarshalV8ToCLR(payload, (V8Type)payloadType));
if (functionTask.IsFaulted)
{
DebugMessage("CoreCLREmbedding::CallFunc (CLR) - .NET method ran synchronously and faulted, marshalling exception data for V8");
V8Type taskExceptionType;
Marshal.WriteInt32(taskState, (int)TaskStatus.Faulted);
Marshal.WriteIntPtr(result, MarshalCLRToV8(functionTask.Exception, out taskExceptionType));
Marshal.WriteInt32(resultType, (int)V8Type.Exception);
}
else if (functionTask.IsCompleted)
{
DebugMessage("CoreCLREmbedding::CallFunc (CLR) - .NET method ran synchronously, marshalling data for V8");
V8Type taskResultType;
IntPtr marshalData = MarshalCLRToV8(functionTask.Result, out taskResultType);
DebugMessage("CoreCLREmbedding::CallFunc (CLR) - Method return data is of type {0}", taskResultType.ToString("G"));
Marshal.WriteInt32(taskState, (int)TaskStatus.RanToCompletion);
Marshal.WriteIntPtr(result, marshalData);
Marshal.WriteInt32(resultType, (int)taskResultType);
}
else
{
DebugMessage("CoreCLREmbedding::CallFunc (CLR) - .NET method ran asynchronously, returning task handle and status");
GCHandle taskHandle = GCHandle.Alloc(functionTask);
Marshal.WriteInt32(taskState, (int)functionTask.Status);
Marshal.WriteIntPtr(result, GCHandle.ToIntPtr(taskHandle));
Marshal.WriteInt32(resultType, (int)V8Type.Task);
}
DebugMessage("CoreCLREmbedding::CallFunc (CLR) - Finished");
}
catch (Exception e)
{
DebugMessage("CoreCLREmbedding::CallFunc (CLR) - Exception was thrown: {0}", e.Message);
V8Type v8Type;
Marshal.WriteIntPtr(result, MarshalCLRToV8(e, out v8Type));
Marshal.WriteInt32(resultType, (int)v8Type);
Marshal.WriteInt32(taskState, (int)TaskStatus.Faulted);
}
}
private static void TaskCompleted(Task<object> task, object state)
{
DebugMessage("CoreCLREmbedding::TaskCompleted (CLR) - Task completed with a state of {0}", task.Status.ToString("G"));
DebugMessage("CoreCLREmbedding::TaskCompleted (CLR) - Marshalling data to return to V8", task.Status.ToString("G"));
V8Type v8Type;
TaskState actualState = (TaskState)state;
IntPtr resultObject;
TaskStatus taskStatus;
if (task.IsFaulted)
{
taskStatus = TaskStatus.Faulted;
try
{
resultObject = MarshalCLRToV8(task.Exception, out v8Type);
}
catch (Exception e)
{
taskStatus = TaskStatus.Faulted;
resultObject = MarshalCLRToV8(e, out v8Type);
}
}
else
{
taskStatus = TaskStatus.RanToCompletion;
try
{
resultObject = MarshalCLRToV8(task.Result, out v8Type);
}
catch (Exception e)
{
taskStatus = TaskStatus.Faulted;
resultObject = MarshalCLRToV8(e, out v8Type);
}
}
DebugMessage("CoreCLREmbedding::TaskCompleted (CLR) - Invoking unmanaged callback");
actualState.Callback(resultObject, (int)v8Type, (int)taskStatus, actualState.Context);
}
[SecurityCritical]
public static void ContinueTask(IntPtr task, IntPtr context, IntPtr callback, IntPtr exception)
{
try
{
Marshal.WriteIntPtr(exception, IntPtr.Zero);
DebugMessage("CoreCLREmbedding::ContinueTask (CLR) - Starting");
GCHandle taskHandle = GCHandle.FromIntPtr(task);
Task<Object> actualTask = (Task<Object>)taskHandle.Target;
TaskCompleteDelegate taskCompleteDelegate = Marshal.GetDelegateForFunctionPointer<TaskCompleteDelegate>(callback);
DebugMessage("CoreCLREmbedding::ContinueTask (CLR) - Marshalled unmanaged callback successfully");
actualTask.ContinueWith(TaskCompleted, new TaskState(taskCompleteDelegate, context));
DebugMessage("CoreCLREmbedding::ContinueTask (CLR) - Finished");
}
catch (Exception e)
{
DebugMessage("CoreCLREmbedding::ContinueTask (CLR) - Exception was thrown: {0}", e.Message);
V8Type v8Type;
Marshal.WriteIntPtr(exception, MarshalCLRToV8(e, out v8Type));
}
}
[SecurityCritical]
public static void SetCallV8FunctionDelegate(IntPtr callV8Function, IntPtr exception)
{
try
{
Marshal.WriteIntPtr(exception, IntPtr.Zero);
NodejsFuncInvokeContext.CallV8Function = Marshal.GetDelegateForFunctionPointer<CallV8FunctionDelegate>(callV8Function);
}
catch (Exception e)
{
DebugMessage("CoreCLREmbedding::SetCallV8FunctionDelegate (CLR) - Exception was thrown: {0}", e.Message);
V8Type v8Type;
Marshal.WriteIntPtr(exception, MarshalCLRToV8(e, out v8Type));
}
}
[SecurityCritical]
public static void FreeMarshalData(IntPtr marshalData, int v8Type)
{
switch ((V8Type)v8Type)
{
case V8Type.String:
case V8Type.Int32:
case V8Type.Boolean:
case V8Type.Number:
case V8Type.Date:
Marshal.FreeHGlobal(marshalData);
break;
case V8Type.Object:
case V8Type.Exception:
V8ObjectData objectData = Marshal.PtrToStructure<V8ObjectData>(marshalData);
for (int i = 0; i < objectData.propertiesCount; i++)
{
int propertyType = Marshal.ReadInt32(objectData.propertyTypes, i * sizeof(int));
IntPtr propertyValue = Marshal.ReadIntPtr(objectData.propertyValues, i * PointerSize);
IntPtr propertyName = Marshal.ReadIntPtr(objectData.propertyNames, i * PointerSize);
FreeMarshalData(propertyValue, propertyType);
Marshal.FreeHGlobal(propertyName);
}
Marshal.FreeHGlobal(objectData.propertyTypes);
Marshal.FreeHGlobal(objectData.propertyValues);
Marshal.FreeHGlobal(objectData.propertyNames);
Marshal.FreeHGlobal(marshalData);
break;
case V8Type.Array:
V8ArrayData arrayData = Marshal.PtrToStructure<V8ArrayData>(marshalData);
for (int i = 0; i < arrayData.arrayLength; i++)
{
int itemType = Marshal.ReadInt32(arrayData.itemTypes, i * sizeof(int));
IntPtr itemValue = Marshal.ReadIntPtr(arrayData.itemValues, i * PointerSize);
FreeMarshalData(itemValue, itemType);
}
Marshal.FreeHGlobal(arrayData.itemTypes);
Marshal.FreeHGlobal(arrayData.itemValues);
Marshal.FreeHGlobal(marshalData);
break;
case V8Type.Buffer:
V8BufferData bufferData = Marshal.PtrToStructure<V8BufferData>(marshalData);
Marshal.FreeHGlobal(bufferData.buffer);
Marshal.FreeHGlobal(marshalData);
break;
case V8Type.Null:
case V8Type.Function:
break;
default:
throw new Exception("Unsupported marshalled data type: " + v8Type);
}
}
// ReSharper disable once InconsistentNaming
public static IntPtr MarshalCLRToV8(object clrObject, out V8Type v8Type)
{
if (clrObject == null)
{
v8Type = V8Type.Null;
return IntPtr.Zero;
}
else if (clrObject is string)
{
v8Type = V8Type.String;
return Marshal.StringToHGlobalAnsi((string) clrObject);
}
else if (clrObject is char)
{
v8Type = V8Type.String;
return Marshal.StringToHGlobalAnsi(clrObject.ToString());
}
else if (clrObject is bool)
{
v8Type = V8Type.Boolean;
IntPtr memoryLocation = Marshal.AllocHGlobal(sizeof (int));
Marshal.WriteInt32(memoryLocation, ((bool) clrObject)
? 1
: 0);
return memoryLocation;
}
else if (clrObject is Guid)
{
v8Type = V8Type.String;
return Marshal.StringToHGlobalAnsi(clrObject.ToString());
}
else if (clrObject is DateTime)
{
v8Type = V8Type.Date;
DateTime dateTime = (DateTime) clrObject;
if (dateTime.Kind == DateTimeKind.Local)
{
dateTime = dateTime.ToUniversalTime();
}
else if (dateTime.Kind == DateTimeKind.Unspecified)
{
dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Utc);
}
long ticks = (dateTime.Ticks - MinDateTimeTicks)/10000;
IntPtr memoryLocation = Marshal.AllocHGlobal(sizeof (double));
WriteDouble(memoryLocation, ticks);
return memoryLocation;
}
else if (clrObject is DateTimeOffset)
{
v8Type = V8Type.String;
return Marshal.StringToHGlobalAnsi(clrObject.ToString());
}
else if (clrObject is Uri)
{
v8Type = V8Type.String;
return Marshal.StringToHGlobalAnsi(clrObject.ToString());
}
else if (clrObject is short)
{
v8Type = V8Type.Int32;
IntPtr memoryLocation = Marshal.AllocHGlobal(sizeof (int));
Marshal.WriteInt32(memoryLocation, Convert.ToInt32(clrObject));
return memoryLocation;
}
else if (clrObject is int)
{
v8Type = V8Type.Int32;
IntPtr memoryLocation = Marshal.AllocHGlobal(sizeof (int));
Marshal.WriteInt32(memoryLocation, (int) clrObject);
return memoryLocation;
}
else if (clrObject is long)
{
v8Type = V8Type.Number;
IntPtr memoryLocation = Marshal.AllocHGlobal(sizeof (double));
WriteDouble(memoryLocation, Convert.ToDouble((long) clrObject));
return memoryLocation;
}
else if (clrObject is double)
{
v8Type = V8Type.Number;
IntPtr memoryLocation = Marshal.AllocHGlobal(sizeof (double));
WriteDouble(memoryLocation, (double) clrObject);
return memoryLocation;
}
else if (clrObject is float)
{
v8Type = V8Type.Number;
IntPtr memoryLocation = Marshal.AllocHGlobal(sizeof (double));
WriteDouble(memoryLocation, Convert.ToDouble((Single) clrObject));
return memoryLocation;
}
else if (clrObject is decimal)
{
v8Type = V8Type.String;
return Marshal.StringToHGlobalAnsi(clrObject.ToString());
}
else if (clrObject is Enum)
{
v8Type = V8Type.String;
return Marshal.StringToHGlobalAnsi(clrObject.ToString());
}
else if (clrObject is byte[] || clrObject is IEnumerable<byte>)
{
v8Type = V8Type.Buffer;
V8BufferData bufferData = new V8BufferData();
byte[] buffer;
if (clrObject is byte[])
{
buffer = (byte[]) clrObject;
}
else
{
buffer = ((IEnumerable<byte>) clrObject).ToArray();
}
bufferData.bufferLength = buffer.Length;
bufferData.buffer = Marshal.AllocHGlobal(buffer.Length*sizeof (byte));
Marshal.Copy(buffer, 0, bufferData.buffer, bufferData.bufferLength);
IntPtr destinationPointer = Marshal.AllocHGlobal(V8BufferDataSize);
Marshal.StructureToPtr(bufferData, destinationPointer, false);
return destinationPointer;
}
else if (clrObject is IDictionary || clrObject is ExpandoObject)
{
v8Type = V8Type.Object;
IEnumerable keys;
int keyCount;
Func<object, object> getValue;
if (clrObject is ExpandoObject)
{
IDictionary<string, object> objectDictionary = (IDictionary<string, object>) clrObject;
keys = objectDictionary.Keys;
keyCount = objectDictionary.Keys.Count;
getValue = index => objectDictionary[index.ToString()];
}
else
{
IDictionary objectDictionary = (IDictionary) clrObject;
keys = objectDictionary.Keys;
keyCount = objectDictionary.Keys.Count;
getValue = index => objectDictionary[index];
}
V8ObjectData objectData = new V8ObjectData();
int counter = 0;
objectData.propertiesCount = keyCount;
objectData.propertyNames = Marshal.AllocHGlobal(PointerSize*keyCount);
objectData.propertyTypes = Marshal.AllocHGlobal(sizeof (int)*keyCount);
objectData.propertyValues = Marshal.AllocHGlobal(PointerSize*keyCount);
foreach (object key in keys)
{
Marshal.WriteIntPtr(objectData.propertyNames, counter*PointerSize, Marshal.StringToHGlobalAnsi(key.ToString()));
V8Type propertyType;
Marshal.WriteIntPtr(objectData.propertyValues, counter*PointerSize, MarshalCLRToV8(getValue(key), out propertyType));
Marshal.WriteInt32(objectData.propertyTypes, counter*sizeof (int), (int) propertyType);
counter++;
}
IntPtr destinationPointer = Marshal.AllocHGlobal(V8ObjectDataSize);
Marshal.StructureToPtr(objectData, destinationPointer, false);
return destinationPointer;
}
else if (clrObject is IEnumerable)
{
v8Type = V8Type.Array;
V8ArrayData arrayData = new V8ArrayData();
List<IntPtr> itemValues = new List<IntPtr>();
List<int> itemTypes = new List<int>();
foreach (object item in (IEnumerable) clrObject)
{
V8Type itemType;
itemValues.Add(MarshalCLRToV8(item, out itemType));
itemTypes.Add((int) itemType);
}
arrayData.arrayLength = itemValues.Count;
arrayData.itemTypes = Marshal.AllocHGlobal(sizeof (int)*arrayData.arrayLength);
arrayData.itemValues = Marshal.AllocHGlobal(PointerSize*arrayData.arrayLength);
Marshal.Copy(itemTypes.ToArray(), 0, arrayData.itemTypes, arrayData.arrayLength);
Marshal.Copy(itemValues.ToArray(), 0, arrayData.itemValues, arrayData.arrayLength);
IntPtr destinationPointer = Marshal.AllocHGlobal(V8ArrayDataSize);
Marshal.StructureToPtr(arrayData, destinationPointer, false);
return destinationPointer;
}
else if (clrObject.GetType().GetTypeInfo().IsGenericType && clrObject.GetType().GetGenericTypeDefinition() == typeof (Func<,>))
{
Func<object, Task<object>> funcObject = clrObject as Func<object, Task<object>>;
if (funcObject == null)
{
throw new Exception("Properties that return Func<> instances must return Func<object, Task<object>> instances");
}
v8Type = V8Type.Function;
return GCHandle.ToIntPtr(GCHandle.Alloc(funcObject));
}
else
{
v8Type = clrObject is Exception
? V8Type.Exception
: V8Type.Object;
if (clrObject is Exception)
{
AggregateException aggregateException = clrObject as AggregateException;
if (aggregateException?.InnerExceptions != null && aggregateException.InnerExceptions.Count > 0)
{
clrObject = aggregateException.InnerExceptions[0];
}
else
{
TargetInvocationException targetInvocationException = clrObject as TargetInvocationException;
if (targetInvocationException?.InnerException != null)
{
clrObject = targetInvocationException.InnerException;
}
}
}
List<Tuple<string, Func<object, object>>> propertyAccessors = GetPropertyAccessors(clrObject.GetType());
V8ObjectData objectData = new V8ObjectData();
int counter = 0;
objectData.propertiesCount = propertyAccessors.Count;
objectData.propertyNames = Marshal.AllocHGlobal(PointerSize*propertyAccessors.Count);
objectData.propertyTypes = Marshal.AllocHGlobal(sizeof (int)*propertyAccessors.Count);
objectData.propertyValues = Marshal.AllocHGlobal(PointerSize*propertyAccessors.Count);
foreach (Tuple<string, Func<object, object>> propertyAccessor in propertyAccessors)
{
Marshal.WriteIntPtr(objectData.propertyNames, counter*PointerSize, Marshal.StringToHGlobalAnsi(propertyAccessor.Item1));
V8Type propertyType;
Marshal.WriteIntPtr(objectData.propertyValues, counter*PointerSize, MarshalCLRToV8(propertyAccessor.Item2(clrObject), out propertyType));
Marshal.WriteInt32(objectData.propertyTypes, counter*sizeof (int), (int) propertyType);
counter++;
}
IntPtr destinationPointer = Marshal.AllocHGlobal(V8ObjectDataSize);
Marshal.StructureToPtr(objectData, destinationPointer, false);
return destinationPointer;
}
}
public static object MarshalV8ToCLR(IntPtr v8Object, V8Type objectType)
{
switch (objectType)
{
case V8Type.String:
return Marshal.PtrToStringAnsi(v8Object);
case V8Type.Object:
return V8ObjectToExpando(Marshal.PtrToStructure<V8ObjectData>(v8Object));
case V8Type.Boolean:
return Marshal.ReadByte(v8Object) != 0;
case V8Type.Number:
return ReadDouble(v8Object);
case V8Type.Date:
double ticks = ReadDouble(v8Object);
return new DateTime(Convert.ToInt64(ticks) * 10000 + MinDateTimeTicks, DateTimeKind.Utc);
case V8Type.Null:
return null;
case V8Type.Int32:
return Marshal.ReadInt32(v8Object);
case V8Type.UInt32:
return (uint)Marshal.ReadInt32(v8Object);
case V8Type.Function:
NodejsFunc nodejsFunc = new NodejsFunc(v8Object);
return nodejsFunc.GetFunc();
case V8Type.Array:
V8ArrayData arrayData = Marshal.PtrToStructure<V8ArrayData>(v8Object);
object[] array = new object[arrayData.arrayLength];
for (int i = 0; i < arrayData.arrayLength; i++)
{
int itemType = Marshal.ReadInt32(arrayData.itemTypes, i * sizeof(int));
IntPtr itemValuePointer = Marshal.ReadIntPtr(arrayData.itemValues, i * PointerSize);
array[i] = MarshalV8ToCLR(itemValuePointer, (V8Type)itemType);
}
return array;
case V8Type.Buffer:
V8BufferData bufferData = Marshal.PtrToStructure<V8BufferData>(v8Object);
byte[] buffer = new byte[bufferData.bufferLength];
Marshal.Copy(bufferData.buffer, buffer, 0, bufferData.bufferLength);
return buffer;
case V8Type.Exception:
string message = Marshal.PtrToStringAnsi(v8Object);
return new Exception(message);
default:
throw new Exception("Unsupported V8 object type: " + objectType + ".");
}
}
private static unsafe void WriteDouble(IntPtr pointer, double value)
{
try
{
byte* address = (byte*)pointer;
if ((unchecked((int)address) & 0x7) == 0)
{
*((double*)address) = value;
}
else
{
byte* valuePointer = (byte*)&value;
address[0] = valuePointer[0];
address[1] = valuePointer[1];
address[2] = valuePointer[2];
address[3] = valuePointer[3];
address[4] = valuePointer[4];
address[5] = valuePointer[5];
address[6] = valuePointer[6];
address[7] = valuePointer[7];
}
}
catch (NullReferenceException)
{
throw new Exception("Access violation.");
}
}
private static unsafe double ReadDouble(IntPtr pointer)
{
try
{
byte* address = (byte*)pointer;
if ((unchecked((int)address) & 0x7) == 0)
{
return *((double*)address);
}
else
{
double value;
byte* valuePointer = (byte*)&value;
valuePointer[0] = address[0];
valuePointer[1] = address[1];
valuePointer[2] = address[2];
valuePointer[3] = address[3];
valuePointer[4] = address[4];
valuePointer[5] = address[5];
valuePointer[6] = address[6];
valuePointer[7] = address[7];
return value;
}
}
catch (NullReferenceException)
{
throw new Exception("Access violation.");
}
}
private static ExpandoObject V8ObjectToExpando(V8ObjectData v8Object)
{
ExpandoObject expando = new ExpandoObject();
IDictionary<string, object> expandoDictionary = expando;
for (int i = 0; i < v8Object.propertiesCount; i++)
{
int propertyType = Marshal.ReadInt32(v8Object.propertyTypes, i * sizeof(int));
IntPtr propertyNamePointer = Marshal.ReadIntPtr(v8Object.propertyNames, i * PointerSize);
string propertyName = Marshal.PtrToStringAnsi(propertyNamePointer);
IntPtr propertyValuePointer = Marshal.ReadIntPtr(v8Object.propertyValues, i * PointerSize);
expandoDictionary.Add(propertyName, MarshalV8ToCLR(propertyValuePointer, (V8Type)propertyType));
}
return expando;
}
[Conditional("DEBUG")]
internal static void DebugMessage(string message, params object[] parameters)
{
if (DebugMode)
{
Console.WriteLine(message, parameters);
}
}
private static List<Tuple<string, Func<object, object>>> GetPropertyAccessors(Type type)
{
if (TypePropertyAccessors.ContainsKey(type))
{
return TypePropertyAccessors[type];
}
List<Tuple<string, Func<object, object>>> propertyAccessors = new List<Tuple<string, Func<object, object>>>();
foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
ParameterExpression instance = Expression.Parameter(typeof(object));
UnaryExpression instanceConvert = Expression.TypeAs(instance, type);
MemberExpression property = Expression.Property(instanceConvert, propertyInfo);
UnaryExpression propertyConvert = Expression.TypeAs(property, typeof(object));
propertyAccessors.Add(new Tuple<string, Func<object, object>>(propertyInfo.Name, (Func<object, object>)Expression.Lambda(propertyConvert, instance).Compile()));
}
foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
ParameterExpression instance = Expression.Parameter(typeof(object));
UnaryExpression instanceConvert = Expression.TypeAs(instance, type);
MemberExpression field = Expression.Field(instanceConvert, fieldInfo);
UnaryExpression fieldConvert = Expression.TypeAs(field, typeof(object));
propertyAccessors.Add(new Tuple<string, Func<object, object>>(fieldInfo.Name, (Func<object, object>)Expression.Lambda(fieldConvert, instance).Compile()));
}
if (typeof(Exception).IsAssignableFrom(type) && !propertyAccessors.Any(a => a.Item1 == "Name"))
{
propertyAccessors.Add(new Tuple<string, Func<object, object>>("Name", o => type.FullName));
}
TypePropertyAccessors[type] = propertyAccessors;
return propertyAccessors;
}
}
| |
using System.Collections.Generic;
using Raccoon.Util;
namespace Raccoon {
public static class SAT {
#region Public Methods
/// <summary>
/// Tests a Polygon with another Polygon with explicit axes.
/// </summary>
/// <param name="A">First element in the test.</param>
/// <param name="B">Second element in the test.</param>
/// <param name="axes">Separating axes to use when testing.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(Polygon A, Polygon B, IEnumerable<Vector2> axes, out Contact? contact) {
if (A.IsConvex) {
if (B.IsConvex) {
return TestConvexPolygons(A, B, axes, out contact);
}
return TestConvexPolygonWithConcavePolygon(A, B, axes, out contact);
}
if (B.IsConvex) {
return TestConvexPolygonWithConcavePolygon(B, A, axes, out contact);
}
return TestConcavePolygons(A, B, axes, out contact);
}
/// <summary>
/// Tests a Polygon with another Polygon without explicit axes.
/// The axes will be infered by the Polygons faces normals.
/// </summary>
/// <param name="A">First element in the test.</param>
/// <param name="B">Second element in the test.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(Polygon A, Polygon B, out Contact? contact) {
if (A.IsConvex) {
if (B.IsConvex) {
return TestConvexPolygons(A, B, out contact);
}
return TestConvexPolygonWithConcavePolygon(A, B, out contact);
}
if (B.IsConvex) {
return TestConvexPolygonWithConcavePolygon(B, A, out contact);
}
return TestConcavePolygons(A, B, out contact);
}
/// <summary>
/// Tests a IShape with another IShape with explicit axes.
/// </summary>
/// <param name="shapeA">First IShape in the test.</param>
/// <param name="posA">First IShape position.</param>
/// <param name="shapeB">Second IShape in the test.</param>
/// <param name="posB">Second IShape position.</param>
/// <param name="axes">Separating axes to use when testing.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(IShape shapeA, Vector2 posA, IShape shapeB, Vector2 posB, ICollection<Vector2> axes, out Contact? contact) {
Polygon polygonA = null,
polygonB = null;
if (shapeA is PolygonShape polygonShapeA) {
polygonA = new Polygon(polygonShapeA.Shape);
polygonA.Translate(posA);
}
if (shapeB is PolygonShape polygonShapeB) {
polygonB = new Polygon(polygonShapeB.Shape);
polygonB.Translate(posB);
}
if (polygonA != null) {
if (polygonB != null) {
if (polygonA.IsConvex) {
if (polygonB.IsConvex) {
return TestConvexPolygons(polygonA, polygonB, axes, out contact);
}
return TestConvexPolygonWithConcavePolygon(polygonA, polygonB, axes, out contact);
}
if (polygonB.IsConvex) {
return TestConvexPolygonWithConcavePolygon(polygonB, polygonA, axes, out contact);
}
return TestConcavePolygons(polygonA, polygonB, axes, out contact);
}
if (polygonA.IsConvex) {
return TestIShapeWithConvexPolygon(shapeB, posB, polygonA, axes, out contact);
}
return TestIShapeWithConcavePolygon(shapeB, posB, polygonA, axes, out contact);
} else if (polygonB != null) {
if (polygonB.IsConvex) {
return TestIShapeWithConvexPolygon(shapeA, posA, polygonB, axes, out contact);
}
return TestIShapeWithConcavePolygon(shapeA, posA, polygonB, axes, out contact);
}
return TestIShapeWithIShape(shapeA, posA, shapeB, posB, axes, out contact);
}
/// <summary>
/// Tests a IShape with another IShape without explicit axes.
/// The axes will be infered by IShapes normals only.
/// </summary>
/// <param name="shapeA">First IShape in the test.</param>
/// <param name="posA">First IShape position.</param>
/// <param name="shapeB">Second IShape in the test.</param>
/// <param name="posB">Second IShape position.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(IShape shapeA, Vector2 posA, IShape shapeB, Vector2 posB, out Contact? contact) {
Polygon polygonA = null,
polygonB = null;
if (shapeA is PolygonShape polygonShapeA) {
polygonA = new Polygon(polygonShapeA.Shape);
polygonA.Translate(posA);
}
if (shapeB is PolygonShape polygonShapeB) {
polygonB = new Polygon(polygonShapeB.Shape);
polygonB.Translate(posB);
}
if (polygonA != null) {
if (polygonB != null) {
if (polygonA.IsConvex) {
if (polygonB.IsConvex) {
return TestConvexPolygons(polygonA, polygonB, out contact);
}
return TestConvexPolygonWithConcavePolygon(polygonA, polygonB, out contact);
}
if (polygonB.IsConvex) {
return TestConvexPolygonWithConcavePolygon(polygonB, polygonA, out contact);
}
return TestConcavePolygons(polygonA, polygonB, out contact);
}
if (polygonA.IsConvex) {
return TestIShapeWithConvexPolygon(shapeB, posB, polygonA, out contact);
}
return TestIShapeWithConcavePolygon(shapeB, posB, polygonA, out contact);
} else if (polygonB != null) {
if (polygonB.IsConvex) {
return TestIShapeWithConvexPolygon(shapeA, posA, polygonB, out contact);
}
return TestIShapeWithConcavePolygon(shapeA, posA, polygonB, out contact);
}
return TestIShapeWithIShape(shapeA, posA, shapeB, posB, out contact);
}
/// <summary>
/// Tests IShape with a Polygon with explicit axes.
/// </summary>
/// <param name="shape">First element in the test.</param>
/// <param name="shapePos">IShape position.</param>
/// <param name="polygon">Second element in the test.</param>
/// <param name="axes">Separating axes to use when testing.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(IShape shape, Vector2 shapePos, Polygon polygon, ICollection<Vector2> axes, out Contact? contact) {
if (polygon.IsConvex) {
return TestIShapeWithConvexPolygon(shape, shapePos, polygon, axes, out contact);
}
return TestIShapeWithConcavePolygon(shape, shapePos, polygon, axes, out contact);
}
/// <summary>
/// Tests IShape with a Polygon without explicit axes.
/// The axes will be infered by Polygon face normals only.
/// </summary>
/// <param name="shape">First element in the test.</param>
/// <param name="shapePos">IShape position.</param>
/// <param name="polygon">Second element in the test.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(IShape shape, Vector2 shapePos, Polygon polygon, out Contact? contact) {
if (polygon.IsConvex) {
return TestIShapeWithConvexPolygon(shape, shapePos, polygon, out contact);
}
return TestIShapeWithConcavePolygon(shape, shapePos, polygon, out contact);
}
/// <summary>
/// Tests a line segment with a IShape with explicit axes.
/// </summary>
/// <param name="startPoint">Start point at line segment.</param>
/// <param name="endPoint">End point at line segment.</param>
/// <param name="shape">IShape element to test.</param>
/// <param name="shapePos">IShape position.</param>
/// <param name="axes">Separating axes to use when testing.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(Vector2 startPoint, Vector2 endPoint, IShape shape, Vector2 shapePos, IEnumerable<Vector2> axes, out Contact? contact) {
if (shape is PolygonShape polygonShape) {
Polygon polygon = new Polygon(polygonShape.Shape);
polygon.Translate(shapePos);
if (polygon.IsConvex) {
return TestLineSegmentWithConvexPolygon(startPoint, endPoint, polygon, axes, out contact);
}
return TestLineSegmentWithConcavePolygon(startPoint, endPoint, polygon, axes, out contact);
}
return TestLineSegmentWithIShape(startPoint, endPoint, shape, shapePos, axes, out contact);
}
///
/// <summary>
/// Tests a line segment with a IShape without explicit axes.
/// The axes will be infered by the IShape normals and line segment direction and perpendicular.
/// </summary>
/// <param name="startPoint">Start point at line segment.</param>
/// <param name="endPoint">End point at line segment.</param>
/// <param name="shape">IShape element to test.</param>
/// <param name="shapePos">IShape position.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(Vector2 startPoint, Vector2 endPoint, IShape shape, Vector2 shapePos, out Contact? contact) {
if (shape is PolygonShape polygonShape) {
Polygon polygon = new Polygon(polygonShape.Shape);
polygon.Translate(shapePos);
if (polygon.IsConvex) {
return TestLineSegmentWithConvexPolygon(startPoint, endPoint, polygon, out contact);
}
return TestLineSegmentWithConcavePolygon(startPoint, endPoint, polygon, out contact);
}
return TestLineSegmentWithIShape(startPoint, endPoint, shape, shapePos, out contact);
}
/// <summary>
/// Tests a line segment with a Polygon with explicit axes.
/// </summary>
/// <param name="startPoint">Start point at line segment.</param>
/// <param name="endPoint">End point at line segment.</param>
/// <param name="polygon">Polygon to test.</param>
/// <param name="axes">Separating axes to use when testing.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(Vector2 startPoint, Vector2 endPoint, Polygon polygon, IEnumerable<Vector2> axes, out Contact? contact) {
if (polygon.IsConvex) {
return TestLineSegmentWithConvexPolygon(startPoint, endPoint, polygon, axes, out contact);
}
return TestLineSegmentWithConcavePolygon(startPoint, endPoint, polygon, axes, out contact);
}
/// <summary>
/// Tests a line segment with a Polygon without explicit axes.
/// The axes will be infered by the Polygon face normals and line segment direction and perpendicular.
/// </summary>
/// <param name="startPoint">Start point at line segment.</param>
/// <param name="endPoint">End point at line segment.</param>
/// <param name="polygon">Polygon to test.</param>
/// <param name="contact">Contact info about the test, Null otherwise.</param>
/// <returns>True if they're intersecting, False otherwise.</returns>
public static bool Test(Vector2 startPoint, Vector2 endPoint, Polygon polygon, out Contact? contact) {
if (polygon.IsConvex) {
return TestLineSegmentWithConvexPolygon(startPoint, endPoint, polygon, out contact);
}
return TestLineSegmentWithConcavePolygon(startPoint, endPoint, polygon, out contact);
}
#endregion Public Methods
#region Private Methods
#region Polygon with Polygon
private static bool TestConvexPolygons(Polygon A, Polygon B, IEnumerable<Vector2> axes, out Contact? contact) {
Contact leastPenetrationContact = new Contact {
Position = A[0],
PenetrationDepth = float.PositiveInfinity
};
foreach (Vector2 axis in axes) {
Range projectionA = A.Projection(axis),
projectionB = B.Projection(axis);
if (!projectionA.Overlaps(projectionB, out float penetrationDepth)) {
contact = null;
return false;
}
if (penetrationDepth < leastPenetrationContact.PenetrationDepth) {
leastPenetrationContact.PenetrationDepth = penetrationDepth;
leastPenetrationContact.Normal = projectionA.Min > projectionB.Min ? -axis : axis;
}
}
// contact points
(Vector2 MaxProjVertex, Line Edge) edgeA = FindBestEdge(A, leastPenetrationContact.Normal);
(Vector2 MaxProjVertex, Line Edge) edgeB = FindBestEdge(B, -leastPenetrationContact.Normal);
Vector2[] contactPoints = CalculateContactPoints(edgeA, edgeB, leastPenetrationContact.Normal);
if (contactPoints.Length > 0) {
leastPenetrationContact.Position = contactPoints[0];
}
contact = leastPenetrationContact;
return true;
}
private static bool TestConvexPolygons(Polygon A, Polygon B, out Contact? contact) {
Vector2[] axes = new Vector2[A.Normals.Length + B.Normals.Length/* + 1*/];
/*
axes[0] = (B.Center - A.Center).Normalized();
int i = 1;
*/
int i = 0;
// polygon A axes
foreach (Vector2 normal in A.Normals) {
axes[i] = normal;
i++;
}
// polygon B axes
foreach (Vector2 normal in B.Normals) {
axes[i] = normal;
i++;
}
return TestConvexPolygons(A, B, axes, out contact);
}
private static bool TestConcavePolygons(Polygon A, Polygon B, IEnumerable<Vector2> axes, out Contact? contact) {
List<Vector2[]> componentsA = A.ConvexComponents(),
componentsB = B.ConvexComponents();
Vector2 polyAAnchor = A[0],
polyBAnchor = B[0];
foreach (Vector2[] componentA in componentsA) {
Polygon componentPolyA = new Polygon(componentA);
componentPolyA.Translate(polyAAnchor);
foreach (Vector2[] componentB in componentsB) {
Polygon componentPolyB = new Polygon(componentB);
componentPolyB.Translate(polyBAnchor);
if (TestConvexPolygons(componentPolyA, componentPolyB, axes, out contact)) {
return true;
}
}
}
contact = null;
return false;
}
private static bool TestConcavePolygons(Polygon A, Polygon B, out Contact? contact) {
List<Vector2[]> componentsA = A.ConvexComponents(),
componentsB = B.ConvexComponents();
Vector2 polyAAnchor = A[0],
polyBAnchor = B[0];
Vector2[] axes;
int i;
foreach (Vector2[] componentA in componentsA) {
Polygon componentPolyA = new Polygon(componentA);
componentPolyA.Translate(polyAAnchor);
foreach (Vector2[] componentB in componentsB) {
Polygon componentPolyB = new Polygon(componentB);
componentPolyB.Translate(polyBAnchor);
axes = new Vector2[componentPolyA.Normals.Length + componentPolyB.Normals.Length];
i = 0;
// component polygon A axes
foreach (Vector2 normal in componentPolyA.Normals) {
axes[i] = normal;
i++;
}
// component polygon B axes
foreach (Vector2 normal in componentPolyB.Normals) {
axes[i] = normal;
i++;
}
if (TestConvexPolygons(componentPolyA, componentPolyB, axes, out contact)) {
return true;
}
}
}
contact = null;
return false;
}
private static bool TestConvexPolygonWithConcavePolygon(Polygon convexPolygon, Polygon concavePolygon, IEnumerable<Vector2> axes, out Contact? contact) {
List<Vector2[]> concavePolygonComponents = concavePolygon.ConvexComponents();
Vector2 concavePolygonAnchor = concavePolygon[0];
foreach (Vector2[] component in concavePolygonComponents) {
Polygon componentPolygon = new Polygon(component);
componentPolygon.Translate(concavePolygonAnchor);
if (TestConvexPolygons(convexPolygon, componentPolygon, axes, out contact)) {
return true;
}
}
contact = null;
return false;
}
private static bool TestConvexPolygonWithConcavePolygon(Polygon convexPolygon, Polygon concavePolygon, out Contact? contact) {
List<Vector2[]> concavePolygonComponents = concavePolygon.ConvexComponents();
Vector2 concavePolygonAnchor = concavePolygon[0];
Vector2[] axes;
int i;
foreach (Vector2[] component in concavePolygonComponents) {
Polygon componentPolygon = new Polygon(component);
componentPolygon.Translate(concavePolygonAnchor);
axes = new Vector2[componentPolygon.Normals.Length + convexPolygon.Normals.Length];
i = 0;
// component polygon A axes
foreach (Vector2 normal in convexPolygon.Normals) {
axes[i] = normal;
i++;
}
// component polygon B axes
foreach (Vector2 normal in componentPolygon.Normals) {
axes[i] = normal;
i++;
}
if (TestConvexPolygons(convexPolygon, componentPolygon, axes, out contact)) {
return true;
}
}
contact = null;
return false;
}
#endregion Polygon with Polygon
#region IShape with Polygon
public static bool TestIShapeWithConvexPolygon(IShape shape, Vector2 shapePos, Polygon polygon, ICollection<Vector2> axes, out Contact? contact) {
Debug.Assert(!(shape is PolygonShape), "TestIShapeWithConvexPolygon can't handle PolygonShape correctly. Please use another polygon specific variant.");
Contact leastPenetrationContact = new Contact {
Position = shapePos,
PenetrationDepth = float.PositiveInfinity
};
foreach (Vector2 axis in axes) {
Range projectionA = shape.Projection(shapePos, axis),
projectionB = polygon.Projection(axis);
if (!projectionA.Overlaps(projectionB, out float penetrationDepth)) {
contact = null;
return false;
}
if (penetrationDepth < leastPenetrationContact.PenetrationDepth) {
leastPenetrationContact.PenetrationDepth = penetrationDepth;
leastPenetrationContact.Normal = projectionA.Min > projectionB.Min ? -axis : axis;
}
}
// contact points
(Vector2 MaxProjVertex, Line Edge) edgeA = shape.FindBestClippingEdge(shapePos, leastPenetrationContact.Normal);
(Vector2 MaxProjVertex, Line Edge) edgeB = FindBestEdge(polygon, -leastPenetrationContact.Normal);
if (edgeA.Edge.PointA != edgeA.Edge.PointB) {
Vector2[] contactPoints = CalculateContactPoints(edgeA, edgeB, leastPenetrationContact.Normal);
if (contactPoints.Length > 0) {
leastPenetrationContact.Position = contactPoints[0];
}
}
contact = leastPenetrationContact;
return true;
}
public static bool TestIShapeWithConvexPolygon(IShape shape, Vector2 shapePos, Polygon polygon, out Contact? contact) {
Vector2[] shapeAxes = shape.CalculateAxes();
Vector2[] axes = new Vector2[shapeAxes.Length + polygon.Normals.Length];
shapeAxes.CopyTo(axes, 0);
polygon.Normals.CopyTo(axes, shapeAxes.Length);
return TestIShapeWithConvexPolygon(shape, shapePos, polygon, polygon.Normals, out contact);
}
public static bool TestIShapeWithConcavePolygon(IShape shape, Vector2 shapePos, Polygon concavePolygon, ICollection<Vector2> axes, out Contact? contact) {
List<Vector2[]> concavePolygonComponents = concavePolygon.ConvexComponents();
Vector2 concavePolygonAnchor = concavePolygon[0];
foreach (Vector2[] component in concavePolygonComponents) {
Polygon componentPolygon = new Polygon(component);
componentPolygon.Translate(concavePolygonAnchor);
if (TestIShapeWithConvexPolygon(shape, shapePos, componentPolygon, axes, out contact)) {
return true;
}
}
contact = null;
return false;
}
public static bool TestIShapeWithConcavePolygon(IShape shape, Vector2 shapePos, Polygon concavePolygon, out Contact? contact) {
List<Vector2[]> concavePolygonComponents = concavePolygon.ConvexComponents();
Vector2 concavePolygonAnchor = concavePolygon[0];
Vector2[] shapeAxes = shape.CalculateAxes();
Vector2[] axes;
foreach (Vector2[] component in concavePolygonComponents) {
Polygon componentPolygon = new Polygon(component);
componentPolygon.Translate(concavePolygonAnchor);
axes = new Vector2[shapeAxes.Length + componentPolygon.Normals.Length];
shapeAxes.CopyTo(axes, 0);
componentPolygon.Normals.CopyTo(axes, shapeAxes.Length);
if (TestIShapeWithConvexPolygon(shape, shapePos, componentPolygon, axes, out contact)) {
return true;
}
}
contact = null;
return false;
}
#endregion IShape with Polygon
#region IShape with IShape
public static bool TestIShapeWithIShape(IShape shapeA, Vector2 posA, IShape shapeB, Vector2 posB, ICollection<Vector2> axes, out Contact? contact) {
Debug.Assert(!(shapeA is PolygonShape), "TestIShapeWithIShape can't handle PolygonShape correctly. Please use another polygon specific variant.");
Debug.Assert(!(shapeB is PolygonShape), "TestIShapeWithIShape can't handle PolygonShape correctly. Please use another polygon specific variant.");
Contact leastPenetrationContact = new Contact {
Position = posA,
PenetrationDepth = float.PositiveInfinity
};
foreach (Vector2 axis in axes) {
Range projectionA = shapeA.Projection(posA, axis),
projectionB = shapeB.Projection(posB, axis);
if (!projectionA.Overlaps(projectionB, out float penetrationDepth)) {
contact = null;
return false;
}
if (penetrationDepth < leastPenetrationContact.PenetrationDepth) {
leastPenetrationContact.PenetrationDepth = penetrationDepth;
leastPenetrationContact.Normal = projectionA.Min > projectionB.Min ? -axis : axis;
}
}
// contact points
(Vector2 MaxProjVertex, Line Edge) edgeA = shapeA.FindBestClippingEdge(posA, leastPenetrationContact.Normal);
(Vector2 MaxProjVertex, Line Edge) edgeB = shapeB.FindBestClippingEdge(posB, -leastPenetrationContact.Normal);
if (!(edgeA.Edge.PointA == edgeA.Edge.PointB || edgeB.Edge.PointA == edgeA.Edge.PointB)) {
Vector2[] contactPoints = CalculateContactPoints(edgeA, edgeB, leastPenetrationContact.Normal);
if (contactPoints.Length > 0) {
leastPenetrationContact.Position = contactPoints[0];
}
}
contact = leastPenetrationContact;
return true;
}
public static bool TestIShapeWithIShape(IShape shapeA, Vector2 posA, IShape shapeB, Vector2 posB, out Contact? contact) {
Vector2[] shapeAAxes = shapeA.CalculateAxes(),
shapeBAxes = shapeB.CalculateAxes();
Vector2[] axes = new Vector2[shapeAAxes.Length + shapeBAxes.Length];
shapeAAxes.CopyTo(axes, 0);
shapeBAxes.CopyTo(axes, shapeAAxes.Length);
return TestIShapeWithIShape(shapeA, posA, shapeB, posB, axes, out contact);
}
#endregion IShape with IShape
#region Line Segment with Polygon
public static bool TestLineSegmentWithConvexPolygon(Vector2 startPoint, Vector2 endPoint, Polygon polygon, IEnumerable<Vector2> axes, out Contact? contact) {
Vector2[] intersections = polygon.Intersects(new Line(startPoint, endPoint));
// no intersections, no contact
if (intersections.Length == 0) {
contact = null;
return false;
}
Contact leastPenetrationContact = new Contact {
Position = intersections[0],
PenetrationDepth = float.PositiveInfinity
};
// calculate line-segment first contact point position
float closestIntersectionDist = Math.DistanceSquared(startPoint, intersections[0]);
for (int i = 1; i < intersections.Length; i++) {
float d = Math.DistanceSquared(startPoint, intersections[i]);
if (d < closestIntersectionDist) {
leastPenetrationContact.Position = intersections[i];
closestIntersectionDist = d;
}
}
foreach (Vector2 axis in axes) {
Range projectionA = axis.Projection(startPoint, endPoint),
projectionB = polygon.Projection(axis);
if (!projectionA.Overlaps(projectionB, out float penetrationDepth)) {
contact = null;
return false;
}
if (penetrationDepth < leastPenetrationContact.PenetrationDepth) {
leastPenetrationContact.PenetrationDepth = penetrationDepth;
leastPenetrationContact.Normal = projectionA.Min > projectionB.Min ? -axis : axis;
}
}
contact = leastPenetrationContact;
return true;
}
public static bool TestLineSegmentWithConvexPolygon(Vector2 startPoint, Vector2 endPoint, Polygon polygon, out Contact? contact) {
Vector2[] axes = new Vector2[2 + polygon.Normals.Length];
Vector2 direction = (endPoint - startPoint).Normalized();
axes[0] = direction;
axes[1] = direction.PerpendicularCW();
polygon.Normals.CopyTo(axes, 2);
return TestLineSegmentWithConvexPolygon(startPoint, endPoint, polygon, axes, out contact);
}
public static bool TestLineSegmentWithConcavePolygon(Vector2 startPoint, Vector2 endPoint, Polygon concavePolygon, IEnumerable<Vector2> axes, out Contact? contact) {
List<Vector2[]> concavePolygonComponents = concavePolygon.ConvexComponents();
Vector2 concavePolygonAnchor = concavePolygon[0];
foreach (Vector2[] component in concavePolygonComponents) {
Polygon componentPolygon = new Polygon(component);
componentPolygon.Translate(concavePolygonAnchor);
if (TestLineSegmentWithConvexPolygon(startPoint, endPoint, componentPolygon, axes, out contact)) {
return true;
}
}
contact = null;
return false;
}
public static bool TestLineSegmentWithConcavePolygon(Vector2 startPoint, Vector2 endPoint, Polygon concavePolygon, out Contact? contact) {
List<Vector2[]> concavePolygonComponents = concavePolygon.ConvexComponents();
Vector2 concavePolygonAnchor = concavePolygon[0];
Vector2 direction = (endPoint - startPoint).Normalized();
Vector2[] axes;
int i;
foreach (Vector2[] component in concavePolygonComponents) {
Polygon componentPolygon = new Polygon(component);
componentPolygon.Translate(concavePolygonAnchor);
axes = new Vector2[2 + componentPolygon.Normals.Length];
axes[0] = direction;
axes[1] = direction.PerpendicularCW();
i = 2;
// component polygon A axes
foreach (Vector2 normal in componentPolygon.Normals) {
axes[i] = normal;
i++;
}
if (TestLineSegmentWithConvexPolygon(startPoint, endPoint, componentPolygon, axes, out contact)) {
return true;
}
}
contact = null;
return false;
}
#endregion Line Segment with Polygon
#region Line Segment with IShape
public static bool TestLineSegmentWithIShape(Vector2 startPoint, Vector2 endPoint, IShape shape, Vector2 shapePos, IEnumerable<Vector2> axes, out Contact? contact) {
Debug.Assert(!(shape is PolygonShape), "TestILineSegmentWithIShape can't handle PolygonShape correctly. Please use another polygon specific variant.");
Contact leastPenetrationContact = new Contact {
Position = shapePos,
PenetrationDepth = float.PositiveInfinity
};
foreach (Vector2 axis in axes) {
Range projectionA = axis.Projection(startPoint, endPoint), projectionB = shape.Projection(shapePos, axis);
if (!projectionA.Overlaps(projectionB, out float penetrationDepth)) {
contact = null;
return false;
}
if (penetrationDepth < leastPenetrationContact.PenetrationDepth) {
leastPenetrationContact.PenetrationDepth = penetrationDepth;
leastPenetrationContact.Normal = projectionA.Min > projectionB.Min ? -axis : axis;
}
}
// contact points
float startPointProjection = startPoint.Projection(leastPenetrationContact.Normal),
endPointProjection = endPoint.Projection(leastPenetrationContact.Normal);
Vector2 maxProjVertex;
if (startPointProjection > endPointProjection) {
maxProjVertex = startPoint;
} else {
maxProjVertex = endPoint;
}
(Vector2 MaxProjVertex, Line Edge) edgeA = (maxProjVertex, new Line(startPoint, endPoint));
(Vector2 MaxProjVertex, Line Edge) edgeB = shape.FindBestClippingEdge(shapePos, -leastPenetrationContact.Normal);
if (edgeB.Edge.PointA != edgeB.Edge.PointB) {
Vector2[] contactPoints = CalculateContactPoints(edgeA, edgeB, leastPenetrationContact.Normal);
if (contactPoints.Length > 0) {
leastPenetrationContact.Position = contactPoints[0];
}
}
contact = leastPenetrationContact;
return true;
}
public static bool TestLineSegmentWithIShape(Vector2 startPoint, Vector2 endPoint, IShape shape, Vector2 shapePos, out Contact? contact) {
Vector2[] shapeAxes = shape.CalculateAxes();
Vector2[] axes = new Vector2[2 + shapeAxes.Length];
Vector2 direction = (endPoint - startPoint).Normalized();
axes[0] = direction;
axes[1] = direction.PerpendicularCW();
shapeAxes.CopyTo(axes, 2);
return TestLineSegmentWithIShape(startPoint, endPoint, shape, shapePos, axes, out contact);
}
#endregion Line Segment with IShape
#region Contact Points by Clipping
internal static (Vector2 MaxProjVertex, Line Edge) FindBestEdge(Polygon polygon, Vector2 normal) {
float maxProjection = float.NegativeInfinity;
int index = -1;
for (int i = 0; i < polygon.VertexCount; i++) {
Vector2 v = polygon[i];
float projection = v.Projection(normal);
if (projection > maxProjection) {
maxProjection = projection;
index = i;
}
}
Vector2 vertex = polygon[index],
nextVertex = polygon[(index + 1) % polygon.VertexCount],
previousVertex = polygon[index - 1 < 0 ? polygon.VertexCount - 1 : index - 1];
Vector2 left = (vertex - nextVertex).Normalized(),
right = (vertex - previousVertex).Normalized();
if (Vector2.Dot(right, normal) <= Vector2.Dot(left, normal)) {
return (vertex, new Line(previousVertex, vertex));
}
return (vertex, new Line(vertex, nextVertex));
}
private static Vector2[] CalculateContactPoints((Vector2 MaxProjVertex, Line Edge) edgeA, (Vector2 MaxProjVertex, Line Edge) edgeB, Vector2 normal) {
(Vector2 MaxProjVertex, Line Edge) referenceEdge,
incidentEdge;
bool flip = false;
if (Math.Abs(Vector2.Dot(edgeA.Edge.ToVector2(), normal)) <= Math.Abs(Vector2.Dot(edgeB.Edge.ToVector2(), normal))) {
referenceEdge = edgeA;
incidentEdge = edgeB;
} else {
flip = true;
referenceEdge = edgeA;
incidentEdge = edgeB;
}
//
Vector2 refEdgeNormalized = referenceEdge.Edge.ToVector2().Normalized();
float offsetA = Vector2.Dot(refEdgeNormalized, referenceEdge.Edge.PointA);
List<Vector2> clippedPoints = Clip(incidentEdge.Edge.PointA, incidentEdge.Edge.PointB, refEdgeNormalized, offsetA);
if (clippedPoints.Count < 2) {
return new Vector2[0];
}
float offsetB = Vector2.Dot(refEdgeNormalized, referenceEdge.Edge.PointB);
clippedPoints = Clip(clippedPoints[0], clippedPoints[1], -refEdgeNormalized, -offsetB);
if (clippedPoints.Count < 2) {
return new Vector2[0];
}
Vector2 refNormal = Vector2.Cross(referenceEdge.Edge.ToVector2(), -1f);
if (flip) {
refNormal = -refNormal;
}
float max = Vector2.Dot(refNormal, referenceEdge.MaxProjVertex);
Vector2 clippedPointA = clippedPoints[0],
clippedPointB = clippedPoints[1];
if (Vector2.Dot(refNormal, clippedPointA) - max < 0f) {
clippedPoints.Remove(clippedPointA);
}
if (Vector2.Dot(refNormal, clippedPointB) - max < 0f) {
clippedPoints.Remove(clippedPointB);
}
return clippedPoints.ToArray();
}
private static List<Vector2> Clip(Vector2 pointA, Vector2 pointB, Vector2 normal, float offset) {
List<Vector2> clippedPoints = new List<Vector2>();
float dA = Vector2.Dot(normal, pointA) - offset,
dB = Vector2.Dot(normal, pointB) - offset;
if (dA >= 0f) {
clippedPoints.Add(pointA);
}
if (dB >= 0f) {
clippedPoints.Add(pointB);
}
if (dA * dB < 0f) {
float u = dA / (dA - dB);
Vector2 edge = pointA + u * (pointB - pointA);
clippedPoints.Add(edge);
}
return clippedPoints;
}
#endregion Contact Points by Clipping
#endregion Private Methods
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Eto.Forms
{
/// <summary>
/// Represents an immutable, inclusive start/end range of <see cref="IComparable{T}"/> values
/// </summary>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public struct Range<T> : IEquatable<Range<T>>
where T : struct, IComparable<T>
{
T start;
T end;
/// <summary>
/// Gets the start value of the range
/// </summary>
/// <value>The start of the range.</value>
public T Start { get { return start; } }
/// <summary>
/// Gets the end value of the range.
/// </summary>
/// <value>The end of the range.</value>
public T End { get { return end; } }
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.Range{T}"/> struct with a value for both the start and end.
/// </summary>
/// <param name="value">Value for the start and end of the range.</param>
public Range(T value)
{
start = value;
end = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.Range{T}"/> struct.
/// </summary>
/// <param name="start">Start of the range (inclusive).</param>
/// <param name="end">End of the range (inclusive).</param>
public Range(T start, T end)
{
this.start = start;
this.end = end;
}
/// <summary>
/// Creates a copy of the current range with a different start value.
/// </summary>
/// <returns>A new instance of the range with the specified start value.</returns>
/// <param name="start">Start of the new range.</param>
public Range<T> WithStart(T start)
{
return new Range<T>(start, End);
}
/// <summary>
/// Creates a copy of the current range with a different end value.
/// </summary>
/// <returns>A new instance of the range with the specified end value.</returns>
/// <param name="end">End of the new range.</param>
public Range<T> WithEnd(T end)
{
return new Range<T>(Start, end);
}
/// <summary>
/// Determines if the specified <paramref name="value"/> is between or equal to the <see cref="Start"/> and <see cref="End"/> of this range.
/// </summary>
/// <param name="value">Value to check if it is within this range.</param>
public bool Contains(T value)
{
var comparer = Comparer<T>.Default;
return comparer.Compare(Start, value) <= 0
&& comparer.Compare(End, value) >= 0;
}
/// <summary>
/// Iterates the range between the start and end values.
/// </summary>
/// <remarks>
/// This can be used to return an enumerable that iterates between the start and end of the range given the
/// specified <paramref name="increment"/> function.
/// </remarks>
/// <example>
/// <code>
/// // iterate over an int range
/// var intRange = new Range<int>(1, 200);
/// foreach (var item in intRange.Iterate(i => i + 1))
/// {
/// // logic
/// }
///
/// // iterate over a date range by minute
/// var dateRange = new Range<DateTime>(DateTime.Today, DateTime.Today.AddDays(2));
/// foreach (var item in dateRange.Iterate(i => i.AddMinutes(1)))
/// {
/// // logic
/// }
/// </code>
/// </example>
/// <param name="increment">Delegate to increment the value for each iteration of the enumerable.</param>
public IEnumerable<T> Iterate(Func<T, T> increment)
{
T item = start;
var comparer = Comparer<T>.Default;
while (comparer.Compare(item, end) <= 0)
{
yield return item;
item = increment(item);
}
}
/// <summary>
/// Determines if the specified <paramref name="range"/> touches (but doesn't intersect) this instance.
/// </summary>
/// <remarks>
/// This can be used to determine if one range comes after or before another range, given the specified
/// <paramref name="increment"/> function.
/// The increment function is used as this class does not assume how to increment each value, e.g. for a
/// <see cref="DateTime"/> value, you can increment by day, minute, second, etc.
/// </remarks>
/// <param name="range">Range to check if it touches this range.</param>
/// <param name="increment">Delegate to increment the value for checking if the ranges touch.</param>
/// <returns><c>true</c> if the ranges touch, <c>false</c> otherwise.</returns>
public bool Touches(Range<T> range, Func<T, T> increment)
{
var comparer = Comparer<T>.Default;
return comparer.Compare(Start, increment(range.End)) == 0
|| comparer.Compare(increment(End), range.Start) == 0;
}
/// <summary>
/// Determines if the specified <paramref name="range"/> intersects (overlaps) this instance.
/// </summary>
/// <param name="range">Range to check for intersection.</param>
/// <returns><c>true</c> if the range intersects this instance, <c>false</c> otherwise.</returns>
public bool Intersects(Range<T> range)
{
var comparer = Comparer<T>.Default;
var startVal = comparer.Compare(Start, range.Start) >= 0 ? Start : range.Start;
var endVal = comparer.Compare(End, range.End) <= 0 ? End : range.End;
return comparer.Compare(startVal, endVal) <= 0;
}
/// <summary>
/// Gets the intersection of this instance and the specified <paramref name="range"/>.
/// </summary>
/// <param name="range">Range to intersect with.</param>
/// <returns>A new instance of a range that is the intersection of this instance and the specified range, or null if they do not intersect.</returns>
public Range<T>? Intersect(Range<T> range)
{
var comparer = Comparer<T>.Default;
var startVal = comparer.Compare(Start, range.Start) >= 0 ? Start : range.Start;
var endVal = comparer.Compare(End, range.End) <= 0 ? End : range.End;
return comparer.Compare(startVal, endVal) <= 0 ? (Range<T>?)new Range<T>(startVal, endVal) : null;
}
/// <summary>
/// Gets the union of this instance and the specified <paramref name="range"/>, including touching ranges.
/// </summary>
/// <remarks>
/// This is similar to <see cref="Union(Range{T})"/>, however this handles when the two ranges are touching.
/// The <paramref name="increment"/> delegate is used to determine if the ranges are touching by incrementing the ends
/// of the ranges and comparing that value to the start of the other range.
/// </remarks>
/// <param name="range">Range to union with.</param>
/// <param name="increment">Delegate to increment the value for checking if the ranges touch.</param>
/// <returns>The union of this instance and the specified range, or null if they are neither intersecting or touching.</returns>
public Range<T>? Union(Range<T> range, Func<T, T> increment)
{
if (Intersects(range) || Touches(range, increment))
{
var comparer = Comparer<T>.Default;
var startVal = comparer.Compare(Start, range.Start) <= 0 ? Start : range.Start;
var endVal = comparer.Compare(End, range.End) >= 0 ? End : range.End;
return comparer.Compare(startVal, endVal) <= 0 ? (Range<T>?)new Range<T>(startVal, endVal) : null;
}
return null;
}
/// <summary>
/// Gets the union of this instance and an intersecting <paramref name="range"/>.
/// </summary>
/// <remarks>
/// This is similar to <see cref="Union(Range{T},Func{T,T})"/>, however this only handles when the two ranges are intersecting.
/// To union two ranges that touch, use the <see cref="Union(Range{T},Func{T,T})"/> method instead.
/// </remarks>
/// <param name="range">Range to union with.</param>
/// <returns>The union of this instance and the specified range, or null if they are not intersecting.</returns>
public Range<T>? Union(Range<T> range)
{
if (Intersects(range))
{
var comparer = Comparer<T>.Default;
var startVal = comparer.Compare(Start, range.Start) <= 0 ? Start : range.Start;
var endVal = comparer.Compare(End, range.End) >= 0 ? End : range.End;
return comparer.Compare(startVal, endVal) <= 0 ? (Range<T>?)new Range<T>(startVal, endVal) : null;
}
return null;
}
/// <summary>
/// Operator to compare two ranges for inequality.
/// </summary>
/// <param name="range1">First range to compare.</param>
/// <param name="range2">Second range to compare.</param>
/// <returns><c>true</c> if the two ranges are not equal, <c>false</c> if they are.</returns>
public static bool operator !=(Range<T> range1, Range<T> range2)
{
return !(range1 == range2);
}
/// <summary>
/// Operator to compare two ranges for equality
/// </summary>
/// <param name="range1">First range to compare.</param>
/// <param name="range2">Second range to compare.</param>
/// <returns><c>true</c> if the two ranges are equal, <c>false</c> if they are not.</returns>
public static bool operator ==(Range<T> range1, Range<T> range2)
{
var comparer = Comparer<T>.Default;
return comparer.Compare(range1.Start, range2.Start) == 0
&& comparer.Compare(range1.End, range2.End) == 0;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="Range{T}"/>.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="Range{T}"/>.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current <see cref="Range{T}"/>; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
return obj is Range<T> && ((Range<T>)obj == this);
}
/// <summary>
/// Serves as a hash function for a <see cref="Eto.Forms.Range{T}"/> object.
/// </summary>
/// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a hash table.</returns>
public override int GetHashCode()
{
return Start.GetHashCode() ^ End.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="Range{T}"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="Range{T}"/>.</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Start={0}, End={1}", Start, End);
}
/// <summary>
/// Determines whether the specified <paramref name="other"/> range is equal to the current <see cref="Range{T}"/>.
/// </summary>
/// <param name="other">The <see cref="Range{T}"/> to compare with the current <see cref="Range{T}"/>.</param>
/// <returns><c>true</c> if the specified <see cref="Range{T}"/> is equal to the current <see cref="Range{T}"/>; otherwise, <c>false</c>.</returns>
public bool Equals(Range<T> other)
{
return this == other;
}
}
/// <summary>
/// Extensions for the <see cref="Range{T}"/> structure
/// </summary>
public static class RangeExtensions
{
/// <summary>
/// Gets the interval for the specified <paramref name="range"/> between the start and end dates.
/// </summary>
/// <param name="range">Range to get the interval for.</param>
/// <returns>A new TimeSpan that is the difference between the start and end dates of the specified range.</returns>
public static TimeSpan Interval(this Range<DateTime> range)
{
return range.End - range.Start;
}
/// <summary>
/// Gets the length of the specified <paramref name="range"/> between the start and end values.
/// </summary>
/// <param name="range">Range to get the length for.</param>
/// <returns>The length between the start and end values of the specified range.</returns>
public static int Length(this Range<int> range)
{
return range.End - range.Start + 1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net;
using System.Runtime.InteropServices;
using System.Collections;
using System.DirectoryServices.Interop;
using System.Text;
using INTPTR_INTPTRCAST = System.IntPtr;
namespace System.DirectoryServices
{
/// <devdoc>
/// Contains the instances of <see cref='System.DirectoryServices.SearchResult'/> returned during a
/// query to the Active Directory hierarchy through <see cref='System.DirectoryServices.DirectorySearcher'/>.
/// </devdoc>
public class SearchResultCollection : MarshalByRefObject, ICollection, IEnumerable, IDisposable
{
private IntPtr _handle;
private UnsafeNativeMethods.IDirectorySearch _searchObject;
private ArrayList _innerList;
private bool _disposed;
private readonly DirectoryEntry _rootEntry; // clone of parent entry object
private const string ADS_DIRSYNC_COOKIE = "fc8cb04d-311d-406c-8cb9-1ae8b843b418";
private IntPtr _adsDirsynCookieName = Marshal.StringToCoTaskMemUni(ADS_DIRSYNC_COOKIE);
private const string ADS_VLV_RESPONSE = "fc8cb04d-311d-406c-8cb9-1ae8b843b419";
private IntPtr _adsVLVResponseName = Marshal.StringToCoTaskMemUni(ADS_VLV_RESPONSE);
internal DirectorySearcher srch = null;
internal SearchResultCollection(DirectoryEntry root, IntPtr searchHandle, string[] propertiesLoaded, DirectorySearcher srch)
{
_handle = searchHandle;
PropertiesLoaded = propertiesLoaded;
Filter = srch.Filter;
_rootEntry = root;
this.srch = srch;
}
public SearchResult this[int index] => (SearchResult)InnerList[index];
public int Count => InnerList.Count;
internal string Filter { get; }
private ArrayList InnerList
{
get
{
if (_innerList == null)
{
_innerList = new ArrayList();
IEnumerator enumerator = new ResultsEnumerator(this,
_rootEntry.GetUsername(),
_rootEntry.GetPassword(),
_rootEntry.AuthenticationType);
while (enumerator.MoveNext())
_innerList.Add(enumerator.Current);
}
return _innerList;
}
}
internal UnsafeNativeMethods.IDirectorySearch SearchObject
{
get
{
if (_searchObject == null)
{
_searchObject = (UnsafeNativeMethods.IDirectorySearch)_rootEntry.AdsObject; // get it only once
}
return _searchObject;
}
}
/// <devdoc>
/// Gets the handle returned by IDirectorySearch::ExecuteSearch, which was called
/// by the DirectorySearcher that created this object
/// </devdoc>
public IntPtr Handle
{
get
{
//The handle is no longer valid since the object has been disposed.
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _handle;
}
}
/// <devdoc>
/// Gets a read-only collection of the properties specified on <see cref='System.DirectoryServices.DirectorySearcher'/> before the
/// search was executed.
/// </devdoc>
public string[] PropertiesLoaded { get; }
internal byte[] DirsyncCookie => RetrieveDirectorySynchronizationCookie();
internal DirectoryVirtualListView VLVResponse => RetrieveVLVResponse();
private unsafe byte[] RetrieveDirectorySynchronizationCookie()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// get the dirsync cookie back
AdsSearchColumn column = new AdsSearchColumn();
AdsSearchColumn* pColumn = &column;
SearchObject.GetColumn(Handle, _adsDirsynCookieName, (INTPTR_INTPTRCAST)pColumn);
try
{
AdsValue* pValue = column.pADsValues;
byte[] value = (byte[])new AdsValueHelper(*pValue).GetValue();
return value;
}
finally
{
try
{
SearchObject.FreeColumn((INTPTR_INTPTRCAST)pColumn);
}
catch (COMException)
{
}
}
}
private unsafe DirectoryVirtualListView RetrieveVLVResponse()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// get the vlv response back
AdsSearchColumn column = new AdsSearchColumn();
AdsSearchColumn* pColumn = &column;
SearchObject.GetColumn(Handle, _adsVLVResponseName, (INTPTR_INTPTRCAST)pColumn);
try
{
AdsValue* pValue = column.pADsValues;
DirectoryVirtualListView value = (DirectoryVirtualListView)new AdsValueHelper(*pValue).GetVlvValue();
return value;
}
finally
{
try
{
SearchObject.FreeColumn((INTPTR_INTPTRCAST)pColumn);
}
catch (COMException)
{
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (_handle != (IntPtr)0 && _searchObject != null && disposing)
{
// NOTE: We can't call methods on SearchObject in the finalizer because it
// runs on a different thread. The IDirectorySearch object is STA, so COM must create
// a proxy stub to marshal the call back to the original thread. Unfortunately, the
// IDirectorySearch interface cannot be registered, because it is not automation
// compatible. Therefore the QI for IDirectorySearch on this thread fails, and we get
// an InvalidCastException. The conclusion is that the user simply must call Dispose
// on this object.
_searchObject.CloseSearchHandle(_handle);
_handle = (IntPtr)0;
}
if (disposing)
_rootEntry.Dispose();
if (_adsDirsynCookieName != (IntPtr)0)
Marshal.FreeCoTaskMem(_adsDirsynCookieName);
if (_adsVLVResponseName != (IntPtr)0)
Marshal.FreeCoTaskMem(_adsVLVResponseName);
_disposed = true;
}
}
~SearchResultCollection() => Dispose(false);
public IEnumerator GetEnumerator()
{
// Two ResultsEnumerators can't exist at the same time over the
// same object. Need to get a new handle, which means re-querying.
return new ResultsEnumerator(this,
_rootEntry.GetUsername(),
_rootEntry.GetPassword(),
_rootEntry.AuthenticationType);
}
public bool Contains(SearchResult result) => InnerList.Contains(result);
public void CopyTo(SearchResult[] results, int index)
{
InnerList.CopyTo(results, index);
}
public int IndexOf(SearchResult result) => InnerList.IndexOf(result);
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
void ICollection.CopyTo(Array array, int index)
{
InnerList.CopyTo(array, index);
}
/// <devdoc>
/// Supports a simple ForEach-style iteration over a collection.
/// </devdoc>
private class ResultsEnumerator : IEnumerator
{
private NetworkCredential _parentCredentials;
private AuthenticationTypes _parentAuthenticationType;
private SearchResultCollection _results;
private bool _initialized;
private SearchResult _currentResult;
private bool _eof;
private bool _waitForResult = false;
internal ResultsEnumerator(SearchResultCollection results, string parentUserName, string parentPassword, AuthenticationTypes parentAuthenticationType)
{
if (parentUserName != null && parentPassword != null)
_parentCredentials = new NetworkCredential(parentUserName, parentPassword);
_parentAuthenticationType = parentAuthenticationType;
_results = results;
_initialized = false;
}
/// <devdoc>
/// Gets the current element in the collection.
/// </devdoc>
public SearchResult Current
{
get
{
if (!_initialized || _eof)
throw new InvalidOperationException(SR.DSNoCurrentEntry);
if (_currentResult == null)
_currentResult = GetCurrentResult();
return _currentResult;
}
}
private unsafe SearchResult GetCurrentResult()
{
SearchResult entry = new SearchResult(_parentCredentials, _parentAuthenticationType);
int hr = 0;
IntPtr pszColumnName = (IntPtr)0;
hr = _results.SearchObject.GetNextColumnName(_results.Handle, (INTPTR_INTPTRCAST)(&pszColumnName));
while (hr == 0)
{
try
{
AdsSearchColumn column = new AdsSearchColumn();
AdsSearchColumn* pColumn = &column;
_results.SearchObject.GetColumn(_results.Handle, pszColumnName, (INTPTR_INTPTRCAST)pColumn);
try
{
int numValues = column.dwNumValues;
AdsValue* pValue = column.pADsValues;
object[] values = new object[numValues];
for (int i = 0; i < numValues; i++)
{
values[i] = new AdsValueHelper(*pValue).GetValue();
pValue++;
}
entry.Properties.Add(Marshal.PtrToStringUni(pszColumnName), new ResultPropertyValueCollection(values));
}
finally
{
try
{
_results.SearchObject.FreeColumn((INTPTR_INTPTRCAST)pColumn);
}
catch (COMException)
{
}
}
}
finally
{
SafeNativeMethods.FreeADsMem(pszColumnName);
}
hr = _results.SearchObject.GetNextColumnName(_results.Handle, (INTPTR_INTPTRCAST)(&pszColumnName));
}
return entry;
}
/// <devdoc>
/// Advances the enumerator to the next element of the collection
/// and returns a Boolean value indicating whether a valid element is available.
/// </devdoc>
public bool MoveNext()
{
DirectorySynchronization tempsync = null;
DirectoryVirtualListView tempvlv = null;
int errorCode = 0;
if (_eof)
return false;
_currentResult = null;
if (!_initialized)
{
int hr = _results.SearchObject.GetFirstRow(_results.Handle);
if (hr != UnsafeNativeMethods.S_ADS_NOMORE_ROWS)
{
//throw a clearer exception if the filter was invalid
if (hr == UnsafeNativeMethods.INVALID_FILTER)
throw new ArgumentException(SR.Format(SR.DSInvalidSearchFilter , _results.Filter));
if (hr != 0)
throw COMExceptionHelper.CreateFormattedComException(hr);
_eof = false;
_initialized = true;
return true;
}
_initialized = true;
}
while (true)
{
// clear the last error first
CleanLastError();
errorCode = 0;
int hr = _results.SearchObject.GetNextRow(_results.Handle);
// SIZE_LIMIT_EXCEEDED occurs when we supply too generic filter or small SizeLimit value.
if (hr == UnsafeNativeMethods.S_ADS_NOMORE_ROWS || hr == UnsafeNativeMethods.SIZE_LIMIT_EXCEEDED)
{
// need to make sure this is not the case that server actually still has record not returned yet
if (hr == UnsafeNativeMethods.S_ADS_NOMORE_ROWS)
{
hr = GetLastError(ref errorCode);
// get last error call failed, we need to bail out
if (hr != 0)
throw COMExceptionHelper.CreateFormattedComException(hr);
}
// not the case that server still has result, we are done here
if (errorCode != SafeNativeMethods.ERROR_MORE_DATA)
{
// get the dirsync cookie as we finished all the rows
if (_results.srch.directorySynchronizationSpecified)
tempsync = _results.srch.DirectorySynchronization;
// get the vlv response as we finished all the rows
if (_results.srch.directoryVirtualListViewSpecified)
tempvlv = _results.srch.VirtualListView;
_results.srch.searchResult = null;
_eof = true;
_initialized = false;
return false;
}
else
{
// if user chooses to wait to continue the search
if (_waitForResult)
{
continue;
}
else
{
uint temp = (uint)errorCode;
temp = ((((temp) & 0x0000FFFF) | (7 << 16) | 0x80000000));
throw COMExceptionHelper.CreateFormattedComException((int)temp);
}
}
}
//throw a clearer exception if the filter was invalid
if (hr == UnsafeNativeMethods.INVALID_FILTER)
throw new ArgumentException(SR.Format(SR.DSInvalidSearchFilter , _results.Filter));
if (hr != 0)
throw COMExceptionHelper.CreateFormattedComException(hr);
_eof = false;
return true;
}
}
/// <devdoc>
/// Resets the enumerator back to its initial position before the first element in the collection.
/// </devdoc>
public void Reset()
{
_eof = false;
_initialized = false;
}
object IEnumerator.Current => Current;
private void CleanLastError()
{
SafeNativeMethods.ADsSetLastError(SafeNativeMethods.ERROR_SUCCESS, null, null);
}
private unsafe int GetLastError(ref int errorCode)
{
char c1 = '\0', c2 = '\0';
errorCode = SafeNativeMethods.ERROR_SUCCESS;
return SafeNativeMethods.ADsGetLastError(out errorCode, &c1, 0, &c2, 0);
}
}
}
}
| |
// 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.IO;
using System.Xml.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
namespace System
{
public static partial class PlatformDetection
{
public static bool IsWindowsIoTCore => false;
public static bool IsWindows => false;
public static bool IsWindows7 => false;
public static bool IsWindows8x => false;
public static bool IsWindows10Version1607OrGreater => false;
public static bool IsWindows10Version1703OrGreater => false;
public static bool IsWindows10InsiderPreviewBuild16215OrGreater => false;
public static bool IsWindows10Version16251OrGreater => false;
public static bool IsNotOneCoreUAP => true;
public static bool IsNetfx462OrNewer() { return false; }
public static bool IsNetfx470OrNewer() { return false; }
public static bool IsNetfx471OrNewer() { return false; }
public static bool IsWinRT => false;
public static int WindowsVersion => -1;
public static bool IsOpenSUSE => IsDistroAndVersion("opensuse");
public static bool IsUbuntu => IsDistroAndVersion("ubuntu");
public static bool IsDebian => IsDistroAndVersion("debian");
public static bool IsDebian8 => IsDistroAndVersion("debian", "8");
public static bool IsUbuntu1404 => IsDistroAndVersion("ubuntu", "14.04");
public static bool IsCentos7 => IsDistroAndVersion("centos", "7");
public static bool IsTizen => IsDistroAndVersion("tizen");
public static bool IsNotFedoraOrRedHatOrCentos => !IsDistroAndVersion("fedora") && !IsDistroAndVersion("rhel") && !IsDistroAndVersion("centos");
public static bool IsFedora => IsDistroAndVersion("fedora");
public static bool IsWindowsNanoServer => false;
public static bool IsWindowsAndElevated => false;
public static bool IsRedHat => IsDistroAndVersion("rhel") || IsDistroAndVersion("rhl");
public static bool IsNotRedHat => !IsRedHat;
public static bool IsRedHat69 => IsDistroAndVersion("rhel", "6.9") || IsDistroAndVersion("rhl", "6.9");
public static bool IsNotRedHat69 => !IsRedHat69;
public static Version OSXKernelVersion { get; } = GetOSXKernelVersion();
public static string GetDistroVersionString()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return "";
}
DistroInfo v = ParseOsReleaseFile();
return "Distro=" + v.Id + " VersionId=" + v.VersionId + " Pretty=" + v.PrettyName + " Version=" + v.Version;
}
private static readonly Version s_osxProductVersion = GetOSXProductVersion();
public static bool IsMacOsHighSierraOrHigher { get; } =
IsOSX && (s_osxProductVersion.Major > 10 || (s_osxProductVersion.Major == 10 && s_osxProductVersion.Minor >= 13));
private static readonly Version s_icuVersion = GetICUVersion();
public static Version ICUVersion => s_icuVersion;
private static Version GetICUVersion()
{
int ver = GlobalizationNative_GetICUVersion();
return new Version( ver & 0xFF,
(ver >> 8) & 0xFF,
(ver >> 16) & 0xFF,
ver >> 24);
}
private static DistroInfo ParseOsReleaseFile()
{
Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Linux));
DistroInfo ret = new DistroInfo();
ret.Id = "";
ret.VersionId = "";
ret.Version = "";
ret.PrettyName = "";
if (File.Exists("/etc/os-release"))
{
foreach (string line in File.ReadLines("/etc/os-release"))
{
if (line.StartsWith("ID=", System.StringComparison.Ordinal))
{
ret.Id = RemoveQuotes(line.Substring("ID=".Length));
}
else if (line.StartsWith("VERSION_ID=", System.StringComparison.Ordinal))
{
ret.VersionId = RemoveQuotes(line.Substring("VERSION_ID=".Length));
}
else if (line.StartsWith("VERSION=", System.StringComparison.Ordinal))
{
ret.Version = RemoveQuotes(line.Substring("VERSION=".Length));
}
else if (line.StartsWith("PRETTY_NAME=", System.StringComparison.Ordinal))
{
ret.PrettyName = RemoveQuotes(line.Substring("PRETTY_NAME=".Length));
}
}
}
else
{
string fileName = null;
if (File.Exists("/etc/redhat-release"))
fileName = "/etc/redhat-release";
if (fileName == null && File.Exists("/etc/system-release"))
fileName = "/etc/system-release";
if (fileName != null)
{
// Parse the format like the following line:
// Red Hat Enterprise Linux Server release 7.3 (Maipo)
using (StreamReader file = new StreamReader(fileName))
{
string line = file.ReadLine();
if (!String.IsNullOrEmpty(line))
{
if (line.StartsWith("Red Hat Enterprise Linux", StringComparison.OrdinalIgnoreCase))
{
ret.Id = "rhel";
}
else if (line.StartsWith("Centos", StringComparison.OrdinalIgnoreCase))
{
ret.Id = "centos";
}
else if (line.StartsWith("Red Hat", StringComparison.OrdinalIgnoreCase))
{
ret.Id = "rhl";
}
else
{
// automatically generate the distro label
string [] words = line.Split(' ');
StringBuilder sb = new StringBuilder();
foreach (string word in words)
{
if (word.Length > 0)
{
if (Char.IsNumber(word[0]) ||
word.Equals("release", StringComparison.OrdinalIgnoreCase) ||
word.Equals("server", StringComparison.OrdinalIgnoreCase))
{
break;
}
sb.Append(Char.ToLower(word[0]));
}
}
ret.Id = sb.ToString();
}
int i = 0;
while (i < line.Length && !Char.IsNumber(line[i])) // stop at first number
i++;
if (i < line.Length)
{
int j = i + 1;
while (j < line.Length && (Char.IsNumber(line[j]) || line[j] == '.'))
j++;
ret.VersionId = line.Substring(i, j - i);
ret.Version = line.Substring(i, line.Length - i);
}
ret.PrettyName = line;
}
}
}
}
return ret;
}
private static string RemoveQuotes(string s)
{
s = s.Trim();
if (s.Length >= 2 && s[0] == '"' && s[s.Length - 1] == '"')
{
// Remove quotes.
s = s.Substring(1, s.Length - 2);
}
return s;
}
private struct DistroInfo
{
public string Id { get; set; }
public string VersionId { get; set; }
public string Version { get; set; }
public string PrettyName { get; set; }
}
/// <summary>
/// Get whether the OS platform matches the given Linux distro and optional version.
/// </summary>
/// <param name="distroId">The distribution id.</param>
/// <param name="versionId">The distro version. If omitted, compares the distro only.</param>
/// <returns>Whether the OS platform matches the given Linux distro and optional version.</returns>
private static bool IsDistroAndVersion(string distroId, string versionId = null)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
DistroInfo v = ParseOsReleaseFile();
if (v.Id == distroId && (versionId == null || v.VersionId == versionId))
{
return true;
}
}
return false;
}
private static Version GetOSXKernelVersion()
{
if (IsOSX)
{
byte[] bytes = new byte[256];
IntPtr bytesLength = new IntPtr(bytes.Length);
Assert.Equal(0, sysctlbyname("kern.osrelease", bytes, ref bytesLength, null, IntPtr.Zero));
string versionString = Encoding.UTF8.GetString(bytes);
return Version.Parse(versionString);
}
return new Version(0, 0, 0);
}
private static Version GetOSXProductVersion()
{
try
{
if (IsOSX)
{
// <plist version="1.0">
// <dict>
// <key>ProductBuildVersion</key>
// <string>17A330h</string>
// <key>ProductCopyright</key>
// <string>1983-2017 Apple Inc.</string>
// <key>ProductName</key>
// <string>Mac OS X</string>
// <key>ProductUserVisibleVersion</key>
// <string>10.13</string>
// <key>ProductVersion</key>
// <string>10.13</string>
// </dict>
// </plist>
XElement dict = XDocument.Load("/System/Library/CoreServices/SystemVersion.plist").Root.Element("dict");
if (dict != null)
{
foreach (XElement key in dict.Elements("key"))
{
if ("ProductVersion".Equals(key.Value))
{
XElement stringElement = key.NextNode as XElement;
if (stringElement != null && stringElement.Name.LocalName.Equals("string"))
{
string versionString = stringElement.Value;
if (versionString != null)
{
return Version.Parse(versionString);
}
}
}
}
}
}
}
catch
{
}
// In case of exception or couldn't get the version
return new Version(0, 0, 0);
}
[DllImport("libc", SetLastError = true)]
private static extern int sysctlbyname(string ctlName, byte[] oldp, ref IntPtr oldpLen, byte[] newp, IntPtr newpLen);
[DllImport("libc", SetLastError = true)]
internal static extern unsafe uint geteuid();
[DllImport("System.Globalization.Native", SetLastError = true)]
private static extern int GlobalizationNative_GetICUVersion();
public static bool IsSuperUser => geteuid() == 0;
}
}
| |
//
// Addin.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Specialized;
using Mono.Addins.Description;
using Mono.Addins.Database;
using System.Linq;
namespace Mono.Addins
{
/// <summary>
/// An add-in.
/// </summary>
public class Addin
{
AddinInfo addin;
string sourceFile;
WeakReference desc;
AddinDatabase database;
bool? isLatestVersion;
bool? isUserAddin;
string id;
string domain;
internal Addin (AddinDatabase database, string domain, string id)
{
this.database = database;
this.id = id;
this.domain = domain;
LoadAddinInfo ();
}
/// <summary>
/// Full identifier of the add-in, including namespace and version.
/// </summary>
public string Id {
get { return id; }
}
/// <summary>
/// Namespace of the add-in.
/// </summary>
public string Namespace {
get { return this.AddinInfo.Namespace; }
}
/// <summary>
/// Identifier of the add-in (without namespace)
/// </summary>
public string LocalId {
get { return this.AddinInfo.LocalId; }
}
/// <summary>
/// Version of the add-in
/// </summary>
public string Version {
get { return this.AddinInfo.Version; }
}
/// <summary>
/// Display name of the add-in
/// </summary>
public string Name {
get { return this.AddinInfo.Name; }
}
/// <summary>
/// Custom properties specified in the add-in header
/// </summary>
public AddinPropertyCollection Properties {
get { return this.AddinInfo.Properties; }
}
internal string PrivateDataPath {
get { return Path.Combine (database.AddinPrivateDataPath, Path.GetFileNameWithoutExtension (Description.FileName)); }
}
/// <summary>
/// Checks version compatibility.
/// </summary>
/// <param name="version">
/// An add-in version.
/// </param>
/// <returns>
/// True if the provided version is compatible with this add-in.
/// </returns>
/// <remarks>
/// This method checks the CompatVersion property to know if the provided version is compatible with the version of this add-in.
/// </remarks>
public bool SupportsVersion (string version)
{
return AddinInfo.SupportsVersion (version);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="Mono.Addins.Addin"/>.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents the current <see cref="Mono.Addins.Addin"/>.
/// </returns>
public override string ToString ()
{
return Id;
}
internal AddinInfo AddinInfo {
get {
if (addin == null) {
try {
addin = AddinInfo.ReadFromDescription (Description);
} catch (Exception ex) {
throw new InvalidOperationException ("Could not read add-in file: " + database.GetDescriptionPath (domain, id), ex);
}
}
return addin;
}
}
/// <summary>
/// Gets or sets the enabled status of the add-in.
/// </summary>
/// <remarks>
/// This property can be used to enable or disable an add-in.
/// The enabled status of an add-in is stored in the add-in registry,
/// so when an add-in is disabled, it will be disabled for all applications
/// sharing the same registry.
/// When an add-in is enabled or disabled, the extension points currently loaded
/// in memory will be properly updated to include or exclude extensions from the add-in.
/// </remarks>
public bool Enabled {
get {
if (!IsLatestVersion)
return false;
return AddinInfo.IsRoot ? true : database.IsAddinEnabled (Description.Domain, AddinInfo.Id, true);
}
set {
if (value)
database.EnableAddin (Description.Domain, AddinInfo.Id, true);
else
database.DisableAddin (Description.Domain, AddinInfo.Id);
}
}
internal bool IsLatestVersion {
get {
if (isLatestVersion == null) {
string id, version;
Addin.GetIdParts (AddinInfo.Id, out id, out version);
var addins = database.GetInstalledAddins (null, AddinSearchFlagsInternal.IncludeAll | AddinSearchFlagsInternal.LatestVersionsOnly);
isLatestVersion = addins.Where (a => Addin.GetIdName (a.Id) == id && a.Version == version).Any ();
}
return isLatestVersion.Value;
}
set {
isLatestVersion = value;
}
}
/// <summary>
/// Returns 'true' if the add-in is installed in the user's personal folder
/// </summary>
public bool IsUserAddin {
get {
if (isUserAddin == null)
SetIsUserAddin (Description);
return isUserAddin.Value;
}
}
void SetIsUserAddin (AddinDescription adesc)
{
string installPath = database.Registry.DefaultAddinsFolder;
if (installPath [installPath.Length - 1] != Path.DirectorySeparatorChar)
installPath += Path.DirectorySeparatorChar;
isUserAddin = adesc != null && Path.GetFullPath (adesc.AddinFile).StartsWith (installPath);
}
/// <summary>
/// Path to the add-in file (it can be an assembly or a standalone XML manifest)
/// </summary>
public string AddinFile {
get {
if (sourceFile == null && addin == null)
LoadAddinInfo ();
return sourceFile;
}
}
void LoadAddinInfo ()
{
if (addin == null) {
try {
AddinDescription m = Description;
sourceFile = m.AddinFile;
addin = AddinInfo.ReadFromDescription (m);
} catch (Exception ex) {
throw new InvalidOperationException ("Could not read add-in file: " + database.GetDescriptionPath (domain, id), ex);
}
}
}
/// <summary>
/// Description of the add-in
/// </summary>
public AddinDescription Description {
get {
if (desc != null) {
AddinDescription d = desc.Target as AddinDescription;
if (d != null)
return d;
}
var configFile = database.GetDescriptionPath (domain, id);
AddinDescription m;
database.ReadAddinDescription (new ConsoleProgressStatus (true), configFile, out m);
if (m == null) {
try {
if (File.Exists (configFile)) {
// The file is corrupted. Remove it.
File.Delete (configFile);
}
} catch {
// Ignore
}
throw new InvalidOperationException ("Could not read add-in description");
}
if (addin == null) {
addin = AddinInfo.ReadFromDescription (m);
sourceFile = m.AddinFile;
}
SetIsUserAddin (m);
if (!isUserAddin.Value)
m.Flags |= AddinFlags.CantUninstall;
desc = new WeakReference (m);
return m;
}
}
internal void ResetCachedData ()
{
// The domain may have changed
if (sourceFile != null)
domain = database.GetFolderDomain (null, Path.GetDirectoryName (sourceFile));
desc = null;
addin = null;
}
/// <summary>
/// Compares two add-in versions
/// </summary>
/// <returns>
/// -1 if v1 is greater than v2, 0 if v1 == v2, 1 if v1 less than v2
/// </returns>
/// <param name='v1'>
/// A version
/// </param>
/// <param name='v2'>
/// A version
/// </param>
public static int CompareVersions (string v1, string v2)
{
string[] a1 = v1.Split ('.');
string[] a2 = v2.Split ('.');
for (int n=0; n<a1.Length; n++) {
if (n >= a2.Length)
return -1;
if (a1[n].Length == 0) {
if (a2[n].Length != 0)
return 1;
continue;
}
try {
int n1 = int.Parse (a1[n]);
int n2 = int.Parse (a2[n]);
if (n1 < n2)
return 1;
else if (n1 > n2)
return -1;
} catch {
return 1;
}
}
if (a2.Length > a1.Length)
return 1;
return 0;
}
/// <summary>
/// Returns the identifier of an add-in
/// </summary>
/// <returns>
/// The full identifier.
/// </returns>
/// <param name='ns'>
/// Namespace of the add-in
/// </param>
/// <param name='id'>
/// Name of the add-in
/// </param>
/// <param name='version'>
/// Version of the add-in
/// </param>
public static string GetFullId (string ns, string id, string version)
{
string res;
if (id.StartsWith ("::"))
res = id.Substring (2);
else if (ns != null && ns.Length > 0)
res = ns + "." + id;
else
res = id;
if (version != null && version.Length > 0)
return res + "," + version;
else
return res;
}
/// <summary>
/// Given a full add-in identifier, returns the namespace and name of the add-in (it removes the version number)
/// </summary>
/// <param name='addinId'>
/// Add-in identifier.
/// </param>
public static string GetIdName (string addinId)
{
int i = addinId.IndexOf (',');
if (i != -1)
return addinId.Substring (0, i);
else
return addinId;
}
/// <summary>
/// Given a full add-in identifier, returns the version the add-in
/// </summary>
/// <returns>
/// The version.
/// </returns>
public static string GetIdVersion (string addinId)
{
int i = addinId.IndexOf (',');
if (i != -1)
return addinId.Substring (i + 1).Trim ();
else
return string.Empty;
}
/// <summary>
/// Splits a full add-in identifier in name and version
/// </summary>
/// <param name='addinId'>
/// Add-in identifier.
/// </param>
/// <param name='name'>
/// The resulting name
/// </param>
/// <param name='version'>
/// The resulting version
/// </param>
public static void GetIdParts (string addinId, out string name, out string version)
{
int i = addinId.IndexOf (',');
if (i != -1) {
name = addinId.Substring (0, i);
version = addinId.Substring (i+1).Trim ();
} else {
name = addinId;
version = string.Empty;
}
}
}
}
| |
using System;
using System.Diagnostics;
namespace Core.Command
{
public partial class Update
{
public static void sqlite3ColumnDefault(Vdbe v, Table table, int i, int regId)
{
Debug.Assert(table != null);
if (table.Select == null)
{
TEXTENCODE encode = Context.CTXENCODE(v.Ctx);
Column col = table.Cols[i];
v.VdbeComment("%s.%s", table.Name, col.Name);
Debug.Assert(i < table.Cols.length);
Mem value = new Mem();
sqlite3ValueFromExpr(v.Ctx, col.Dflt, encode, col.Affinity, ref value);
if (value != null)
v.ChangeP4(-1, value, Vdbe.P4T.MEM);
#if !OMIT_FLOATING_POINT
if (regId >= 0 && table.Cols[i].Affinity == AFF.REAL)
v.AddOp1(OP.RealAffinity, regId);
#endif
}
}
public static void sqlite3Update(Parse parse, SrcList tabList, ExprList changes, Expr where_, OE onError)
{
int i, j; // Loop counters
AuthContext sContext = new AuthContext(); // The authorization context
Context ctx = parse.Ctx; // The database structure
if (parse.Errs != 0 || ctx.MallocFailed)
goto update_cleanup;
Debug.Assert(tabList.Srcs == 1);
// Locate the table which we want to update.
Table table = sqlite3SrcListLookup(parse, tabList); // The table to be updated
if (table == null) goto update_cleanup;
int db = sqlite3SchemaToIndex(ctx, table.Schema); // Database containing the table being updated
// Figure out if we have any triggers and if the table being updated is a view.
#if !OMIT_TRIGGER
int tmask = 0; // Mask of TRIGGER_BEFORE|TRIGGER_AFTER
Trigger trigger = sqlite3TriggersExist(parse, table, TK.UPDATE, changes, out tmask); // List of triggers on pTab, if required
#if OMIT_VIEW
const bool isView = false;
#else
bool isView = (table.Select != null); // True when updating a view (INSTEAD OF trigger)
#endif
Debug.Assert(trigger != null || tmask == 0);
#else
const Trigger trigger = null;
const int tmask = 0;
const bool isView = false;
#endif
if (sqlite3ViewGetColumnNames(parse, table) != 0 || sqlite3IsReadOnly(parse, table, tmask))
goto update_cleanup;
int[] xrefs = new int[table.Cols.length]; // xrefs[i] is the index in pChanges->a[] of the an expression for the i-th column of the table. xrefs[i]==-1 if the i-th column is not changed.
if (xrefs == null) goto update_cleanup;
for (i = 0; i < table.Cols.length; i++) xrefs[i] = -1;
// Allocate a cursors for the main database table and for all indices. The index cursors might not be used, but if they are used they
// need to occur right after the database cursor. So go ahead and allocate enough space, just in case.
int curId; // VDBE Cursor number of pTab
tabList.Ids[0].Cursor = curId = parse.Tabs++;
Index idx; // For looping over indices
for (idx = table.Index; idx != null; idx = idx.Next)
parse.Tabs++;
// Initialize the name-context
NameContext sNC = new NameContext(); // The name-context to resolve expressions in
sNC.Parse = parse;
sNC.SrcList = tabList;
// Resolve the column names in all the expressions of the of the UPDATE statement. Also find the column index
// for each column to be updated in the pChanges array. For each column to be updated, make sure we have authorization to change that column.
bool chngRowid = false; // True if the record number is being changed
Expr rowidExpr = null; // Expression defining the new record number
for (i = 0; i < changes.Exprs; i++)
{
if (sqlite3ResolveExprNames(sNC, ref changes.Ids[i].Expr) != 0)
goto update_cleanup;
for (j = 0; j < table.Cols.length; j++)
{
if (string.Equals(table.Cols[j].Name, changes.Ids[i].Name, StringComparison.OrdinalIgnoreCase))
{
if (j == table.PKey)
{
chngRowid = true;
rowidExpr = changes.Ids[i].Expr;
}
xrefs[j] = i;
break;
}
}
if (j >= table.Cols.length)
{
if (Expr::IsRowid(changes.Ids[i].Name))
{
chngRowid = true;
rowidExpr = changes.Ids[i].Expr;
}
else
{
parse.ErrorMsg("no such column: %s", changes.Ids[i].Name);
parse.CheckSchema = 1;
goto update_cleanup;
}
}
#if !OMIT_AUTHORIZATION
{
ARC rc = Auth.Check(parse, AUTH.UPDATE, table.Name, table.Cols[j].Name, ctx.DBs[db].Name);
if (rc == ARC.DENY) goto update_cleanup;
else if (rc == ARC.IGNORE) xrefs[j] = -1;
}
#endif
}
bool hasFK = sqlite3FkRequired(parse, table, xrefs, chngRowid ? 1 : 0); // True if foreign key processing is required
// Allocate memory for the array aRegIdx[]. There is one entry in the array for each index associated with table being updated. Fill in
// the value with a register number for indices that are to be used and with zero for unused indices.
int idxLength; // Number of indices that need updating
for (idxLength = 0, idx = table.Index; idx != null; idx = idx.Next, idxLength++) ;
int[] regIdxs = null; // One register assigned to each index to be updated
if (idxLength > 0)
{
regIdxs = new int[idxLength];
if (regIdxs == null) goto update_cleanup;
}
for (j = 0, idx = table.Index; idx != null; idx = idx.Next, j++)
{
int regId;
if (hasFK || chngRowid)
regId = ++parse.Mems;
else
{
regId = 0;
for (i = 0; i < idx.Columns.length; i++)
if (xrefs[idx.Columns[i]] >= 0)
{
regId = ++parse.Mems;
break;
}
}
regIdxs[j] = regId;
}
// Begin generating code.
Vdbe v = parse.GetVdbe(); // The virtual database engine
if (v == null) goto update_cleanup;
if (parse.Nested == 0) v.CountChanges();
parse.BeginWriteOperation(1, db);
#if !OMIT_VIRTUALTABLE
// Virtual tables must be handled separately
if (IsVirtual(table))
{
UpdateVirtualTable(parse, tabList, table, changes, rowidExpr, xrefs, where_, onError);
where_ = null;
tabList = null;
goto update_cleanup;
}
#endif
// Register Allocations
int regRowCount = 0; // A count of rows changed
int regOldRowid; // The old rowid
int regNewRowid; // The new rowid
int regNew;
int regOld = 0;
int regRowSet = 0; // Rowset of rows to be updated
// Allocate required registers.
regOldRowid = regNewRowid = ++parse.Mems;
if (trigger != null || hasFK)
{
regOld = parse.Mems + 1;
parse.Mems += table.Cols.length;
}
if (chngRowid || trigger != null || hasFK)
regNewRowid = ++parse.Mems;
regNew = parse.Mems + 1;
parse.Mems += table.Cols.length;
// Start the view context.
if (isView)
Auth.ContextPush(parse, sContext, table.Name);
// If we are trying to update a view, realize that view into a ephemeral table.
#if !OMIT_VIEW && !OMIT_TRIGGER
if (isView)
sqlite3MaterializeView(parse, table, where_, curId);
#endif
// Resolve the column names in all the expressions in the WHERE clause.
if (sqlite3ResolveExprNames(sNC, ref where_) != 0)
goto update_cleanup;
// Begin the database scan
v.AddOp2(OP.Null, 0, regOldRowid);
ExprList dummy = null;
WhereInfo winfo = Where.Begin(parse, tabList, where_, ref dummy, WHERE.ONEPASS_DESIRED); // Information about the WHERE clause
if (winfo == null) goto update_cleanup;
bool okOnePass = winfo.OkOnePass; // True for one-pass algorithm without the FIFO
// Remember the rowid of every item to be updated.
v.AddOp2(OP.Rowid, curId, regOldRowid);
if (!okOnePass)
v.AddOp2(OP.RowSetAdd, regRowSet, regOldRowid);
// End the database scan loop.
Where.End(winfo);
// Initialize the count of updated rows
if ((ctx.Flags & Context.FLAG.CountRows) != 0 && parse.TriggerTab == null)
{
regRowCount = ++parse.Mems;
v.AddOp2(OP.Integer, 0, regRowCount);
}
bool openAll = false; // True if all indices need to be opened
if (!isView)
{
// Open every index that needs updating. Note that if any index could potentially invoke a REPLACE conflict resolution
// action, then we need to open all indices because we might need to be deleting some records.
if (!okOnePass) sqlite3OpenTable(parse, curId, db, table, OP.OpenWrite);
if (onError == OE.Replace)
openAll = true;
else
{
openAll = false;
for (idx = table.Index; idx != null; idx = idx.Next)
{
if (idx.OnError == OE.Replace)
{
openAll = true;
break;
}
}
}
for (i = 0, idx = table.Index; idx != null; idx = idx.Next, i++)
{
if (openAll || regIdxs[i] > 0)
{
KeyInfo key = sqlite3IndexKeyinfo(parse, idx);
v.AddOp4(OP.OpenWrite, curId + i + 1, idx.Id, db, key, Vdbe.P4T.KEYINFO_HANDOFF);
Debug.Assert(parse.Tabs > curId + i + 1);
}
}
}
// Top of the update loop
int addr = 0; // VDBE instruction address of the start of the loop
if (okOnePass)
{
int a1 = v.AddOp1(OP.NotNull, regOldRowid);
addr = v.AddOp0(OP.Goto);
v.JumpHere(a1);
}
else
addr = v.AddOp3(OP.RowSetRead, regRowSet, 0, regOldRowid);
// Make cursor iCur point to the record that is being updated. If this record does not exist for some reason (deleted by a trigger,
// for example, then jump to the next iteration of the RowSet loop.
v.AddOp3(OP.NotExists, curId, addr, regOldRowid);
// If the record number will change, set register regNewRowid to contain the new value. If the record number is not being modified,
// then regNewRowid is the same register as regOldRowid, which is already populated.
Debug.Assert(chngRowid || trigger != null || hasFK || regOldRowid == regNewRowid);
if (chngRowid)
{
Expr.Code(parse, rowidExpr, regNewRowid);
v.AddOp1(OP.MustBeInt, regNewRowid);
}
// If there are triggers on this table, populate an array of registers with the required old.* column data.
if (hasFK || trigger != null)
{
uint oldmask = (hasFK ? sqlite3FkOldmask(parse, table) : 0);
oldmask |= sqlite3TriggerColmask(parse, trigger, changes, 0, TRIGGER_BEFORE | TRIGGER_AFTER, table, onError);
for (i = 0; i < table.Cols.length; i++)
{
if (xrefs[i] < 0 || oldmask == 0xffffffff || (i < 32 && 0 != (oldmask & (1 << i))))
Expr.CodeGetColumnOfTable(v, table, curId, i, regOld + i);
else
v.AddOp2(OP.Null, 0, regOld + i);
}
if (!chngRowid)
v.AddOp2(OP.Copy, regOldRowid, regNewRowid);
}
// Populate the array of registers beginning at regNew with the new row data. This array is used to check constaints, create the new
// table and index records, and as the values for any new.* references made by triggers.
//
// If there are one or more BEFORE triggers, then do not populate the registers associated with columns that are (a) not modified by
// this UPDATE statement and (b) not accessed by new.* references. The values for registers not modified by the UPDATE must be reloaded from
// the database after the BEFORE triggers are fired anyway (as the trigger may have modified them). So not loading those that are not going to
// be used eliminates some redundant opcodes.
int newmask = (int)sqlite3TriggerColmask(parse, trigger, changes, 1, TRIGGER_BEFORE, table, onError); // Mask of NEW.* columns accessed by BEFORE triggers
for (i = 0; i < table.Cols.length; i++)
{
if (i == table.PKey)
{
//v.AddOp2(OP.Null, 0, regNew + i);
}
else
{
j = xrefs[i];
if (j >= 0)
Expr.Code(parse, changes.Ids[j].Expr, regNew + i);
else if ((tmask & TRIGGER_BEFORE) == 0 || i > 31 || (newmask & (1 << i)) != 0)
{
// This branch loads the value of a column that will not be changed into a register. This is done if there are no BEFORE triggers, or
// if there are one or more BEFORE triggers that use this value via a new.* reference in a trigger program.
C.ASSERTCOVERAGE(i == 31);
C.ASSERTCOVERAGE(i == 32);
v.AddOp3(OP.Column, curId, i, regNew + i);
v.ColumnDefault(table, i, regNew + i);
}
}
}
// Fire any BEFORE UPDATE triggers. This happens before constraints are verified. One could argue that this is wrong.
if ((tmask & TRIGGER_BEFORE) != 0)
{
v.AddOp2(OP.Affinity, regNew, table.Cols.length);
sqlite3TableAffinityStr(v, table);
sqlite3CodeRowTrigger(parse, trigger, TK.UPDATE, changes, TRIGGER_BEFORE, table, regOldRowid, onError, addr);
// The row-trigger may have deleted the row being updated. In this case, jump to the next row. No updates or AFTER triggers are
// required. This behavior - what happens when the row being updated is deleted or renamed by a BEFORE trigger - is left undefined in the documentation.
v.AddOp3(OP.NotExists, curId, addr, regOldRowid);
// If it did not delete it, the row-trigger may still have modified some of the columns of the row being updated. Load the values for
// all columns not modified by the update statement into their registers in case this has happened.
for (i = 0; i < table.Cols.length; i++)
if (xrefs[i] < 0 && i != table.PKey)
{
v.AddOp3(OP.Column, curId, i, regNew + i);
v.ColumnDefault(table, i, regNew + i);
}
}
if (!isView)
{
// Do constraint checks.
int dummy2;
sqlite3GenerateConstraintChecks(parse, table, curId, regNewRowid, regIdxs, (chngRowid ? regOldRowid : 0), true, onError, addr, out dummy2);
// Do FK constraint checks.
if (hasFK)
sqlite3FkCheck(parse, table, regOldRowid, 0);
// Delete the index entries associated with the current record.
int j1 = v.AddOp3(OP.NotExists, curId, 0, regOldRowid); // Address of jump instruction
sqlite3GenerateRowIndexDelete(parse, table, curId, regIdxs);
// If changing the record number, delete the old record.
if (hasFK || chngRowid)
v.AddOp2(OP.Delete, curId, 0);
v.JumpHere(j1);
if (hasFK)
sqlite3FkCheck(parse, table, 0, regNewRowid);
// Insert the new index entries and the new record.
sqlite3CompleteInsertion(parse, table, curId, regNewRowid, regIdxs, true, false, false);
// Do any ON CASCADE, SET NULL or SET DEFAULT operations required to handle rows (possibly in other tables) that refer via a foreign key
// to the row just updated.
if (hasFK)
sqlite3FkActions(parse, table, changes, regOldRowid);
}
// Increment the row counter
if ((ctx.Flags & Context.FLAG.CountRows) != 0 && parse.TriggerTab == null)
v.AddOp2(OP.AddImm, regRowCount, 1);
sqlite3CodeRowTrigger(parse, trigger, TK.UPDATE, changes, TRIGGER_AFTER, table, regOldRowid, onError, addr);
// Repeat the above with the next record to be updated, until all record selected by the WHERE clause have been updated.
v.AddOp2(OP.Goto, 0, addr);
v.JumpHere(addr);
// Close all tables
Debug.Assert(regIdxs != null);
for (i = 0, idx = table.Index; idx != null; idx = idx.Next, i++)
if (openAll || regIdxs[i] > 0)
v.AddOp2(OP.Close, curId + i + 1, 0);
v.AddOp2(OP.Close, curId, 0);
// Update the sqlite_sequence table by storing the content of the maximum rowid counter values recorded while inserting into
// autoincrement tables.
if (parse.Nested == 0 && parse.TriggerTab == null)
sqlite3AutoincrementEnd(parse);
// Return the number of rows that were changed. If this routine is generating code because of a call to sqlite3NestedParse(), do not
// invoke the callback function.
if ((ctx.Flags & Context.FLAG.CountRows) != 0 && parse.TriggerTab == null && parse.Nested == 0)
{
v.AddOp2(OP.ResultRow, regRowCount, 1);
v.SetNumCols(1);
v.SetColName(0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
}
update_cleanup:
#if !OMIT_AUTHORIZATION
Auth.ContextPop(sContext);
#endif
C._tagfree(ctx, ref regIdxs);
C._tagfree(ctx, ref xrefs);
SrcList.Delete(ctx, ref tabList);
ExprList.Delete(ctx, ref changes);
Expr.Delete(ctx, ref where_);
return;
}
#if !OMIT_VIRTUALTABLE
static void UpdateVirtualTable(Parse parse, SrcList src, Table table, ExprList changes, Expr rowid, int[] xrefs, Expr where_, int onError)
{
int i;
Context ctx = parse.Ctx; // Database connection
VTable vtable = VTable.GetVTable(ctx, table);
SelectDest dest = new SelectDest();
// Construct the SELECT statement that will find the new values for all updated rows.
ExprList list = ExprList.Append(parse, 0, Expr.Expr(ctx, TK.ID, "_rowid_")); // The result set of the SELECT statement
if (rowid != null)
list = ExprList.Append(parse, list, Expr.Dup(ctx, rowid, 0));
Debug.Assert(table.PKey < 0);
for (i = 0; i < table.Cols.length; i++)
{
Expr expr = (xrefs[i] >= 0 ? Expr.Dup(ctx, changes.Ids[xrefs[i]].Expr, 0) : Expr.Expr(ctx, TK.ID, table.Cols[i].Name)); // Temporary expression
list = ExprList.Append(parse, list, expr);
}
Select select = Select.New(parse, list, src, where_, null, null, null, 0, null, null); // The SELECT statement
// Create the ephemeral table into which the update results will be stored.
Vdbe v = parse.V; // Virtual machine under construction
Debug.Assert(v != null);
int ephemTab = parse.Tabs++; // Table holding the result of the SELECT
v.AddOp2(OP.OpenEphemeral, ephemTab, table.Cols.length + 1 + (rowid != null ? 1 : 0));
v.ChangeP5(BTREE_UNORDERED);
// fill the ephemeral table
Select.DestInit(dest, SRT.Table, ephemTab);
Select.Select(parse, select, ref dest);
// Generate code to scan the ephemeral table and call VUpdate.
int regId = ++parse.Mems;// First register in set passed to OP_VUpdate
parse.Mems += table.Cols.length + 1;
int addr = v.AddOp2(OP.Rewind, ephemTab, 0); // Address of top of loop
v.AddOp3(OP.Column, ephemTab, 0, regId);
v.AddOp3(OP.Column, ephemTab, (rowid != null ? 1 : 0), regId + 1);
for (i = 0; i < table.nCol; i++)
v.AddOp3(OP.Column, ephemTab, i + 1 + (rowid != null ? 1 : 0), regId + 2 + i);
sqlite3VtabMakeWritable(parse, table);
v.AddOp4(OP_VUpdate, 0, table.Cols.length + 2, regId, vtable, P4_VTAB);
v.ChangeP5((byte)(onError == OE_Default ? OE_Abort : onError));
parse.MayAbort();
v.AddOp2(OP.Next, ephemTab, addr + 1);
v.JumpHere(addr);
v.AddOp2(OP.Close, ephemTab, 0);
// Cleanup
Select.Delete(ctx, ref select);
}
#endif
}
}
| |
namespace CRM.WebApi.InfrastructureModel.ApplicationManager
{
using Entities;
using Models.Request;
using Models.Response;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
public partial class ApplicationManager : IDisposable
{
private readonly CRMContext _database;
private readonly ParserProvider _parser;
public ApplicationManager()
{
_parser = new ParserProvider();
_database = new CRMContext();
_database.Configuration.LazyLoadingEnabled = false;
}
public async Task<List<ViewContactModel>> GetAllContactsAsync()
{
var list = await _database.Contacts.ToListAsync();
if (ReferenceEquals(list, null)) return null;
var data = new List<ViewContactModel>();
AutoMapper.Mapper.Map(list, data);
return data;
}
public async Task<bool> UpdateContactAsync(ViewContactModel model)
{
using (var transaction = _database.Database.BeginTransaction())
{
try
{
var original = await _database.Contacts.FirstOrDefaultAsync(p => p.GuID == model.GuID);
var replace = new Contact();
AutoMapper.Mapper.Map(model, replace);
replace.ContactId = original.ContactId;
replace.DateModified = DateTime.UtcNow;
_database.Entry(original).CurrentValues.SetValues(replace);
await _database.SaveChangesAsync();
transaction.Commit();
return true;
}
catch
{
transaction.Rollback();
throw;
}
}
}
public async Task<bool> AddContactAsync(ViewContactModel model)
{
var contact = new Contact();
AutoMapper.Mapper.Map(model, contact);
contact.GuID = Guid.NewGuid();
contact.DateInserted = DateTime.UtcNow;
using (var transaction = _database.Database.BeginTransaction())
{
try
{
_database.Contacts.Add(contact);
await _database.SaveChangesAsync();
transaction.Commit();
return true;
}
catch
{
transaction.Rollback();
throw;
}
}
}
public async Task<bool> DeleteContactAsync(Guid guid)
{
var cont = await _database.Contacts.FirstOrDefaultAsync(p => p.GuID == guid);
_database.Contacts.Remove(cont);
await _database.SaveChangesAsync();
return true;
}
public async Task<bool> DeleteContactsAsync(List<Guid> guids)
{
var list = new List<Contact>();
foreach (Guid guid in guids)
list.Add(await _database.Contacts.FirstOrDefaultAsync(p => p.GuID == guid));
_database.Contacts.RemoveRange(list);
await _database.SaveChangesAsync();
return true;
}
public async Task<int> PageCountAsync()
{
return await _database.Contacts.CountAsync() / 10 + 1;
}
#region FilterOrderPaging
public async Task<List<ViewContactModel>> FilterOrderByRequestAsync(RequestContact request)
{
if (ReferenceEquals(request, null)) return null;
ViewContactModel filter = request.FilterBy;
List<ViewContactModel> result = new List<ViewContactModel>();
try
{
if (filter.FullName != null)
result = await FilterSortAsync(request, FilterBy.Name);
if (filter.CompanyName != null)
{
result = await FilterSortAsync(request, FilterBy.Company);
if (filter.FullName != null)
result = await FilterSortAsync(request, FilterBy.NameCompany);
}
if (filter.Position != null)
{
result = await FilterSortAsync(request, FilterBy.Position);
if (filter.FullName != null)
result = await FilterSortAsync(request, FilterBy.NamePosition);
if (filter.CompanyName != null)
result = await FilterSortAsync(request, FilterBy.CompanyPosition);
if (filter.FullName != null && filter.CompanyName != null)
result = await FilterSortAsync(request, FilterBy.NameCompanyPosition);
}
if (filter.Country != null)
{
result = await FilterSortAsync(request, FilterBy.Country);
if (filter.FullName != null)
result = await FilterSortAsync(request, FilterBy.NameCountry);
if (filter.Position != null)
result = await FilterSortAsync(request, FilterBy.CountryPosition);
if (filter.FullName != null && filter.Position != null)
result = await FilterSortAsync(request, FilterBy.NamePositionCountry);
}
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task<List<ViewContactModel>> FilterSortAsync(RequestContact model, FilterBy filter)
{
var data = new List<Contact>();
var sortby = model.SortBy;
var filterby = model.FilterBy;
#region SWITCH
switch (filter)
{
case FilterBy.Name:
data = await
_database.Contacts
.Where(p => p.FullName == filterby.FullName)
.ToListAsync();
break;
case FilterBy.Company:
data = await
_database.Contacts
.Where(p => p.CompanyName == filterby.CompanyName)
.ToListAsync();
break;
case FilterBy.NameCompany:
data =
await
_database.Contacts.Where(
p => p.FullName == filterby.FullName && p.CompanyName == filterby.CompanyName)
.ToListAsync();
break;
case FilterBy.Position:
data = await _database.Contacts.Where(p => p.Position == filterby.Position).ToListAsync();
break;
case FilterBy.NamePosition:
data =
await
_database.Contacts.Where(
p => p.FullName == filterby.FullName && p.Position == filterby.Position).ToListAsync();
break;
case FilterBy.NameCompanyPosition:
data =
await
_database.Contacts.Where(
p =>
p.FullName == filterby.FullName && p.CompanyName == filterby.CompanyName &&
p.Position == filterby.Position).ToListAsync();
break;
case FilterBy.Country:
data = await _database.Contacts.Where(p => p.Country == filterby.Country).ToListAsync();
break;
case FilterBy.NameCountry:
data =
await
_database.Contacts.Where(
p => p.FullName == filterby.FullName && p.Country == filterby.Country).ToListAsync();
break;
case FilterBy.NameCompanyCountry:
data =
await
_database.Contacts.Where(
p =>
p.FullName == filterby.FullName && p.CompanyName == filterby.CompanyName &&
p.Country == filterby.Country).ToListAsync();
break;
case FilterBy.NameCompanyPositionCountry:
data =
await
_database.Contacts.Where(
p =>
p.FullName == filterby.FullName && p.CompanyName == filterby.CompanyName &&
p.Position == filterby.Position && p.Country == filterby.Country).ToListAsync();
break;
case FilterBy.NamePositionCountry:
data =
await
_database.Contacts.Where(
p =>
p.FullName == filterby.FullName && p.Position == filterby.Position &&
p.Country == filterby.Country).ToListAsync();
break;
case FilterBy.CountryPosition:
data =
await
_database.Contacts.Where(
p => p.Country == filterby.Country && p.Position == filterby.Position).ToListAsync();
break;
}
#endregion
#region PAGING
string first = "Start", second = "Count";
if (sortby.ContainsKey(first) && sortby.ContainsKey(second))
{
int start;
bool st = int.TryParse(sortby[first], out start);
int count;
bool end = int.TryParse(sortby[second], out count);
if (st && end) data = Paging(data, start, count);
}
#endregion
#region ORDERBY
if (sortby.ContainsKey("OrderBy"))
{
string orderby = sortby["OrderBy"];
if (orderby == "Ascending" || orderby == "0" || orderby == "Asc")
data = Sort(data, OrderBy.Ascending);
if (orderby == "Descending" || orderby == "1" || orderby == "Desc")
data = Sort(data, OrderBy.Descending);
}
#endregion
var list = new List<ViewContactModel>();
AutoMapper.Mapper.Map(data, list);
return list;
}
public List<Contact> Sort(List<Contact> contacts, OrderBy sortby)
{
List<Contact> result = new List<Contact>();
if (ReferenceEquals(contacts, null)) return null;
switch (sortby)
{
case OrderBy.Ascending:
result = contacts.OrderBy(p => p.ContactId).ToList();
break;
case OrderBy.Descending:
result = contacts.OrderByDescending(p => p.ContactId).ToList();
break;
}
return result;
}
public List<Contact> Paging(List<Contact> contacts, int skip, int count)
{
if (count < skip || count == 0) return null;
return contacts.Skip(skip).Take(count).ToList();
}
#endregion
public async Task AddToDatabaseFromBytes(byte[] bytes)
{
string path = System.Web.HttpContext.Current?.Request.MapPath("~//log");
using (var transaction = _database.Database.BeginTransaction())
{
try
{
List<Contact> contacts = _parser.GetContactsFromBytes(bytes, path);
contacts.ForEach(p => p.GuID = Guid.NewGuid());
_database.Contacts.AddRange(contacts);
await _database.SaveChangesAsync();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
public void Dispose()
{
_database.Dispose();
}
}
public enum FilterBy
{
Name,
Company,
NameCompany,
Position,
NamePosition,
CompanyPosition,
CountryPosition,
NameCompanyPosition,
Country,
NameCountry,
NamePositionCountry,
NameCompanyCountry,
NameCompanyPositionCountry,
DateInserted
}
public enum OrderBy
{
Ascending,
Descending
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryNullablePowerTests
{
#region Test methods
[Fact]
public static void CheckNullableBytePowerTest()
{
byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableBytePower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableSBytePowerTest()
{
sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSBytePower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableUShortPowerTest()
{
ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortPower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableShortPowerTest()
{
short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortPower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableUIntPowerTest()
{
uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntPower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableIntPowerTest()
{
int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntPower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableULongPowerTest()
{
ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongPower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableLongPowerTest()
{
long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongPower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableFloatPowerTest()
{
float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableFloatPower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableDoublePowerTest()
{
double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDoublePower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableDecimalPowerTest()
{
decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDecimalPower(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableCharPowerTest()
{
char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableCharPower(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableBytePower(byte? a, byte? b)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.Power(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerByte")
));
Func<byte?> f = e.Compile();
// compute with expression tree
byte? etResult = default(byte);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
byte? csResult = default(byte);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (byte?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableSBytePower(sbyte? a, sbyte? b)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.Power(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerSByte")
));
Func<sbyte?> f = e.Compile();
// compute with expression tree
sbyte? etResult = default(sbyte);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
sbyte? csResult = default(sbyte);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (sbyte?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableUShortPower(ushort? a, ushort? b)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Power(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerUShort")
));
Func<ushort?> f = e.Compile();
// compute with expression tree
ushort? etResult = default(ushort);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
ushort? csResult = default(ushort);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (ushort?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableShortPower(short? a, short? b)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Power(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerShort")
));
Func<short?> f = e.Compile();
// compute with expression tree
short? etResult = default(short);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
short? csResult = default(short);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (short?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableUIntPower(uint? a, uint? b)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Power(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerUInt")
));
Func<uint?> f = e.Compile();
// compute with expression tree
uint? etResult = default(uint);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
uint? csResult = default(uint);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (uint?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableIntPower(int? a, int? b)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Power(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerInt")
));
Func<int?> f = e.Compile();
// compute with expression tree
int? etResult = default(int);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
int? csResult = default(int);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (int?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableULongPower(ulong? a, ulong? b)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Power(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerULong")
));
Func<ulong?> f = e.Compile();
// compute with expression tree
ulong? etResult = default(ulong);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
ulong? csResult = default(ulong);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (ulong?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableLongPower(long? a, long? b)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Power(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerLong")
));
Func<long?> f = e.Compile();
// compute with expression tree
long? etResult = default(long);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
long? csResult = default(long);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (long?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableFloatPower(float? a, float? b)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Power(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerFloat")
));
Func<float?> f = e.Compile();
// compute with expression tree
float? etResult = default(float);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
float? csResult = default(float);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (float?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableDoublePower(double? a, double? b)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Power(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerDouble")
));
Func<double?> f = e.Compile();
// compute with expression tree
double? etResult = default(double);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
double? csResult = default(double);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (double?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableDecimalPower(decimal? a, decimal? b)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Power(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerDecimal")
));
Func<decimal?> f = e.Compile();
// compute with expression tree
decimal? etResult = default(decimal);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
decimal? csResult = default(decimal);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (decimal?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableCharPower(char? a, char? b)
{
Expression<Func<char?>> e =
Expression.Lambda<Func<char?>>(
Expression.Power(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerChar")
));
Func<char?> f = e.Compile();
// compute with expression tree
char? etResult = default(char);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
char? csResult = default(char);
Exception csException = null;
if (a == null || b == null)
{
csResult = null;
}
else
{
try
{
csResult = (char?)Math.Pow((double)a, (double)b);
}
catch (Exception ex)
{
csException = ex;
}
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
#endregion
#region Helper methods
public static byte PowerByte(byte a, byte b)
{
return (byte)Math.Pow((double)a, (double)b);
}
public static sbyte PowerSByte(sbyte a, sbyte b)
{
return (sbyte)Math.Pow((double)a, (double)b);
}
public static ushort PowerUShort(ushort a, ushort b)
{
return (ushort)Math.Pow((double)a, (double)b);
}
public static short PowerShort(short a, short b)
{
return (short)Math.Pow((double)a, (double)b);
}
public static uint PowerUInt(uint a, uint b)
{
return (uint)Math.Pow((double)a, (double)b);
}
public static int PowerInt(int a, int b)
{
return (int)Math.Pow((double)a, (double)b);
}
public static ulong PowerULong(ulong a, ulong b)
{
return (ulong)Math.Pow((double)a, (double)b);
}
public static long PowerLong(long a, long b)
{
return (long)Math.Pow((double)a, (double)b);
}
public static float PowerFloat(float a, float b)
{
return (float)Math.Pow((double)a, (double)b);
}
public static double PowerDouble(double a, double b)
{
return (double)Math.Pow((double)a, (double)b);
}
public static decimal PowerDecimal(decimal a, decimal b)
{
return (decimal)Math.Pow((double)a, (double)b);
}
public static char PowerChar(char a, char b)
{
return (char)Math.Pow((double)a, (double)b);
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: operations/arrival_letter_template.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Operations {
/// <summary>Holder for reflection information generated from operations/arrival_letter_template.proto</summary>
public static partial class ArrivalLetterTemplateReflection {
#region Descriptor
/// <summary>File descriptor for operations/arrival_letter_template.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ArrivalLetterTemplateReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CihvcGVyYXRpb25zL2Fycml2YWxfbGV0dGVyX3RlbXBsYXRlLnByb3RvEhZo",
"b2xtcy50eXBlcy5vcGVyYXRpb25zGhRwcmltaXRpdmUvdXVpZC5wcm90byKD",
"AQoVQXJyaXZhbExldHRlclRlbXBsYXRlEi4KCWVudGl0eV9pZBgBIAEoCzIb",
"LmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5VdWlkEg0KBXRpdGxlGAIgASgJEhQK",
"DHJ0Zl90ZW1wbGF0ZRgDIAEoCRIVCg1odG1sX3RlbXBsYXRlGAQgASgJQiVa",
"Cm9wZXJhdGlvbnOqAhZIT0xNUy5UeXBlcy5PcGVyYXRpb25zYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.UuidReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.ArrivalLetterTemplate), global::HOLMS.Types.Operations.ArrivalLetterTemplate.Parser, new[]{ "EntityId", "Title", "RtfTemplate", "HtmlTemplate" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ArrivalLetterTemplate : pb::IMessage<ArrivalLetterTemplate> {
private static readonly pb::MessageParser<ArrivalLetterTemplate> _parser = new pb::MessageParser<ArrivalLetterTemplate>(() => new ArrivalLetterTemplate());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ArrivalLetterTemplate> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.ArrivalLetterTemplateReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrivalLetterTemplate() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrivalLetterTemplate(ArrivalLetterTemplate other) : this() {
EntityId = other.entityId_ != null ? other.EntityId.Clone() : null;
title_ = other.title_;
rtfTemplate_ = other.rtfTemplate_;
htmlTemplate_ = other.htmlTemplate_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrivalLetterTemplate Clone() {
return new ArrivalLetterTemplate(this);
}
/// <summary>Field number for the "entity_id" field.</summary>
public const int EntityIdFieldNumber = 1;
private global::HOLMS.Types.Primitive.Uuid entityId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.Uuid EntityId {
get { return entityId_; }
set {
entityId_ = value;
}
}
/// <summary>Field number for the "title" field.</summary>
public const int TitleFieldNumber = 2;
private string title_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Title {
get { return title_; }
set {
title_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "rtf_template" field.</summary>
public const int RtfTemplateFieldNumber = 3;
private string rtfTemplate_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string RtfTemplate {
get { return rtfTemplate_; }
set {
rtfTemplate_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "html_template" field.</summary>
public const int HtmlTemplateFieldNumber = 4;
private string htmlTemplate_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string HtmlTemplate {
get { return htmlTemplate_; }
set {
htmlTemplate_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ArrivalLetterTemplate);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ArrivalLetterTemplate other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EntityId, other.EntityId)) return false;
if (Title != other.Title) return false;
if (RtfTemplate != other.RtfTemplate) return false;
if (HtmlTemplate != other.HtmlTemplate) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (entityId_ != null) hash ^= EntityId.GetHashCode();
if (Title.Length != 0) hash ^= Title.GetHashCode();
if (RtfTemplate.Length != 0) hash ^= RtfTemplate.GetHashCode();
if (HtmlTemplate.Length != 0) hash ^= HtmlTemplate.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (entityId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(EntityId);
}
if (Title.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Title);
}
if (RtfTemplate.Length != 0) {
output.WriteRawTag(26);
output.WriteString(RtfTemplate);
}
if (HtmlTemplate.Length != 0) {
output.WriteRawTag(34);
output.WriteString(HtmlTemplate);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (entityId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId);
}
if (Title.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Title);
}
if (RtfTemplate.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(RtfTemplate);
}
if (HtmlTemplate.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(HtmlTemplate);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ArrivalLetterTemplate other) {
if (other == null) {
return;
}
if (other.entityId_ != null) {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Primitive.Uuid();
}
EntityId.MergeFrom(other.EntityId);
}
if (other.Title.Length != 0) {
Title = other.Title;
}
if (other.RtfTemplate.Length != 0) {
RtfTemplate = other.RtfTemplate;
}
if (other.HtmlTemplate.Length != 0) {
HtmlTemplate = other.HtmlTemplate;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Primitive.Uuid();
}
input.ReadMessage(entityId_);
break;
}
case 18: {
Title = input.ReadString();
break;
}
case 26: {
RtfTemplate = input.ReadString();
break;
}
case 34: {
HtmlTemplate = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using WbemUtilities_v1;
using WbemClient_v1;
using System.Globalization;
using System.Reflection;
using System.ComponentModel.Design.Serialization;
namespace System.Management
{
/// <summary>
/// <para>Provides a wrapper for parsing and building paths to WMI objects.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample displays all properties in a ManagementPath object.
///
/// class Sample_ManagementPath
/// {
/// public static int Main(string[] args) {
/// ManagementPath path = new ManagementPath( "\\\\MyServer\\MyNamespace:Win32_logicaldisk='c:'");
///
/// // Results of full path parsing
/// Console.WriteLine("Path: " + path.Path);
/// Console.WriteLine("RelativePath: " + path.RelativePath);
/// Console.WriteLine("Server: " + path.Server);
/// Console.WriteLine("NamespacePath: " + path.NamespacePath);
/// Console.WriteLine("ClassName: " + path.ClassName);
/// Console.WriteLine("IsClass: " + path.IsClass);
/// Console.WriteLine("IsInstance: " + path.IsInstance);
/// Console.WriteLine("IsSingleton: " + path.IsSingleton);
///
/// // Change a portion of the full path
/// path.Server = "AnotherServer";
/// Console.WriteLine("New Path: " + path.Path);
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// 'This sample displays all properties in a ManagementPath object.
/// Class Sample_ManagementPath Overloads
/// Public Shared Function Main(args() As String) As Integer
/// Dim path As _ New
/// ManagementPath("\\MyServer\MyNamespace:Win32_LogicalDisk='c:'")
///
/// ' Results of full path parsing
/// Console.WriteLine("Path: " & path.Path)
/// Console.WriteLine("RelativePath: " & path.RelativePath)
/// Console.WriteLine("Server: " & path.Server)
/// Console.WriteLine("NamespacePath: " & path.NamespacePath)
/// Console.WriteLine("ClassName: " & path.ClassName)
/// Console.WriteLine("IsClass: " & path.IsClass)
/// Console.WriteLine("IsInstance: " & path.IsInstance)
/// Console.WriteLine("IsSingleton: " & path.IsSingleton)
///
/// ' Change a portion of the full path
/// path.Server= "AnotherServer"
/// Console.WriteLine("New Path: " & path.Path)
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
[TypeConverter(typeof(ManagementPathConverter ))]
public class ManagementPath : ICloneable
{
private static ManagementPath defaultPath = new ManagementPath("//./root/cimv2");
//Used to minimize the cases in which new wbemPath (WMI object path parser) objects need to be constructed
//This is done for performance reasons.
private bool isWbemPathShared = false;
internal event IdentifierChangedEventHandler IdentifierChanged;
//Fires IdentifierChanged event
private void FireIdentifierChanged()
{
if (IdentifierChanged != null)
IdentifierChanged(this, null);
}
//internal factory
/// <summary>
/// Internal static "factory" method for making a new ManagementPath
/// from the system property of a WMI object
/// </summary>
/// <param name="wbemObject">The WMI object whose __PATH property will
/// be used to supply the returned object</param>
internal static string GetManagementPath (
IWbemClassObjectFreeThreaded wbemObject)
{
string path = null;
int status = (int)ManagementStatus.Failed;
if (null != wbemObject)
{
int dummy1 = 0, dummy2 = 0;
object val = null;
status = wbemObject.Get_ ("__PATH", 0, ref val, ref dummy1, ref dummy2);
if ((status < 0) || (val == System.DBNull.Value))
{
//try to get the relpath instead
status = wbemObject.Get_ ("__RELPATH", 0, ref val, ref dummy1, ref dummy2);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
}
if (System.DBNull.Value == val)
path = null;
else
path = (string)val;
}
return path;
}
//Used internally to check whether a string passed in as a namespace is indeed syntactically correct
//for a namespace (e.g. either has "\" or "/" in it or is the special case of "root")
//This doesn't check for the existance of that namespace, nor does it guarrantee correctness.
internal static bool IsValidNamespaceSyntax(string nsPath)
{
if (nsPath.Length != 0)
{
// Any path separators present?
char[] pathSeparators = { '\\', '/' };
if (nsPath.IndexOfAny(pathSeparators) == -1)
{
// No separators. The only valid path is "root".
if (String.Compare("root", nsPath, StringComparison.OrdinalIgnoreCase) != 0)
return false;
}
}
return true;
}
internal static ManagementPath _Clone(ManagementPath path)
{
return ManagementPath._Clone(path, null);
}
internal static ManagementPath _Clone(ManagementPath path, IdentifierChangedEventHandler handler)
{
ManagementPath pathTmp = new ManagementPath();
// Wire up change handler chain. Use supplied handler, if specified;
// otherwise, default to that of the path argument.
if (handler != null)
pathTmp.IdentifierChanged = handler;
// Assign ManagementPath IWbemPath to this.wmiPath.
// Optimization for performance : As long as the path is only read, we share this interface.
// On the first write, a private copy will be needed;
// isWbemPathShared signals ManagementPath to create such a copy at write-time.
if (path != null && path.wmiPath != null)
{
pathTmp.wmiPath = path.wmiPath;
pathTmp.isWbemPathShared = path.isWbemPathShared = true;
}
return pathTmp;
}
/// <overload>
/// Initializes a new instance
/// of the <see cref='System.Management.ManagementPath'/> class.
/// </overload>
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementPath'/> class that is empty. This is the default constructor.</para>
/// </summary>
public ManagementPath () : this ((string) null) {}
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementPath'/> class for the given path.</para>
/// </summary>
/// <param name='path'> The object path. </param>
public ManagementPath(string path)
{
if ((null != path) && (0 < path.Length))
wmiPath = CreateWbemPath(path);
}
/// <summary>
/// <para>Returns the full object path as the string representation.</para>
/// </summary>
/// <returns>
/// A string containing the full object
/// path represented by this object. This value is equivalent to the value of the
/// <see cref='System.Management.ManagementPath.Path'/> property.
/// </returns>
public override string ToString ()
{
return this.Path;
}
/// <summary>
/// <para>Returns a copy of the <see cref='System.Management.ManagementPath'/>.</para>
/// </summary>
/// <returns>
/// The cloned object.
/// </returns>
public ManagementPath Clone ()
{
return new ManagementPath (Path);
}
/// <summary>
/// Standard Clone returns a copy of this ManagementPath as a generic "Object" type
/// </summary>
/// <returns>
/// The cloned object.
/// </returns>
object ICloneable.Clone ()
{
return Clone ();
}
/// <summary>
/// <para>Gets or sets the default scope path used when no scope is specified.
/// The default scope is /-/ \\.\root\cimv2, and can be changed by setting this property.</para>
/// </summary>
/// <value>
/// <para>By default the scope value is /-/ \\.\root\cimv2, or a different scope path if
/// the default was changed.</para>
/// </value>
public static ManagementPath DefaultPath
{
get { return ManagementPath.defaultPath; }
set { ManagementPath.defaultPath = value; }
}
//private members
private IWbemPath wmiPath;
private IWbemPath CreateWbemPath(string path)
{
IWbemPath wbemPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath));//new WbemDefPath();
SetWbemPath(wbemPath, path);
return wbemPath;
}
private void SetWbemPath(string path)
{
// Test/utilize isWbemPathShared *only* on public + internal members!
if (wmiPath == null)
wmiPath = CreateWbemPath(path);
else
SetWbemPath(wmiPath, path);
}
private static void SetWbemPath(IWbemPath wbemPath, string path)
{
if (null != wbemPath)
{
uint flags = (uint) tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_CREATE_ACCEPT_ALL;
//For now we have to special-case the "root" namespace -
// this is because in the case of "root", the path parser cannot tell whether
// this is a namespace name or a class name
//
if (String.Compare(path, "root", StringComparison.OrdinalIgnoreCase) == 0)
flags = flags | (uint) tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_TREAT_SINGLE_IDENT_AS_NS;
int status = wbemPath.SetText_(flags, path);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
}
}
private string GetWbemPath()
{
return GetWbemPath(this.wmiPath);
}
private static string GetWbemPath(IWbemPath wbemPath)
{
String pathStr = String.Empty;
if (null != wbemPath)
{
//
int flags = (int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_TOO;
uint nCount = 0;
int status = (int)ManagementStatus.NoError;
status = wbemPath.GetNamespaceCount_(out nCount);
if (status >= 0)
{
if (0 == nCount)
flags = (int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY;
// Get the space we need to reserve
uint bufLen = 0;
status = wbemPath.GetText_(flags, ref bufLen, null);
if (status >= 0 && 0 < bufLen)
{
pathStr = new String ('0', (int) bufLen-1);
status = wbemPath.GetText_(flags, ref bufLen, pathStr);
}
}
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_PARAMETER)
{
// Interpret as unspecified - return ""
}
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
}
return pathStr;
}
private void ClearKeys (bool setAsSingleton)
{
// Test/utilize isWbemPathShared *only* on public + internal members!
int status = (int)ManagementStatus.NoError;
try
{
if (null != wmiPath)
{
IWbemPathKeyList keyList = null;
status = wmiPath.GetKeyList_(out keyList);
if (null != keyList)
{
status = keyList.RemoveAllKeys_(0);
if ((status & 0x80000000) == 0)
{
sbyte bSingleton = (setAsSingleton) ? (sbyte)(-1) : (sbyte)0;
status = keyList.MakeSingleton_(bSingleton);
FireIdentifierChanged (); //
}
}
}
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status);
}
}
internal bool IsEmpty
{
get
{
return (Path.Length == 0 ) ;
}
}
//
// Methods
//
/// <summary>
/// <para> Sets the path as a new class path. This means that the path must have
/// a class name but not key values.</para>
/// </summary>
public void SetAsClass ()
{
if (IsClass || IsInstance)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
if (isWbemPathShared)
{
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
ClearKeys (false);
}
else
throw new ManagementException (ManagementStatus.InvalidOperation, null, null);
}
/// <summary>
/// <para> Sets the path as a new singleton object path. This means that it is a path to an instance but
/// there are no key values.</para>
/// </summary>
public void SetAsSingleton ()
{
if (IsClass || IsInstance)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
if (isWbemPathShared)
{
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
ClearKeys (true);
}
else
throw new ManagementException (ManagementStatus.InvalidOperation, null, null);
}
//
// Properties
//
/// <summary>
/// <para> Gets or sets the string representation of the full path in the object.</para>
/// </summary>
/// <value>
/// <para>A string containing the full path
/// represented in this object.</para>
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string Path
{
get
{
return this.GetWbemPath();
}
set
{
try
{
// Before overwriting, check it's OK
// Note, we've never done such validation, should we?
//
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
if (isWbemPathShared)
{
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
this.SetWbemPath(value);
}
catch
{
throw new ArgumentOutOfRangeException ("value");
}
FireIdentifierChanged();
}
}
/// <summary>
/// <para> Gets or sets the relative path: class name and keys only.</para>
/// </summary>
/// <value>
/// A string containing the relative
/// path (not including the server and namespace portions) represented in this
/// object.
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string RelativePath
{
get
{
String pathStr = String.Empty;
if (null != wmiPath)
{
// Get the space we need to reserve
uint bufLen = 0;
int status = wmiPath.GetText_(
(int) tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY,
ref bufLen,
null);
if (status >= 0 && 0 < bufLen)
{
pathStr = new String ('0', (int) bufLen-1);
status = wmiPath.GetText_(
(int) tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY,
ref bufLen,
pathStr);
}
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_PARAMETER)
{
// Interpret as unspecified - return ""
}
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
}
return pathStr;
}
set
{
try
{
// No need for isWbemPathShared here since internal SetRelativePath
// always creates a new copy.
SetRelativePath (value);
}
catch (COMException)
{
throw new ArgumentOutOfRangeException ("value");
}
FireIdentifierChanged();
}
}
internal void SetRelativePath (string relPath)
{
// No need for isWbemPathShared here since internal SetRelativePath
// always creates a new copy.
ManagementPath newPath = new ManagementPath (relPath);
newPath.NamespacePath = this.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
newPath.Server = this.Server;
wmiPath = newPath.wmiPath;
}
//Used to update the relative path when the user changes any key properties
internal void UpdateRelativePath(string relPath)
{
if (relPath == null)
return;
//Get the server & namespace part from the existing path, and concatenate the given relPath.
//NOTE : we need to do this because IWbemPath doesn't have a function to set the relative path alone...
string newPath = String.Empty;
string nsPath = this.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
if (nsPath.Length>0 )
newPath = String.Concat(nsPath, ":", relPath);
else
newPath = relPath;
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
if (isWbemPathShared)
{
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
this.SetWbemPath(newPath);
}
/// <summary>
/// <para>Gets or sets the server part of the path.</para>
/// </summary>
/// <value>
/// A string containing the server name
/// from the path represented in this object.
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string Server
{
get
{
String pathStr = String.Empty;
if (null != wmiPath)
{
uint uLen = 0;
int status = wmiPath.GetServer_(ref uLen, null);
if (status >= 0 && 0 < uLen)
{
pathStr = new String ('0', (int) uLen-1);
status = wmiPath.GetServer_(ref uLen, pathStr);
}
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_NOT_AVAILABLE)
{
// Interpret as unspecified - return ""
}
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
}
return pathStr;
}
set
{
String oldValue = Server;
// Only set if changed
if (0 != String.Compare(oldValue,value,StringComparison.OrdinalIgnoreCase))
{
if (null == wmiPath)
wmiPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath));//new WbemDefPath ();
else if (isWbemPathShared)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
int status = wmiPath.SetServer_(value);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
FireIdentifierChanged();
}
}
}
internal string SetNamespacePath(string nsPath, out bool bChange)
{
int status = (int)ManagementStatus.NoError;
string nsOrg = null;
string nsNew = null;
IWbemPath wmiPathTmp = null;
bChange = false;
Debug.Assert(nsPath != null);
//Do some validation on the path to make sure it is a valid namespace path (at least syntactically)
if (!IsValidNamespaceSyntax(nsPath))
ManagementException.ThrowWithExtendedInfo((ManagementStatus)tag_WBEMSTATUS.WBEM_E_INVALID_NAMESPACE);
wmiPathTmp = CreateWbemPath(nsPath);
if (wmiPath == null)
wmiPath = this.CreateWbemPath("");
else if (isWbemPathShared)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
nsOrg = GetNamespacePath(wmiPath,
(int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_NAMESPACE_ONLY);
nsNew = GetNamespacePath(wmiPathTmp,
(int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_NAMESPACE_ONLY);
if (String.Compare(nsOrg, nsNew, StringComparison.OrdinalIgnoreCase) != 0)
{
wmiPath.RemoveAllNamespaces_(); // Out with the old... Ignore status code.
// Add the new ones in
bChange = true; // Now dirty from above.
uint nCount = 0;
status = wmiPathTmp.GetNamespaceCount_(out nCount);
if (status >= 0)
{
for (uint i = 0; i < nCount; i++)
{
uint uLen = 0;
status = wmiPathTmp.GetNamespaceAt_(i, ref uLen, null);
if (status >= 0)
{
string nSpace = new String('0', (int) uLen-1);
status = wmiPathTmp.GetNamespaceAt_(i, ref uLen, nSpace);
if (status >= 0)
{
status = wmiPath.SetNamespaceAt_(i, nSpace);
if (status < 0)
break;
}
else
break;
}
else
break;
}
}
}
else {;} // Continue on. Could have different server name, same ns specified.
//
// Update Server property if specified in the namespace.
// eg: "\\MyServer\root\cimv2".
//
if (status >= 0 && nsPath.Length > 1 &&
(nsPath[0] == '\\' && nsPath[1] == '\\' ||
nsPath[0] == '/' && nsPath[1] == '/'))
{
uint uLen = 0;
status = wmiPathTmp.GetServer_(ref uLen, null);
if (status >= 0 && uLen > 0)
{
string serverNew = new String ('0', (int) uLen-1);
status = wmiPathTmp.GetServer_(ref uLen, serverNew);
if (status >= 0)
{
// Compare server name on this object, if specified, to the caller's.
// Update this object if different or unspecified.
uLen = 0;
status = wmiPath.GetServer_(ref uLen, null); // NB: Cannot use property get since it may throw.
if (status >= 0)
{
string serverOrg = new String('0', (int)uLen-1);
status = wmiPath.GetServer_(ref uLen, serverOrg);
if (status >= 0 && String.Compare(serverOrg, serverNew, StringComparison.OrdinalIgnoreCase) != 0)
status = wmiPath.SetServer_(serverNew);
}
else if (status == (int)tag_WBEMSTATUS.WBEM_E_NOT_AVAILABLE)
{
status = wmiPath.SetServer_(serverNew);
if (status >= 0)
bChange = true;
}
}
}
else if (status == (int)tag_WBEMSTATUS.WBEM_E_NOT_AVAILABLE) // No caller-supplied server name;
status = (int)ManagementStatus.NoError; // Ignore error.
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
return nsNew;
}
internal string GetNamespacePath(int flags)
{
return GetNamespacePath(wmiPath, flags);
}
internal static string GetNamespacePath(IWbemPath wbemPath, int flags)
{
string pathStr = String.Empty;
if (null != wbemPath)
{
//
uint nCount = 0;
int status = (int)ManagementStatus.NoError;
status = wbemPath.GetNamespaceCount_(out nCount);
if (status >= 0 && nCount > 0)
{
// Get the space we need to reserve
uint bufLen = 0;
status = wbemPath.GetText_(flags, ref bufLen, null);
if (status >= 0 && bufLen > 0)
{
pathStr = new String ('0', (int) bufLen-1);
status = wbemPath.GetText_(flags, ref bufLen, pathStr);
}
}
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_PARAMETER)
{
// Interpret as unspecified - return ""
}
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
}
return pathStr;
}
/// <summary>
/// <para>Gets or sets the namespace part of the path. Note that this does not include
/// the server name, which can be retrieved separately.</para>
/// </summary>
/// <value>
/// A string containing the namespace
/// portion of the path represented in this object.
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string NamespacePath
{
get
{
return GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_NAMESPACE_ONLY);
}
set
{
bool bChange = false;
try
{
// isWbemPathShared handled in internal SetNamespacePath.
SetNamespacePath(value, out bChange);
}
catch (COMException)
{
throw new ArgumentOutOfRangeException ("value");
}
if (bChange)
FireIdentifierChanged();
}
}
/// <summary>
/// Gets or sets the class portion of the path.
/// </summary>
/// <value>
/// A string containing the name of the
/// class.
/// </value>
[RefreshProperties(RefreshProperties.All)]
public string ClassName
{
get
{
return internalClassName;
}
set
{
String oldValue = ClassName;
// Only set if changed
if (0 != String.Compare(oldValue,value,StringComparison.OrdinalIgnoreCase))
{
// isWbemPathShared handled in internal className property accessor.
internalClassName = value;
FireIdentifierChanged();
}
}
}
internal string internalClassName
{
get
{
String pathStr = String.Empty;
int status = (int)ManagementStatus.NoError;
if (null != wmiPath)
{
uint bufLen = 0;
status = wmiPath.GetClassName_(ref bufLen, null);
if (status >= 0 && 0 < bufLen)
{
pathStr = new String ('0', (int) bufLen-1);
status = wmiPath.GetClassName_(ref bufLen, pathStr);
if (status < 0)
pathStr = String.Empty;
}
}
return pathStr;
}
set
{
int status = (int)ManagementStatus.NoError;
if (wmiPath == null)
wmiPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath));//new WbemDefPath();
else if (isWbemPathShared)
{
// Check if this IWbemPath is shared among multiple managed objects.
// With this write, it will have to maintain its own copy.
wmiPath = CreateWbemPath(this.GetWbemPath());
isWbemPathShared = false;
}
try
{
status = wmiPath.SetClassName_(value);
}
catch (COMException)
{ //
throw new ArgumentOutOfRangeException ("value");
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether this is a class path.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if this is a class path; otherwise,
/// <see langword='false'/>.</para>
/// </value>
public bool IsClass
{
get
{
if (null == wmiPath)
return false;
ulong uInfo = 0;
int status = wmiPath.GetInfo_(0, out uInfo);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
return (0 != (uInfo & (ulong)tag_WBEM_PATH_STATUS_FLAG.WBEMPATH_INFO_IS_CLASS_REF));
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether this is an instance path.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if this is an instance path; otherwise,
/// <see langword='false'/>.</para>
/// </value>
public bool IsInstance
{
get
{
if (null == wmiPath)
return false;
ulong uInfo = 0;
int status = wmiPath.GetInfo_(0, out uInfo);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
return (0 != (uInfo & (ulong)tag_WBEM_PATH_STATUS_FLAG.WBEMPATH_INFO_IS_INST_REF));
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether this is a singleton instance path.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if this is a singleton instance path; otherwise,
/// <see langword='false'/>.</para>
/// </value>
public bool IsSingleton
{
get
{
if (null == wmiPath)
return false;
ulong uInfo = 0;
int status = wmiPath.GetInfo_(0, out uInfo);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status);
}
return (0 != (uInfo & (ulong)tag_WBEM_PATH_STATUS_FLAG.WBEMPATH_INFO_IS_SINGLETON));
}
}
}
/// <summary>
/// Converts a String to a ManagementPath
/// </summary>
class ManagementPathConverter : ExpandableObjectConverter
{
/// <summary>
/// Determines if this converter can convert an object in the given source type to the native type of the converter.
/// </summary>
/// <param name='context'>An ITypeDescriptorContext that provides a format context.</param>
/// <param name='sourceType'>A Type that represents the type you wish to convert from.</param>
/// <returns>
/// <para>true if this converter can perform the conversion; otherwise, false.</para>
/// </returns>
public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if ((sourceType == typeof(ManagementPath)))
{
return true;
}
return base.CanConvertFrom(context,sourceType);
}
/// <summary>
/// Gets a value indicating whether this converter can convert an object to the given destination type using the context.
/// </summary>
/// <param name='context'>An ITypeDescriptorContext that provides a format context.</param>
/// <param name='destinationType'>A Type that represents the type you wish to convert to.</param>
/// <returns>
/// <para>true if this converter can perform the conversion; otherwise, false.</para>
/// </returns>
public override Boolean CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if ((destinationType == typeof(InstanceDescriptor)))
{
return true;
}
return base.CanConvertTo(context,destinationType);
}
/// <summary>
/// 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.
/// </summary>
/// <param name='context'>An ITypeDescriptorContext that provides a format context.</param>
/// <param name='culture'>A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param>
/// <param name='value'>The Object to convert.</param>
/// <param name='destinationType'>The Type to convert the value parameter to.</param>
/// <returns>An Object that represents the converted value.</returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
if (value is ManagementPath && destinationType == typeof(InstanceDescriptor))
{
ManagementPath obj = ((ManagementPath)(value));
ConstructorInfo ctor = typeof(ManagementPath).GetConstructor(new Type[] {typeof(System.String)});
if (ctor != null)
{
return new InstanceDescriptor(ctor, new object[] {obj.Path});
}
}
return base.ConvertTo(context,culture,value,destinationType);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// A set of initialization methods for instances of <see cref="ImmutableDictionary{TKey, TValue}"/>.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public static class ImmutableDictionary
{
/// <summary>
/// Returns an empty collection.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <returns>The immutable collection.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>()
{
return ImmutableDictionary<TKey, TValue>.Empty;
}
/// <summary>
/// Returns an empty collection with the specified key comparer.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>
/// The immutable collection.
/// </returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>(IEqualityComparer<TKey> keyComparer)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer);
}
/// <summary>
/// Returns an empty collection with the specified comparers.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>
/// The immutable collection.
/// </returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableDictionary<TKey, TValue>.Empty.AddRange(items);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer).AddRange(items);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(items);
}
/// <summary>
/// Creates a new immutable dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <returns>The new builder.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>()
{
return Create<TKey, TValue>().ToBuilder();
}
/// <summary>
/// Creates a new immutable dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>The new builder.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IEqualityComparer<TKey> keyComparer)
{
return Create<TKey, TValue>(keyComparer).ToBuilder();
}
/// <summary>
/// Creates a new immutable dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>The new builder.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
return Create<TKey, TValue>(keyComparer, valueComparer).ToBuilder();
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <param name="valueComparer">The value comparer to use for the map.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(source, nameof(source));
Requires.NotNull(keySelector, nameof(keySelector));
Requires.NotNull(elementSelector, nameof(elementSelector));
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer)
.AddRange(source.Select(element => new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element))));
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IEqualityComparer<TKey> keyComparer)
{
return ToImmutableDictionary(source, keySelector, elementSelector, keyComparer, null);
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TSource> ToImmutableDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
return ToImmutableDictionary(source, keySelector, v => v, null, null);
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TSource> ToImmutableDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> keyComparer)
{
return ToImmutableDictionary(source, keySelector, v => v, keyComparer, null);
}
/// <summary>
/// Constructs an immutable dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector)
{
return ToImmutableDictionary(source, keySelector, elementSelector, null, null);
}
/// <summary>
/// Creates an immutable dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <param name="keyComparer">The key comparer to use when building the immutable map.</param>
/// <param name="valueComparer">The value comparer to use for the immutable map.</param>
/// <returns>An immutable map.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(source, nameof(source));
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var existingDictionary = source as ImmutableDictionary<TKey, TValue>;
if (existingDictionary != null)
{
return existingDictionary.WithComparers(keyComparer, valueComparer);
}
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(source);
}
/// <summary>
/// Creates an immutable dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <param name="keyComparer">The key comparer to use when building the immutable map.</param>
/// <returns>An immutable map.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> keyComparer)
{
return ToImmutableDictionary(source, keyComparer, null);
}
/// <summary>
/// Creates an immutable dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <returns>An immutable map.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source)
{
return ToImmutableDictionary(source, null, null);
}
/// <summary>
/// Determines whether this map contains the specified key-value pair.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="map">The map to search.</param>
/// <param name="key">The key to check for.</param>
/// <param name="value">The value to check for on a matching key, if found.</param>
/// <returns>
/// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>.
/// </returns>
[Pure]
public static bool Contains<TKey, TValue>(this IImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Requires.NotNull(map, nameof(map));
Requires.NotNullAllowStructs(key, nameof(key));
return map.Contains(new KeyValuePair<TKey, TValue>(key, value));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="dictionary">The dictionary to retrieve the value from.</param>
/// <param name="key">The key to search for.</param>
/// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns>
[Pure]
public static TValue GetValueOrDefault<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary, TKey key)
{
return GetValueOrDefault(dictionary, key, default(TValue));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary to retrieve the value from.</param>
/// <param name="key">The key to search for.</param>
/// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param>
/// <returns>
/// The value for the key, or <paramref name="defaultValue"/> if no matching key was found.
/// </returns>
[Pure]
public static TValue GetValueOrDefault<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
Requires.NotNull(dictionary, nameof(dictionary));
Requires.NotNullAllowStructs(key, nameof(key));
TValue value;
if (dictionary.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel.Design;
using GuruComponents.Netrix.WebEditing.Elements;
using System.ComponentModel;
using System.Collections;
using System.Reflection;
using GuruComponents.Netrix.Events;
using System.Web.UI.Design;
namespace GuruComponents.Netrix.Designer
{
/// <summary>
/// Default designer support class.
/// </summary>
/// <remarks>
/// Primarily, this class supports the elements infrastructur behavior. User can replace this class
/// by adding the <see cref="DesignerAttribute"/> to element derived from <see cref="Element"/> as well other inheritable classes,
/// which derive from <see cref="Element"/>.
/// <seealso cref="IElement"/>
/// <seealso cref="Element"/>
/// </remarks>
public class ElementDesigner : ComponentDesigner
{
IElement component;
/// <summary>
/// The element which is currently assigned to this designer.
/// </summary>
public IElement Element
{
get { return component; }
set { component = value; }
}
/// <summary>
/// Just override to avoid null ref exception in case of UI calls (like PropertyGrid).
/// </summary>
[Obsolete()]
public override void OnSetComponentDefaults()
{
// just override to avoid null ref exception in case of UI calls (like PropertyGrid)
}
/// <summary>
/// Called by internal designer host to initialize the designer.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the default event attribute is being used, but the exposed event did not exists.</exception>
/// <param name="component"></param>
public override void Initialize(System.ComponentModel.IComponent component)
{
this.component = (IElement)component;
object[] attr = this.component.GetType().GetCustomAttributes(typeof(DefaultEventAttribute), true);
if (attr != null && attr.Length >= 1)
{
DefaultEventAttribute dea = (DefaultEventAttribute)attr[0];
EventInfo ei = this.component.GetType().GetEvent(dea.Name);
if (ei != null)
{
ei.AddEventHandler(component, new GuruComponents.Netrix.Events.DocumentEventHandler(component_Action));
}
else
{
throw new ArgumentOutOfRangeException("The default event defined by the element's class does not exist in that element. Event: " + dea.Name);
}
}
//this.component.DblClick -= new GuruComponents.Netrix.Events.DocumentEventHandler(component_DblClick);
//this.component.DblClick += new GuruComponents.Netrix.Events.DocumentEventHandler(component_DblClick);
}
void component_Action(object sender, GuruComponents.Netrix.Events.DocumentEventArgs e)
{
DoDefaultAction();
}
/// <summary>
/// The default action for the component.
/// </summary>
/// <remarks>
/// The default event on an element causes this method to be called. Override this method to change the default
/// behavior. In an application which behaves like Visual Studio a double click might open the code editor
/// and add a event handler for the default event of the element.
/// <para>
/// The abstract base class, <see cref="GuruComponents.Netrix.WebEditing.Elements.Element">Element</see> defines the
/// attribute <see cref="DefaultEventAttribute"/> with the value "Click". This makes the click event the default
/// event for any element. If one writes a new element class, which derives from <see cref="GuruComponents.Netrix.WebEditing.Elements.Element">Element</see>
/// or which implements <see cref="GuruComponents.Netrix.WebEditing.Elements.IElement">IElement</see>, the attribute could
/// be overwritten with each other handler name.
/// </para>
/// <para>
/// To fully implement this behavior one must:
/// <list type="bullet">
/// <item>1. Add the DefaultEventAttribute to the component's class.</item>
/// <item>2. Override the DoDefaultAction method to receive the event at design time.</item>
/// </list>
/// At design time, the user may issue the event by some action. Then the event manager receives the event and calles
/// the attached handler, which in turn calles DoDefaultAction.
/// </para>
/// <para>
/// <b>Important Note to implementors:</b> Some events, like MouseMove, PropertyChange, or Resize are called very
/// frequently and using these event in the scenario described above could slow the performance drastically. It's strongly
/// recommended to use only events which have slow performance impact (so called single event actions). This is the case
/// for events like Click, ResizeStart, ResizeEnd, MoveStart, MoveEnd, DblClick, MouseUp, MouseDown. It could be critical
/// for key events and several mixed events, like those for drag 'n drop, for editing (cut/copy/paste) and selection.
/// </para>
/// </remarks>
public override void DoDefaultAction()
{
base.DoDefaultAction();
}
/// <summary>
/// Allows adding properties to the properties which show up in the PropertyGrid.
/// </summary>
/// <remarks>
/// Allows a designer to add to the set of properties that it exposes through
/// a <see cref="System.ComponentModel.TypeDescriptor"/>.
/// </remarks>
/// <param name="properties">List of properties defined by the component.</param>
protected override void PreFilterProperties(System.Collections.IDictionary properties)
{
Hashtable ht = new Hashtable(properties);
foreach (DictionaryEntry de in properties)
{
PropertyDescriptor pd = (PropertyDescriptor)de.Value;
if (pd.Name == "EnableViewState")
{
ht.Remove(pd);
}
}
base.PreFilterProperties(properties);
}
/// <summary>
/// Allows change or modify properties to the properties which show up in the PropertyGrid.
/// </summary>
/// <remarks>
/// Allows a designer to change or modify to the set of properties that it exposes through
/// a <see cref="System.ComponentModel.TypeDescriptor"/>.
/// </remarks>
/// <param name="properties">List of properties defined by the component.</param>
protected override void PostFilterProperties(IDictionary properties)
{
Hashtable ht = new Hashtable(properties);
foreach (DictionaryEntry de in properties)
{
PropertyDescriptor pd = (PropertyDescriptor)de.Value;
if (pd.Name == "Expression"
||
pd.Name == "EnableViewState"
||
pd.Name == "ID")
{
ht.Remove(pd);
}
}
base.PostFilterProperties(ht);
}
/// <summary>
/// Gets the parent element in the element's hierarchy.
/// </summary>
protected override IComponent ParentComponent
{
get
{
return component.GetParent() as IComponent;
}
}
/// <summary>
/// Gets the children of the element in the element's hierarchy.
/// </summary>
public override ICollection AssociatedComponents
{
get
{
return component.ElementDom.GetChildNodes();
}
}
/// <summary>
/// This property provides commands.
/// </summary>
/// <remarks>
/// Command apperar in PropertyGrid's command area or a IMenuCommandService driven context menu, if the
/// host makes use of the designer host. Inheritors should override this property and either add commands
/// or replace the existing command.
/// </remarks>
/// <example>
/// The following example shows how to create new commands:
/// <code>
/// <![CDATA[
/// DesignerVerbCollection verbs = new DesignerVerbCollection();
/// verbs.Add(new DesignerVerb("This Name appears in the menu", OnAction));
/// ]]>
/// </code>
/// <c>OnAction</c> is a default event handler (<see cref="System.EventHandler"/>). To access the component which
/// later issues the command one can get the <see cref="Element"/>.
/// </example>
public override DesignerVerbCollection Verbs
{
get
{
DesignerVerbCollection verbs = new DesignerVerbCollection();
return verbs;
}
}
/// <summary>
/// Called from event chain before any internal processing.
/// </summary>
/// <remarks>
/// Inheritors may implement here private behavior to change the default event handling.
/// Returning <c>True</c> will cause the internal chain to stop event processing.
/// </remarks>
/// <param name="sender">The EditHost which received and re-fired the event.</param>
/// <param name="e">Information about the event.</param>
/// <returns>Return <c>true</c> to inform the caller that any default handling has to be suppressed. Default is <c>false</c>.</returns>
public virtual bool OnPreHandleEvent(object sender, DocumentEventArgs e)
{
return false;
}
/// <summary>
/// Called from event chain after default internal processing.
/// </summary>
/// <remarks>
/// Inheritors may implement here private behavior to change the default event handling.
/// Returning <c>True</c> will cause the internal chain to stop event processing.
/// </remarks>
/// <param name="sender">The EditHost which received and re-fired the event.</param>
/// <param name="e">Information about the event.</param>
/// <returns>Return <c>true</c> to inform the caller that any default handling has to be suppressed. Default is <c>false</c>.</returns>
public virtual bool OnPostHandleEvent(object sender, DocumentEventArgs e)
{
return false;
}
/// <summary>
/// Called from event chain before any internal and external processing.
/// </summary>
/// <remarks>
/// This is to inform the designer that any internal processing is done. The purpose is to check the results of any
/// previous action or refresh the state of an object after finishing the event chain.
/// </remarks>
/// <param name="sender">The EditHost which received and re-fired the event.</param>
/// <param name="e">Information about the event.</param>
public virtual void OnPostEditorNotify(object sender, DocumentEventArgs e)
{
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
using System.Text;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
[TestFixture]
public class CookieImplementationTest : DriverTestFixture
{
private Random random = new Random();
private bool isOnAlternativeHostName;
private string hostname;
[SetUp]
public void GoToSimplePageAndDeleteCookies()
{
GotoValidDomainAndClearCookies("animals");
AssertNoCookiesArePresent();
}
[Test]
public void ShouldGetCookieByName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = string.Format("key_{0}", new Random().Next());
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key);
Cookie cookie = driver.Manage().Cookies.GetCookieNamed(key);
Assert.AreEqual("set", cookie.Value);
}
[Test]
public void ShouldBeAbleToAddCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = GenerateUniqueKey();
string value = "foo";
Cookie cookie = new Cookie(key, value);
AssertCookieIsNotPresentWithName(key);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieHasValue(key, value);
Assert.That(driver.Manage().Cookies.AllCookies.Contains(cookie), "Cookie was not added successfully");
}
[Test]
public void GetAllCookies()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key1 = GenerateUniqueKey();
string key2 = GenerateUniqueKey();
AssertCookieIsNotPresentWithName(key1);
AssertCookieIsNotPresentWithName(key2);
ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
int count = cookies.Count;
Cookie one = new Cookie(key1, "value");
Cookie two = new Cookie(key2, "value");
driver.Manage().Cookies.AddCookie(one);
driver.Manage().Cookies.AddCookie(two);
driver.Url = simpleTestPage;
cookies = driver.Manage().Cookies.AllCookies;
Assert.AreEqual(count + 2, cookies.Count);
Assert.That(cookies, Does.Contain(one));
Assert.That(cookies, Does.Contain(two));
}
[Test]
public void DeleteAllCookies()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = 'foo=set';");
AssertSomeCookiesArePresent();
driver.Manage().Cookies.DeleteAllCookies();
AssertNoCookiesArePresent();
}
[Test]
public void DeleteCookieWithName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key1 = GenerateUniqueKey();
string key2 = GenerateUniqueKey();
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key1);
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key2);
AssertCookieIsPresentWithName(key1);
AssertCookieIsPresentWithName(key2);
driver.Manage().Cookies.DeleteCookieNamed(key1);
AssertCookieIsNotPresentWithName(key1);
AssertCookieIsPresentWithName(key2);
}
[Test]
public void ShouldNotDeleteCookiesWithASimilarName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieOneName = "fish";
Cookie cookie1 = new Cookie(cookieOneName, "cod");
Cookie cookie2 = new Cookie(cookieOneName + "x", "earth");
IOptions options = driver.Manage();
AssertCookieIsNotPresentWithName(cookie1.Name);
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
AssertCookieIsPresentWithName(cookie1.Name);
options.Cookies.DeleteCookieNamed(cookieOneName);
Assert.That(driver.Manage().Cookies.AllCookies, Does.Not.Contain(cookie1));
Assert.That(driver.Manage().Cookies.AllCookies, Does.Contain(cookie2));
}
[Test]
public void AddCookiesWithDifferentPathsThatAreRelatedToOurs()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
UrlBuilder builder = EnvironmentManager.Instance.UrlBuilder;
driver.Url = builder.WhereIs("animals");
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
AssertCookieIsPresentWithName(cookie1.Name);
AssertCookieIsPresentWithName(cookie2.Name);
driver.Url = builder.WhereIs("simpleTest.html");
AssertCookieIsNotPresentWithName(cookie1.Name);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome does not retrieve cookies when in frame.")]
public void GetCookiesInAFrame()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
Cookie cookie1 = new Cookie("fish", "cod", "/common/animals");
driver.Manage().Cookies.AddCookie(cookie1);
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("frameWithAnimals.html");
AssertCookieIsNotPresentWithName(cookie1.Name);
driver.SwitchTo().Frame("iframe1");
AssertCookieIsPresentWithName(cookie1.Name);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void CannotGetCookiesWithPathDifferingOnlyInCase()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "fish";
driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod", "/Common/animals"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
Assert.That(driver.Manage().Cookies.GetCookieNamed(cookieName), Is.Null);
}
[Test]
public void ShouldNotGetCookieOnDifferentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "fish";
driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod"));
AssertCookieIsPresentWithName(cookieName);
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html");
AssertCookieIsNotPresentWithName(cookieName);
}
[Test]
public void ShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
AssertCookieIsNotPresentWithName("name");
Regex replaceRegex = new Regex(".*?\\.");
string shorter = replaceRegex.Replace(this.hostname, ".", 1);
Cookie cookie = new Cookie("name", "value", shorter, "/", GetTimeInTheFuture());
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName("name");
}
[Test]
public void ShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "name";
AssertCookieIsNotPresentWithName(cookieName);
Regex replaceRegex = new Regex(".*?\\.");
string subdomain = replaceRegex.Replace(this.hostname, "subdomain.", 1);
Cookie cookie = new Cookie(cookieName, "value", subdomain, "/", GetTimeInTheFuture());
string originalUrl = driver.Url;
string subdomainUrl = originalUrl.Replace(this.hostname, subdomain);
driver.Url = subdomainUrl;
driver.Manage().Cookies.AddCookie(cookie);
driver.Url = originalUrl;
AssertCookieIsNotPresentWithName(cookieName);
}
[Test]
public void ShouldBeAbleToIncludeLeadingPeriodInDomainName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
AssertCookieIsNotPresentWithName("name");
// Replace the first part of the name with a period
Regex replaceRegex = new Regex(".*?\\.");
string shorter = replaceRegex.Replace(this.hostname, ".", 1);
Cookie cookie = new Cookie("name", "value", shorter, "/", DateTime.Now.AddSeconds(100000));
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName("name");
}
[Test]
public void ShouldBeAbleToSetDomainToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
Uri url = new Uri(driver.Url);
String host = url.Host + ":" + url.Port.ToString();
Cookie cookie1 = new Cookie("fish", "cod", host, "/", null);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
driver.Url = javascriptPage;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Contain(cookie1));
}
[Test]
public void ShouldWalkThePathToDeleteACookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod");
driver.Manage().Cookies.AddCookie(cookie1);
int count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = childPage;
Cookie cookie2 = new Cookie("rodent", "hamster", "/" + basePath + "/child");
driver.Manage().Cookies.AddCookie(cookie2);
count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = grandchildPage;
Cookie cookie3 = new Cookie("dog", "dalmation", "/" + basePath + "/child/grandchild/");
driver.Manage().Cookies.AddCookie(cookie3);
count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("child/grandchild"));
driver.Manage().Cookies.DeleteCookieNamed("rodent");
count = driver.Manage().Cookies.AllCookies.Count;
Assert.That(driver.Manage().Cookies.GetCookieNamed("rodent"), Is.Null);
ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
Assert.That(cookies, Has.Count.EqualTo(2));
Assert.That(cookies, Does.Contain(cookie1));
Assert.That(cookies, Does.Contain(cookie3));
driver.Manage().Cookies.DeleteAllCookies();
driver.Url = grandchildPage;
AssertNoCookiesArePresent();
}
[Test]
public void ShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
Uri uri = new Uri(driver.Url);
string host = string.Format("{0}:{1}", uri.Host, uri.Port);
string cookieName = "name";
AssertCookieIsNotPresentWithName(cookieName);
Cookie cookie = new Cookie(cookieName, "value", host, "/", null);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName(cookieName);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void CookieEqualityAfterSetAndGet()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
DateTime time = DateTime.Now.AddDays(1);
Cookie cookie1 = new Cookie("fish", "cod", null, "/common/animals", time);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Cookie retrievedCookie = null;
foreach (Cookie tempCookie in cookies)
{
if (cookie1.Equals(tempCookie))
{
retrievedCookie = tempCookie;
break;
}
}
Assert.That(retrievedCookie, Is.Not.Null);
//Cookie.equals only compares name, domain and path
Assert.AreEqual(cookie1, retrievedCookie);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldRetainCookieExpiry()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
// DateTime.Now contains milliseconds; the returned cookie expire date
// will not. So we need to truncate the milliseconds.
DateTime current = DateTime.Now;
DateTime expireDate = new DateTime(current.Year, current.Month, current.Day, current.Hour, current.Minute, current.Second, DateTimeKind.Local).AddDays(1);
Cookie addCookie = new Cookie("fish", "cod", "/common/animals", expireDate);
IOptions options = driver.Manage();
options.Cookies.AddCookie(addCookie);
Cookie retrieved = options.Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
Assert.AreEqual(addCookie.Expiry, retrieved.Expiry, "Cookies are not equal");
}
[Test]
[IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")]
[IgnoreBrowser(Browser.Edge, "Browser does not handle untrusted SSL certificates.")]
public void CanHandleSecureCookie()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals");
Cookie addedCookie = new ReturnedCookie("fish", "cod", null, "/common/animals", null, true, false);
driver.Manage().Cookies.AddCookie(addedCookie);
driver.Navigate().Refresh();
Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
}
[Test]
[IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")]
[IgnoreBrowser(Browser.Edge, "Browser does not handle untrusted SSL certificates.")]
public void ShouldRetainCookieSecure()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals");
ReturnedCookie addedCookie = new ReturnedCookie("fish", "cod", string.Empty, "/common/animals", null, true, false);
driver.Manage().Cookies.AddCookie(addedCookie);
driver.Navigate().Refresh();
Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
Assert.That(retrieved.Secure, "Secure attribute not set to true");
}
[Test]
public void CanHandleHttpOnlyCookie()
{
StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereIs("cookie"));
url.Append("?action=add");
url.Append("&name=").Append("fish");
url.Append("&value=").Append("cod");
url.Append("&path=").Append("/common/animals");
url.Append("&httpOnly=").Append("true");
driver.Url = url.ToString();
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
}
[Test]
public void ShouldRetainHttpOnlyFlag()
{
StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereElseIs("cookie"));
url.Append("?action=add");
url.Append("&name=").Append("fish");
url.Append("&value=").Append("cod");
url.Append("&path=").Append("/common/animals");
url.Append("&httpOnly=").Append("true");
driver.Url = url.ToString();
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
Assert.That(retrieved.IsHttpOnly, "HttpOnly attribute not set to true");
}
[Test]
public void SettingACookieThatExpiredInThePast()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
DateTime expires = DateTime.Now.AddSeconds(-1000);
Cookie cookie = new Cookie("expired", "yes", "/common/animals", expires);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie);
cookie = options.Cookies.GetCookieNamed("expired");
Assert.That(cookie, Is.Null, "Cookie expired before it was set, so nothing should be returned: " + cookie);
}
[Test]
public void CanSetCookieWithoutOptionalFieldsSet()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = GenerateUniqueKey();
string value = "foo";
Cookie cookie = new Cookie(key, value);
AssertCookieIsNotPresentWithName(key);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieHasValue(key, value);
}
[Test]
public void DeleteNotExistedCookie()
{
String key = GenerateUniqueKey();
AssertCookieIsNotPresentWithName(key);
driver.Manage().Cookies.DeleteCookieNamed(key);
}
[Test]
public void DeleteAllCookiesDifferentUrls()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Cookie cookie1 = new Cookie("fish1", "cod", EnvironmentManager.Instance.UrlBuilder.HostName, null, null);
Cookie cookie2 = new Cookie("fish2", "tune", EnvironmentManager.Instance.UrlBuilder.AlternateHostName, null, null);
string url1 = EnvironmentManager.Instance.UrlBuilder.WhereIs("");
string url2 = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
AssertCookieIsPresentWithName(cookie1.Name);
driver.Url = url2;
options.Cookies.AddCookie(cookie2);
AssertCookieIsNotPresentWithName(cookie1.Name);
AssertCookieIsPresentWithName(cookie2.Name);
driver.Url = url1;
AssertCookieIsPresentWithName(cookie1.Name);
AssertCookieIsNotPresentWithName(cookie2.Name);
options.Cookies.DeleteAllCookies();
AssertCookieIsNotPresentWithName(cookie1.Name);
driver.Url = url2;
AssertCookieIsPresentWithName(cookie2.Name);
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void CanSetCookiesOnADifferentPathOfTheSameHost()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/galaxy");
IOptions options = driver.Manage();
ReadOnlyCollection<Cookie> count = options.Cookies.AllCookies;
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
driver.Url = url;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Contain(cookie1));
Assert.That(cookies, Does.Not.Contain(cookie2));
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("galaxy");
cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Not.Contain(cookie1));
Assert.That(cookies, Does.Contain(cookie2));
}
[Test]
public void ShouldNotBeAbleToSetDomainToSomethingThatIsUnrelatedToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Cookie cookie1 = new Cookie("fish", "cod");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html");
driver.Url = url;
Assert.That(options.Cookies.GetCookieNamed("fish"), Is.Null);
}
[Test]
public void GetCookieDoesNotRetriveBeyondCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Cookie cookie1 = new Cookie("fish", "cod");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
String url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("");
driver.Url = url;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Not.Contain(cookie1));
}
[Test]
public void ShouldAddCookieToCurrentDomainAndPath()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Homer", "Simpson", this.hostname, "/" + EnvironmentManager.Instance.UrlBuilder.Path, null);
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies.Contains(cookie), "Valid cookie was not returned");
}
[Test]
public void ShouldNotShowCookieAddedToDifferentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
Assert.Ignore("Not on a standard domain for cookies (localhost doesn't count).");
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Bart", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName + ".com", EnvironmentManager.Instance.UrlBuilder.Path, null);
Assert.That(() => options.Cookies.AddCookie(cookie), Throws.InstanceOf<WebDriverException>().Or.InstanceOf<InvalidOperationException>());
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Not.Contain(cookie), "Invalid cookie was returned");
}
[Test]
public void ShouldNotShowCookieAddedToDifferentPath()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Lisa", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName, "/" + EnvironmentManager.Instance.UrlBuilder.Path + "IDoNotExist", null);
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Not.Contain(cookie), "Invalid cookie was returned");
}
[Test]
public void ShouldThrowExceptionWhenAddingCookieToCookieAverseDocument()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// URLs using a non-network scheme (like "about:" or "data:") are
// averse to cookies, and should throw an InvalidCookieDomainException.
driver.Url = "about:blank";
IOptions options = driver.Manage();
Cookie cookie = new Cookie("question", "dunno");
Assert.That(() => options.Cookies.AddCookie(cookie), Throws.InstanceOf<InvalidCookieDomainException>().Or.InstanceOf<InvalidOperationException>());
}
[Test]
public void ShouldReturnNullBecauseCookieRetainsExpiry()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
Cookie addCookie = new Cookie("fish", "cod", "/common/animals", DateTime.Now.AddHours(-1));
IOptions options = driver.Manage();
options.Cookies.AddCookie(addCookie);
Cookie retrieved = options.Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Null);
}
[Test]
public void ShouldAddCookieToCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Marge", "Simpson", "/");
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies.Contains(cookie), "Valid cookie was not returned");
}
[Test]
public void ShouldDeleteCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookieToDelete = new Cookie("answer", "42");
Cookie cookieToKeep = new Cookie("canIHaz", "Cheeseburguer");
options.Cookies.AddCookie(cookieToDelete);
options.Cookies.AddCookie(cookieToKeep);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
options.Cookies.DeleteCookie(cookieToDelete);
ReadOnlyCollection<Cookie> cookies2 = options.Cookies.AllCookies;
Assert.That(cookies2, Does.Not.Contain(cookieToDelete), "Cookie was not deleted successfully");
Assert.That(cookies2.Contains(cookieToKeep), "Valid cookie was not returned");
}
//////////////////////////////////////////////
// Support functions
//////////////////////////////////////////////
private void GotoValidDomainAndClearCookies(string page)
{
this.hostname = null;
String hostname = EnvironmentManager.Instance.UrlBuilder.HostName;
if (IsValidHostNameForCookieTests(hostname))
{
this.isOnAlternativeHostName = false;
this.hostname = hostname;
}
hostname = EnvironmentManager.Instance.UrlBuilder.AlternateHostName;
if (this.hostname == null && IsValidHostNameForCookieTests(hostname))
{
this.isOnAlternativeHostName = true;
this.hostname = hostname;
}
GoToPage(page);
driver.Manage().Cookies.DeleteAllCookies();
}
private bool CheckIsOnValidHostNameForCookieTests()
{
bool correct = this.hostname != null && IsValidHostNameForCookieTests(this.hostname);
if (!correct)
{
System.Console.WriteLine("Skipping test: unable to find domain name to use");
}
return correct;
}
private void GoToPage(String pageName)
{
driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName);
}
private void GoToOtherPage(String pageName)
{
driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName);
}
private bool IsValidHostNameForCookieTests(string hostname)
{
// TODO(JimEvan): Some coverage is better than none, so we
// need to ignore the fact that localhost cookies are problematic.
// Reenable this when we have a better solution per DanielWagnerHall.
// ChromeDriver2 has trouble with localhost. IE and Firefox don't.
// return !IsIpv4Address(hostname) && "localhost" != hostname;
bool isLocalHostOkay = true;
if ("localhost" == hostname && TestUtilities.IsChrome(driver))
{
isLocalHostOkay = false;
}
return !IsIpv4Address(hostname) && isLocalHostOkay;
}
private static bool IsIpv4Address(string addrString)
{
return Regex.IsMatch(addrString, "\\d{1,3}(?:\\.\\d{1,3}){3}");
}
private string GenerateUniqueKey()
{
return string.Format("key_{0}", random.Next());
}
private string GetDocumentCookieOrNull()
{
IJavaScriptExecutor jsDriver = driver as IJavaScriptExecutor;
if (jsDriver == null)
{
return null;
}
try
{
return (string)jsDriver.ExecuteScript("return document.cookie");
}
catch (InvalidOperationException)
{
return null;
}
}
private void AssertNoCookiesArePresent()
{
Assert.That(driver.Manage().Cookies.AllCookies.Count, Is.EqualTo(0), "Cookies were not empty");
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.AreEqual(string.Empty, documentCookie, "Cookies were not empty");
}
}
private void AssertSomeCookiesArePresent()
{
Assert.That(driver.Manage().Cookies.AllCookies.Count, Is.Not.EqualTo(0), "Cookies were empty");
String documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.AreNotEqual(string.Empty, documentCookie, "Cookies were empty");
}
}
private void AssertCookieIsNotPresentWithName(string key)
{
Assert.That(driver.Manage().Cookies.GetCookieNamed(key), Is.Null, "Cookie was present with name " + key);
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.That(documentCookie, Does.Not.Contain(key + "="));
}
}
private void AssertCookieIsPresentWithName(string key)
{
Assert.That(driver.Manage().Cookies.GetCookieNamed(key), Is.Not.Null, "Cookie was present with name " + key);
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.That(documentCookie, Does.Contain(key + "="));
}
}
private void AssertCookieHasValue(string key, string value)
{
Assert.AreEqual(value, driver.Manage().Cookies.GetCookieNamed(key).Value, "Cookie had wrong value");
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.That(documentCookie, Does.Contain(key + "=" + value));
}
}
private DateTime GetTimeInTheFuture()
{
return DateTime.Now.Add(TimeSpan.FromMilliseconds(100000));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.X86
{
/// <summary>
/// This class provides access to Intel SSE4.2 hardware instructions via intrinsics
/// </summary>
[CLSCompliant(false)]
public static class Sse42
{
public static bool IsSupported { get => IsSupported; }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareImplicitLength(Vector128<sbyte> left, Vector128<sbyte> right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode);
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareImplicitLength(Vector128<byte> left, Vector128<byte> right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode);
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareImplicitLength(Vector128<short> left, Vector128<short> right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode);
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareImplicitLength(Vector128<ushort> left, Vector128<ushort> right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode);
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareExplicitLength(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode);
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareExplicitLength(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode);
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareExplicitLength(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode);
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareExplicitLength(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode);
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode);
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode);
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode);
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode);
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode);
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode);
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode);
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode);
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode);
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode);
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode);
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode);
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode);
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode);
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode);
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode);
/// <summary>
/// __m128i _mm_cmpgt_epi64 (__m128i a, __m128i b)
/// PCMPGTQ xmm, xmm/m128
/// </summary>
public static Vector128<long> CompareGreaterThan(Vector128<long> left, Vector128<long> right) => CompareGreaterThan(left, right);
/// <summary>
/// unsigned int _mm_crc32_u8 (unsigned int crc, unsigned char v)
/// CRC32 reg, reg/m8
/// </summary>
public static uint Crc32(uint crc, byte data) => Crc32(crc, data);
/// <summary>
/// unsigned int _mm_crc32_u16 (unsigned int crc, unsigned short v)
/// CRC32 reg, reg/m16
/// </summary>
public static uint Crc32(uint crc, ushort data) => Crc32(crc, data);
/// <summary>
/// unsigned int _mm_crc32_u32 (unsigned int crc, unsigned int v)
/// CRC32 reg, reg/m32
/// </summary>
public static uint Crc32(uint crc, uint data) => Crc32(crc, data);
/// <summary>
/// unsigned __int64 _mm_crc32_u64 (unsigned __int64 crc, unsigned __int64 v)
/// CRC32 reg, reg/m64
/// </summary>
public static ulong Crc32(ulong crc, ulong data) => Crc32(crc, data);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit.Sdk;
namespace Xunit
{
/// <summary>
/// Contains various static methods that are used to verify that conditions are met during the
/// process of running tests.
/// </summary>
public class Assert
{
/// <summary>
/// Used by the Throws and DoesNotThrow methods.
/// </summary>
public delegate void ThrowsDelegate();
/// <summary>
/// Initializes a new instance of the <see cref="Assert"/> class.
/// </summary>
protected Assert() { }
/// <summary>
/// Verifies that a collection contains a given object.
/// </summary>
/// <typeparam name="T">The type of the object to be verified</typeparam>
/// <param name="expected">The object expected to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ContainsException">Thrown when the object is not present in the collection</exception>
public static void Contains<T>(T expected,
IEnumerable<T> collection)
{
Contains(expected, collection, GetComparer<T>());
}
/// <summary>
/// Verifies that a collection contains a given object, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the object to be verified</typeparam>
/// <param name="expected">The object expected to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <param name="comparer">The comparer used to equate objects in the collection with the expected object</param>
/// <exception cref="ContainsException">Thrown when the object is not present in the collection</exception>
public static void Contains<T>(T expected,
IEnumerable<T> collection,
IComparer<T> comparer)
{
foreach (T item in collection)
if (comparer.Compare(expected, item) == 0)
return;
throw new ContainsException(expected);
}
/// <summary>
/// Verifies that a string contains a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string expected to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <exception cref="ContainsException">Thrown when the sub-string is not present inside the string</exception>
public static void Contains(string expectedSubString,
string actualString)
{
Contains(expectedSubString, actualString, StringComparison.CurrentCulture);
}
/// <summary>
/// Verifies that a string contains a given sub-string, using the given comparison type.
/// </summary>
/// <param name="expectedSubString">The sub-string expected to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <param name="comparisonType">The type of string comparison to perform</param>
/// <exception cref="ContainsException">Thrown when the sub-string is not present inside the string</exception>
public static void Contains(string expectedSubString,
string actualString,
StringComparison comparisonType)
{
if (actualString.IndexOf(expectedSubString, comparisonType) < 0)
throw new ContainsException(expectedSubString);
}
/// <summary>
/// Verifies that a collection does not contain a given object.
/// </summary>
/// <typeparam name="T">The type of the object to be compared</typeparam>
/// <param name="expected">The object that is expected not to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="DoesNotContainException">Thrown when the object is present inside the container</exception>
public static void DoesNotContain<T>(T expected,
IEnumerable<T> collection)
{
DoesNotContain(expected, collection, GetComparer<T>());
}
/// <summary>
/// Verifies that a collection does not contain a given object, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the object to be compared</typeparam>
/// <param name="expected">The object that is expected not to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <param name="comparer">The comparer used to equate objects in the collection with the expected object</param>
/// <exception cref="DoesNotContainException">Thrown when the object is present inside the container</exception>
public static void DoesNotContain<T>(T expected,
IEnumerable<T> collection,
IComparer<T> comparer)
{
foreach (T item in collection)
if (comparer.Compare(expected, item) == 0)
throw new DoesNotContainException(expected);
}
/// <summary>
/// Verifies that a string does not contain a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string which is expected not to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <exception cref="DoesNotContainException">Thrown when the sub-string is present inside the string</exception>
public static void DoesNotContain(string expectedSubString,
string actualString)
{
DoesNotContain(expectedSubString, actualString, StringComparison.CurrentCulture);
}
/// <summary>
/// Verifies that a string does not contain a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string which is expected not to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <param name="comparisonType">The type of string comparison to perform</param>
/// <exception cref="DoesNotContainException">Thrown when the sub-string is present inside the given string</exception>
public static void DoesNotContain(string expectedSubString,
string actualString,
StringComparison comparisonType)
{
if (actualString.IndexOf(expectedSubString, comparisonType) >= 0)
throw new DoesNotContainException(expectedSubString);
}
/// <summary>
/// Verifies that a block of code does not throw any exceptions.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
public static void DoesNotThrow(ThrowsDelegate testCode)
{
Exception ex = Record.Exception(testCode);
if (ex != null)
throw new DoesNotThrowException(ex);
}
/// <summary>
/// Verifies that a collection is empty.
/// </summary>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ArgumentNullException">Thrown when the collection is null</exception>
/// <exception cref="EmptyException">Thrown when the collection is not empty</exception>
public static void Empty(IEnumerable collection)
{
if (collection == null) throw new ArgumentNullException("collection", "cannot be null");
#pragma warning disable 168
foreach (object @object in collection)
throw new EmptyException();
#pragma warning restore 168
}
/// <summary>
/// Verifies that two objects are equal, using a default comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <exception cref="EqualException">Thrown when the objects are not equal</exception>
public static void Equal<T>(T expected,
T actual)
{
Equal(expected, actual, GetComparer<T>());
}
/// <summary>
/// Verifies that two objects are equal, using a custom comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="comparer">The comparer used to compare the two objects</param>
/// <exception cref="EqualException">Thrown when the objects are not equal</exception>
public static void Equal<T>(T expected,
T actual,
IComparer<T> comparer)
{
if (comparer.Compare(expected, actual) != 0)
throw new EqualException(expected, actual);
}
/// <summary>Do not call this method.</summary>
[Obsolete("This is an override of Object.Equals(). Call Assert.Equal() instead.", true)]
public new static bool Equals(object a,
object b)
{
throw new InvalidOperationException("Assert.Equals should not be used");
}
/// <summary>
/// Verifies that the condition is false.
/// </summary>
/// <param name="condition">The condition to be tested</param>
/// <exception cref="FalseException">Thrown if the condition is not false</exception>
public static void False(bool condition)
{
False(condition, null);
}
/// <summary>
/// Verifies that the condition is false.
/// </summary>
/// <param name="condition">The condition to be tested</param>
/// <param name="userMessage">The message to show when the condition is not false</param>
/// <exception cref="FalseException">Thrown if the condition is not false</exception>
public static void False(bool condition,
string userMessage)
{
if (condition)
throw new FalseException(userMessage);
}
static IComparer<T> GetComparer<T>()
{
return new AssertComparer<T>();
}
/// <summary>
/// Verifies that a value is within a given range.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <exception cref="InRangeException">Thrown when the value is not in the given range</exception>
public static void InRange<T>(T actual,
T low,
T high)
{
InRange(actual, low, high, GetComparer<T>());
}
/// <summary>
/// Verifies that a value is within a given range, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <param name="comparer">The comparer used to evaluate the value's range</param>
/// <exception cref="InRangeException">Thrown when the value is not in the given range</exception>
public static void InRange<T>(T actual,
T low,
T high,
IComparer<T> comparer)
{
if (comparer.Compare(low, actual) > 0 || comparer.Compare(actual, high) > 0)
throw new InRangeException(actual, low, high);
}
/// <summary>
/// Verifies that an object is of the given type or a derived type.
/// </summary>
/// <typeparam name="T">The type the object should be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <returns>The object, casted to type T when successful</returns>
/// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception>
public static T IsAssignableFrom<T>(object @object)
{
IsAssignableFrom(typeof(T), @object);
return (T)@object;
}
/// <summary>
/// Verifies that an object is of the given type or a derived type.
/// </summary>
/// <param name="expectedType">The type the object should be</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception>
public static void IsAssignableFrom(Type expectedType,
object @object)
{
if (@object == null || !expectedType.IsAssignableFrom(@object.GetType()))
throw new IsAssignableFromException(expectedType, @object);
}
/// <summary>
/// Verifies that an object is not exactly the given type.
/// </summary>
/// <typeparam name="T">The type the object should not be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsNotTypeException">Thrown when the object is the given type</exception>
public static void IsNotType<T>(object @object)
{
IsNotType(typeof(T), @object);
}
/// <summary>
/// Verifies that an object is not exactly the given type.
/// </summary>
/// <param name="expectedType">The type the object should not be</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsNotTypeException">Thrown when the object is the given type</exception>
public static void IsNotType(Type expectedType,
object @object)
{
if (expectedType.Equals(@object.GetType()))
throw new IsNotTypeException(expectedType, @object);
}
/// <summary>
/// Verifies that an object is exactly the given type (and not a derived type).
/// </summary>
/// <typeparam name="T">The type the object should be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <returns>The object, casted to type T when successful</returns>
/// <exception cref="IsTypeException">Thrown when the object is not the given type</exception>
public static T IsType<T>(object @object)
{
IsType(typeof(T), @object);
return (T)@object;
}
/// <summary>
/// Verifies that an object is exactly the given type (and not a derived type).
/// </summary>
/// <param name="expectedType">The type the object should be</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsTypeException">Thrown when the object is not the given type</exception>
public static void IsType(Type expectedType,
object @object)
{
if (@object == null || !expectedType.Equals(@object.GetType()))
throw new IsTypeException(expectedType, @object);
}
/// <summary>
/// Verifies that a collection is not empty.
/// </summary>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ArgumentNullException">Thrown when a null collection is passed</exception>
/// <exception cref="NotEmptyException">Thrown when the collection is empty</exception>
public static void NotEmpty(IEnumerable collection)
{
if (collection == null) throw new ArgumentNullException("collection", "cannot be null");
#pragma warning disable 168
foreach (object @object in collection)
return;
#pragma warning restore 168
throw new NotEmptyException();
}
/// <summary>
/// Verifies that two objects are not equal, using a default comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <exception cref="NotEqualException">Thrown when the objects are equal</exception>
public static void NotEqual<T>(T expected,
T actual)
{
NotEqual(expected, actual, GetComparer<T>());
}
/// <summary>
/// Verifies that two objects are not equal, using a custom comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <param name="comparer">The comparer used to examine the objects</param>
/// <exception cref="NotEqualException">Thrown when the objects are equal</exception>
public static void NotEqual<T>(T expected,
T actual,
IComparer<T> comparer)
{
if (comparer.Compare(expected, actual) == 0)
throw new NotEqualException();
}
/// <summary>
/// Verifies that a value is not within a given range, using the default comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception>
public static void NotInRange<T>(T actual,
T low,
T high)
{
NotInRange(actual, low, high, GetComparer<T>());
}
/// <summary>
/// Verifies that a value is not within a given range, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <param name="comparer">The comparer used to evaluate the value's range</param>
/// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception>
public static void NotInRange<T>(T actual,
T low,
T high,
IComparer<T> comparer)
{
if (comparer.Compare(low, actual) <= 0 && comparer.Compare(actual, high) <= 0)
throw new NotInRangeException(actual, low, high);
}
/// <summary>
/// Verifies that an object reference is not null.
/// </summary>
/// <param name="object">The object to be validated</param>
/// <exception cref="NotNullException">Thrown when the object is not null</exception>
public static void NotNull(object @object)
{
if (@object == null)
throw new NotNullException();
}
/// <summary>
/// Verifies that two objects are not the same instance.
/// </summary>
/// <param name="expected">The expected object instance</param>
/// <param name="actual">The actual object instance</param>
/// <exception cref="NotSameException">Thrown when the objects are the same instance</exception>
public static void NotSame(object expected,
object actual)
{
if (object.ReferenceEquals(expected, actual))
throw new NotSameException();
}
/// <summary>
/// Verifies that an object reference is null.
/// </summary>
/// <param name="object">The object to be inspected</param>
/// <exception cref="NullException">Thrown when the object reference is not null</exception>
public static void Null(object @object)
{
if (@object != null)
throw new NullException(@object);
}
/// <summary>
/// Verifies that two objects are the same instance.
/// </summary>
/// <param name="expected">The expected object instance</param>
/// <param name="actual">The actual object instance</param>
/// <exception cref="SameException">Thrown when the objects are not the same instance</exception>
public static void Same(object expected,
object actual)
{
if (!object.ReferenceEquals(expected, actual))
throw new SameException(expected, actual);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <typeparam name="T">The type of the exception expected to be thrown</typeparam>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static T Throws<T>(ThrowsDelegate testCode)
where T : Exception
{
return (T)Throws(typeof(T), testCode);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <typeparam name="T">The type of the exception expected to be thrown</typeparam>
/// <param name="userMessage">The message to be shown if the test fails</param>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static T Throws<T>(string userMessage,
ThrowsDelegate testCode)
where T : Exception
{
return (T)Throws(typeof(T), testCode);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <param name="exceptionType">The type of the exception expected to be thrown</param>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static Exception Throws(Type exceptionType,
ThrowsDelegate testCode)
{
Exception exception = Record.Exception(testCode);
if (exception == null)
throw new ThrowsException(exceptionType);
if (!exceptionType.Equals(exception.GetType()))
throw new ThrowsException(exceptionType, exception);
return exception;
}
/// <summary>
/// Verifies that an expression is true.
/// </summary>
/// <param name="condition">The condition to be inspected</param>
/// <exception cref="TrueException">Thrown when the condition is false</exception>
public static void True(bool condition)
{
True(condition, null);
}
/// <summary>
/// Verifies that an expression is true.
/// </summary>
/// <param name="condition">The condition to be inspected</param>
/// <param name="userMessage">The message to be shown when the condition is false</param>
/// <exception cref="TrueException">Thrown when the condition is false</exception>
public static void True(bool condition,
string userMessage)
{
if (!condition)
throw new TrueException(userMessage);
}
class AssertComparer<T> : IComparer<T>
{
public int Compare(T x,
T y)
{
Type type = typeof(T);
// Null?
if (!type.IsValueType || (type.IsGenericType && type.GetGenericTypeDefinition().IsAssignableFrom(typeof(Nullable<>))))
{
if (Equals(x, default(T)))
{
if (Equals(y, default(T)))
return 0;
return -1;
}
if (Equals(y, default(T)))
return -1;
}
// Same type?
if (x.GetType() != y.GetType())
return -1;
// Arrays?
if (x.GetType().IsArray)
{
Array xArray = x as Array;
Array yArray = y as Array;
if (xArray != null && yArray != null)
{
if (xArray.Rank != 1)
throw new ArgumentException("Multi-dimension array comparison is not supported");
if (xArray.Length != yArray.Length)
return -1;
for (int index = 0; index < xArray.Length; index++)
if (!Equals(xArray.GetValue(index), yArray.GetValue(index)))
return -1;
return 0;
}
}
// Implements IComparable<T>?
IComparable<T> comparable1 = x as IComparable<T>;
if (comparable1 != null)
return comparable1.CompareTo(y);
// Implements IComparable?
IComparable comparable2 = x as IComparable;
if (comparable2 != null)
return comparable2.CompareTo(y);
// Implements IEquatable<T>?
IEquatable<T> equatable = x as IEquatable<T>;
if (equatable != null)
return equatable.Equals(y) ? 0 : -1;
// Last case, rely on Object.Equals
return Equals(x, y) ? 0 : -1;
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Net;
using System.Web;
using System.Xml;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Web.Core.Files;
using ASC.Web.Files.Classes;
using ASC.Web.Files.Helpers;
using ASC.Web.Files.Resources;
using ASC.Web.Files.Services.NotifyService;
using ASC.Web.Studio.UserControls.Statistics;
namespace ASC.Web.Files.HttpHandlers
{
public class DocuSignHandler : IHttpHandler
{
public static string Path
{
get { return FilesLinkUtility.FilesBaseAbsolutePath + "httphandlers/docusignhandler.ashx"; }
}
private static ILog Log
{
get { return Global.Logger; }
}
public void ProcessRequest(HttpContext context)
{
if (TenantStatisticsProvider.IsNotPaid())
{
context.Response.StatusCode = (int)HttpStatusCode.PaymentRequired;
context.Response.StatusDescription = "Payment Required.";
return;
}
try
{
switch ((context.Request[FilesLinkUtility.Action] ?? "").ToLower())
{
case "redirect":
Redirect(context);
break;
case "webhook":
Webhook(context);
break;
default:
throw new HttpException((int)HttpStatusCode.BadRequest, FilesCommonResource.ErrorMassage_BadRequest);
}
}
catch (InvalidOperationException e)
{
throw new HttpException((int)HttpStatusCode.InternalServerError, FilesCommonResource.ErrorMassage_BadRequest, e);
}
}
private static void Redirect(HttpContext context)
{
Log.Info("DocuSign redirect query: " + context.Request.QueryString);
var eventRedirect = context.Request["event"];
switch (eventRedirect.ToLower())
{
case "send":
context.Response.Redirect(PathProvider.StartURL + "#message/" + HttpUtility.UrlEncode(FilesCommonResource.DocuSignStatusSended), true);
break;
case "save":
case "cancel":
context.Response.Redirect(PathProvider.StartURL + "#error/" + HttpUtility.UrlEncode(FilesCommonResource.DocuSignStatusNotSended), true);
break;
case "error":
case "sessionend":
context.Response.Redirect(PathProvider.StartURL + "#error/" + HttpUtility.UrlEncode(FilesCommonResource.DocuSignStatusError), true);
break;
}
context.Response.Redirect(PathProvider.StartURL, true);
}
private const string XmlPrefix = "docusign";
private static void Webhook(HttpContext context)
{
Global.Logger.Info("DocuSign webhook: " + context.Request.QueryString);
try
{
var xmldoc = new XmlDocument();
xmldoc.Load(context.Request.InputStream);
Global.Logger.Info("DocuSign webhook outerXml: " + xmldoc.OuterXml);
var mgr = new XmlNamespaceManager(xmldoc.NameTable);
mgr.AddNamespace(XmlPrefix, "http://www.docusign.net/API/3.0");
var envelopeStatusNode = GetSingleNode(xmldoc, "DocuSignEnvelopeInformation/" + XmlPrefix + ":EnvelopeStatus", mgr);
var envelopeId = GetSingleNode(envelopeStatusNode, "EnvelopeID", mgr).InnerText;
var subject = GetSingleNode(envelopeStatusNode, "Subject", mgr).InnerText;
var statusString = GetSingleNode(envelopeStatusNode, "Status", mgr).InnerText;
DocuSignStatus status;
if (!Enum.TryParse(statusString, true, out status))
{
throw new Exception("DocuSign webhook unknown status: " + statusString);
}
Global.Logger.Info("DocuSign webhook: " + envelopeId + " " + subject + " " + status);
var customFieldUserIdNode = GetSingleNode(envelopeStatusNode, "CustomFields/" + XmlPrefix + ":CustomField[" + XmlPrefix + ":Name='" + DocuSignHelper.UserField + "']", mgr);
var userIdString = GetSingleNode(customFieldUserIdNode, "Value", mgr).InnerText;
Auth(userIdString);
switch (status)
{
case DocuSignStatus.Completed:
var documentStatuses = GetSingleNode(envelopeStatusNode, "DocumentStatuses", mgr);
foreach (XmlNode documentStatus in documentStatuses.ChildNodes)
{
try
{
var documentId = GetSingleNode(documentStatus, "ID", mgr).InnerText;
var documentName = GetSingleNode(documentStatus, "Name", mgr).InnerText;
string folderId = null;
string sourceTitle = null;
var documentFiels = GetSingleNode(documentStatus, "DocumentFields", mgr, true);
if (documentFiels != null)
{
var documentFieldFolderNode = GetSingleNode(documentFiels, "DocumentField[" + XmlPrefix + ":Name='" + FilesLinkUtility.FolderId + "']", mgr, true);
if (documentFieldFolderNode != null)
{
folderId = GetSingleNode(documentFieldFolderNode, "Value", mgr).InnerText;
}
var documentFieldTitleNode = GetSingleNode(documentFiels, "DocumentField[" + XmlPrefix + ":Name='" + FilesLinkUtility.FileTitle + "']", mgr, true);
if (documentFieldTitleNode != null)
{
sourceTitle = GetSingleNode(documentFieldTitleNode, "Value", mgr).InnerText;
}
}
var file = DocuSignHelper.SaveDocument(envelopeId, documentId, documentName, folderId);
NotifyClient.SendDocuSignComplete(file, sourceTitle ?? documentName);
}
catch (Exception ex)
{
Global.Logger.Error("DocuSign webhook save document: " + documentStatus.InnerText, ex);
}
}
break;
case DocuSignStatus.Declined:
case DocuSignStatus.Voided:
var statusFromResource = status == DocuSignStatus.Declined
? FilesCommonResource.DocuSignStatusDeclined
: FilesCommonResource.DocuSignStatusVoided;
NotifyClient.SendDocuSignStatus(subject, statusFromResource);
break;
}
}
catch (Exception e)
{
Global.Logger.Error("DocuSign webhook", e);
throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
}
}
private static void Auth(string userIdString)
{
Guid userId;
if (!Guid.TryParse(userIdString ?? "", out userId))
{
throw new Exception("DocuSign incorrect User ID: " + userIdString);
}
SecurityContext.AuthenticateMe(userId);
}
private static XmlNode GetSingleNode(XmlNode node, string xpath, XmlNamespaceManager mgr, bool canMiss = false)
{
var result = node.SelectSingleNode(XmlPrefix + ":" + xpath, mgr);
if (!canMiss && result == null) throw new Exception(xpath + " is null");
return result;
}
public bool IsReusable
{
get { return false; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Common.Logging;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using JenkinsTray.BusinessComponents;
using JenkinsTray.Entities;
using JenkinsTray.Utils;
using JenkinsTray.Utils.Logging;
using Spring.Context.Support;
using Spring.Collections.Generic;
namespace JenkinsTray.UI
{
public partial class TrayNotifier : Component
{
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static readonly int MAX_TOOLTIP_LENGTH = 127;
public static readonly int BALLOON_TOOLTIP_TIMEOUT = 3000;
public static TrayNotifier Instance
{
get
{
var instance = (TrayNotifier) ContextRegistry.GetContext().GetObject("TrayNotifier");
return instance;
}
}
private BuildStatus lastBuildStatus;
private readonly IDictionary<Project, AllBuildDetails> lastProjectsBuildDetails =
new Dictionary<Project, AllBuildDetails>();
private readonly IDictionary<Project, BuildStatus> acknowledgedStatusByProject =
new Dictionary<Project, BuildStatus>();
private IDictionary<string, Icon> iconsByKey;
public ConfigurationService ConfigurationService { get; set; }
public JenkinsService JenkinsService { get; set; }
public ProjectsUpdateService UpdateService { get; set; }
public NotificationService NotificationService { get; set; }
public TrayNotifier()
{
InitializeComponent();
LoadIcons();
}
public void Initialize()
{
ConfigurationService.ConfigurationUpdated += configurationService_ConfigurationUpdated;
UpdateService.ProjectsUpdated += updateService_ProjectsUpdated;
Disposed += delegate
{
ConfigurationService.ConfigurationUpdated -= configurationService_ConfigurationUpdated;
UpdateService.ProjectsUpdated -= updateService_ProjectsUpdated;
};
}
private void configurationService_ConfigurationUpdated()
{
UpdateNotifier();
}
#if false
private delegate void ProjectsUpdatedDelegate();
private void updateService_ProjectsUpdated()
{
Delegate del = new ProjectsUpdatedDelegate(OnProjectsUpdated);
MainForm.Instance.BeginInvoke(del);
}
private void OnProjectsUpdated()
{
UpdateGlobalStatus();
}
#else
private void updateService_ProjectsUpdated()
{
UpdateNotifier();
}
#endif
// FIXME: the framework doesn't fire correctly MouseClick and MouseDoubleClick,
// so this is deactivated
private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
try
{
// order the projects by build status
var projectsByStatus = new Dictionary<BuildStatusEnum, Spring.Collections.Generic.SortedSet<Project>>();
foreach (var pair in lastProjectsBuildDetails)
{
var status = BuildStatusEnum.Unknown;
if (pair.Value != null)
status = BuildStatusUtils.DegradeStatus(pair.Value.Status).Value;
var projects = new Spring.Collections.Generic.SortedSet<Project>();
if (projectsByStatus.TryGetValue(status, out projects) == false)
{
projects = new Spring.Collections.Generic.SortedSet<Project>();
projectsByStatus.Add(status, projects);
}
projects.Add(pair.Key);
}
var text = new StringBuilder();
string prefix = null;
foreach (var pair in projectsByStatus)
{
// don't display successful projects unless this is the only status
if (pair.Key == BuildStatusEnum.Successful || projectsByStatus.Count == 1)
continue;
if (prefix != null)
text.Append(prefix);
var statusText = JenkinsTrayResources.ResourceManager
.GetString("BuildStatus_" + pair.Key);
text.Append(statusText);
foreach (var project in pair.Value)
{
text.Append("\n - ").Append(project.Name);
var lastFailedBuild = project.LastFailedBuild;
if (lastFailedBuild != null && lastFailedBuild.Users != null && lastFailedBuild.Users.Count > 0)
{
var users = StringUtils.Join(lastFailedBuild.Users, ", ");
text.Append(" (").Append(users).Append(")");
}
}
prefix = "\n";
}
var textToDisplay = text.ToString();
if (string.IsNullOrEmpty(textToDisplay))
textToDisplay = JenkinsTrayResources.DisplayBuildStatus_NoProjects;
notifyIcon.ShowBalloonTip(BALLOON_TOOLTIP_TIMEOUT, JenkinsTrayResources.DisplayBuildStatus_Caption,
textToDisplay, ToolTipIcon.Info);
}
catch (Exception ex)
{
LoggingHelper.LogError(logger, ex);
}
}
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
MainForm.ShowOrFocus();
}
private void openMenuItem_Click(object sender, EventArgs e)
{
MainForm.ShowOrFocus();
}
private void refreshMenuItem_Click(object sender, EventArgs e)
{
UpdateService.UpdateProjects();
}
private void settingsMenuItem_Click(object sender, EventArgs e)
{
MainForm.Instance.Show();
SettingsForm.ShowDialogOrFocus();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
MainForm.Instance.Exit();
}
private void aboutMenuItem_Click(object sender, EventArgs e)
{
MainForm.Instance.Show();
AboutForm.ShowDialogOrFocus();
}
public void UpdateNotifier()
{
try
{
DoUpdateNotifier();
}
catch (Exception ex)
{
LoggingHelper.LogError(logger, ex);
UpdateIcon(BuildStatus.UNKNOWN_BUILD_STATUS);
}
}
public void UpdateNotifierStartup()
{
UpdateIcon(BuildStatus.UNKNOWN_BUILD_STATUS);
notifyIcon.Text = Assembly.GetExecutingAssembly().GetName().Name;
}
private void DoUpdateNotifier()
{
BuildStatusEnum? worstBuildStatus = null;
var buildInProgress = false;
var buildIsStuck = false;
var errorProjects = new HashedSet<Project>();
var regressingProjects = new HashedSet<Project>();
var progressingAndErrorProjects = new HashedSet<Project>();
var interestingProjects = new HashedSet<Project>();
var totalProjectCount = 0;
foreach (var server in ConfigurationService.Servers)
{
foreach (var project in server.Projects)
{
totalProjectCount++;
var status = GetProjectStatus(project);
if (worstBuildStatus == null || status.Value > worstBuildStatus)
worstBuildStatus = status.Value;
if (status.Value >= BuildStatusEnum.Failed)
errorProjects.Add(project);
if (status.Value > BuildStatusEnum.Successful)
progressingAndErrorProjects.Add(project);
if (status.IsInProgress)
{
buildInProgress = true;
progressingAndErrorProjects.Add(project);
}
if (status.IsStuck)
buildIsStuck = true;
if (IsRegressing(project))
regressingProjects.Add(project);
lastProjectsBuildDetails[project] = project.AllBuildDetails;
if (project.Activity.HasBuildActivity)
{
interestingProjects.Add(project);
}
}
}
if (worstBuildStatus == null)
worstBuildStatus = BuildStatusEnum.Unknown;
#if false // tests
lastBuildStatus++;
if (lastBuildStatus > BuildStatus.Failed_BuildInProgress)
lastBuildStatus = 0;
worstBuildStatus = lastBuildStatus;
Console.WriteLine("tray:"+lastBuildStatus);
#endif
var buildStatus = new BuildStatus(worstBuildStatus.Value, buildInProgress, buildIsStuck);
UpdateIcon(buildStatus);
UpdateTrayTooltip(progressingAndErrorProjects, totalProjectCount);
if (ConfigurationService.NotificationSettings.BalloonNotifications)
{
UpdateBalloonTip(errorProjects, regressingProjects);
ShowBallowTip(interestingProjects);
}
lastBuildStatus = buildStatus;
}
private BuildStatus GetProjectStatus(Project project)
{
var status = project.Status;
var acknowledgedStatus = GetAcknowledgedStatus(project);
if (project.IsAcknowledged || (acknowledgedStatus != null))
{
if (project.IsAcknowledged || (status.Value == acknowledgedStatus.Value))
return new BuildStatus(BuildStatusEnum.Successful, false, false);
if (status.Value != BuildStatusEnum.Unknown && BuildStatusUtils.IsWorse(acknowledgedStatus, status))
ClearAcknowledgedStatus(project);
}
return status;
}
private bool IsRegressing(Project project)
{
AllBuildDetails lastBuildDetails;
if (lastProjectsBuildDetails.TryGetValue(project, out lastBuildDetails) == false
|| lastBuildDetails == null)
return false;
var newBuildDetails = project.AllBuildDetails;
if (newBuildDetails == null)
return false;
// moving from unknown/aborted to successful should not be considered as a regression
if (newBuildDetails.Status.Value <= BuildStatusEnum.Successful)
return false;
var res = BuildStatusUtils.IsWorse(newBuildDetails.Status, lastBuildDetails.Status);
return res;
}
private void UpdateTrayTooltip(ICollection<Project> progressingAndErrorProjects, int totalProjectCount)
{
var tooltipText = new StringBuilder();
string prefix = null;
if (totalProjectCount == 0)
{
tooltipText.Append(JenkinsTrayResources.Tooltip_NoProjects);
}
else if (progressingAndErrorProjects != null && progressingAndErrorProjects.Count > 0)
{
foreach (var project in progressingAndErrorProjects)
{
if (project.IsAcknowledged)
continue;
lock (acknowledgedStatusByProject)
{
if (acknowledgedStatusByProject.ContainsKey(project))
continue;
}
if (prefix != null)
tooltipText.Append(prefix);
var status = GetProjectStatus(project);
var buildDetails = project.LastBuild;
if (status.IsInProgress && (status.Value == BuildStatusEnum.Failed))
{
tooltipText.Append(string.Format(JenkinsTrayResources.Tooltip_Failed_And_InProgress,
project.Name));
}
else if (status.IsInProgress)
{
tooltipText.Append(string.Format(JenkinsTrayResources.Tooltip_InProgress, project.Name));
}
else
{
tooltipText.Append(string.Format(JenkinsTrayResources.Tooltip_BuildStatus, project.Name,
status.Value));
}
prefix = "\n";
if (tooltipText.ToString().Length > MAX_TOOLTIP_LENGTH)
break;
}
}
else
{
tooltipText.Append(JenkinsTrayResources.Tooltip_AllGood);
}
prefix = tooltipText.ToString();
SetNotifyIconText(notifyIcon, prefix);
}
public void ShowBallowTip(ICollection<Project> interestingProjects)
{
foreach (var project in interestingProjects)
{
try
{
var info = project.Activity.ActivityDetails;
// Need a queue so no events are skipped
notifyIcon.ShowBalloonTip(BALLOON_TOOLTIP_TIMEOUT, info.Caption, info.Message, info.Icon);
}
catch (Exception ex)
{
LoggingHelper.LogError(logger, ex);
}
}
}
private void UpdateBalloonTip(ICollection<Project> errorProjects, ICollection<Project> regressingProjects)
{
if (lastBuildStatus != null && lastBuildStatus.Value < BuildStatusEnum.Failed
&& errorProjects != null && errorProjects.Count > 0)
{
var errorProjectsText = new StringBuilder();
string prefix = null;
foreach (var project in errorProjects)
{
if (prefix != null)
errorProjectsText.Append(prefix);
var buildDetails = project.LastFailedBuild;
if (buildDetails == null)
logger.Warn("No details for the last failed build of project in error: " + project.Url);
var users = buildDetails != null ? buildDetails.Users : null;
FormatProjectDetails(project.Name, users, errorProjectsText);
prefix = "\n";
}
notifyIcon.ShowBalloonTip(BALLOON_TOOLTIP_TIMEOUT, JenkinsTrayResources.BuildFailed_Caption,
errorProjectsText.ToString(), ToolTipIcon.Error);
}
else if (regressingProjects != null && regressingProjects.Count > 0)
{
var regressingProjectsText = new StringBuilder();
string prefix = null;
foreach (var project in regressingProjects)
{
if (prefix != null)
regressingProjectsText.Append(prefix);
var buildDetails = project.AllBuildDetails.LastCompletedBuild;
if (buildDetails == null)
logger.Warn("No details for the last failed build of project in error: " + project.Url);
var users = buildDetails != null ? buildDetails.Users : null;
FormatProjectDetails(project.Name, users, regressingProjectsText);
prefix = "\n";
}
notifyIcon.ShowBalloonTip(10000, JenkinsTrayResources.BuildRegressions_Caption,
regressingProjectsText.ToString(), ToolTipIcon.Warning);
}
}
private void FormatProjectDetails(string projectName, Spring.Collections.Generic.ISet<string> users, StringBuilder builder)
{
builder.Append(projectName);
if (users != null && users.Count > 0)
{
var userString = StringUtils.Join(users, ", ");
builder.Append(" (").Append(userString).Append(")");
}
}
private void UpdateIcon(BuildStatus buildStatus)
{
var icon = iconsByKey[buildStatus.Key];
notifyIcon.Icon = icon;
// update the main window's icon
if (ConfigurationService.GeneralSettings.UpdateMainWindowIcon)
MainForm.Instance.UpdateIcon(icon);
}
private void LoadIcons()
{
iconsByKey = new Dictionary<string, Icon>();
foreach (BuildStatusEnum statusValue in Enum.GetValues(typeof(BuildStatusEnum)))
{
LoadIcon(statusValue, false, false);
LoadIcon(statusValue, false, true);
LoadIcon(statusValue, true, false);
LoadIcon(statusValue, true, true);
}
}
private void LoadIcon(BuildStatusEnum statusValue, bool isInProgress, bool isStuck)
{
var status = new BuildStatus(statusValue, isInProgress, isStuck);
if (iconsByKey.ContainsKey(status.Key))
return;
try
{
var resourceName = string.Format("JenkinsTray.Resources.TrayIcons.{0}.ico", status.Key);
var icon = ResourceImageHelper.CreateIconFromResources(resourceName, GetType().Assembly);
iconsByKey.Add(status.Key, icon);
}
catch (Exception ex)
{
XtraMessageBox.Show(JenkinsTrayResources.FailedLoadingIcons_Text,
JenkinsTrayResources.FailedLoadingIcons_Caption,
MessageBoxButtons.OK, MessageBoxIcon.Error);
LoggingHelper.LogError(logger, ex);
throw new Exception("Failed loading icon: " + statusValue, ex);
}
}
private void notifyIcon_MouseUp(object sender, MouseEventArgs e)
{
Console.WriteLine(e.Clicks);
}
public void AcknowledgedProject()
{
UpdateNotifier();
}
public void AcknowledgeStatus(Project project, BuildStatus currentStatus)
{
lock (acknowledgedStatusByProject)
{
acknowledgedStatusByProject[project] = currentStatus;
}
UpdateNotifier();
}
public void ClearAcknowledgedStatus(Project project)
{
lock (acknowledgedStatusByProject)
{
acknowledgedStatusByProject.Remove(project);
}
UpdateNotifier();
}
private BuildStatus GetAcknowledgedStatus(Project project)
{
BuildStatus status;
lock (acknowledgedStatusByProject)
{
if (acknowledgedStatusByProject.TryGetValue(project, out status) == false)
return null;
}
return status;
}
public bool IsStatusAcknowledged(Project project)
{
lock (acknowledgedStatusByProject)
{
return acknowledgedStatusByProject.ContainsKey(project);
}
}
public static void SetNotifyIconText(NotifyIcon notifyIcon, string text)
{
if (text.Length > MAX_TOOLTIP_LENGTH)
{
text = text.Remove(MAX_TOOLTIP_LENGTH - 4) + " ...";
}
var t = typeof(NotifyIcon);
var hidden = BindingFlags.NonPublic | BindingFlags.Instance;
t.GetField("text", hidden).SetValue(notifyIcon, text);
if ((bool) t.GetField("added", hidden).GetValue(notifyIcon))
t.GetMethod("UpdateIcon", hidden).Invoke(notifyIcon, new object[] {true});
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ConfigurationManager.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration {
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Configuration.Internal;
using System.IO;
using System.Security.Permissions;
using System.Threading;
public static class ConfigurationManager {
// The Configuration System
private static volatile IInternalConfigSystem s_configSystem;
// Initialization state
private static volatile InitState s_initState;
private static object s_initLock;
private static volatile Exception s_initError;
private enum InitState {
// Initialization has not yet started.
NotStarted = 0,
// Initialization has started.
Started,
// The config system can be used, but initialization is not yet complete.
Usable,
// The config system has been completely initialized.
Completed
};
static ConfigurationManager() {
s_initState = InitState.NotStarted;
s_initLock = new object();
}
// to be used by System.Diagnostics to avoid false config results during config init
internal static bool SetConfigurationSystemInProgress {
get {
return InitState.NotStarted < s_initState && s_initState < InitState.Completed;
}
}
// Called by ASP.NET to allow hierarchical configuration settings and ASP.NET specific extenstions.
internal static void SetConfigurationSystem(IInternalConfigSystem configSystem, bool initComplete) {
lock (s_initLock) {
// It is an error if the configuration system has already been set.
if (s_initState != InitState.NotStarted) {
throw new InvalidOperationException(SR.GetString(SR.Config_system_already_set));
}
s_configSystem = configSystem;
if (initComplete) {
s_initState = InitState.Completed;
}
else {
s_initState = InitState.Usable;
}
}
}
private static void EnsureConfigurationSystem() {
// If a configuration system has not yet been set,
// create the DefaultConfigurationSystem for exe's.
lock (s_initLock) {
if (s_initState < InitState.Usable) {
s_initState = InitState.Started;
try {
try {
// Create the system, but let it initialize itself
// when GetConfig is called, so that it can handle its
// own re-entrancy issues during initialization.
// When initialization is complete, the DefaultConfigurationSystem
// will call CompleteConfigInit to mark initialization as
// having completed.
// Note: the ClientConfigurationSystem has a 2-stage initialization,
// and that's why s_initState isn't set to InitState.Completed yet.
s_configSystem = new ClientConfigurationSystem();
s_initState = InitState.Usable;
}
catch (Exception e) {
s_initError = new ConfigurationErrorsException(SR.GetString(SR.Config_client_config_init_error), e);
throw s_initError;
}
}
catch {
s_initState = InitState.Completed;
throw;
}
}
}
}
// Set the initialization error.
internal static void SetInitError(Exception initError) {
s_initError = initError;
}
// Mark intiailization as having completed.
internal static void CompleteConfigInit() {
lock (s_initLock) {
s_initState = InitState.Completed;
}
}
private static void PrepareConfigSystem() {
// Ensure the configuration system is usable.
if (s_initState < InitState.Usable) {
EnsureConfigurationSystem();
}
// If there was an initialization error, throw it.
if (s_initError != null) {
throw s_initError;
}
}
internal static bool SupportsUserConfig {
get {
PrepareConfigSystem();
return s_configSystem.SupportsUserConfig;
}
}
//
// *************************************************
// ** Static Runtime Functions to retrieve config **
// *************************************************
//
public static NameValueCollection AppSettings {
get {
object section = GetSection("appSettings");
if (section == null || !(section is NameValueCollection)) {
// If config is null or not the type we expect, the declaration was changed.
// Treat it as a configuration error.
throw new ConfigurationErrorsException(SR.GetString(SR.Config_appsettings_declaration_invalid));
}
return (NameValueCollection) section;
}
}
public static ConnectionStringSettingsCollection ConnectionStrings {
get {
object section = GetSection("connectionStrings");
// Verify type, and return the collection
if (section == null || section.GetType() != typeof(ConnectionStringsSection)) {
// If config is null or not the type we expect, the declaration was changed.
// Treat it as a configuration error.
throw new ConfigurationErrorsException(SR.GetString(SR.Config_connectionstrings_declaration_invalid));
}
ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection) section;
return connectionStringsSection.ConnectionStrings;
}
}
// GetSection
//
// Retrieve a Section from the configuration system
//
public static object GetSection(string sectionName) {
// Avoid unintended AV's by ensuring sectionName is not empty.
// For compatibility, we cannot throw an InvalidArgumentException.
if (String.IsNullOrEmpty(sectionName)) {
return null;
}
PrepareConfigSystem();
object section = s_configSystem.GetSection(sectionName);
return section;
}
public static void RefreshSection(string sectionName) {
// Avoid unintended AV's by ensuring sectionName is not empty.
// For consistency with GetSection, we should not throw an InvalidArgumentException.
if (String.IsNullOrEmpty(sectionName)) {
return;
}
PrepareConfigSystem();
s_configSystem.RefreshConfig(sectionName);
}
//
// *************************************************
// ** Static Management Functions to edit config **
// *************************************************
//
//
// OpenMachineConfiguration
//
public static Configuration OpenMachineConfiguration() {
return OpenExeConfigurationImpl(null, true, ConfigurationUserLevel.None, null);
}
public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap) {
return OpenExeConfigurationImpl(fileMap, true, ConfigurationUserLevel.None, null);
}
//
// OpenExeConfiguration
//
public static Configuration OpenExeConfiguration(ConfigurationUserLevel userLevel) {
return OpenExeConfigurationImpl(null, false, userLevel, null);
}
public static Configuration OpenExeConfiguration(string exePath) {
return OpenExeConfigurationImpl(null, false, ConfigurationUserLevel.None, exePath);
}
public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel) {
return OpenExeConfigurationImpl(fileMap, false, userLevel, null);
}
public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel, bool preLoad) {
return OpenExeConfigurationImpl(fileMap, false, userLevel, null, preLoad);
}
private static Configuration OpenExeConfigurationImpl(ConfigurationFileMap fileMap, bool isMachine, ConfigurationUserLevel userLevel, string exePath, bool preLoad = false) {
// exePath must be specified if not running inside ClientConfigurationSystem
if ( !isMachine &&
( ( ( fileMap == null ) && ( exePath == null ) ) ||
( ( fileMap != null ) && ( ( ( ExeConfigurationFileMap ) fileMap ).ExeConfigFilename == null ) )
)
) {
if ( ( s_configSystem != null ) &&
( s_configSystem.GetType() != typeof( ClientConfigurationSystem ) ) ) {
throw new ArgumentException(SR.GetString(SR.Config_configmanager_open_noexe));
}
}
Configuration config = ClientConfigurationHost.OpenExeConfiguration(fileMap, isMachine, userLevel, exePath);
if (preLoad) {
PreloadConfiguration(config);
}
return config;
}
/// <summary>
/// Recursively loads configuration section groups and sections belonging to a configuration object.
/// </summary>
private static void PreloadConfiguration(Configuration configuration) {
if (null == configuration) {
return;
}
// Preload root-level sections.
foreach (ConfigurationSection section in configuration.Sections) {
}
// Recursively preload all section groups and sections.
foreach (ConfigurationSectionGroup sectionGroup in configuration.SectionGroups) {
PreloadConfigurationSectionGroup(sectionGroup);
}
}
private static void PreloadConfigurationSectionGroup(ConfigurationSectionGroup sectionGroup) {
if (null == sectionGroup) {
return;
}
// Preload sections just by iterating.
foreach (ConfigurationSection section in sectionGroup.Sections) {
}
// Load child section groups.
foreach (ConfigurationSectionGroup childSectionGroup in sectionGroup.SectionGroups) {
PreloadConfigurationSectionGroup(childSectionGroup);
}
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>
/// All (tainted) sinks are named `sink[Param|Field|Property]N`, for some N, and all
/// non-sinks are named `nonSink[Param|Field|Property]N`, for some N.
/// Both sinks and non-sinks are passed to the method `Check` for convenience in the
/// test query.
/// </summary>
public class DataFlow
{
public void M()
{
// Static field, tainted
Test.SinkField0 = "taint source";
Check(Test.SinkField0);
// Static field, not tainted
Test.NonSinkField0 = "not tainted";
Check(Test.NonSinkField0);
// Static property, tainted
Test.SinkProperty0 = Test.SinkField0;
Check(Test.SinkProperty0);
// Static property, not tainted
Test.NonSinkProperty0 = Test.NonSinkField0;
Check(Test.NonSinkProperty0);
Test.NonSinkProperty1 = Test.SinkField0;
Check(Test.NonSinkProperty1);
// Flow into a callable (non-delegate), tainted
In0(Test.SinkProperty0);
var methodInfo = typeof(DataFlow).GetMethod("In1");
var args = new object[] { Test.SinkProperty0 };
methodInfo.Invoke(null, args);
// Flow into a callable (non-delegate), not tainted
NonIn0("");
// Flow into a callable (delegate, locally resolvable), tainted
Action<string> in2 = sinkParam2 => Check(sinkParam2);
in2(Test.SinkProperty0);
// Flow into a callable (delegate, locally resolvable), not tainted
Action<string> nonIn1 = nonSinkParam1 => Check(nonSinkParam1);
nonIn1("");
// Flow into a callable (delegate, resolvable via call), tainted
Apply(In3, Test.SinkProperty0);
Apply(x => In4(x), Test.SinkProperty0);
ApplyDelegate(new MyDelegate(In5), Test.SinkProperty0);
ApplyDelegate(In6, Test.SinkProperty0);
myDelegate = new MyDelegate(x => In7(x));
ApplyDelegate(myDelegate, Test.SinkProperty0);
// Flow into a callable (delegate, resolvable via call), not tainted
Apply(nonSinkParam0 => Check(nonSinkParam0), "not tainted");
ApplyDelegate(new MyDelegate(nonSinkParam0 => Check(nonSinkParam0)), "not tainted");
// Flow into a callable (property), tainted
InProperty = Test.SinkProperty0;
// Flow into a callable (property), not tainted
NonInProperty = "not tainted";
// Flow through a callable that returns the argument (non-delegate), tainted
var sink0 = Return(Test.SinkProperty0);
Check(sink0);
var sink1 = (string)typeof(DataFlow).GetMethod("Return").Invoke(null, new object[] { sink0 });
Check(sink1);
string sink2;
ReturnOut(sink1, out sink2, out var _);
Check(sink2);
var sink3 = "";
ReturnRef(sink2, ref sink3, ref sink3);
Check(sink3);
var sink13 = ((IEnumerable<string>)new string[] { sink3 }).SelectEven(x => x).First();
Check(sink13);
var sink14 = ((IEnumerable<string>)new string[] { sink13 }).Select(ReturnCheck).First();
Check(sink14);
var sink15 = ((IEnumerable<string>)new string[] { sink14 }).Zip(((IEnumerable<string>)new string[] { "" }), (x, y) => x).First();
Check(sink15);
var sink16 = ((IEnumerable<string>)new string[] { "" }).Zip(((IEnumerable<string>)new string[] { sink15 }), (x, y) => y).First();
Check(sink16);
var sink17 = ((IEnumerable<string>)new string[] { sink14 }).Aggregate("", (acc, s) => acc + s, x => x);
Check(sink17);
var sink18 = ((IEnumerable<string>)new string[] { "" }).Aggregate(sink14, (acc, s) => acc + s, x => x);
Check(sink18);
int sink21;
Int32.TryParse(sink18, out sink21);
Check(sink21);
bool sink22;
bool.TryParse(sink18, out sink22);
Check(sink22);
int sink21b;
Int32.TryParse(sink18, System.Globalization.NumberStyles.None, null, out sink21b);
Check(sink21b);
// Flow through a callable that returns the argument (non-delegate), not tainted
var nonSink0 = Return("");
Check(nonSink0);
nonSink0 = (string)typeof(DataFlow).GetMethod("Return").Invoke(null, new object[] { nonSink0 });
Check(nonSink0);
ReturnOut("", out nonSink0, out string _);
Check(nonSink0);
ReturnOut(sink1, out var _, out nonSink0);
Check(nonSink0);
ReturnRef("", ref nonSink0, ref nonSink0);
Check(nonSink0);
ReturnRef(sink1, ref sink1, ref nonSink0);
Check(nonSink0);
nonSink0 = ((IEnumerable<string>)new string[] { nonSink0 }).SelectEven(x => x).First();
Check(nonSink0);
nonSink0 = ((IEnumerable<string>)new string[] { nonSink0 }).Select(x => x).First();
Check(nonSink0);
nonSink0 = ((IEnumerable<string>)new string[] { sink14 }).Zip(((IEnumerable<string>)new string[] { "" }), (x, y) => y).First();
Check(nonSink0);
nonSink0 = ((IEnumerable<string>)new string[] { "" }).Zip(((IEnumerable<string>)new string[] { sink15 }), (x, y) => x).First();
Check(nonSink0);
nonSink0 = ((IEnumerable<string>)new string[] { sink14 }).Aggregate("", (acc, s) => acc, x => x);
Check(nonSink0);
nonSink0 = ((IEnumerable<string>)new string[] { sink14 }).Aggregate("", (acc, s) => acc + s, x => "");
Check(nonSink0);
nonSink0 = ((IEnumerable<string>)new string[] { nonSink0 }).Aggregate(sink1, (acc, s) => s, x => x);
Check(nonSink0);
int nonSink2;
Int32.TryParse(nonSink0, out nonSink2);
Check(nonSink2);
bool nonSink3;
bool.TryParse(nonSink0, out nonSink3);
Check(nonSink3);
// Flow through a callable that returns the argument (delegate, locally resolvable), tainted
Func<string, string> @return = x => ApplyFunc(Return, x);
var sink4 = @return(sink3);
Check(sink4);
// Flow through a callable that returns the argument (delegate, locally resolvable), not tainted
nonSink0 = @return(nonSink0);
Check(nonSink0);
// Flow through a callable that returns the argument (delegate, resolvable via call), tainted
var sink5 = ApplyFunc(Return, sink4);
Check(sink5);
// Flow through a callable that (doesn't) return(s) the argument (delegate, resolvable via call), not tainted
nonSink0 = ApplyFunc(Return, "");
Check(nonSink0);
nonSink0 = ApplyFunc(_ => "", sink5);
Check(nonSink0);
// Flow out of a callable (non-delegate), tainted
var sink6 = Out();
Check(sink6);
string sink7;
OutOut(out sink7);
Check(sink7);
var sink8 = "";
OutRef(ref sink8);
Check(sink8);
var sink12 = OutYield().First();
Check(sink12);
var sink23 = TaintedParam(nonSink0); // even though the argument is not tainted, the parameter is considered tainted
Check(sink23);
// Flow out of a callable (non-delegate), not tainted
nonSink0 = NonOut();
Check(nonSink0);
NonOutOut(out nonSink0);
Check(nonSink0);
NonOutRef(ref nonSink0);
Check(nonSink0);
nonSink0 = NonOutYield().First();
Check(nonSink0);
nonSink0 = NonTaintedParam(nonSink0);
Check(nonSink0);
// Flow out of a callable (delegate), tainted
Func<string> @out = () => "taint source";
var sink9 = @out();
Check(sink9);
// Flow out of a callable (delegate), not tainted
Func<string> nonOut = () => "";
nonSink0 = nonOut();
Check(nonSink0);
// Flow out of a callable (method access), tainted
var sink10 = new Lazy<string>(Out).Value;
Check(sink10);
// Flow out of a callable (method access), not tainted
nonSink0 = new Lazy<string>(NonOut).Value;
Check(nonSink0);
// Flow out of a callable (property), tainted
var sink19 = OutProperty;
Check(sink19);
// Flow out of a callable (property), not tainted
nonSink0 = NonOutProperty;
Check(nonSink0);
}
public void M2()
{
IQueryable<string> tainted = new[] { "taint source" }.AsQueryable();
IQueryable<string> notTainted = new[] { "not tainted" }.AsQueryable();
// Flow into a callable via library call, tainted
Func<string, string> f1 = sinkParam10 => { Check(sinkParam10); return sinkParam10; };
System.Linq.Expressions.Expression<Func<string, string>> f2 = x => ReturnCheck2(x);
var sink24 = tainted.Select(f1).First();
Check(sink24);
var sink25 = tainted.Select(f2).First();
Check(sink25);
var sink26 = tainted.Select(ReturnCheck3).First();
Check(sink26);
// Flow into a callable via library call, not tainted
Func<string, string> f3 = nonSinkParam => { Check(nonSinkParam); return nonSinkParam; };
System.Linq.Expressions.Expression<Func<string, string>> f4 = x => NonReturnCheck(x);
var nonSink = notTainted.Select(f1).First();
Check(nonSink);
nonSink = notTainted.Select(f2).First();
Check(nonSink);
nonSink = notTainted.Select(f3).First();
Check(nonSink);
nonSink = notTainted.Select(f4).First();
Check(nonSink);
nonSink = notTainted.Select(ReturnCheck3).First();
Check(nonSink);
}
public async void M3()
{
// async await, tainted
var task = Task.Run(() => "taint source");
var sink41 = task.Result;
Check(sink41);
var sink42 = await task;
Check(sink42);
// async await, not tainted
task = Task.Run(() => "");
var nonSink0 = task.Result;
Check(nonSink0);
var nonSink1 = await task;
Check(nonSink1);
}
static void Check<T>(T x) { }
static void In0<T>(T sinkParam0)
{
In0<T>(sinkParam0);
Check(sinkParam0);
}
static void In1<T>(T sinkParam1)
{
Check(sinkParam1);
}
static void In3<T>(T sinkParam3)
{
Check(sinkParam3);
}
static void In4<T>(T sinkParam4)
{
Check(sinkParam4);
}
static void In5<T>(T sinkParam5)
{
Check(sinkParam5);
}
static void In6<T>(T sinkParam6)
{
Check(sinkParam6);
}
static void In7<T>(T sinkParam7)
{
Check(sinkParam7);
}
static void NonIn0<T>(T nonSinkParam0)
{
Check(nonSinkParam0);
}
static T Return<T>(T x)
{
var y = ApplyFunc(x0 => x0, x);
return y == null ? default(T) : y;
}
static void ReturnOut<T>(T x, out T y, out T z)
{
y = x;
z = default(T);
}
static void ReturnRef<T>(T x, ref T y, ref T z)
{
y = x;
}
static T ReturnCheck<T>(T sinkParam8)
{
Check(sinkParam8);
return sinkParam8;
}
static T ReturnCheck2<T>(T sinkParam9)
{
Check(sinkParam9);
return sinkParam9;
}
static T ReturnCheck3<T>(T sinkParam11)
{
Check(sinkParam11);
return sinkParam11;
}
static T NonReturnCheck<T>(T nonSinkParam)
{
Check(nonSinkParam);
return nonSinkParam;
}
string Out()
{
return "taint source";
}
void OutOut(out string x)
{
x = "taint source";
}
void OutRef(ref string x)
{
x = "taint source";
}
IEnumerable<string> OutYield()
{
yield return "";
yield return "taint source";
yield return "";
}
string NonOut()
{
return "";
}
void NonOutOut(out string x)
{
x = "";
}
void NonOutRef(ref string x)
{
x = "";
}
IEnumerable<string> NonOutYield()
{
yield return "";
yield return "";
}
static void Apply<T>(Action<T> a, T x)
{
a(x);
}
static T ApplyFunc<S, T>(Func<S, T> f, S x)
{
return f(x);
}
public delegate void MyDelegate(string x);
static MyDelegate myDelegate;
static void ApplyDelegate(MyDelegate a, string x)
{
a(x);
}
static string TaintedParam(string tainted)
{
var sink11 = tainted;
Check(sink11);
return sink11;
}
static string NonTaintedParam(string nonTainted)
{
var nonSink0 = nonTainted;
Check(nonSink0);
return nonSink0;
}
class Test
{
public static string SinkField0;
public static string SinkProperty0 { get; set; }
public static string NonSinkField0;
public static string NonSinkProperty0 { get; set; }
public static string NonSinkProperty1 { get { return ""; } set { } }
}
string InProperty
{
get { return ""; }
set { var sink20 = value; Check(sink20); }
}
string NonInProperty
{
get { return ""; }
set { var nonSink0 = value; Check(nonSink0); }
}
string OutProperty
{
get { return "taint source"; }
}
string NonOutProperty
{
get { return ""; }
}
static void AppendToStringBuilder(StringBuilder sb, string s)
{
sb.Append(s);
}
void TestStringBuilderFlow()
{
var sb = new StringBuilder();
AppendToStringBuilder(sb, "taint source");
var sink43 = sb.ToString();
Check(sink43);
sb.Clear();
var nonSink = sb.ToString();
Check(nonSink);
}
void TestStringFlow()
{
var sink44 = string.Join(",", "whatever", "taint source");
Check(sink44);
var nonSink = string.Join(",", "whatever", "not tainted");
Check(nonSink);
}
public void M4()
{
var task = Task.Run(() => "taint source");
var awaitable = task.ConfigureAwait(false);
var awaiter = awaitable.GetAwaiter();
var sink45 = awaiter.GetResult();
Check(sink45);
}
void M5(bool b)
{
void Inner(Action<string> a, bool b, string arg)
{
if (b)
a = s => Check(s);
a(arg);
}
Inner(_ => { }, b, "taint source");
}
}
static class IEnumerableExtensions
{
public static IEnumerable<S> SelectEven<S, T>(this IEnumerable<T> e, Func<T, S> f)
{
int i = 0;
foreach (var x in e)
{
if (i++ % 2 == 0) yield return f(x);
}
}
}
| |
using System;
using System.Collections.Generic;
using Cake.Core;
using Cake.Curl.Tests.Fixtures;
using Cake.Testing;
using Xunit;
namespace Cake.Curl.Tests
{
public sealed class CurlUploadFileTests
{
public sealed class TheExecutable
{
[Fact]
public void Should_Throw_If_File_Path_Is_Null()
{
// Given
var fixture = new CurlUploadFileFixture();
fixture.FilePath = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
Assert.IsType<ArgumentNullException>(result);
Assert.Equal("filePath", ((ArgumentNullException)result).ParamName);
}
[Fact]
public void Should_Throw_If_Host_Is_Null()
{
// Given
var fixture = new CurlUploadFileFixture();
fixture.Host = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
Assert.IsType<ArgumentNullException>(result);
Assert.Equal("host", ((ArgumentNullException)result).ParamName);
}
[Fact]
public void Should_Throw_If_Settings_Are_Null()
{
// Given
var fixture = new CurlUploadFileFixture();
fixture.Settings = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
Assert.IsType<ArgumentNullException>(result);
Assert.Equal("settings", ((ArgumentNullException)result).ParamName);
}
[Fact]
public void Should_Throw_If_Curl_Executable_Was_Not_Found()
{
// Given
var fixture = new CurlUploadFileFixture();
fixture.GivenDefaultToolDoNotExist();
// When
var result = Record.Exception(() => fixture.Run());
// Then
Assert.IsType<CakeException>(result);
Assert.Equal("curl: Could not locate executable.", result.Message);
}
[Theory]
[InlineData("/bin/curl", "/bin/curl")]
[InlineData("./tools/curl", "/Working/tools/curl")]
public void Should_Use_Curl_Runner_From_Tool_Path_If_Provided(
string toolPath,
string expected)
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { ToolPath = toolPath }
};
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
#if NETFX
[Theory]
[InlineData(@"C:\bin\curl.exe", "C:/bin/curl.exe")]
[InlineData(@".\tools\curl.exe", "/Working/tools/curl.exe")]
public void Should_Use_Curl_Runner_From_Tool_Path_If_Provided_On_Windows(
string toolPath,
string expected)
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { ToolPath = toolPath }
};
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
#endif
[Fact]
public void Should_Find_Curl_Runner_If_Tool_Path_Not_Provided()
{
// Given
var fixture = new CurlUploadFileFixture();
// When
var result = fixture.Run();
// Then
Assert.Equal("/Working/tools/curl", result.Path.FullPath);
}
[Fact]
public void Should_Set_The_Absolute_Path_Of_The_File_To_Upload_In_Quotes_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
FilePath = "file/to/upload"
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--upload-file \"/Working/file/to/upload\"", result.Args);
}
[Fact]
public void Should_Set_The_Url_Of_The_Host_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Host = new Uri("protocol://host/path")
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--url protocol://host/path", result.Args);
}
[Fact]
public void Should_Set_The_User_Credentials_In_Quotes_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { Username = "user", Password = "password" }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--user \"user:password\"", result.Args);
}
[Fact]
public void Should_Redact_The_User_Password_In_The_Safe_Arguments()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { Username = "user", Password = "password" }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--user \"user:[REDACTED]\"", result.SafeArgs);
}
[Fact]
public void Should_Not_Set_The_User_Credentials_As_Argument_If_Username_Is_Null()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { Username = null, Password = "password" }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--user", result.Args);
}
[Fact]
public void Should_Set_The_Verbose_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { Verbose = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--verbose", result.Args);
}
[Fact]
public void Should_Set_The_Progress_Bar_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { ProgressBar = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--progress-bar", result.Args);
}
[Fact]
public void Should_Set_The_Headers_In_Quotes_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings =
{
Headers = new Dictionary<string, string>
{
["name"] = "value"
}
}
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--header \"name:value\"", result.Args);
}
[Fact]
public void Should_Set_Multiple_Headers_In_Quotes_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings =
{
Headers = new Dictionary<string, string>
{
["name1"] = "value1",
["name2"] = "value2",
["name3"] = "value3"
}
}
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--header \"name1:value1\" --header \"name2:value2\" --header \"name3:value3\"", result.Args);
}
[Fact]
public void Should_Set_The_Request_Command_In_Quotes_And_Upper_Case_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RequestCommand = "Command" }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--request \"COMMAND\"", result.Args);
}
[Fact]
public void Should_Set_The_Location_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { FollowRedirects = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--location", result.Args);
}
[Fact]
public void Should_Not_Set_The_Location_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { FollowRedirects = false }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--location", result.Args);
}
[Fact]
public void Should_Set_The_Fail_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { Fail = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--fail", result.Args);
}
[Fact]
public void Should_Not_Set_The_Fail_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { Fail = false }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--fail", result.Args);
}
[Fact]
public void Should_Set_The_Retry_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RetryCount = 3 }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--retry 3", result.Args);
}
[Fact]
public void Should_Not_Set_The_Retry_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RetryCount = 0 }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--retry", result.Args);
}
[Fact]
public void Should_Set_The_RetryDelay_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RetryDelaySeconds = 30 }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--retry-delay 30", result.Args);
}
[Fact]
public void Should_Not_Set_The_RetryDelay_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RetryDelaySeconds = 0 }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--retry-delay", result.Args);
}
[Fact]
public void Should_Set_The_RetryMaxTime_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RetryMaxTimeSeconds = 300 }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--retry-max-time 300", result.Args);
}
[Fact]
public void Should_Not_Set_The_RetryMaxTime_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RetryMaxTimeSeconds = 0 }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--retry-max-time", result.Args);
}
[Fact]
public void Should_Set_The_RetryConnRefused_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RetryOnConnectionRefused = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--retry-connrefused", result.Args);
}
[Fact]
public void Should_Not_Set_The_RetryConnRefused_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { RetryOnConnectionRefused = false }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--retry-connrefused", result.Args);
}
[Fact]
public void Should_Set_The_MaxTime_Option_As_Argument()
{
// Given
var maxTime = TimeSpan.FromSeconds(2.37);
var fixture = new CurlUploadFileFixture
{
Settings = { MaxTime = maxTime }
};
// When
var result = fixture.Run();
// Then
Assert.Contains(
$"--max-time {maxTime.TotalSeconds}",
result.Args);
}
[Fact]
public void Should_Not_Set_The_MaxTime_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { MaxTime = null }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--max-time", result.Args);
}
[Fact]
public void Should_Set_The_ConnectTimeout_Option_As_Argument()
{
// Given
var connectionTimeout = TimeSpan.FromSeconds(5.5);
var fixture = new CurlUploadFileFixture
{
Settings = { ConnectionTimeout = connectionTimeout }
};
// When
var result = fixture.Run();
// Then
Assert.Contains(
$"--connect-timeout {connectionTimeout.TotalSeconds}",
result.Args);
}
[Fact]
public void Should_Not_Set_The_ConnectTimeout_Option_As_Argument()
{
// Given
var fixture = new CurlUploadFileFixture
{
Settings = { ConnectionTimeout = null }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--connect-timeout", result.Args);
}
}
}
}
| |
//
// ContextPane.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena.Gui;
using Hyena.Widgets;
using Banshee.Base;
using Banshee.Configuration;
using Banshee.Collection;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
using Banshee.Gui;
namespace Banshee.ContextPane
{
public class ContextPane : Gtk.HBox
{
private Gtk.Notebook notebook;
private VBox vbox;
private bool large = false;
private bool initialized = false;
private RoundedFrame no_active;
private RoundedFrame loading;
private RadioButton radio_group = new RadioButton (null, "");
private Dictionary<BaseContextPage, RadioButton> pane_tabs = new Dictionary<BaseContextPage, RadioButton> ();
private Dictionary<BaseContextPage, Widget> pane_pages = new Dictionary<BaseContextPage, Widget> ();
private List<BaseContextPage> pages = new List<BaseContextPage> ();
private BaseContextPage active_page;
private Action<bool> expand_handler;
public Action<bool> ExpandHandler {
set { expand_handler = value; }
}
public bool Large {
get { return large; }
}
public ContextPane ()
{
HeightRequest = 200;
CreateContextNotebook ();
CreateTabButtonBox ();
new ContextPageManager (this);
initialized = true;
RestoreLastActivePage ();
Enabled = ShowSchema.Get ();
ShowAction.Activated += OnShowContextPane;
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.TrackInfoUpdated);
}
private void RestoreLastActivePage ()
{
// TODO restore the last page
string last_id = LastContextPageSchema.Get ();
if (!String.IsNullOrEmpty (last_id)) {
var page = pages.FirstOrDefault (p => p.Id == last_id);
if (page != null) {
SetActivePage (page);
pane_tabs[page].Active = true;
}
}
if (active_page == null) {
ActivateFirstPage ();
}
}
private void CreateTabButtonBox ()
{
vbox = new VBox ();
HBox hbox = new HBox ();
var max = new Button (new Image (IconThemeUtils.LoadIcon ("context-pane-maximize", 7)));
max.Clicked += (o, a) => { large = !large; expand_handler (large); };
max.TooltipText = Catalog.GetString ("Make the context pane larger or smaller");
var close = new Button (new Image (IconThemeUtils.LoadIcon ("context-pane-close", 7)));
close.Clicked += (o, a) => ShowAction.Activate ();
close.TooltipText = Catalog.GetString ("Hide context pane");
max.Relief = close.Relief = ReliefStyle.None;
hbox.PackStart (max, false, false, 0);
hbox.PackStart (close, false, false, 0);
vbox.PackStart (hbox, false, false, 0);
PackStart (vbox, false, false, 6);
vbox.ShowAll ();
}
private void CreateContextNotebook ()
{
notebook = new Notebook () {
ShowBorder = false,
ShowTabs = false
};
// 'No active track' and 'Loading' widgets
no_active = new RoundedFrame ();
no_active.Add (new Label () {
Markup = String.Format ("<b>{0}</b>", Catalog.GetString ("Waiting for playback to begin..."))
});
no_active.ShowAll ();
notebook.Add (no_active);
loading = new RoundedFrame ();
loading.Add (new Label () { Markup = String.Format ("<b>{0}</b>", Catalog.GetString ("Loading...")) });
loading.ShowAll ();
notebook.Add (loading);
PackStart (notebook, true, true, 0);
notebook.Show ();
}
private void OnPlayerEvent (PlayerEventArgs args)
{
if (Enabled) {
SetCurrentTrackForActivePage ();
}
}
private void SetCurrentTrackForActivePage ()
{
TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack;
if (track != null && active_page != null) {
active_page.SetTrack (track);
}
}
private void OnActivePageStateChanged (ContextState state)
{
if (active_page == null || !pane_pages.ContainsKey (active_page)) {
return;
}
if (state == ContextState.NotLoaded)
notebook.CurrentPage = notebook.PageNum (no_active);
else if (state == ContextState.Loading)
notebook.CurrentPage = notebook.PageNum (loading);
else if (state == ContextState.Loaded)
notebook.CurrentPage = notebook.PageNum (pane_pages[active_page]);
}
private Gtk.ToggleAction ShowAction {
get { return ServiceManager.Get<InterfaceActionService> ().ViewActions["ShowContextPaneAction"] as ToggleAction; }
}
private void OnShowContextPane (object o, EventArgs args)
{
Enabled = ShowAction.Active;
}
private bool Enabled {
get { return ShowSchema.Get (); }
set {
ShowSchema.Set (value);
SetCurrentTrackForActivePage ();
UpdateVisibility ();
}
}
private void UpdateVisibility ()
{
int npages = pages.Count;
bool enabled = Enabled;
ShowAction.Sensitive = npages > 0;
if (enabled && npages > 0) {
Show ();
} else {
if (expand_handler != null) {
expand_handler (false);
}
large = false;
Hide ();
}
vbox.Visible = true;//enabled && npages > 1;
}
private void SetActivePage (BaseContextPage page)
{
if (page == null || page == active_page)
return;
if (active_page != null)
active_page.StateChanged -= OnActivePageStateChanged;
active_page = page;
active_page.StateChanged += OnActivePageStateChanged;
LastContextPageSchema.Set (page.Id);
OnActivePageStateChanged (active_page.State);
SetCurrentTrackForActivePage ();
}
public void AddPage (BaseContextPage page)
{
Hyena.Log.DebugFormat ("Adding context page {0}", page.Id);
// TODO delay adding the page.Widget until the page is first activated,
// that way we don't even create those objects unless used
var frame = new Hyena.Widgets.RoundedFrame ();
frame.Add (page.Widget);
frame.Show ();
// TODO implement DnD?
/*if (page is ITrackContextPage) {
Gtk.Drag.DestSet (frame, DestDefaults.Highlight | DestDefaults.Motion,
new TargetEntry [] { Banshee.Gui.DragDrop.DragDropTarget.UriList },
Gdk.DragAction.Default);
frame.DragDataReceived += delegate(object o, DragDataReceivedArgs args) {
};
}*/
page.Widget.Show ();
notebook.AppendPage (frame, null);
pane_pages[page] = frame;
// Setup the tab-like button that switches the notebook to this page
var tab_image = new Image (IconThemeUtils.LoadIcon (22, page.IconNames));
var toggle_button = new RadioButton (radio_group) {
Child = tab_image,
DrawIndicator = false,
Relief = ReliefStyle.None
};
toggle_button.TooltipText = page.Name;
toggle_button.Clicked += (s, e) => {
if (pane_pages.ContainsKey (page)) {
if (page.State == ContextState.Loaded) {
notebook.CurrentPage = notebook.PageNum (pane_pages[page]);
}
SetActivePage (page);
}
};
toggle_button.ShowAll ();
vbox.PackStart (toggle_button, false, false, 0);
pane_tabs[page] = toggle_button;
pages.Add (page);
if (initialized && pages.Count == 1) {
SetActivePage (page);
toggle_button.Active = true;
}
UpdateVisibility ();
}
public void RemovePage (BaseContextPage page)
{
Hyena.Log.DebugFormat ("Removing context page {0}", page.Id);
// Remove the notebook page
notebook.RemovePage (notebook.PageNum (pane_pages[page]));
pane_pages.Remove (page);
// Remove the tab button
bool was_active = pane_tabs[page].Active;
vbox.Remove (pane_tabs[page]);
pane_tabs.Remove (page);
pages.Remove (page);
// Set a new page as the default
if (was_active) {
ActivateFirstPage ();
}
UpdateVisibility ();
}
private void ActivateFirstPage ()
{
if (pages.Count > 0) {
SetActivePage (pages[0]);
pane_tabs[active_page].Active = true;
}
}
internal static readonly SchemaEntry<bool> ShowSchema = new SchemaEntry<bool>(
"interface", "show_context_pane",
false,
"Show context pane",
"Show context pane for the currently playing track"
);
private static readonly SchemaEntry<string> LastContextPageSchema = new SchemaEntry<string>(
"interface", "last_context_page",
null,
"The id of the last context page",
"The string id of the last context page, which will be defaulted to when Banshee starts"
);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core.Xml;
namespace Umbraco.Core
{
/// <summary>
/// Extension methods for xml objects
/// </summary>
internal static class XmlExtensions
{
public static bool HasAttribute(this XmlAttributeCollection attributes, string attributeName)
{
return attributes.Cast<XmlAttribute>().Any(x => x.Name == attributeName);
}
/// <summary>
/// Selects a list of XmlNode matching an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The list of XmlNode matching the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNodeList SelectNodes(this XmlNode source, string expression, IEnumerable<XPathVariable> variables)
{
var av = variables == null ? null : variables.ToArray();
return SelectNodes(source, expression, av);
}
/// <summary>
/// Selects a list of XmlNode matching an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The list of XmlNode matching the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNodeList SelectNodes(this XmlNode source, XPathExpression expression, IEnumerable<XPathVariable> variables)
{
var av = variables == null ? null : variables.ToArray();
return SelectNodes(source, expression, av);
}
/// <summary>
/// Selects a list of XmlNode matching an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The list of XmlNode matching the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNodeList SelectNodes(this XmlNode source, string expression, params XPathVariable[] variables)
{
if (variables == null || variables.Length == 0 || variables[0] == null)
return source.SelectNodes(expression);
var iterator = source.CreateNavigator().Select(expression, variables);
return XmlNodeListFactory.CreateNodeList(iterator);
}
/// <summary>
/// Selects a list of XmlNode matching an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The list of XmlNode matching the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNodeList SelectNodes(this XmlNode source, XPathExpression expression, params XPathVariable[] variables)
{
if (variables == null || variables.Length == 0 || variables[0] == null)
return source.SelectNodes(expression);
var iterator = source.CreateNavigator().Select(expression, variables);
return XmlNodeListFactory.CreateNodeList(iterator);
}
/// <summary>
/// Selects the first XmlNode that matches an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The first XmlNode that matches the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNode SelectSingleNode(this XmlNode source, string expression, IEnumerable<XPathVariable> variables)
{
var av = variables == null ? null : variables.ToArray();
return SelectSingleNode(source, expression, av);
}
/// <summary>
/// Selects the first XmlNode that matches an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The first XmlNode that matches the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNode SelectSingleNode(this XmlNode source, XPathExpression expression, IEnumerable<XPathVariable> variables)
{
var av = variables == null ? null : variables.ToArray();
return SelectSingleNode(source, expression, av);
}
/// <summary>
/// Selects the first XmlNode that matches an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The first XmlNode that matches the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNode SelectSingleNode(this XmlNode source, string expression, params XPathVariable[] variables)
{
if (variables == null || variables.Length == 0 || variables[0] == null)
return source.SelectSingleNode(expression);
return SelectNodes(source, expression, variables).Cast<XmlNode>().FirstOrDefault();
}
/// <summary>
/// Selects the first XmlNode that matches an XPath expression.
/// </summary>
/// <param name="source">A source XmlNode.</param>
/// <param name="expression">An XPath expression.</param>
/// <param name="variables">A set of XPathVariables.</param>
/// <returns>The first XmlNode that matches the XPath expression.</returns>
/// <remarks>
/// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single
/// value which itself is <c>null</c>, then variables are ignored.</para>
/// <para>The XPath expression should reference variables as <c>$var</c>.</para>
/// </remarks>
public static XmlNode SelectSingleNode(this XmlNode source, XPathExpression expression, params XPathVariable[] variables)
{
if (variables == null || variables.Length == 0 || variables[0] == null)
return source.SelectSingleNode(expression);
return SelectNodes(source, expression, variables).Cast<XmlNode>().FirstOrDefault();
}
/// <summary>
/// Converts from an XDocument to an XmlDocument
/// </summary>
/// <param name="xDocument"></param>
/// <returns></returns>
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
/// <summary>
/// Converts from an XmlDocument to an XDocument
/// </summary>
/// <param name="xmlDocument"></param>
/// <returns></returns>
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
///// <summary>
///// Converts from an XElement to an XmlElement
///// </summary>
///// <param name="xElement"></param>
///// <returns></returns>
//public static XmlNode ToXmlElement(this XContainer xElement)
//{
// var xmlDocument = new XmlDocument();
// using (var xmlReader = xElement.CreateReader())
// {
// xmlDocument.Load(xmlReader);
// }
// return xmlDocument.DocumentElement;
//}
/// <summary>
/// Converts from an XmlElement to an XElement
/// </summary>
/// <param name="xmlElement"></param>
/// <returns></returns>
public static XElement ToXElement(this XmlNode xmlElement)
{
using (var nodeReader = new XmlNodeReader(xmlElement))
{
nodeReader.MoveToContent();
return XElement.Load(nodeReader);
}
}
public static T AttributeValue<T>(this XElement xml, string attributeName)
{
if (xml == null) throw new ArgumentNullException("xml");
if (xml.HasAttributes == false) return default(T);
if (xml.Attribute(attributeName) == null)
return default(T);
var val = xml.Attribute(attributeName).Value;
var result = val.TryConvertTo<T>();
if (result.Success)
return result.Result;
return default(T);
}
public static T AttributeValue<T>(this XmlNode xml, string attributeName)
{
if (xml == null) throw new ArgumentNullException("xml");
if (xml.Attributes == null) return default(T);
if (xml.Attributes[attributeName] == null)
return default(T);
var val = xml.Attributes[attributeName].Value;
var result = val.TryConvertTo<T>();
if (result.Success)
return result.Result;
return default(T);
}
public static XElement GetXElement(this XmlNode node)
{
XDocument xDoc = new XDocument();
using (XmlWriter xmlWriter = xDoc.CreateWriter())
node.WriteTo(xmlWriter);
return xDoc.Root;
}
public static XmlNode GetXmlNode(this XContainer element)
{
using (XmlReader xmlReader = element.CreateReader())
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlReader);
return xmlDoc.FirstChild;
}
}
public static XmlNode GetXmlNode(this XContainer element, XmlDocument xmlDoc)
{
using (XmlReader xmlReader = element.CreateReader())
{
xmlDoc.Load(xmlReader);
return xmlDoc.DocumentElement;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Its.Log.Instrumentation;
using Microsoft.Its.Domain.Sql.CommandScheduler;
using Microsoft.Its.Recipes;
using NUnit.Framework;
using Sample.Domain;
using Sample.Domain.Ordering;
using Sample.Domain.Ordering.Commands;
using System;
using System.Linq;
using System.Reactive.Disposables;
using System.Threading.Tasks;
namespace Microsoft.Its.Domain.Testing.Tests
{
[TestFixture]
public abstract class ScenarioBuilderTests
{
private CompositeDisposable disposables;
protected ScenarioBuilderTests()
{
Command<CustomerAccount>.AuthorizeDefault = (customer, command) => true;
Command<Order>.AuthorizeDefault = (order, command) => true;
}
[SetUp]
public virtual void SetUp()
{
disposables = new CompositeDisposable(
Disposable.Create(() => ConfigurationContext.Current
.IfNotNull()
.ThenDo(c => c.Dispose())));
}
[TearDown]
public virtual void TearDown()
{
disposables.Dispose();
}
protected void RegisterForDisposal(IDisposable disposable)
{
disposables.Add(disposable);
}
[Test]
public void Events_added_to_the_scenario_are_used_to_source_aggregates()
{
var name = Any.FullName();
var aggregateId = Any.Guid();
var orderNumber = Any.Int(2000, 5000).ToString();
var scenario = CreateScenarioBuilder()
.AddEvents(new Order.Created
{
AggregateId = aggregateId,
OrderNumber = orderNumber
}, new Order.CustomerInfoChanged
{
AggregateId = aggregateId,
CustomerName = name
}).Prepare();
var order = scenario.Aggregates.Single() as Order;
order.Should().NotBeNull();
order.OrderNumber.Should().Be(orderNumber);
order.CustomerName.Should().Be(name);
order.Id.Should().Be(aggregateId);
}
[Test]
public void If_no_aggregate_id_is_specified_when_adding_events_then_a_default_is_chosen_and_reused()
{
var created = new Order.Created();
var customerInfoChanged = new Order.CustomerInfoChanged();
CreateScenarioBuilder()
.AddEvents(created, customerInfoChanged);
created.AggregateId.Should().NotBeEmpty();
customerInfoChanged.AggregateId.Should().Be(created.AggregateId);
}
[Test]
public async Task If_no_aggregate_id_is_specified_when_calling_GetLatest_and_a_single_instance_is_in_the_scenario_then_it_is_returned()
{
var aggregateId = Any.Guid();
var created = new Order.Created
{
AggregateId = aggregateId
};
var scenario = CreateScenarioBuilder().AddEvents(created).Prepare();
var aggregate = await scenario.GetLatestAsync<Order>();
aggregate.Should().NotBeNull();
aggregate.Id.Should().Be(aggregateId);
}
[Test]
public void If_no_aggregate_id_is_specified_when_calling_GetLatest_and_no_instance_is_in_the_scenario_then_it_throws()
{
var scenario = CreateScenarioBuilder()
.AddEvents(new Order.Created
{
AggregateId = Any.Guid()
}, new Order.Created
{
AggregateId = Any.Guid()
}).Prepare();
Action getLatest = () => scenario.GetLatestAsync<Order>().Wait();
getLatest.ShouldThrow<InvalidOperationException>();
}
[Test]
public void If_no_aggregate_id_is_specified_when_calling_GetLatest_and_multiple_instances_are_in_the_scenario_then_it_throws()
{
var scenario = CreateScenarioBuilder().Prepare();
Action getLatest = () => scenario.GetLatestAsync<Order>().Wait();
getLatest.ShouldThrow<InvalidOperationException>();
}
[Test]
public void When_no_sequence_numbers_are_specified_then_events_are_applied_in_order()
{
var aggregateId = Any.Guid();
var firstCustomerName = Any.FullName();
var scenario = CreateScenarioBuilder()
.AddEvents(new Order.CustomerInfoChanged
{
AggregateId = aggregateId,
CustomerName = Any.FullName()
}, new Order.CustomerInfoChanged
{
AggregateId = aggregateId,
CustomerName = firstCustomerName
}).Prepare();
var order = scenario.Aggregates.OfType<Order>().Single();
order.CustomerName.Should().Be(firstCustomerName);
}
[Test]
public void DynamicProjectors_registered_as_event_handlers_in_ScenarioBuilder_run_catchups_when_prepare_is_called()
{
var firstShipHandled = false;
var secondShipHandled = false;
var handler = Domain.Projector.CreateDynamic(dynamicEvent =>
{
var @event = dynamicEvent as IEvent;
@event.IfTypeIs<CommandScheduled<Order>>()
.ThenDo(c =>
{
var shipmentId = (c.Command as Ship).ShipmentId;
Console.WriteLine("Handling [{0}] Shipment", shipmentId);
if (shipmentId == "first")
{
firstShipHandled = true;
}
else if (shipmentId == "second")
{
secondShipHandled = true;
}
});
},
"Order.Scheduled:Ship");
CreateScenarioBuilder()
.AddHandler(handler)
.AddEvents(
new CommandScheduled<Order>
{
Command = new Ship { ShipmentId = "first" },
DueTime = DateTime.Now
},
new CommandScheduled<Order>
{
Command = new Ship { ShipmentId = "second" },
DueTime = DateTime.Now
})
.Prepare();
firstShipHandled.Should().BeTrue();
secondShipHandled.Should().BeTrue();
}
[Test]
public void When_sequence_numbers_are_specified_it_overrides_the_order_in_which_the_events_were_added()
{
var aggregateId = Any.Guid();
var firstCustomerName = Any.FullName();
var scenario = CreateScenarioBuilder()
.AddEvents(new Order.CustomerInfoChanged
{
AggregateId = aggregateId,
CustomerName = firstCustomerName,
SequenceNumber = 2
}, new Order.CustomerInfoChanged
{
AggregateId = aggregateId,
CustomerName = Any.FullName(),
SequenceNumber = 1
}).Prepare();
var order = scenario.Aggregates.OfType<Order>().Single();
order.CustomerName.Should().Be(firstCustomerName);
}
[Test]
public void Multiple_aggregates_of_the_same_type_can_be_sourced_in_one_scenario()
{
var builder = CreateScenarioBuilder()
.AddEvents(new Order.Created
{
AggregateId = Any.Guid()
}, new Order.Created
{
AggregateId = Any.Guid()
});
builder.Prepare().Aggregates
.OfType<Order>()
.Count()
.Should().Be(2);
}
[Test]
public void Multiple_aggregates_of_different_types_can_be_sourced_in_one_scenario()
{
// arrange
var builder = CreateScenarioBuilder()
.AddEvents(new Order.Created
{
AggregateId = Any.Guid()
}, new CustomerAccount.EmailAddressChanged
{
AggregateId = Any.Guid()
});
// act
var scenario = builder.Prepare();
// assert
scenario.Aggregates
.Should()
.ContainSingle(a => a is CustomerAccount)
.And
.ContainSingle(a => a is Order);
}
[Test]
public void Multiple_aggregates_of_the_same_type_can_be_organized_using_For()
{
var aggregateId1 = Any.Guid();
var aggregateId2 = Any.Guid();
var builder = CreateScenarioBuilder();
builder.For<Order>(aggregateId1)
.AddEvents(new Order.ItemAdded { ProductName = "one" });
builder.For<Order>(aggregateId2)
.AddEvents(new Order.ItemAdded { ProductName = "two" });
var aggregates = builder.Prepare().Aggregates.OfType<Order>().ToArray();
aggregates.Count().Should().Be(2);
aggregates.Should().Contain(a => a.Id == aggregateId1 && a.Items.Single().ProductName == "one");
aggregates.Should().Contain(a => a.Id == aggregateId2 && a.Items.Single().ProductName == "two");
}
[Test]
public void Projectors_added_before_Prepare_is_called_are_subscribed_to_all_events()
{
var onDeliveredCalls = 0;
var onEmailAddedCalls = 0;
var delivered = new Order.Delivered();
var addressChanged = new CustomerAccount.EmailAddressChanged();
CreateScenarioBuilder()
.AddEvents(delivered, addressChanged)
.AddHandler(new Projector
{
OnDelivered = e =>
{
Console.WriteLine(e.ToLogString());
onDeliveredCalls++;
},
OnEmailAdded = e =>
{
Console.WriteLine(e.ToLogString());
onEmailAddedCalls++;
}
})
.Prepare();
onDeliveredCalls.Should().Be(1);
onEmailAddedCalls.Should().Be(1);
}
[Test]
public async Task Projectors_added_after_Prepare_is_called_are_subscribed_to_future_events()
{
// arrange
var onDeliveredCalls = 0;
var onEmailAddedCalls = 0;
var scenarioBuilder = CreateScenarioBuilder();
var aggregateId = Any.Guid();
var scenario = scenarioBuilder
.AddEvents(new Order.Created
{
AggregateId = aggregateId
})
.Prepare();
scenarioBuilder.AddHandler(new Projector
{
OnDelivered = e => onDeliveredCalls++,
OnEmailAdded = e => onEmailAddedCalls++
});
var order = new Order();
order.Apply(new Deliver());
var customer = new CustomerAccount();
customer.Apply(new ChangeEmailAddress(Any.Email()));
// act
await scenario.SaveAsync(order);
await scenario.SaveAsync(customer);
// assert
onDeliveredCalls.Should().Be(1);
onEmailAddedCalls.Should().Be(1);
}
[Test]
public void When_event_handling_errors_occur_during_Prepare_then_an_exception_is_thrown()
{
// arrange
var scenarioBuilder = CreateScenarioBuilder();
scenarioBuilder.AddEvents(new Order.Delivered());
scenarioBuilder.AddHandler(new Projector
{
OnDelivered = e => { throw new Exception("oops!"); }
});
// act
Action prepare = () => scenarioBuilder.Prepare();
// assert
prepare.ShouldThrow<ScenarioSetupException>()
.And
.Message
.Should()
.Contain("The following event handling errors occurred during projection catchup")
.And
.Contain("oops!");
}
[Test]
public async Task When_event_handling_errors_occur_after_Prepare_then_they_can_be_verified_during_the_test()
{
// arrange
var scenarioBuilder = CreateScenarioBuilder();
var scenario = scenarioBuilder.AddHandler(new Projector
{
OnDelivered = e => { throw new Exception("oops!"); }
}).Prepare();
var order = new Order();
order.Apply(new Deliver());
await scenario.SaveAsync(order);
// act
Action verify = () => scenario.VerifyNoEventHandlingErrors();
// assert
verify.ShouldThrow<AssertionException>()
.And
.Message
.Should()
.Contain("The following event handling errors occurred")
.And
.Contain("oops!");
}
[Test]
public void Consequenters_are_not_triggered_by_Prepare()
{
// arrange
var onDeliveredCalls = 0;
var scenarioBuilder = CreateScenarioBuilder();
var aggregateId = Any.Guid();
var builder = scenarioBuilder
.AddEvents(
new Order.Created
{
AggregateId = aggregateId
},
new Order.Delivered())
.AddHandler(new Consequenter
{
OnDelivered = e => onDeliveredCalls++
});
// act
builder.Prepare();
// assert
onDeliveredCalls.Should().Be(0);
}
[Test]
public async Task Events_that_are_saved_as_a_result_of_commands_can_be_verified_using_the_EventBus()
{
// arrange
var builder = CreateScenarioBuilder();
var scenario = builder.Prepare();
var customerName = Any.FullName();
// act
await scenario.SaveAsync(new Order(new CreateOrder(customerName)));
// assert
builder.EventBus
.PublishedEvents()
.OfType<Order.Created>()
.Should()
.ContainSingle(e => e.CustomerName == customerName);
}
[Test]
public void AggregateBuilder_can_be_used_to_access_all_events_added_to_the_scenario_for_that_aggregate()
{
var scenarioBuilder = CreateScenarioBuilder();
var orderId = Any.Guid();
scenarioBuilder.For<Order>(orderId).AddEvents(new Order.Created());
scenarioBuilder.AddEvents(new Order.ItemAdded
{
AggregateId = orderId
});
scenarioBuilder.For<Order>(orderId).InitialEvents.Count().Should().Be(2);
}
[Test]
public void Event_timestamps_can_be_set_using_VirtualClock()
{
var startTime = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(Any.PositiveInt(10000)));
using (VirtualClock.Start(startTime))
{
var scenario = CreateScenarioBuilder();
scenario.AddEvents(new Order.Cancelled());
scenario.InitialEvents.Last().Timestamp.Should().Be(startTime);
}
}
[Test]
public void Scenario_clock_can_be_advanced_by_a_specified_timespan()
{
var startTime = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(Any.PositiveInt(10000)));
var timespan = TimeSpan.FromMinutes(Any.PositiveInt(1000));
using (VirtualClock.Start(startTime))
{
var scenario = CreateScenarioBuilder()
.AdvanceClockTo(startTime)
.AdvanceClockBy(timespan);
scenario.AddEvents(new Order.Cancelled());
scenario.InitialEvents.Last().Timestamp.Should().Be(startTime + timespan);
}
}
[Test]
public void Scenario_clock_does_not_overwrite_specified_TimeStamp()
{
var time = Any.DateTimeOffset();
ScenarioBuilder builder;
using (VirtualClock.Start(time))
{
builder = CreateScenarioBuilder()
.AddEvents(new Order.ItemAdded
{
Timestamp = time
});
}
builder.InitialEvents.Single().Timestamp.Should().Be(time);
}
[Test]
public void ScenarioBuilder_StartTime_returns_clock_time_when_there_are_no_initial_events()
{
var clockTime = Any.DateTimeOffset();
using (VirtualClock.Start(clockTime))
{
var builder = CreateScenarioBuilder().AdvanceClockTo(clockTime);
builder.StartTime().Should().Be(clockTime);
}
}
[Test]
public void ScenarioBuilder_StartTime_returns_earliest_event_timestamp_if_it_is_earlier_than_clock()
{
var eventTime = Any.DateTimeOffset();
var clockTime = eventTime.Add(TimeSpan.FromDays(31));
using (VirtualClock.Start(clockTime))
{
var builder = CreateScenarioBuilder()
.AdvanceClockTo(clockTime)
.AddEvents(new Order.ItemAdded
{
Timestamp = eventTime
});
builder.StartTime().Should().Be(eventTime);
}
}
[Test]
public void ScenarioBuilder_StartTime_returns_clock_if_it_is_earlier_than_earliest_event_timestamp()
{
var clockTime = Any.DateTimeOffset();
using (VirtualClock.Start(clockTime))
{
var eventTime = clockTime.Add(TimeSpan.FromMinutes(Any.PositiveInt(1000)));
var builder = CreateScenarioBuilder()
.AddEvents(new Order.ItemAdded
{
Timestamp = eventTime
});
builder.StartTime().Should().Be(clockTime);
}
}
[Test]
public async Task Scheduled_commands_in_initial_events_are_executed_if_they_become_due_after_Prepare_is_called()
{
using (VirtualClock.Start(Any.DateTimeOffset()))
{
var customerAccountId = Any.Guid();
var scenario = CreateScenarioBuilder()
.AddEvents(
new CustomerAccount.Created
{
AggregateId= customerAccountId
},
new Order.Created
{
CustomerName = Any.FullName(),
OrderNumber = "42",
CustomerId = customerAccountId
},
new CommandScheduled<Order>
{
Command = new Cancel(),
DueTime = Clock.Now().AddDays(102)
}).Prepare();
scenario.AdvanceClockBy(TimeSpan.FromDays(103));
(await scenario.GetLatestAsync<Order>())
.EventHistory
.Last()
.Should()
.BeOfType<Order.Cancelled>();
}
}
[Test]
public async Task Recursive_scheduling_is_supported_when_the_scenario_clock_is_advanced()
{
// arrange
using (VirtualClock.Start(DateTimeOffset.Parse("2014-10-08 06:52:10 AM -07:00")))
{
var scenario = CreateScenarioBuilder()
.AddEvents(new CustomerAccount.EmailAddressChanged
{
NewEmailAddress = Any.Email()
})
.Prepare();
// act
var account = (await scenario.GetLatestAsync<CustomerAccount>())
.Apply(new RequestSpam())
.Apply(new SendMarketingEmail());
await scenario.SaveAsync(account);
scenario.AdvanceClockBy(TimeSpan.FromDays(30));
await scenario.CommandSchedulerDone();
account = await scenario.GetLatestAsync<CustomerAccount>();
// assert
account.Events()
.OfType<CommandScheduled<CustomerAccount>>()
.Select(e => e.Timestamp.Date)
.Should()
.BeEquivalentTo(new[]
{
DateTime.Parse("2014-10-08"),
DateTime.Parse("2014-10-15"),
DateTime.Parse("2014-10-22"),
DateTime.Parse("2014-10-29"),
DateTime.Parse("2014-11-05")
});
account.Events()
.OfType<CustomerAccount.MarketingEmailSent>()
.Select(e => e.Timestamp.Date)
.Should()
.BeEquivalentTo(new[]
{
DateTime.Parse("2014-10-08"),
DateTime.Parse("2014-10-15"),
DateTime.Parse("2014-10-22"),
DateTime.Parse("2014-10-29"),
DateTime.Parse("2014-11-05")
});
account.Events()
.Last()
.Should()
.BeOfType<CommandScheduled<CustomerAccount>>();
if (UsesSqlStorage)
{
using (var db = new CommandSchedulerDbContext())
{
var scheduledCommands = db.ScheduledCommands
.Where(c => c.AggregateId == account.Id)
.ToArray();
// all but the last command (which didn't come due yet) should have been marked as applied
scheduledCommands
.OrderByDescending(c => c.CreatedTime)
.Skip(1)
.Should()
.OnlyContain(c => c.AppliedTime != null);
}
}
}
}
public abstract bool UsesSqlStorage { get; }
[Test]
public async Task Recursive_scheduling_is_supported_when_the_virtual_clock_is_advanced()
{
// arrange
using (VirtualClock.Start(DateTimeOffset.Parse("2014-10-08 06:52:10 AM -07:00")))
{
var scenario = CreateScenarioBuilder()
.AddEvents(new CustomerAccount.EmailAddressChanged
{
NewEmailAddress = Any.Email()
})
.Prepare();
// act
var account = (await scenario.GetLatestAsync<CustomerAccount>())
.Apply(new RequestSpam())
.Apply(new SendMarketingEmail());
await scenario.SaveAsync(account);
VirtualClock.Current.AdvanceBy(TimeSpan.FromDays((7*4) + 2));
await scenario.CommandSchedulerDone();
account = await scenario.GetLatestAsync<CustomerAccount>();
// assert
account.Events()
.OfType<CommandScheduled<CustomerAccount>>()
.Select(e => e.Timestamp.Date)
.Should()
.BeEquivalentTo(new[]
{
DateTime.Parse("2014-10-08"),
DateTime.Parse("2014-10-15"),
DateTime.Parse("2014-10-22"),
DateTime.Parse("2014-10-29"),
DateTime.Parse("2014-11-05")
});
account.Events()
.OfType<CustomerAccount.MarketingEmailSent>()
.Select(e => e.Timestamp.Date)
.Should()
.BeEquivalentTo(new[]
{
DateTime.Parse("2014-10-08"),
DateTime.Parse("2014-10-15"),
DateTime.Parse("2014-10-22"),
DateTime.Parse("2014-10-29"),
DateTime.Parse("2014-11-05")
});
account.Events()
.Last()
.Should()
.BeOfType<CommandScheduled<CustomerAccount>>();
if (UsesSqlStorage)
{
using (var db = new CommandSchedulerDbContext())
{
var scheduledCommands = db.ScheduledCommands
.Where(c => c.AggregateId == account.Id)
.ToArray();
// all but the last command (which didn't come due yet) should have been marked as applied
scheduledCommands
.OrderByDescending(c => c.CreatedTime)
.Skip(1)
.Should()
.OnlyContain(c => c.AppliedTime != null);
}
}
}
}
[Test]
public async Task Scheduled_commands_in_initial_events_are_not_executed_if_they_become_due_before_Prepare_is_called()
{
var aggregateId = Any.Guid();
using (VirtualClock.Start())
{
var scenario = CreateScenarioBuilder()
.AddEvents(new CommandScheduled<Order>
{
AggregateId = aggregateId,
Command = new Cancel(),
DueTime = Clock.Now().AddDays(2)
})
.AdvanceClockBy(TimeSpan.FromDays(3))
.Prepare();
(await scenario.GetLatestAsync<Order>(aggregateId))
.EventHistory
.Last()
.Should()
.BeOfType<CommandScheduled<Order>>();
}
}
[Test]
public async Task Handlers_can_be_added_by_type_and_are_instantiated_by_the_internal_container()
{
var customerId = Guid.NewGuid();
var customerName = Any.FullName();
var scenarioBuilder = CreateScenarioBuilder()
.AddEvents(new CustomerAccount.UserNameAcquired
{
AggregateId = customerId,
UserName = customerName
});
var scenario = scenarioBuilder.Prepare();
scenarioBuilder.AddHandlers(typeof (SideEffectingConsequenter));
var customerAccount = await scenario.GetLatestAsync<CustomerAccount>(customerId);
customerAccount.Apply(new RequestNoSpam());
await scenario.SaveAsync(customerAccount);
await scenario.CommandSchedulerDone();
var latest = await scenario.GetLatestAsync<CustomerAccount>(customerId);
latest.EmailAddress.Should().Be("devnull@nowhere.com");
}
[Test]
public void A_new_Scenario_can_be_prepared_while_another_is_still_active()
{
Configuration outerConfiguration = null;
Configuration innerConfiguration = null;
using (new ScenarioBuilder(c => { outerConfiguration = c; }).Prepare())
using (new ScenarioBuilder(c => { innerConfiguration = c; }).Prepare())
{
Configuration.Current.Should().Be(innerConfiguration);
}
}
protected abstract ScenarioBuilder CreateScenarioBuilder();
public class Projector :
IUpdateProjectionWhen<Order.Delivered>,
IUpdateProjectionWhen<CustomerAccount.EmailAddressChanged>
{
public Action<Order.Delivered> OnDelivered = e => { };
public Action<CustomerAccount.EmailAddressChanged> OnEmailAdded = e => { };
public void UpdateProjection(Order.Delivered @event)
{
OnDelivered(@event);
}
public void UpdateProjection(CustomerAccount.EmailAddressChanged @event)
{
OnEmailAdded(@event);
}
}
public class Consequenter :
IHaveConsequencesWhen<Order.Delivered>
{
public Action<Order.Delivered> OnDelivered = e => { };
public void HaveConsequences(Order.Delivered @event)
{
OnDelivered(@event);
}
}
public class SideEffectingConsequenter :
IHaveConsequencesWhen<CustomerAccount.RequestedNoSpam>
{
private readonly IEventSourcedRepository<CustomerAccount> customerRepository;
public SideEffectingConsequenter(IEventSourcedRepository<CustomerAccount> customerRepository)
{
if (customerRepository == null)
{
throw new ArgumentNullException("customerRepository");
}
this.customerRepository = customerRepository;
}
public void HaveConsequences(CustomerAccount.RequestedNoSpam @event)
{
var customer = customerRepository.GetLatest(@event.AggregateId).Result;
customer.Apply(new ChangeEmailAddress
{
NewEmailAddress = "devnull@nowhere.com"
});
customerRepository.Save(customer).Wait();
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Cecil.PE;
using Mono.Collections.Generic;
using RVA = System.UInt32;
namespace Mono.Cecil.Cil {
sealed class CodeReader : BinaryStreamReader {
readonly internal MetadataReader reader;
int start;
MethodDefinition method;
MethodBody body;
int Offset {
get { return Position - start; }
}
public CodeReader (MetadataReader reader)
: base (reader.image.Stream.value)
{
this.reader = reader;
}
public int MoveTo (MethodDefinition method)
{
this.method = method;
this.reader.context = method;
var position = this.Position;
this.Position = (int) reader.image.ResolveVirtualAddress ((uint) method.RVA);
return position;
}
public void MoveBackTo (int position)
{
this.reader.context = null;
this.Position = position;
}
public MethodBody ReadMethodBody (MethodDefinition method)
{
var position = MoveTo (method);
this.body = new MethodBody (method);
ReadMethodBody ();
MoveBackTo (position);
return this.body;
}
public int ReadCodeSize (MethodDefinition method)
{
var position = MoveTo (method);
var code_size = ReadCodeSize ();
MoveBackTo (position);
return code_size;
}
int ReadCodeSize ()
{
var flags = ReadByte ();
switch (flags & 0x3) {
case 0x2: // tiny
return flags >> 2;
case 0x3: // fat
Advance (-1 + 2 + 2); // go back, 2 bytes flags, 2 bytes stack size
return (int) ReadUInt32 ();
default:
throw new InvalidOperationException ();
}
}
void ReadMethodBody ()
{
var flags = ReadByte ();
switch (flags & 0x3) {
case 0x2: // tiny
body.code_size = flags >> 2;
body.MaxStackSize = 8;
ReadCode ();
break;
case 0x3: // fat
Advance (-1);
ReadFatMethod ();
break;
default:
throw new InvalidOperationException ();
}
var symbol_reader = reader.module.symbol_reader;
if (symbol_reader != null && method.debug_info == null)
method.debug_info = symbol_reader.Read (method);
if (method.debug_info != null)
ReadDebugInfo ();
}
void ReadFatMethod ()
{
var flags = ReadUInt16 ();
body.max_stack_size = ReadUInt16 ();
body.code_size = (int) ReadUInt32 ();
body.local_var_token = new MetadataToken (ReadUInt32 ());
body.init_locals = (flags & 0x10) != 0;
if (body.local_var_token.RID != 0)
body.variables = ReadVariables (body.local_var_token);
ReadCode ();
if ((flags & 0x8) != 0)
ReadSection ();
}
public VariableDefinitionCollection ReadVariables (MetadataToken local_var_token)
{
var position = reader.position;
var variables = reader.ReadVariables (local_var_token);
reader.position = position;
return variables;
}
void ReadCode ()
{
start = Position;
var code_size = body.code_size;
if (code_size < 0 || Length <= (uint) (code_size + Position))
code_size = 0;
var end = start + code_size;
var instructions = body.instructions = new InstructionCollection (method, (code_size + 1) / 2);
while (Position < end) {
var offset = Position - start;
var opcode = ReadOpCode ();
var current = new Instruction (offset, opcode);
if (opcode.OperandType != OperandType.InlineNone)
current.operand = ReadOperand (current);
instructions.Add (current);
}
ResolveBranches (instructions);
}
OpCode ReadOpCode ()
{
var il_opcode = ReadByte ();
return il_opcode != 0xfe
? OpCodes.OneByteOpCode [il_opcode]
: OpCodes.TwoBytesOpCode [ReadByte ()];
}
object ReadOperand (Instruction instruction)
{
switch (instruction.opcode.OperandType) {
case OperandType.InlineSwitch:
var length = ReadInt32 ();
var base_offset = Offset + (4 * length);
var branches = new int [length];
for (int i = 0; i < length; i++)
branches [i] = base_offset + ReadInt32 ();
return branches;
case OperandType.ShortInlineBrTarget:
return ReadSByte () + Offset;
case OperandType.InlineBrTarget:
return ReadInt32 () + Offset;
case OperandType.ShortInlineI:
if (instruction.opcode == OpCodes.Ldc_I4_S)
return ReadSByte ();
return ReadByte ();
case OperandType.InlineI:
return ReadInt32 ();
case OperandType.ShortInlineR:
return ReadSingle ();
case OperandType.InlineR:
return ReadDouble ();
case OperandType.InlineI8:
return ReadInt64 ();
case OperandType.ShortInlineVar:
return GetVariable (ReadByte ());
case OperandType.InlineVar:
return GetVariable (ReadUInt16 ());
case OperandType.ShortInlineArg:
return GetParameter (ReadByte ());
case OperandType.InlineArg:
return GetParameter (ReadUInt16 ());
case OperandType.InlineSig:
return GetCallSite (ReadToken ());
case OperandType.InlineString:
return GetString (ReadToken ());
case OperandType.InlineTok:
case OperandType.InlineType:
case OperandType.InlineMethod:
case OperandType.InlineField:
return reader.LookupToken (ReadToken ());
default:
throw new NotSupportedException ();
}
}
public string GetString (MetadataToken token)
{
return reader.image.UserStringHeap.Read (token.RID);
}
public ParameterDefinition GetParameter (int index)
{
return body.GetParameter (index);
}
public VariableDefinition GetVariable (int index)
{
return body.GetVariable (index);
}
public CallSite GetCallSite (MetadataToken token)
{
return reader.ReadCallSite (token);
}
void ResolveBranches (Collection<Instruction> instructions)
{
var items = instructions.items;
var size = instructions.size;
for (int i = 0; i < size; i++) {
var instruction = items [i];
switch (instruction.opcode.OperandType) {
case OperandType.ShortInlineBrTarget:
case OperandType.InlineBrTarget:
instruction.operand = GetInstruction ((int) instruction.operand);
break;
case OperandType.InlineSwitch:
var offsets = (int []) instruction.operand;
var branches = new Instruction [offsets.Length];
for (int j = 0; j < offsets.Length; j++)
branches [j] = GetInstruction (offsets [j]);
instruction.operand = branches;
break;
}
}
}
Instruction GetInstruction (int offset)
{
return GetInstruction (body.Instructions, offset);
}
static Instruction GetInstruction (Collection<Instruction> instructions, int offset)
{
var size = instructions.size;
var items = instructions.items;
if (offset < 0 || offset > items [size - 1].offset)
return null;
int min = 0;
int max = size - 1;
while (min <= max) {
int mid = min + ((max - min) / 2);
var instruction = items [mid];
var instruction_offset = instruction.offset;
if (offset == instruction_offset)
return instruction;
if (offset < instruction_offset)
max = mid - 1;
else
min = mid + 1;
}
return null;
}
void ReadSection ()
{
Align (4);
const byte fat_format = 0x40;
const byte more_sects = 0x80;
var flags = ReadByte ();
if ((flags & fat_format) == 0)
ReadSmallSection ();
else
ReadFatSection ();
if ((flags & more_sects) != 0)
ReadSection ();
}
void ReadSmallSection ()
{
var count = ReadByte () / 12;
Advance (2);
ReadExceptionHandlers (
count,
() => (int) ReadUInt16 (),
() => (int) ReadByte ());
}
void ReadFatSection ()
{
Advance (-1);
var count = (ReadInt32 () >> 8) / 24;
ReadExceptionHandlers (
count,
ReadInt32,
ReadInt32);
}
// inline ?
void ReadExceptionHandlers (int count, Func<int> read_entry, Func<int> read_length)
{
for (int i = 0; i < count; i++) {
var handler = new ExceptionHandler (
(ExceptionHandlerType) (read_entry () & 0x7));
handler.TryStart = GetInstruction (read_entry ());
handler.TryEnd = GetInstruction (handler.TryStart.Offset + read_length ());
handler.HandlerStart = GetInstruction (read_entry ());
handler.HandlerEnd = GetInstruction (handler.HandlerStart.Offset + read_length ());
ReadExceptionHandlerSpecific (handler);
this.body.ExceptionHandlers.Add (handler);
}
}
void ReadExceptionHandlerSpecific (ExceptionHandler handler)
{
switch (handler.HandlerType) {
case ExceptionHandlerType.Catch:
handler.CatchType = (TypeReference) reader.LookupToken (ReadToken ());
break;
case ExceptionHandlerType.Filter:
handler.FilterStart = GetInstruction (ReadInt32 ());
break;
default:
Advance (4);
break;
}
}
public MetadataToken ReadToken ()
{
return new MetadataToken (ReadUInt32 ());
}
void ReadDebugInfo ()
{
if (method.debug_info.sequence_points != null)
ReadSequencePoints ();
if (method.debug_info.scope != null)
ReadScope (method.debug_info.scope);
if (method.custom_infos != null)
ReadCustomDebugInformations (method);
}
void ReadCustomDebugInformations (MethodDefinition method)
{
var custom_infos = method.custom_infos;
for (int i = 0; i < custom_infos.Count; i++) {
var state_machine_scope = custom_infos [i] as StateMachineScopeDebugInformation;
if (state_machine_scope != null)
ReadStateMachineScope (state_machine_scope);
var async_method = custom_infos [i] as AsyncMethodBodyDebugInformation;
if (async_method != null)
ReadAsyncMethodBody (async_method);
}
}
void ReadAsyncMethodBody (AsyncMethodBodyDebugInformation async_method)
{
if (async_method.catch_handler.Offset > -1)
async_method.catch_handler = new InstructionOffset (GetInstruction (async_method.catch_handler.Offset));
if (!async_method.yields.IsNullOrEmpty ())
for (int i = 0; i < async_method.yields.Count; i++)
async_method.yields [i] = new InstructionOffset (GetInstruction (async_method.yields [i].Offset));
if (!async_method.resumes.IsNullOrEmpty ())
for (int i = 0; i < async_method.resumes.Count; i++)
async_method.resumes [i] = new InstructionOffset (GetInstruction (async_method.resumes [i].Offset));
}
void ReadStateMachineScope (StateMachineScopeDebugInformation state_machine_scope)
{
if (state_machine_scope.scopes.IsNullOrEmpty ())
return;
foreach (var scope in state_machine_scope.scopes) {
scope.start = new InstructionOffset (GetInstruction (scope.start.Offset));
var end_instruction = GetInstruction (scope.end.Offset);
scope.end = end_instruction == null
? new InstructionOffset ()
: new InstructionOffset (end_instruction);
}
}
void ReadSequencePoints ()
{
var symbol = method.debug_info;
for (int i = 0; i < symbol.sequence_points.Count; i++) {
var sequence_point = symbol.sequence_points [i];
var instruction = GetInstruction (sequence_point.Offset);
if (instruction != null)
sequence_point.offset = new InstructionOffset (instruction);
}
}
void ReadScopes (Collection<ScopeDebugInformation> scopes)
{
for (int i = 0; i < scopes.Count; i++)
ReadScope (scopes [i]);
}
void ReadScope (ScopeDebugInformation scope)
{
var start_instruction = GetInstruction (scope.Start.Offset);
if (start_instruction != null)
scope.Start = new InstructionOffset (start_instruction);
var end_instruction = GetInstruction (scope.End.Offset);
scope.End = end_instruction != null
? new InstructionOffset (end_instruction)
: new InstructionOffset ();
if (!scope.variables.IsNullOrEmpty ()) {
for (int i = 0; i < scope.variables.Count; i++) {
var variable_info = scope.variables [i];
var variable = GetVariable (variable_info.Index);
if (variable != null)
variable_info.index = new VariableIndex (variable);
}
}
if (!scope.scopes.IsNullOrEmpty ())
ReadScopes (scope.scopes);
}
#if !READ_ONLY
public ByteBuffer PatchRawMethodBody (MethodDefinition method, CodeWriter writer, out int code_size, out MetadataToken local_var_token)
{
var position = MoveTo (method);
var buffer = new ByteBuffer ();
var flags = ReadByte ();
switch (flags & 0x3) {
case 0x2: // tiny
buffer.WriteByte (flags);
local_var_token = MetadataToken.Zero;
code_size = flags >> 2;
PatchRawCode (buffer, code_size, writer);
break;
case 0x3: // fat
Advance (-1);
PatchRawFatMethod (buffer, writer, out code_size, out local_var_token);
break;
default:
throw new NotSupportedException ();
}
MoveBackTo (position);
return buffer;
}
void PatchRawFatMethod (ByteBuffer buffer, CodeWriter writer, out int code_size, out MetadataToken local_var_token)
{
var flags = ReadUInt16 ();
buffer.WriteUInt16 (flags);
buffer.WriteUInt16 (ReadUInt16 ());
code_size = ReadInt32 ();
buffer.WriteInt32 (code_size);
local_var_token = ReadToken ();
if (local_var_token.RID > 0) {
var variables = ReadVariables (local_var_token);
buffer.WriteUInt32 (variables != null
? writer.GetStandAloneSignature (variables).ToUInt32 ()
: 0);
} else
buffer.WriteUInt32 (0);
PatchRawCode (buffer, code_size, writer);
if ((flags & 0x8) != 0)
PatchRawSection (buffer, writer.metadata);
}
void PatchRawCode (ByteBuffer buffer, int code_size, CodeWriter writer)
{
var metadata = writer.metadata;
buffer.WriteBytes (ReadBytes (code_size));
var end = buffer.position;
buffer.position -= code_size;
while (buffer.position < end) {
OpCode opcode;
var il_opcode = buffer.ReadByte ();
if (il_opcode != 0xfe) {
opcode = OpCodes.OneByteOpCode [il_opcode];
} else {
var il_opcode2 = buffer.ReadByte ();
opcode = OpCodes.TwoBytesOpCode [il_opcode2];
}
switch (opcode.OperandType) {
case OperandType.ShortInlineI:
case OperandType.ShortInlineBrTarget:
case OperandType.ShortInlineVar:
case OperandType.ShortInlineArg:
buffer.position += 1;
break;
case OperandType.InlineVar:
case OperandType.InlineArg:
buffer.position += 2;
break;
case OperandType.InlineBrTarget:
case OperandType.ShortInlineR:
case OperandType.InlineI:
buffer.position += 4;
break;
case OperandType.InlineI8:
case OperandType.InlineR:
buffer.position += 8;
break;
case OperandType.InlineSwitch:
var length = buffer.ReadInt32 ();
buffer.position += length * 4;
break;
case OperandType.InlineString:
var @string = GetString (new MetadataToken (buffer.ReadUInt32 ()));
buffer.position -= 4;
buffer.WriteUInt32 (
new MetadataToken (
TokenType.String,
metadata.user_string_heap.GetStringIndex (@string)).ToUInt32 ());
break;
case OperandType.InlineSig:
var call_site = GetCallSite (new MetadataToken (buffer.ReadUInt32 ()));
buffer.position -= 4;
buffer.WriteUInt32 (writer.GetStandAloneSignature (call_site).ToUInt32 ());
break;
case OperandType.InlineTok:
case OperandType.InlineType:
case OperandType.InlineMethod:
case OperandType.InlineField:
var provider = reader.LookupToken (new MetadataToken (buffer.ReadUInt32 ()));
buffer.position -= 4;
buffer.WriteUInt32 (metadata.LookupToken (provider).ToUInt32 ());
break;
}
}
}
void PatchRawSection (ByteBuffer buffer, MetadataBuilder metadata)
{
var position = Position;
Align (4);
buffer.WriteBytes (Position - position);
const byte fat_format = 0x40;
const byte more_sects = 0x80;
var flags = ReadByte ();
if ((flags & fat_format) == 0) {
buffer.WriteByte (flags);
PatchRawSmallSection (buffer, metadata);
} else
PatchRawFatSection (buffer, metadata);
if ((flags & more_sects) != 0)
PatchRawSection (buffer, metadata);
}
void PatchRawSmallSection (ByteBuffer buffer, MetadataBuilder metadata)
{
var length = ReadByte ();
buffer.WriteByte (length);
Advance (2);
buffer.WriteUInt16 (0);
var count = length / 12;
PatchRawExceptionHandlers (buffer, metadata, count, false);
}
void PatchRawFatSection (ByteBuffer buffer, MetadataBuilder metadata)
{
Advance (-1);
var length = ReadInt32 ();
buffer.WriteInt32 (length);
var count = (length >> 8) / 24;
PatchRawExceptionHandlers (buffer, metadata, count, true);
}
void PatchRawExceptionHandlers (ByteBuffer buffer, MetadataBuilder metadata, int count, bool fat_entry)
{
const int fat_entry_size = 16;
const int small_entry_size = 6;
for (int i = 0; i < count; i++) {
ExceptionHandlerType handler_type;
if (fat_entry) {
var type = ReadUInt32 ();
handler_type = (ExceptionHandlerType) (type & 0x7);
buffer.WriteUInt32 (type);
} else {
var type = ReadUInt16 ();
handler_type = (ExceptionHandlerType) (type & 0x7);
buffer.WriteUInt16 (type);
}
buffer.WriteBytes (ReadBytes (fat_entry ? fat_entry_size : small_entry_size));
switch (handler_type) {
case ExceptionHandlerType.Catch:
var exception = reader.LookupToken (ReadToken ());
buffer.WriteUInt32 (metadata.LookupToken (exception).ToUInt32 ());
break;
default:
buffer.WriteUInt32 (ReadUInt32 ());
break;
}
}
}
#endif
}
}
| |
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using Bonobo.Git.Server.Configuration;
using Bonobo.Git.Server.Data;
using Bonobo.Git.Server.Models;
using Bonobo.Git.Server.Security;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Bonobo.Git.Server.Test.MembershipTests
{
public abstract class PermissionServiceTestBase
{
protected IRepositoryPermissionService _service;
protected ITeamRepository _teams;
protected IMembershipService _users;
protected IRepositoryRepository _repos;
protected IRoleProvider _roles;
[TestInitialize]
public void Initialse()
{
// This file should never actually get created, but ConfigurationManager needs it for its static initialisation
var configFileName = Path.Combine(Path.GetTempFileName(), "BonoboTestConfig.xml");
ConfigurationManager.AppSettings["UserConfiguration"] = configFileName;
UserConfiguration.InitialiseForTest();
}
[TestMethod]
public void NonExistentRepositoryByNameReturnsFalse()
{
var adminId = GetAdminId();
Assert.IsFalse(_service.HasPermission(adminId, "NonExistentRepos", RepositoryAccessLevel.Pull));
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void NonExistentRepositoryByGuidThrowsException()
{
var adminId = GetAdminId();
Assert.IsFalse(_service.HasPermission(adminId, Guid.NewGuid(), RepositoryAccessLevel.Pull));
}
[TestMethod]
public void AdminIsAuthorisedForAnyRepo()
{
var adminId = GetAdminId();
var repoId = AddRepo("TestRepo");
Assert.IsTrue(CheckPermission(adminId, repoId, RepositoryAccessLevel.Pull));
}
[TestMethod]
public void UnrelatedUserIsNotAuthorisedForRepo()
{
var user = AddUser();
var repoId = AddRepo("TestRepo");
Assert.IsFalse(CheckPermission(user.Id, repoId, RepositoryAccessLevel.Pull));
}
[TestMethod]
public void RepoMemberUserIsAuthorised()
{
var user = AddUser();
var repoId = AddRepo("TestRepo");
AddUserToRepo(repoId, user);
Assert.IsTrue(CheckPermission(user.Id, repoId, RepositoryAccessLevel.Pull));
}
[TestMethod]
public void RepoAdminIsAuthorised()
{
var user = AddUser();
var repoId = AddRepo("TestRepo");
AddAdminToRepo(repoId, user);
Assert.IsTrue(CheckPermission(user.Id, repoId, RepositoryAccessLevel.Pull));
}
[TestMethod]
public void NonTeamMemberIsNotAuthorised()
{
var user = AddUser();
var repoId = AddRepo("TestRepo");
var team = CreateTeam();
AddTeamToRepo(repoId,team);
Assert.IsFalse(CheckPermission(user.Id, repoId, RepositoryAccessLevel.Pull));
}
[TestMethod]
public void TeamMemberIsAuthorised()
{
var user = AddUser();
var repoId = AddRepo("TestRepo");
var team = CreateTeam();
AddTeamToRepo(repoId, team);
// Add the member to the team
team.Members = new[] {user};
UpdateTeam(team);
Assert.IsTrue(CheckPermission(user.Id, repoId, RepositoryAccessLevel.Pull));
}
[TestMethod]
public void SystemAdminIsAlwaysRepositoryAdmin()
{
var repoId = AddRepo("TestRepo");
Assert.IsTrue(_service.HasPermission(GetAdminId(), repoId, RepositoryAccessLevel.Administer));
}
[TestMethod]
public void NormalUserIsNotRepositoryAdmin()
{
var user = AddUser();
var repoId = AddRepo("TestRepo");
AddUserToRepo(repoId, user);
Assert.IsFalse(_service.HasPermission(user.Id, repoId, RepositoryAccessLevel.Administer));
}
[TestMethod]
public void AdminUserIsRepositoryAdmin()
{
var user = AddUser();
var repoId = AddRepo("TestRepo");
AddAdminToRepo(repoId, user);
Assert.IsTrue(_service.HasPermission(user.Id, repoId, RepositoryAccessLevel.Administer));
}
[TestMethod]
public void DefaultRepositoryDoesNotAllowAnonAccess()
{
var repoId = AddRepo("TestRepo");
Assert.IsFalse(_service.HasPermission(Guid.Empty, repoId, RepositoryAccessLevel.Pull));
Assert.IsFalse(_service.HasPermission(Guid.Empty, "TestRepo", RepositoryAccessLevel.Pull));
}
[TestMethod]
public void AllowAnonymousPushDoesNotAffectDefaultRepository()
{
var repoId = AddRepo("TestRepo");
// Allow anon push gobally - it shouldn't have any effect because the repo is not enabled for anon access
UserConfiguration.Current.AllowAnonymousPush = true;
Assert.IsFalse(_service.HasPermission(Guid.Empty, repoId, RepositoryAccessLevel.Pull));
}
[TestMethod]
public void UnknownRepositoryByNameDoesNotAllowAnonAccess()
{
Assert.IsFalse(_service.HasPermission(Guid.Empty, "Unknown", RepositoryAccessLevel.Pull));
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void UnknownRepositoryByGuidThrowsException()
{
Assert.IsFalse(_service.HasPermission(Guid.Empty, Guid.NewGuid(), RepositoryAccessLevel.Pull));
}
[TestMethod]
public void AnonAccessCanBePermittedWithRepoProperty()
{
var repoId = AddRepo("TestRepo");
UpdateRepo(repoId, repo => repo.AnonymousAccess = true);
Assert.IsTrue(_service.HasPermission(Guid.Empty, repoId, RepositoryAccessLevel.Pull));
Assert.IsTrue(_service.HasPermission(Guid.Empty, "TestRepo", RepositoryAccessLevel.Pull));
}
[TestMethod]
public void AnonAccessDoesNotAllowPushByDefault()
{
var repoId = AddRepo("TestRepo");
UpdateRepo(repoId, repo => repo.AnonymousAccess = true);
Assert.IsFalse(_service.HasPermission(Guid.Empty, repoId, RepositoryAccessLevel.Push));
Assert.IsFalse(_service.HasPermission(Guid.Empty, "TestRepo", RepositoryAccessLevel.Push));
}
[TestMethod]
public void AnonPushCanBeEnabledWithConfig()
{
var repoId = AddRepo("TestRepo");
UpdateRepo(repoId, repo => repo.AnonymousAccess = true);
UserConfiguration.Current.AllowAnonymousPush = true;
Assert.IsTrue(_service.HasPermission(Guid.Empty, repoId, RepositoryAccessLevel.Push));
}
[TestMethod]
public void GetAllPermittedReturnsOnlyRepositoriesPermittedForUser()
{
var user = AddUser();
var repo1 = AddRepo("TestRepo1");
AddRepo("TestRepo2");
var repo3 = AddRepo("TestRepo3");
AddUserToRepo(repo1, user);
AddUserToRepo(repo3, user);
CollectionAssert.AreEqual(new[] { "TestRepo1", "TestRepo3" },
_service.GetAllPermittedRepositories(user.Id, RepositoryAccessLevel.Pull).Select(r => r.Name).OrderBy(r => r).ToArray());
}
[TestMethod]
public void GetAllPermittedReturnsAllRepositoriesToSystemAdmin()
{
AddRepo("TestRepo1");
AddRepo("TestRepo2");
AddRepo("TestRepo3");
CollectionAssert.AreEqual(new[] { "TestRepo1", "TestRepo2", "TestRepo3" },
_service.GetAllPermittedRepositories(GetAdminId(), RepositoryAccessLevel.Pull).Select(r => r.Name).OrderBy(r => r).ToArray());
}
[TestMethod]
public void AnonymousRepoIsPermittedToAnybodyToPull()
{
var repo = MakeRepo("Repo1");
repo.AnonymousAccess = true;
Assert.IsTrue(_repos.Create(repo));
var anonymousUser = Guid.Empty;
Assert.AreEqual("Repo1", _service.GetAllPermittedRepositories(anonymousUser, RepositoryAccessLevel.Pull).Single().Name);
}
[TestMethod]
public void AnonymousRepoIsPermittedToNamedUserToPull()
{
// A named user should have at least as good access as an anonymous user
var repo = MakeRepo("Repo1");
repo.AnonymousAccess = true;
Assert.IsTrue(_repos.Create(repo));
var user = AddUser();
Assert.AreEqual("Repo1", _service.GetAllPermittedRepositories(user.Id, RepositoryAccessLevel.Pull).Single().Name);
}
[TestMethod]
public void RepositoryIsPermittedToUser()
{
var user = AddUser();
var repoWithUser = MakeRepo("Repo1");
repoWithUser.Users = new[] { user };
Assert.IsTrue(_repos.Create(repoWithUser));
AddRepo("Repo2");
Assert.AreEqual("Repo1", _service.GetAllPermittedRepositories(user.Id, RepositoryAccessLevel.Pull).Single().Name);
Assert.AreEqual("Repo1", _service.GetAllPermittedRepositories(user.Id, RepositoryAccessLevel.Push).Single().Name);
Assert.IsFalse(_service.GetAllPermittedRepositories(user.Id, RepositoryAccessLevel.Administer).Any());
}
[TestMethod]
public void NewRepositoryNotPermittedToAnonymousUser()
{
var user = AddUser();
var repoWithUser = MakeRepo("Repo1");
repoWithUser.Users = new[] { user };
Assert.IsTrue(_repos.Create(repoWithUser));
Assert.IsFalse(_service.GetAllPermittedRepositories(Guid.Empty, RepositoryAccessLevel.Pull).Any());
}
[TestMethod]
public void RepositoryIsPermittedToRepoAdministrator()
{
var user = AddUser();
var repoWithAdmin = MakeRepo("Repo1");
repoWithAdmin.Administrators = new[] { user };
Assert.IsTrue(_repos.Create(repoWithAdmin));
AddRepo("Repo2");
Assert.AreEqual("Repo1", _service.GetAllPermittedRepositories(user.Id, RepositoryAccessLevel.Administer).Single().Name);
}
[TestMethod]
public void SystemAdministratorCanAlwaysCreateRepo()
{
Assert.IsTrue(_service.HasCreatePermission(GetAdminId()));
}
[TestMethod]
public void NormalUserCannotCreateRepo()
{
var user = AddUser();
Assert.IsFalse(_service.HasCreatePermission(user.Id));
}
[TestMethod]
public void NamedUserCanCreateRepoWithGlobalOptionSet()
{
var user = AddUser();
UserConfiguration.Current.AllowUserRepositoryCreation = true;
Assert.IsTrue(_service.HasCreatePermission(user.Id));
}
[TestMethod]
public void AnonUserCannotCreateRepoWithGlobalOptionSet()
{
UserConfiguration.Current.AllowUserRepositoryCreation = true;
Assert.IsFalse(_service.HasCreatePermission(Guid.Empty));
}
/// <summary>
/// A check-permission routine which runs checks by both name and Guid, and makes sure they agree
/// </summary>
private bool CheckPermission(Guid userId, Guid repoId, RepositoryAccessLevel level)
{
bool byGuid = _service.HasPermission(userId, repoId, level);
bool byName = _service.HasPermission(userId, _repos.GetRepository(repoId).Name, level);
Assert.IsTrue(byGuid == byName);
return byGuid;
}
private UserModel AddUser()
{
_users.CreateUser("fred", "letmein", "Fred", "FredBlogs", "fred@aol");
return _users.GetUserModel("fred");
}
protected abstract TeamModel CreateTeam();
private Guid GetAdminId()
{
return _users.GetUserModel("Admin").Id;
}
private void AddUserToRepo(Guid repoId, UserModel user)
{
UpdateRepo(repoId, repo => repo.Users = new[] { user });
}
private void AddAdminToRepo(Guid repoId, UserModel adminUser)
{
UpdateRepo(repoId, repo => repo.Administrators = new[] { adminUser });
}
private void AddTeamToRepo(Guid repoId, TeamModel team)
{
UpdateRepo(repoId, repo => repo.Teams = new[] { team });
}
protected abstract void UpdateTeam(TeamModel team);
void UpdateRepo(Guid repoId, Action<RepositoryModel> transform)
{
var repo = _repos.GetRepository(repoId);
transform(repo);
_repos.Update(repo);
}
Guid AddRepo(string name)
{
var newRepo = MakeRepo(name);
Assert.IsTrue(_repos.Create(newRepo));
return newRepo.Id;
}
RepositoryModel MakeRepo(string name)
{
var newRepo = new RepositoryModel();
newRepo.Name = name;
return newRepo;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(PORTABLE40 || NET20 || NET35)
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace uWebshop.Newtonsoft.Json.Utilities
{
internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance
{
get { return _instance; }
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, "method");
Type type = typeof (object);
ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
ParameterExpression argsParameterExpression = Expression.Parameter(typeof (object[]), "args");
ParameterInfo[] parametersInfo = method.GetParameters();
var argsExpression = new Expression[parametersInfo.Length];
for (int i = 0; i < parametersInfo.Length; i++)
{
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
paramAccessorExpression = EnsureCastExpression(paramAccessorExpression, parametersInfo[i].ParameterType);
argsExpression[i] = paramAccessorExpression;
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo) method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo) method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo) method, argsExpression);
}
if (method is MethodInfo)
{
var m = (MethodInfo) method;
if (m.ReturnType != typeof (void))
callExpression = EnsureCastExpression(callExpression, type);
else
callExpression = Expression.Block(callExpression, Expression.Constant(null));
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof (MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression);
var compiled = (MethodCall<T, object>) lambdaExpression.Compile();
return compiled;
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
// avoid error from expressions compiler because of abstract class
if (type.IsAbstract())
return () => (T) Activator.CreateInstance(type);
try
{
Type resultType = typeof (T);
Expression expression = Expression.New(type);
expression = EnsureCastExpression(expression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof (Func<T>), expression);
var compiled = (Func<T>) lambdaExpression.Compile();
return compiled;
}
catch
{
// an error can be thrown if constructor is not valid on Win8
// will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag
return () => (T) Activator.CreateInstance(type);
}
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
Type instanceType = typeof (T);
Type resultType = typeof (object);
ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance");
Expression resultExpression;
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod.IsStatic)
{
resultExpression = Expression.MakeMemberAccess(null, propertyInfo);
}
else
{
Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType);
resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo);
}
resultExpression = EnsureCastExpression(resultExpression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof (Func<T, object>), resultExpression, parameterExpression);
var compiled = (Func<T, object>) lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
ParameterExpression sourceParameter = Expression.Parameter(typeof (T), "source");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
fieldExpression = EnsureCastExpression(fieldExpression, typeof (object));
Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof (T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof (object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof (Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression);
var compiled = (Action<T, object>) lambdaExpression.Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
// use reflection for structs
// expression doesn't correctly set value
if (propertyInfo.DeclaringType.IsValueType())
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
Type instanceType = typeof (T);
Type valueType = typeof (object);
ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");
ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
Expression setExpression;
if (setMethod.IsStatic)
{
setExpression = Expression.Call(setMethod, readValueParameter);
}
else
{
Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);
setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof (Action<T, object>), setExpression, instanceParameter, valueParameter);
var compiled = (Action<T, object>) lambdaExpression.Compile();
return compiled;
}
private Expression EnsureCastExpression(Expression expression, Type targetType)
{
Type expressionType = expression.Type;
// check if a cast or conversion is required
if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType)))
return expression;
return Expression.Convert(expression, targetType);
}
}
}
#endif
| |
using NLog;
using NUnit.Framework;
using System;
using System.IO;
using Moq;
namespace CodeSearcher.Tests.IntegrationTests
{
[TestFixture]
[Category("SafeForCI")]
public class CmdLineHandlerTests
{
[Test]
public void GetProgramMode_ParameterAuto_ProgramModeAuto()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new []{"auto"});
Assert.True(result);
Assert.That(sut.GetProgramMode, Is.EqualTo(ProgramModes.Auto));
}
[TestCase("-i")]
[TestCase("--indexPath")]
public void GetProgramMode_ParameterIndex_ProgramModeIndex(string indexPath)
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"index", $"{indexPath}", "SomeIndexPath", "-s", "SomeSourcePath" });
Assert.True(result);
Assert.That(sut.GetProgramMode, Is.EqualTo(ProgramModes.Index));
Assert.That(sut.IndexPath, Is.EqualTo("SomeIndexPath"));
Assert.That(sut.SourcePath, Is.EqualTo("SomeSourcePath"));
Assert.That(sut.GetProgramMode, Is.EqualTo(ProgramModes.Index));
}
[Test]
public void FileExtensions_IndexModeWithOptionalArgument_ReturnsFileExtention()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"index", "--indexPath", "SomeIndexPath", "-f", "txt", "--SourcePath", "SomeSourcePath" });
Assert.True(result);
Assert.That(sut.GetFileExtensionsAsList, Is.EquivalentTo(new [] {"txt"}));
}
[Test]
public void FileExtensions_IndexModeWithoutOptionalExtentionParemeter_ReturnsDefault()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"index", "-i", "SomeIndexPath", "-s", "SomeSourcePath" });
Assert.True(result);
Assert.That(sut.GetFileExtensionsAsList, Is.EquivalentTo(new [] {".cs", ".xml", ".csproj"}));
}
[Test]
public void GetExtention_ParseInputWithExtentionParameter_ReturnsSplittedExtentionList()
{
var extention = ".txt, .doc, .tex";
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
sut.Parse(new string[] {"index", "-i", "SomeIndexPath", "--fileExtensions", $"{extention}", "--sourcePath", "SomeSourcePath" });
Assert.That(sut.GetFileExtensionsAsList(), Is.EquivalentTo(new []{".txt", ".doc", ".tex"}));
}
[Test]
public void GetExtention_ParseInputWithoutExtentionParameter_ReturnsDefaultList()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
sut.Parse(new string[] {"index", "--indexpath", "SomeIndexPath", "-s", "SomeSourcePath" });
Assert.That(sut.GetFileExtensionsAsList(), Is.EquivalentTo(".cs,.xml,.csproj".Split(',')));
}
[Test]
public void GetExtention_ParseNonIndexInput_Null()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
sut.Parse(new string[] {"auto" });
Assert.That(sut.GetFileExtensionsAsList(), Is.Null);
}
[Test]
public void GetProgramMode_ParameterSearch_ProgramModeSearch()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-s", "bla", "-i", "SomeIndexPath"});
Assert.True(result);
Assert.That(sut.GetProgramMode, Is.EqualTo(ProgramModes.Search));
}
[Test]
public void Parse_SearchModeWithoutSearchWord_Failed()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-i", "SomeIndexPath"});
Assert.False(result);
}
[Test]
public void Parse_SearchModeWithoutSearchWord_PrintsHelp()
{
bool executed = false;
Func<TextWriter> consoleRequest = () => { executed = true; return null; };
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), consoleRequest);
sut.Parse(new string[] { "search", "--indexpath", "SomeIndexPath" });
Assert.True(executed);
}
[Test]
public void Parse_SearchModeWithoutIndexPath_Failed()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-s", "bla"});
Assert.False(result);
}
[Test]
public void Parse_SearchModeWithoutIndexPath_PrintsHelp()
{
bool executed = false;
Func<TextWriter> consoleRequest = () => { executed = true; return null; };
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), consoleRequest);
sut.Parse(new string[] { "search", "--searchwOrd", "bla" });
Assert.True(executed);
}
[Test]
public void IndexPath_SearchModeWithIndexPath_ParsedPath()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search", "-s", "bla", "-i", "SomeIndexPath"});
Assert.True(result);
Assert.That(sut.IndexPath, Is.EqualTo("SomeIndexPath"));
}
[Test]
public void SearchedWord_SearchModeWithIndexPath_ParsedPath()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search", "-s", "bla", "-i", "SomeIndexPath"});
Assert.True(result);
Assert.That(sut.SearchWord, Is.EqualTo("bla"));
}
[Test]
public void HitsPerPage_ParseStringWithOptionalArgumentHitsPerPage_GivenArgumentsValue()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-s", "bla", "--IndexPath", "SomeIndexPath", "-p", "100"});
Assert.True(result);
Assert.That(sut.HitsPerPage, Is.EqualTo(100));
}
[Test]
public void HitsPerPage_ParseStringWithoutOptionalArgumentHitsPerPage_Fails()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-s", "bla", "-i", "index", "-p", "SomeIndexPath"});
Assert.False(result);
}
[Test]
public void Parse_OptionalArgumentHitsPerPageNotANumber_Fails()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"-m=search" , "--sw=bla", "--ip=SomeIndexPath", "--hpp=hallo"});
Assert.That(result, Is.False);
}
[Test]
public void NumberOfHits_ParseInputWithoutOptionalArgumentNumberOfHits_GivenArgumentsValue()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-s", "bla", "-n", "100", "-i", "SomeIndexPath"});
Assert.True(result);
Assert.That(sut.NumberOfHits, Is.EqualTo(100));
}
[Test]
public void NumberOfHits_ParseInputWithoutOptionalArgumentNumberOfHits_Default()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-s", "bla", "-i", "SomeIndexPath"});
Assert.True(result);
Assert.That(sut.NumberOfHits, Is.EqualTo(1000));
}
[Test]
public void Parse_NumberOfHitsParameterIsNotANumber_Throws()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] { "-m=search", "--sw=bla", "--ip=SomeIndexPath", "--hits=hallo" });
Assert.That(result, Is.False);
}
[Test]
public void ExportToFile_ParseInputWithOptionalArgument_ExportArgument()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-s", "bla", "--indexPath", "SomeIndexPath", "--export"});
Assert.True(result);
Assert.That(sut.ExportToFile, Is.True);
}
[Test]
public void ExportToFile_ParseInputWithExport_Null()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "--searchWord", "bla", "-i", "SomeIndexPath"});
Assert.True(result);
Assert.That(sut.ExportToFile, Is.False);
}
[Test]
public void WildcardSearch_ParseInputOptionalArgumentWildCard_GivenArgument()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "--searchword", "bla", "--indexPath", "SomeIndexPath", "--wildcard"});
Assert.True(result);
Assert.That(sut.WildCardSearch, Is.True);
}
[Test]
public void WildcardSearch_ParseInputWithOptionalArgumentWildCard_Null()
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search", "-s", "bla", "-i", "SomeIndexPath"});
Assert.True(result);
Assert.That(sut.ExportToFile, Is.False);
}
[Test]
public void Parse_EmptyInput_PrintsHelp()
{
bool executed = false;
Func<TextWriter> consoleRequest = () => { executed = true; return null; };
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), consoleRequest);
sut.Parse(Array.Empty<string>());
Assert.True(executed);
}
[Test]
public void Parse_QuestionMark_PrintsHelp()
{
bool executed = false;
Func<TextWriter> consoleRequest = () => { executed = true; return null; };
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), consoleRequest);
sut.Parse(new []{ "-?"});
Assert.True(executed);
}
[TestCase("--wildcard")]
[TestCase("--wildCard")]
[TestCase("--Wildcard")]
[TestCase("--WildCard")]
[TestCase("--WILDCARD")]
public void Parse_CaseMixedInput_SameResult(string wildCard)
{
CmdLineHandler sut = new CmdLineHandler(Mock.Of<ILogger>(), ()=>null);
var result = sut.Parse(new string[] {"search" , "-s", "bla", "-i", "SomeIndexPath", wildCard});
Assert.True(result);
Assert.That(sut.WildCardSearch, Is.True);
}
}
}
| |
using System;
using System.Drawing;
using System.Net;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace webimgPlugin.Site
{
/// <summary>
/// Website.
/// Each plugin can provide one or more websites.
/// This class already provides a thread for scanning the page.
/// </summary>
public abstract class WebSite
{
#region VARIABLES
private string url, name;
private Post lastPost;
private int interval;
private bool running;
private Thread thread;
private SitePlugin source;
#endregion
#region PROPERTIES
/// <summary>
/// Gets the URL.
/// </summary>
/// <value>
/// The URL.
/// </value>
public string URL {
get { return url; }
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name {
get { return name; }
}
/// <summary>
/// Gets or sets the last post.
/// </summary>
/// <value>
/// The last post.
/// </value>
public Post LastPost {
get { return lastPost; }
protected set { lastPost = value; }
}
/// <summary>
/// Gets or sets the interval (in seconds) that determines the duration between each scan.
/// </summary>
/// <value>
/// The interval (in seconds).
/// </value>
public int Interval {
get { return interval; }
protected set { interval = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="webimgPlugin.Site.WebSite"/> is running.
/// </summary>
/// <value>
/// <c>true</c> if running; otherwise, <c>false</c>.
/// </value>
public bool Running {
get { return running; }
set {
if (running != value) {
running = value;
if (running)
StartThread ();
else
StopThread ();
}
}
}
public SitePlugin Source {
get { return source; }
set { source = value; }
}
#endregion
#region EVENTS
/// <summary>
/// Occurs when new posts were found.
/// </summary>
public event EventHandler PostsFound;
private void OnPostsFound (PostsFoundEventArgs e)
{
if(PostsFound != null)
PostsFound(this, e);
}
#endregion
#region CONSTRUCTORS
/// <summary>
/// Initializes a new instance of the <see cref="webimgPlugin.Site.WebSite"/> class.
/// </summary>
/// <param name='url'>
/// Site-URL.
/// </param>
/// <param name='name'>
/// Site-Name (or site-caption).
/// </param>
/// <param name='interval'>
/// Interval (in seconds) that determines the duration between each scan. Default value is 60 seconds (1 minute).
/// </param>
public WebSite (string url, string name, int interval = 60)
{
this.url = url;
this.name = name;
this.interval = interval;
//DebugMessage("Initiated.");
}
#endregion
#region METHODS
protected void DebugMessage (string message)
{
#if DEBUG
source.DebugMessage(message, this);
#endif
}
protected void DebugMessage (Exception ex)
{
#if DEBUG
source.DebugMessage(ex, this);
#endif
}
/// <summary>
/// Checks for new images.
/// </summary>
/// <returns>
/// The new images.
/// </returns>
/// <param name='firstCheck'>
/// First check. If set to true, this should only scan the first page/set of images on a site.
/// </param>
public abstract Post[] CheckForNewImages (bool firstCheck = false);
private void Run ()
{
DebugMessage("Initiating scans");
Post[] newPosts;
bool firstRun = true;
Stopwatch watch = new Stopwatch();
while (running) {
watch.Start ();
DebugMessage("Running scan");
newPosts = CheckForNewImages (firstRun);
if(newPosts != null) {
DebugMessage (newPosts.Length.ToString () + " Posts found");
DebugMessage("Scan finished after " + new TimeSpan(watch.ElapsedTicks).TotalSeconds + " seconds");
if(firstRun)
firstRun = false;
PipePosts (newPosts);
} else {
DebugMessage("Did not get any posts...(null)");
}
watch.Stop ();
watch.Reset ();
Thread.Sleep (interval * 1000);
}
}
private void StartThread ()
{
thread = new Thread(new ThreadStart(Run));
thread.IsBackground = true;
thread.Start ();
}
private void StopThread ()
{
if (thread != null) {
if(thread.ThreadState == System.Threading.ThreadState.Running) {
thread.Abort ();
}
thread = null;
}
}
private void PipePosts (Post[] posts)
{
if (posts != null) {
if (posts.Length > 0) {
OnPostsFound (new PostsFoundEventArgs (posts, this));
}
}
}
public string ToLongString ()
{
return string.Format ("[WebSite: URL={0}, Name={1}, LastPost={2}, Interval={3}, Running={4}, Source={5}]", URL, Name, LastPost, Interval, Running, Source);
}
public override string ToString() {
return this.name;
}
#endregion
}
}
| |
/*
Copyright 2017 Alexis Ryan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using SQLite;
using Ao3TrackReader.Helper;
namespace Ao3TrackReader
{
public sealed class Work : IWorkChapterEx
{
public Work()
{
}
[PrimaryKey, Column("id")]
public long workid { get; set; }
[Column("chapterid")]
public long chapterid { get; set; }
[Column("number")]
public long number { get; set; }
[Column("timestamp")]
public long Timestamp { get; set; }
[Column("location")]
public long? location { get; set; }
[Column("seq")]
public long Seq { get; set; }
[Ignore]
long? IWorkChapter.seq { get { return Seq; } set { Seq = value ?? 0; } }
[Ignore]
public long paragraph
{
get
{
if (location == null) return long.MaxValue;
return (long)location / 1000000000L;
}
}
[Ignore]
public long frac
{
get
{
if (location == null) return long.MaxValue;
var offset = (long)location % 1000000000L;
if (offset == 500000000L) return 100;
return offset * 100L / 479001600L;
}
}
public bool LessThan(Work newitem)
{
if (newitem.workid != workid) { throw new ArgumentException("Items don't belong to same work", "newitem"); }
if (newitem.Seq > this.Seq) { return true; }
else if (newitem.Seq < this.Seq) { return false; }
if (newitem.number > this.number) { return true; }
else if (newitem.number < this.number) { return false; }
if (this.location == null) { return false; }
if (newitem.location == null) { return true; }
return newitem.location > this.location;
}
public bool LessThan(IWorkChapter newitem)
{
if (newitem is IWorkChapterEx) return LessThan(newitem as IWorkChapterEx);
if (newitem.seq > this.Seq) { return true; }
else if (newitem.seq < this.Seq) { return false; }
if (newitem.number > this.number) { return true; }
else if (newitem.number < this.number) { return false; }
if (this.location == null) { return false; }
if (newitem.location == null) { return true; }
return newitem.location > this.location;
}
public bool LessThan(IWorkChapterEx newitem)
{
if (newitem.workid != workid) { throw new ArgumentException("Items don't belong to same work", "newitem"); }
if (newitem.seq > this.Seq) { return true; }
else if (newitem.seq < this.Seq) { return false; }
if (newitem.number > this.number) { return true; }
else if (newitem.number < this.number) { return false; }
if (this.location == null) { return false; }
if (newitem.location == null) { return true; }
return newitem.location > this.location;
}
public bool LessThanOrEqual(Work newitem)
{
if (newitem.workid != workid) { throw new ArgumentException("Items don't belong to same work", "newitem"); }
if (newitem.Seq > this.Seq) { return true; }
else if (newitem.Seq < this.Seq) { return false; }
if (newitem.number > this.number) { return true; }
else if (newitem.number < this.number) { return false; }
if (newitem.location == null) { return true; }
if (this.location == null) { return false; }
return newitem.location >= this.location;
}
public bool LessThanOrEqual(IWorkChapter newitem)
{
if (newitem is IWorkChapterEx) return LessThanOrEqual(newitem as IWorkChapterEx);
if (newitem.seq > this.Seq) { return true; }
else if (newitem.seq < this.Seq) { return false; }
if (newitem.number > this.number) { return true; }
else if (newitem.number < this.number) { return false; }
if (newitem.location == null) { return true; }
if (this.location == null) { return false; }
return newitem.location >= this.location;
}
public bool LessThanOrEqual(IWorkChapterEx newitem)
{
if (newitem.workid != workid) { throw new ArgumentException("Items don't belong to same work", "newitem"); }
if (newitem.seq > this.Seq) { return true; }
else if (newitem.seq < this.Seq) { return false; }
if (newitem.number > this.number) { return true; }
else if (newitem.number < this.number) { return false; }
if (newitem.location == null) { return true; }
if (this.location == null) { return false; }
return newitem.location >= this.location;
}
public static bool operator >=(Work left, Work right)
{
return !left.LessThan(right);
}
public static bool operator <=(Work left, Work right)
{
return left.LessThanOrEqual(right);
}
public static bool operator >=(Work left, WorkChapter right)
{
return !left.LessThan(right);
}
public static bool operator <=(Work left, WorkChapter right)
{
return left.LessThanOrEqual(right);
}
public static bool operator >=(WorkChapter left, Work right)
{
return !left.LessThan(right);
}
public static bool operator <=(WorkChapter left, Work right)
{
return left.LessThanOrEqual(right);
}
public static bool operator >=(Work left, IWorkChapter right)
{
return !(left as IWorkChapter).LessThan(right);
}
public static bool operator <=(Work left, IWorkChapter right)
{
return (left as IWorkChapter).LessThanOrEqual(right);
}
public static bool operator >=(IWorkChapter left, Work right)
{
return (right as IWorkChapter).LessThanOrEqual(left);
}
public static bool operator <=(IWorkChapter left, Work right)
{
return !(right as IWorkChapter).LessThan(left);
}
}
}
| |
// 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 TestZInt64()
{
var test = new BooleanBinaryOpTest__TestZInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestZInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int64> _fld1;
public Vector128<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestZInt64 testClass)
{
var result = Sse41.TestZ(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestZInt64 testClass)
{
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int64>* pFld2 = &_fld2)
{
var result = Sse41.TestZ(
Sse2.LoadVector128((Int64*)(pFld1)),
Sse2.LoadVector128((Int64*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector128<Int64> _clsVar2;
private Vector128<Int64> _fld1;
private Vector128<Int64> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestZInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
}
public BooleanBinaryOpTest__TestZInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.TestZ(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.TestZ(
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.TestZ(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.TestZ(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int64>* pClsVar2 = &_clsVar2)
{
var result = Sse41.TestZ(
Sse2.LoadVector128((Int64*)(pClsVar1)),
Sse2.LoadVector128((Int64*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr);
var result = Sse41.TestZ(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse41.TestZ(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse41.TestZ(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestZInt64();
var result = Sse41.TestZ(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestZInt64();
fixed (Vector128<Int64>* pFld1 = &test._fld1)
fixed (Vector128<Int64>* pFld2 = &test._fld2)
{
var result = Sse41.TestZ(
Sse2.LoadVector128((Int64*)(pFld1)),
Sse2.LoadVector128((Int64*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.TestZ(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int64>* pFld2 = &_fld2)
{
var result = Sse41.TestZ(
Sse2.LoadVector128((Int64*)(pFld1)),
Sse2.LoadVector128((Int64*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.TestZ(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.TestZ(
Sse2.LoadVector128((Int64*)(&test._fld1)),
Sse2.LoadVector128((Int64*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
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<Int64> op1, Vector128<Int64> op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((left[i] & right[i]) == 0);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.TestZ)}<Int64>(Vector128<Int64>, Vector128<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* PROPRIETARY INFORMATION. This software is proprietary to
* Side Effects Software Inc., and is not to be reproduced,
* transmitted, or disclosed in any way without written permission.
*
* Produced by:
* Side Effects Software Inc
* 123 Front Street West, Suite 1401
* Toronto, Ontario
* Canada M5J 2M2
* 416-504-9876
*
* COMMENTS:
*
*/
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
public partial class HoudiniAssetGUIOTL : HoudiniAssetGUI
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Public
public void handlesOnSceneGUI()
{
if ( myAssetOTL.prShowPinnedInstances )
drawPinnedInstances();
// On mouse up the drag operation is completed.
if ( Event.current.type == EventType.MouseUp )
myOpInProgress = false;
string currentGlobalManipTool = Tools.current.ToString();
if ( currentGlobalManipTool == "Rotate" )
myManipMode = XformManipMode.Rotate;
else if ( currentGlobalManipTool == "Move" )
myManipMode = XformManipMode.Translate;
else if ( currentGlobalManipTool == "Scale" )
myManipMode = XformManipMode.Scale;
if ( myAssetOTL == null )
return;
int node_id = myAssetOTL.prNodeId;
HAPI_HandleInfo[] handleInfos = myAssetOTL.prHandleInfos;
if ( handleInfos == null )
return;
// Detect changes and build asset only when changed.
bool changed = false;
for ( int ii = 0; ii < handleInfos.Length; ++ii )
{
HAPI_HandleInfo handleInfo = handleInfos[ ii ];
if ( handleInfo.typeName == "xform" )
{
float tx = 0, ty = 0, tz = 0;
float rx = 0, ry = 0, rz = 0;
float sx = 1, sy = 1, sz = 1;
HAPI_RSTOrder rstOrder = HAPI_RSTOrder.HAPI_SRT;
HAPI_XYZOrder xyzOrder = HAPI_XYZOrder.HAPI_XYZ;
HAPI_HandleBindingInfo[] bindingInfos = myAssetOTL.prHandleBindingInfos[ ii ];
int[] parm_int_values = myAssetOTL.prParms.prParmIntValues;
float[] parm_float_values = myAssetOTL.prParms.prParmFloatValues;
if ( parm_int_values == null || parm_float_values == null )
{
Debug.LogError( "No parm int/float values yet handles exist?" );
continue;
}
int translate_parm_id = -1;
int rotate_parm_id = -1;
int scale_parm_id = -1;
int rst_order_parm_id = -1;
int xyz_order_parm_id = -1;
foreach ( HAPI_HandleBindingInfo bindingInfo in bindingInfos )
{
string parm_name = bindingInfo.handleParmName;
if ( parm_name == "tx" )
translate_parm_id = bindingInfo.assetParmId;
else if ( parm_name == "rx" )
rotate_parm_id = bindingInfo.assetParmId;
else if ( parm_name == "sx" )
scale_parm_id = bindingInfo.assetParmId;
else if ( parm_name == "trs_order" )
rst_order_parm_id = bindingInfo.assetParmId;
else if ( parm_name == "xyz_order" )
xyz_order_parm_id = bindingInfo.assetParmId;
}
if ( translate_parm_id >= 0 )
{
HAPI_ParmInfo parm_info = myAssetOTL.prParms.findParm( translate_parm_id );
tx = parm_float_values[ parm_info.floatValuesIndex + 0 ];
ty = parm_float_values[ parm_info.floatValuesIndex + 1 ];
tz = parm_float_values[ parm_info.floatValuesIndex + 2 ];
}
if ( rotate_parm_id >= 0 )
{
HAPI_ParmInfo parm_info = myAssetOTL.prParms.findParm( rotate_parm_id );
rx = parm_float_values[ parm_info.floatValuesIndex + 0 ];
ry = parm_float_values[ parm_info.floatValuesIndex + 1 ];
rz = parm_float_values[ parm_info.floatValuesIndex + 2 ];
}
if ( scale_parm_id >= 0 )
{
HAPI_ParmInfo parm_info = myAssetOTL.prParms.findParm( scale_parm_id );
sx = parm_float_values[ parm_info.floatValuesIndex + 0 ];
sy = parm_float_values[ parm_info.floatValuesIndex + 1 ];
sz = parm_float_values[ parm_info.floatValuesIndex + 2 ];
}
if ( rst_order_parm_id >= 0 )
{
HAPI_ParmInfo parm_info = myAssetOTL.prParms.findParm( rst_order_parm_id );
rstOrder = (HAPI_RSTOrder) parm_int_values[ parm_info.intValuesIndex ];
}
if ( xyz_order_parm_id >= 0 )
{
HAPI_ParmInfo parm_info = myAssetOTL.prParms.findParm( xyz_order_parm_id );
xyzOrder = (HAPI_XYZOrder) parm_int_values[ parm_info.intValuesIndex ];
}
HAPI_TransformEuler xform = new HAPI_TransformEuler( true );
// This bit is a little tricky. We will eventually call Handle.PositionHandle
// or Handle.RotationHandle to display the translation and rotation handles.
// These function take a translation parameter and a rotation parameter in
// order to display the handle in its proper location and orientation.
// These functions have an assumed order that it will put the rotation
// and translation back together. Depending whether the order of translation
// and roation matches that of the rstOrder setting, we may, or may not
// need to convert the translation parameter for use with the handle.
if ( rstOrder == HAPI_RSTOrder.HAPI_TSR || rstOrder == HAPI_RSTOrder.HAPI_STR || rstOrder == HAPI_RSTOrder.HAPI_SRT )
{
xform.position[0] = tx;
xform.position[1] = ty;
xform.position[2] = tz;
xform.rotationEuler[0] = rx;
xform.rotationEuler[1] = ry;
xform.rotationEuler[2] = rz;
xform.scale[0] = 1;
xform.scale[1] = 1;
xform.scale[2] = 1;
xform.rotationOrder = xyzOrder;
xform.rstOrder = rstOrder;
}
else
{
xform.position[0] = 0;
xform.position[1] = 0;
xform.position[2] = 0;
xform.rotationEuler[0] = rx;
xform.rotationEuler[1] = ry;
xform.rotationEuler[2] = rz;
xform.scale[0] = 1;
xform.scale[1] = 1;
xform.scale[2] = 1;
xform.rotationOrder = xyzOrder;
xform.rstOrder = rstOrder;
}
xform = HoudiniHost.convertTransform( xform, HAPI_RSTOrder.HAPI_SRT, HAPI_XYZOrder.HAPI_ZXY );
// Axis and Rotation conversions:
// Note that Houdini's X axis points in the opposite direction that Unity's does. Also, Houdini's
// rotation is right handed, whereas Unity is left handed. To account for this, we need to invert
// the x coordinate of the translation, and do the same for the rotations (except for the x rotation,
// which doesn't need to be flipped because the change in handedness AND direction of the left x axis
// causes a double negative - yeah, I know).
xform.position[ 0 ] = -xform.position[ 0 ];
xform.rotationEuler[ 1 ] = -xform.rotationEuler[ 1 ];
xform.rotationEuler[ 2 ] = -xform.rotationEuler[ 2 ];
tx = -tx;
Handles.matrix = myAssetOTL.transform.localToWorldMatrix;
Vector3 position;
if( rstOrder == HAPI_RSTOrder.HAPI_TSR || rstOrder == HAPI_RSTOrder.HAPI_STR || rstOrder == HAPI_RSTOrder.HAPI_SRT )
position = new Vector3( xform.position[ 0 ], xform.position[ 1 ], xform.position[ 2 ] );
else
position = new Vector3( tx, ty, tz );
Quaternion rotation = Quaternion.Euler(
xform.rotationEuler[ 0 ], xform.rotationEuler[ 1 ], xform.rotationEuler[ 2 ] );
Vector3 scale = new Vector3( sx, sy, sz );
if ( myManipMode == XformManipMode.Translate )
{
if ( translate_parm_id < 0 )
continue;
HAPI_ParmInfo parm_info = myAssetOTL.prParms.findParm( translate_parm_id );
if ( parm_info.invisible )
continue;
GUIStyle style = new GUIStyle( EditorStyles.textField );
style.contentOffset = new Vector2( 1.4f, 1.4f );
string handle_name = handleInfo.name;
if ( parm_info.disabled )
handle_name = handle_name + " (disabled)";
GUIContent content = new GUIContent( handle_name );
content.tooltip = handle_name;
Handles.Label( position, content, style );
if ( parm_info.disabled )
{
Handles.lighting = false;
Handles.PositionHandle( position, rotation );
Handles.lighting = true;
continue;
}
Vector3 new_position = Handles.PositionHandle( position, rotation );
if ( new_position != position )
{
changed = true;
if ( !myOpInProgress )
{
Undo.RecordObject( myAssetOTL.prParms.prParmsUndoInfo, handleInfo.name );
myOpInProgress = true;
}
if ( rstOrder == HAPI_RSTOrder.HAPI_TSR
|| rstOrder == HAPI_RSTOrder.HAPI_STR
|| rstOrder == HAPI_RSTOrder.HAPI_SRT )
{
xform.position[ 0 ] = new_position[ 0 ];
xform.position[ 1 ] = new_position[ 1 ];
xform.position[ 2 ] = new_position[ 2 ];
xform = HoudiniHost.convertTransform( xform, rstOrder, xyzOrder );
new_position.x = xform.position[ 0 ];
new_position.y = xform.position[ 1 ];
new_position.z = xform.position[ 2 ];
}
// the - in the x coordinate is to convert back to "Houdini" coordinates
parm_float_values[ parm_info.floatValuesIndex + 0 ] = -new_position.x;
parm_float_values[ parm_info.floatValuesIndex + 1 ] = new_position.y;
parm_float_values[ parm_info.floatValuesIndex + 2 ] = new_position.z;
float[] temp_float_values = new float[ HoudiniConstants.HAPI_POSITION_VECTOR_SIZE ];
for ( int pp = 0; pp < HoudiniConstants.HAPI_POSITION_VECTOR_SIZE; ++pp )
temp_float_values[ pp ] = parm_float_values[ parm_info.floatValuesIndex + pp ];
HoudiniHost.setParmFloatValues( node_id, temp_float_values, parm_info.floatValuesIndex,
parm_info.size );
myAsset.savePreset();
} // if changed
}
else if ( myManipMode == XformManipMode.Rotate )
{
if ( rotate_parm_id < 0 )
continue;
HAPI_ParmInfo parm_info = myAssetOTL.prParms.findParm( rotate_parm_id );
if ( parm_info.invisible )
continue;
GUIStyle style = new GUIStyle( EditorStyles.textField );
style.contentOffset = new Vector2( 1.4f, 1.4f );
string handle_name = handleInfo.name;
if ( parm_info.disabled )
handle_name = handle_name + " (disabled)";
GUIContent content = new GUIContent( handle_name );
content.tooltip = handle_name;
Handles.Label( position, content, style );
if ( parm_info.disabled )
{
Handles.lighting = false;
Handles.RotationHandle( rotation, position );
Handles.lighting = true;
continue;
}
Quaternion new_rotation = Handles.RotationHandle( rotation, position );
if ( new_rotation != rotation )
{
changed = true;
if ( !myOpInProgress )
{
Undo.RecordObject( myAssetOTL.prParms.prParmsUndoInfo, handleInfo.name );
myOpInProgress = true;
}
Vector3 newRot = new_rotation.eulerAngles;
xform.position[0] = 0;
xform.position[1] = 0;
xform.position[2] = 0;
xform.rotationEuler[0] = newRot.x;
xform.rotationEuler[1] = newRot.y;
xform.rotationEuler[2] = newRot.z;
xform.scale[0] = 1;
xform.scale[1] = 1;
xform.scale[2] = 1;
xform.rotationOrder = HAPI_XYZOrder.HAPI_ZXY;
xform.rstOrder = HAPI_RSTOrder.HAPI_SRT;
xform = HoudiniHost.convertTransform( xform, rstOrder, xyzOrder );
parm_float_values[ parm_info.floatValuesIndex + 0 ] = xform.rotationEuler[ 0 ];
// the - in the y & z coordinate is to convert back to "Houdini" coordinates
parm_float_values[ parm_info.floatValuesIndex + 1 ] = -xform.rotationEuler[ 1 ];
parm_float_values[ parm_info.floatValuesIndex + 2 ] = -xform.rotationEuler[ 2 ];
float[] temp_float_values = new float[ HoudiniConstants.HAPI_POSITION_VECTOR_SIZE ];
for ( int pp = 0; pp < HoudiniConstants.HAPI_POSITION_VECTOR_SIZE; ++pp )
temp_float_values[ pp ] = parm_float_values[ parm_info.floatValuesIndex + pp ];
HoudiniHost.setParmFloatValues(
node_id, temp_float_values, parm_info.floatValuesIndex, parm_info.size );
myAsset.savePreset();
} // if changed
}
else if ( myManipMode == XformManipMode.Scale )
{
if ( scale_parm_id < 0 )
continue;
HAPI_ParmInfo parm_info = myAssetOTL.prParms.findParm( scale_parm_id );
if ( parm_info.invisible )
continue;
GUIStyle style = new GUIStyle( EditorStyles.textField );
style.contentOffset = new Vector2( 1.4f, 1.4f );
string handle_name = handleInfo.name;
if ( parm_info.disabled )
handle_name = handle_name + " (disabled)";
GUIContent content = new GUIContent( handle_name );
content.tooltip = handle_name;
Handles.Label( position, content, style );
if ( parm_info.disabled )
{
Handles.lighting = false;
Handles.ScaleHandle( scale, position, rotation, 1.0f );
Handles.lighting = true;
continue;
}
Vector3 new_scale = Handles.ScaleHandle( scale, position, rotation, 1.0f );
if ( new_scale != scale )
{
changed = true;
if ( !myOpInProgress )
{
Undo.RecordObject( myAssetOTL.prParms.prParmsUndoInfo, handleInfo.name );
myOpInProgress = true;
}
parm_float_values[ parm_info.floatValuesIndex + 0 ] = new_scale.x;
parm_float_values[ parm_info.floatValuesIndex + 1 ] = new_scale.y;
parm_float_values[ parm_info.floatValuesIndex + 2 ] = new_scale.z;
float[] temp_float_values = new float[ HoudiniConstants.HAPI_POSITION_VECTOR_SIZE ];
for ( int pp = 0; pp < HoudiniConstants.HAPI_POSITION_VECTOR_SIZE; ++pp )
temp_float_values[ pp ] = parm_float_values[ parm_info.floatValuesIndex + pp ];
HoudiniHost.setParmFloatValues(
node_id, temp_float_values, parm_info.floatValuesIndex,
parm_info.size );
myAsset.savePreset();
} // if changed
} // if myManipMode
} // if typeName
} // for each handle
if ( changed )
myAssetOTL.buildClientSide();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Private
private void drawPinnedInstances()
{
HoudiniInstancer instancer = myAsset.gameObject.GetComponentInChildren< HoudiniInstancer >();
if( instancer == null )
return;
instancer.drawAllPins();
}
private enum XformManipMode
{
Translate = 0,
Rotate,
Scale
}
private XformManipMode myManipMode = XformManipMode.Translate;
private bool myOpInProgress = false;
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Hooker.WebApi.Areas.HelpPage.SampleGeneration
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator _simpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return _simpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return ((IEnumerable)list).AsQueryable();
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => index + 0.1 },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index => String.Format(CultureInfo.CurrentCulture, "sample string {0}", index)
},
{
typeof(TimeSpan), index => TimeSpan.FromTicks(1234567)
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index => new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index))
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 32feet.NET - Personal Area Networking for .NET
//
// InTheHand.Net.Ports.BluetoothSerialPort
//
// Copyright (c) 2003-2008 In The Hand Ltd, All rights reserved.
// This source code is licensed under the In The Hand Community License - see License.txt
using System;
using System.Net;
using System.ComponentModel;
using System.Runtime.InteropServices;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;
#if NETCF
namespace InTheHand.Net.Ports
{
/// <summary>
/// Represents a virtual COM port.
/// </summary>
/// <remarks>Deprecated. Use <see cref="M:InTheHand.Net.Sockets.BluetoothDeviceInfo.SetServiceState(System.Guid,System.Boolean)"/>
/// to enable a virtual COM port.
/// <para>Supported on Windows CE Only.
/// </para>
/// </remarks>
public class BluetoothSerialPort : IDisposable
{
private const int IOCTL_BLUETOOTH_GET_RFCOMM_CHANNEL = 0x1b0060;
private const int IOCTL_BLUETOOTH_GET_PEER_DEVICE = 0x1b0064;
private string portPrefix;
private int portIndex;
private PORTEMUPortParams pep;
private IntPtr handle;
internal BluetoothSerialPort(string portPrefix, int portIndex)
{
pep = new PORTEMUPortParams();
pep.uiportflags = RFCOMM_PORT_FLAGS.REMOTE_DCB;
this.portPrefix = portPrefix;
this.portIndex = portIndex;
}
private void Register()
{
GC.KeepAlive(this);
handle = RegisterDevice(portPrefix, portIndex, "btd.dll", ref pep);
System.Diagnostics.Debug.Write("RegisterDevice: ");
System.Diagnostics.Debug.WriteLine(handle);
if(handle == IntPtr.Zero)
{
int error = Marshal.GetLastWin32Error();
System.Diagnostics.Debug.Write("GetLastWin32Error: ");
System.Diagnostics.Debug.WriteLine(error);
throw new Win32Exception(error, "Error creating virtual com port");
}
}
/// <summary>
/// Create a virtual server port to listen for incoming connections.
/// </summary>
/// <param name="portName">Port name e.g. "COM4"</param>
/// <param name="service">Bluetooth service to listen on.</param>
/// <returns></returns>
public static BluetoothSerialPort CreateServer(string portName, Guid service)
{
string portPrefix;
int portIndex;
SplitPortName(portName, out portPrefix, out portIndex);
BluetoothSerialPort bsp = new BluetoothSerialPort(portPrefix, portIndex);
bsp.pep.flocal = true;
bsp.pep.uuidService = service;
bsp.Register();
return bsp;
}
/// <summary>
/// Create a virtual server port to listen for incoming connections. Auto allocates a port from the COM0-9 range.
/// </summary>
/// <param name="service">Service GUID to listen on.</param>
/// <returns></returns>
public static BluetoothSerialPort CreateServer(Guid service)
{
BluetoothSerialPort bsp = new BluetoothSerialPort("COM", 9);
bsp.pep.flocal = true;
bsp.pep.uuidService = service;
for (int iPort = 8; iPort > -1; iPort--)
{
try
{
bsp.Register();
break;
}
catch
{
bsp.portIndex = iPort;
}
}
if (bsp.portIndex == 0)
{
throw new SystemException("Unable to create a Serial Port");
}
return bsp;
}
/// <summary>
/// Create a client port for connection to a remote device.
/// </summary>
/// <param name="portName">Port name e.g. "COM4"</param>
/// <param name="endPoint">Remote device to connect to</param>
/// <returns>A BluetoothSerialPort.</returns>
public static BluetoothSerialPort CreateClient(string portName, BluetoothEndPoint endPoint)
{
string portPrefix;
int portIndex;
SplitPortName(portName, out portPrefix, out portIndex);
BluetoothSerialPort bsp = new BluetoothSerialPort(portPrefix, portIndex);
bsp.pep.flocal = false;
bsp.pep.device = endPoint.Address.ToInt64();
bsp.pep.uuidService = endPoint.Service;
bsp.Register();
return bsp;
}
/// <summary>
/// Create a client port for connection to a remote device. Auto allocates a port from the COM0-9 range.
/// </summary>
/// <param name="endPoint">Remote device to connect to.</param>
/// <returns></returns>
public static BluetoothSerialPort CreateClient(BluetoothEndPoint endPoint)
{
BluetoothSerialPort bsp = new BluetoothSerialPort("COM", 9);
bsp.pep.flocal = false;
bsp.pep.device = endPoint.Address.ToInt64();
bsp.pep.uuidService = endPoint.Service;
for (int iPort = 8; iPort > -1; iPort--)
{
try
{
bsp.Register();
break;
}
catch
{
bsp.portIndex = iPort;
}
}
if (bsp.portIndex == 0)
{
throw new SystemException("Unable to create a Serial Port");
}
return bsp;
}
/// <summary>
/// Creates a BluetoothSerialPort instance from an existing open virtual serial port handle.
/// </summary>
/// <param name="handle">Handle value created previously by BluetoothSerialPort.</param>
/// <returns>BluetoothSerialPort wrapper around handle.</returns>
public static BluetoothSerialPort FromHandle(IntPtr handle)
{
BluetoothSerialPort bsp = new BluetoothSerialPort("COM", 0);
bsp.handle = handle;
return bsp;
}
/// <summary>
/// The full representation of the port name e.g. "COM5"
/// </summary>
public string PortName
{
get
{
return portPrefix + portIndex.ToString();
}
}
private static void SplitPortName(string portName, out string prefix, out int index)
{
if (portName.Length < 4)
{
throw new ArgumentException("Invalid Port Name");
}
prefix = portName.Substring(0, 3);
index = Int32.Parse(portName.Substring(3,1));
}
/// <summary>
/// The address of the remote device to which this port will connect (Client Ports only).
/// </summary>
public BluetoothAddress Address
{
get
{
return new BluetoothAddress(pep.device);
}
}
/// <summary>
/// The Bluetooth service to connect to.
/// </summary>
public Guid Service
{
get
{
return pep.uuidService;
}
}
#region Local
/// <summary>
/// Specifies whether the port is a local service or for outgoing connections.
/// </summary>
/// <value>TRUE for a server port that accepts connections, or to FALSE for a client port that is used to creating outgoing connections.</value>
public bool Local
{
get
{
return pep.flocal;
}
}
#endregion
#region Handle
/// <summary>
/// Native handle to virtual port.
/// </summary>
public IntPtr Handle
{
get
{
return this.handle;
}
}
#endregion
#region Close
/// <summary>
/// Closes the virtual serial port releasing all resources.
/// </summary>
public void Close()
{
GC.KeepAlive(this);
if(handle != IntPtr.Zero)
{
bool success = DeregisterDevice(handle);
if(success)
{
handle = IntPtr.Zero;
}
else
{
throw new SystemException("Error deregistering virtual COM port " + Marshal.GetLastWin32Error().ToString("X"));
}
}
}
#endregion
#region P/Invokes
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes,
int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr RegisterDevice(
string lpszType,
int dwIndex,
string lpszLib,
ref PORTEMUPortParams dwInfo);
[DllImport("coredll.dll", SetLastError=true)]
private static extern IntPtr RegisterDevice(
string lpszType,
int dwIndex,
string lpszLib,
byte[] dwInfo);
[DllImport("coredll.dll", SetLastError=true)]
private static extern bool DeregisterDevice(
IntPtr handle);
[DllImport("coredll.dll", SetLastError = true)]
private static extern bool DeviceIoControl(IntPtr hDevice, int dwIoControlCode, byte[] lpInBuffer, int nInBufferSize, byte[] lpOutBuffer, int nOutBufferSize, out int lpBytesReturned, int lpOverlapped);
#endregion
#region IDisposable Members
/// <summary>
///
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
try
{
Close();
}
catch { }
if(disposing)
{
portPrefix = null;
}
}
/// <summary>
///
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
///
/// </summary>
~BluetoothSerialPort()
{
Dispose(false);
}
#endregion
}
}
#endif
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the LabResultadoEncabezado class.
/// </summary>
[Serializable]
public partial class LabResultadoEncabezadoCollection : ActiveList<LabResultadoEncabezado, LabResultadoEncabezadoCollection>
{
public LabResultadoEncabezadoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>LabResultadoEncabezadoCollection</returns>
public LabResultadoEncabezadoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
LabResultadoEncabezado o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the LAB_ResultadoEncabezado table.
/// </summary>
[Serializable]
public partial class LabResultadoEncabezado : ActiveRecord<LabResultadoEncabezado>, IActiveRecord
{
#region .ctors and Default Settings
public LabResultadoEncabezado()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public LabResultadoEncabezado(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public LabResultadoEncabezado(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public LabResultadoEncabezado(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("LAB_ResultadoEncabezado", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdProtocolo = new TableSchema.TableColumn(schema);
colvarIdProtocolo.ColumnName = "idProtocolo";
colvarIdProtocolo.DataType = DbType.Int32;
colvarIdProtocolo.MaxLength = 0;
colvarIdProtocolo.AutoIncrement = false;
colvarIdProtocolo.IsNullable = false;
colvarIdProtocolo.IsPrimaryKey = true;
colvarIdProtocolo.IsForeignKey = false;
colvarIdProtocolo.IsReadOnly = false;
colvarIdProtocolo.DefaultSetting = @"";
colvarIdProtocolo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdProtocolo);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = true;
colvarIdEfector.IsForeignKey = false;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"";
colvarIdEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema);
colvarApellido.ColumnName = "apellido";
colvarApellido.DataType = DbType.String;
colvarApellido.MaxLength = 100;
colvarApellido.AutoIncrement = false;
colvarApellido.IsNullable = false;
colvarApellido.IsPrimaryKey = false;
colvarApellido.IsForeignKey = false;
colvarApellido.IsReadOnly = false;
colvarApellido.DefaultSetting = @"";
colvarApellido.ForeignKeyTableName = "";
schema.Columns.Add(colvarApellido);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema);
colvarEdad.ColumnName = "edad";
colvarEdad.DataType = DbType.Int32;
colvarEdad.MaxLength = 0;
colvarEdad.AutoIncrement = false;
colvarEdad.IsNullable = false;
colvarEdad.IsPrimaryKey = false;
colvarEdad.IsForeignKey = false;
colvarEdad.IsReadOnly = false;
colvarEdad.DefaultSetting = @"";
colvarEdad.ForeignKeyTableName = "";
schema.Columns.Add(colvarEdad);
TableSchema.TableColumn colvarUnidadEdad = new TableSchema.TableColumn(schema);
colvarUnidadEdad.ColumnName = "unidadEdad";
colvarUnidadEdad.DataType = DbType.AnsiString;
colvarUnidadEdad.MaxLength = 5;
colvarUnidadEdad.AutoIncrement = false;
colvarUnidadEdad.IsNullable = true;
colvarUnidadEdad.IsPrimaryKey = false;
colvarUnidadEdad.IsForeignKey = false;
colvarUnidadEdad.IsReadOnly = false;
colvarUnidadEdad.DefaultSetting = @"";
colvarUnidadEdad.ForeignKeyTableName = "";
schema.Columns.Add(colvarUnidadEdad);
TableSchema.TableColumn colvarFechaNacimiento = new TableSchema.TableColumn(schema);
colvarFechaNacimiento.ColumnName = "fechaNacimiento";
colvarFechaNacimiento.DataType = DbType.AnsiString;
colvarFechaNacimiento.MaxLength = 10;
colvarFechaNacimiento.AutoIncrement = false;
colvarFechaNacimiento.IsNullable = true;
colvarFechaNacimiento.IsPrimaryKey = false;
colvarFechaNacimiento.IsForeignKey = false;
colvarFechaNacimiento.IsReadOnly = false;
colvarFechaNacimiento.DefaultSetting = @"";
colvarFechaNacimiento.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaNacimiento);
TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema);
colvarSexo.ColumnName = "sexo";
colvarSexo.DataType = DbType.String;
colvarSexo.MaxLength = 1;
colvarSexo.AutoIncrement = false;
colvarSexo.IsNullable = false;
colvarSexo.IsPrimaryKey = false;
colvarSexo.IsForeignKey = false;
colvarSexo.IsReadOnly = false;
colvarSexo.DefaultSetting = @"";
colvarSexo.ForeignKeyTableName = "";
schema.Columns.Add(colvarSexo);
TableSchema.TableColumn colvarNumeroDocumento = new TableSchema.TableColumn(schema);
colvarNumeroDocumento.ColumnName = "numeroDocumento";
colvarNumeroDocumento.DataType = DbType.Int32;
colvarNumeroDocumento.MaxLength = 0;
colvarNumeroDocumento.AutoIncrement = false;
colvarNumeroDocumento.IsNullable = false;
colvarNumeroDocumento.IsPrimaryKey = false;
colvarNumeroDocumento.IsForeignKey = false;
colvarNumeroDocumento.IsReadOnly = false;
colvarNumeroDocumento.DefaultSetting = @"";
colvarNumeroDocumento.ForeignKeyTableName = "";
schema.Columns.Add(colvarNumeroDocumento);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.AnsiString;
colvarFecha.MaxLength = 10;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = true;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarFecha1 = new TableSchema.TableColumn(schema);
colvarFecha1.ColumnName = "fecha1";
colvarFecha1.DataType = DbType.DateTime;
colvarFecha1.MaxLength = 0;
colvarFecha1.AutoIncrement = false;
colvarFecha1.IsNullable = false;
colvarFecha1.IsPrimaryKey = false;
colvarFecha1.IsForeignKey = false;
colvarFecha1.IsReadOnly = false;
colvarFecha1.DefaultSetting = @"";
colvarFecha1.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha1);
TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema);
colvarDomicilio.ColumnName = "domicilio";
colvarDomicilio.DataType = DbType.String;
colvarDomicilio.MaxLength = 261;
colvarDomicilio.AutoIncrement = false;
colvarDomicilio.IsNullable = true;
colvarDomicilio.IsPrimaryKey = false;
colvarDomicilio.IsForeignKey = false;
colvarDomicilio.IsReadOnly = false;
colvarDomicilio.DefaultSetting = @"";
colvarDomicilio.ForeignKeyTableName = "";
schema.Columns.Add(colvarDomicilio);
TableSchema.TableColumn colvarHc = new TableSchema.TableColumn(schema);
colvarHc.ColumnName = "HC";
colvarHc.DataType = DbType.Int32;
colvarHc.MaxLength = 0;
colvarHc.AutoIncrement = false;
colvarHc.IsNullable = false;
colvarHc.IsPrimaryKey = false;
colvarHc.IsForeignKey = false;
colvarHc.IsReadOnly = false;
colvarHc.DefaultSetting = @"";
colvarHc.ForeignKeyTableName = "";
schema.Columns.Add(colvarHc);
TableSchema.TableColumn colvarPrioridad = new TableSchema.TableColumn(schema);
colvarPrioridad.ColumnName = "prioridad";
colvarPrioridad.DataType = DbType.String;
colvarPrioridad.MaxLength = 50;
colvarPrioridad.AutoIncrement = false;
colvarPrioridad.IsNullable = false;
colvarPrioridad.IsPrimaryKey = false;
colvarPrioridad.IsForeignKey = false;
colvarPrioridad.IsReadOnly = false;
colvarPrioridad.DefaultSetting = @"";
colvarPrioridad.ForeignKeyTableName = "";
schema.Columns.Add(colvarPrioridad);
TableSchema.TableColumn colvarOrigen = new TableSchema.TableColumn(schema);
colvarOrigen.ColumnName = "origen";
colvarOrigen.DataType = DbType.String;
colvarOrigen.MaxLength = 50;
colvarOrigen.AutoIncrement = false;
colvarOrigen.IsNullable = false;
colvarOrigen.IsPrimaryKey = false;
colvarOrigen.IsForeignKey = false;
colvarOrigen.IsReadOnly = false;
colvarOrigen.DefaultSetting = @"";
colvarOrigen.ForeignKeyTableName = "";
schema.Columns.Add(colvarOrigen);
TableSchema.TableColumn colvarNumero = new TableSchema.TableColumn(schema);
colvarNumero.ColumnName = "numero";
colvarNumero.DataType = DbType.AnsiString;
colvarNumero.MaxLength = 50;
colvarNumero.AutoIncrement = false;
colvarNumero.IsNullable = true;
colvarNumero.IsPrimaryKey = false;
colvarNumero.IsForeignKey = false;
colvarNumero.IsReadOnly = false;
colvarNumero.DefaultSetting = @"";
colvarNumero.ForeignKeyTableName = "";
schema.Columns.Add(colvarNumero);
TableSchema.TableColumn colvarHiv = new TableSchema.TableColumn(schema);
colvarHiv.ColumnName = "hiv";
colvarHiv.DataType = DbType.Boolean;
colvarHiv.MaxLength = 0;
colvarHiv.AutoIncrement = false;
colvarHiv.IsNullable = true;
colvarHiv.IsPrimaryKey = false;
colvarHiv.IsForeignKey = false;
colvarHiv.IsReadOnly = false;
colvarHiv.DefaultSetting = @"";
colvarHiv.ForeignKeyTableName = "";
schema.Columns.Add(colvarHiv);
TableSchema.TableColumn colvarSolicitante = new TableSchema.TableColumn(schema);
colvarSolicitante.ColumnName = "solicitante";
colvarSolicitante.DataType = DbType.String;
colvarSolicitante.MaxLength = 205;
colvarSolicitante.AutoIncrement = false;
colvarSolicitante.IsNullable = true;
colvarSolicitante.IsPrimaryKey = false;
colvarSolicitante.IsForeignKey = false;
colvarSolicitante.IsReadOnly = false;
colvarSolicitante.DefaultSetting = @"";
colvarSolicitante.ForeignKeyTableName = "";
schema.Columns.Add(colvarSolicitante);
TableSchema.TableColumn colvarSector = new TableSchema.TableColumn(schema);
colvarSector.ColumnName = "sector";
colvarSector.DataType = DbType.AnsiString;
colvarSector.MaxLength = 50;
colvarSector.AutoIncrement = false;
colvarSector.IsNullable = false;
colvarSector.IsPrimaryKey = false;
colvarSector.IsForeignKey = false;
colvarSector.IsReadOnly = false;
colvarSector.DefaultSetting = @"";
colvarSector.ForeignKeyTableName = "";
schema.Columns.Add(colvarSector);
TableSchema.TableColumn colvarSala = new TableSchema.TableColumn(schema);
colvarSala.ColumnName = "sala";
colvarSala.DataType = DbType.AnsiString;
colvarSala.MaxLength = 50;
colvarSala.AutoIncrement = false;
colvarSala.IsNullable = false;
colvarSala.IsPrimaryKey = false;
colvarSala.IsForeignKey = false;
colvarSala.IsReadOnly = false;
colvarSala.DefaultSetting = @"";
colvarSala.ForeignKeyTableName = "";
schema.Columns.Add(colvarSala);
TableSchema.TableColumn colvarCama = new TableSchema.TableColumn(schema);
colvarCama.ColumnName = "cama";
colvarCama.DataType = DbType.AnsiString;
colvarCama.MaxLength = 50;
colvarCama.AutoIncrement = false;
colvarCama.IsNullable = false;
colvarCama.IsPrimaryKey = false;
colvarCama.IsForeignKey = false;
colvarCama.IsReadOnly = false;
colvarCama.DefaultSetting = @"";
colvarCama.ForeignKeyTableName = "";
schema.Columns.Add(colvarCama);
TableSchema.TableColumn colvarEmbarazo = new TableSchema.TableColumn(schema);
colvarEmbarazo.ColumnName = "embarazo";
colvarEmbarazo.DataType = DbType.AnsiString;
colvarEmbarazo.MaxLength = 1;
colvarEmbarazo.AutoIncrement = false;
colvarEmbarazo.IsNullable = false;
colvarEmbarazo.IsPrimaryKey = false;
colvarEmbarazo.IsForeignKey = false;
colvarEmbarazo.IsReadOnly = false;
colvarEmbarazo.DefaultSetting = @"";
colvarEmbarazo.ForeignKeyTableName = "";
schema.Columns.Add(colvarEmbarazo);
TableSchema.TableColumn colvarEfectorSolicitante = new TableSchema.TableColumn(schema);
colvarEfectorSolicitante.ColumnName = "EfectorSolicitante";
colvarEfectorSolicitante.DataType = DbType.String;
colvarEfectorSolicitante.MaxLength = 100;
colvarEfectorSolicitante.AutoIncrement = false;
colvarEfectorSolicitante.IsNullable = false;
colvarEfectorSolicitante.IsPrimaryKey = false;
colvarEfectorSolicitante.IsForeignKey = false;
colvarEfectorSolicitante.IsReadOnly = false;
colvarEfectorSolicitante.DefaultSetting = @"";
colvarEfectorSolicitante.ForeignKeyTableName = "";
schema.Columns.Add(colvarEfectorSolicitante);
TableSchema.TableColumn colvarIdSolicitudScreening = new TableSchema.TableColumn(schema);
colvarIdSolicitudScreening.ColumnName = "idSolicitudScreening";
colvarIdSolicitudScreening.DataType = DbType.Int32;
colvarIdSolicitudScreening.MaxLength = 0;
colvarIdSolicitudScreening.AutoIncrement = false;
colvarIdSolicitudScreening.IsNullable = true;
colvarIdSolicitudScreening.IsPrimaryKey = false;
colvarIdSolicitudScreening.IsForeignKey = false;
colvarIdSolicitudScreening.IsReadOnly = false;
colvarIdSolicitudScreening.DefaultSetting = @"";
colvarIdSolicitudScreening.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdSolicitudScreening);
TableSchema.TableColumn colvarFechaRecibeScreening = new TableSchema.TableColumn(schema);
colvarFechaRecibeScreening.ColumnName = "fechaRecibeScreening";
colvarFechaRecibeScreening.DataType = DbType.DateTime;
colvarFechaRecibeScreening.MaxLength = 0;
colvarFechaRecibeScreening.AutoIncrement = false;
colvarFechaRecibeScreening.IsNullable = true;
colvarFechaRecibeScreening.IsPrimaryKey = false;
colvarFechaRecibeScreening.IsForeignKey = false;
colvarFechaRecibeScreening.IsReadOnly = false;
colvarFechaRecibeScreening.DefaultSetting = @"";
colvarFechaRecibeScreening.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaRecibeScreening);
TableSchema.TableColumn colvarObservacionesResultados = new TableSchema.TableColumn(schema);
colvarObservacionesResultados.ColumnName = "observacionesResultados";
colvarObservacionesResultados.DataType = DbType.String;
colvarObservacionesResultados.MaxLength = 4000;
colvarObservacionesResultados.AutoIncrement = false;
colvarObservacionesResultados.IsNullable = true;
colvarObservacionesResultados.IsPrimaryKey = false;
colvarObservacionesResultados.IsForeignKey = false;
colvarObservacionesResultados.IsReadOnly = false;
colvarObservacionesResultados.DefaultSetting = @"";
colvarObservacionesResultados.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservacionesResultados);
TableSchema.TableColumn colvarTipoMuestra = new TableSchema.TableColumn(schema);
colvarTipoMuestra.ColumnName = "tipoMuestra";
colvarTipoMuestra.DataType = DbType.String;
colvarTipoMuestra.MaxLength = 500;
colvarTipoMuestra.AutoIncrement = false;
colvarTipoMuestra.IsNullable = true;
colvarTipoMuestra.IsPrimaryKey = false;
colvarTipoMuestra.IsForeignKey = false;
colvarTipoMuestra.IsReadOnly = false;
colvarTipoMuestra.DefaultSetting = @"";
colvarTipoMuestra.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoMuestra);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("LAB_ResultadoEncabezado",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdProtocolo")]
[Bindable(true)]
public int IdProtocolo
{
get { return GetColumnValue<int>(Columns.IdProtocolo); }
set { SetColumnValue(Columns.IdProtocolo, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get { return GetColumnValue<int>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("Apellido")]
[Bindable(true)]
public string Apellido
{
get { return GetColumnValue<string>(Columns.Apellido); }
set { SetColumnValue(Columns.Apellido, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("Edad")]
[Bindable(true)]
public int Edad
{
get { return GetColumnValue<int>(Columns.Edad); }
set { SetColumnValue(Columns.Edad, value); }
}
[XmlAttribute("UnidadEdad")]
[Bindable(true)]
public string UnidadEdad
{
get { return GetColumnValue<string>(Columns.UnidadEdad); }
set { SetColumnValue(Columns.UnidadEdad, value); }
}
[XmlAttribute("FechaNacimiento")]
[Bindable(true)]
public string FechaNacimiento
{
get { return GetColumnValue<string>(Columns.FechaNacimiento); }
set { SetColumnValue(Columns.FechaNacimiento, value); }
}
[XmlAttribute("Sexo")]
[Bindable(true)]
public string Sexo
{
get { return GetColumnValue<string>(Columns.Sexo); }
set { SetColumnValue(Columns.Sexo, value); }
}
[XmlAttribute("NumeroDocumento")]
[Bindable(true)]
public int NumeroDocumento
{
get { return GetColumnValue<int>(Columns.NumeroDocumento); }
set { SetColumnValue(Columns.NumeroDocumento, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public string Fecha
{
get { return GetColumnValue<string>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("Fecha1")]
[Bindable(true)]
public DateTime Fecha1
{
get { return GetColumnValue<DateTime>(Columns.Fecha1); }
set { SetColumnValue(Columns.Fecha1, value); }
}
[XmlAttribute("Domicilio")]
[Bindable(true)]
public string Domicilio
{
get { return GetColumnValue<string>(Columns.Domicilio); }
set { SetColumnValue(Columns.Domicilio, value); }
}
[XmlAttribute("Hc")]
[Bindable(true)]
public int Hc
{
get { return GetColumnValue<int>(Columns.Hc); }
set { SetColumnValue(Columns.Hc, value); }
}
[XmlAttribute("Prioridad")]
[Bindable(true)]
public string Prioridad
{
get { return GetColumnValue<string>(Columns.Prioridad); }
set { SetColumnValue(Columns.Prioridad, value); }
}
[XmlAttribute("Origen")]
[Bindable(true)]
public string Origen
{
get { return GetColumnValue<string>(Columns.Origen); }
set { SetColumnValue(Columns.Origen, value); }
}
[XmlAttribute("Numero")]
[Bindable(true)]
public string Numero
{
get { return GetColumnValue<string>(Columns.Numero); }
set { SetColumnValue(Columns.Numero, value); }
}
[XmlAttribute("Hiv")]
[Bindable(true)]
public bool? Hiv
{
get { return GetColumnValue<bool?>(Columns.Hiv); }
set { SetColumnValue(Columns.Hiv, value); }
}
[XmlAttribute("Solicitante")]
[Bindable(true)]
public string Solicitante
{
get { return GetColumnValue<string>(Columns.Solicitante); }
set { SetColumnValue(Columns.Solicitante, value); }
}
[XmlAttribute("Sector")]
[Bindable(true)]
public string Sector
{
get { return GetColumnValue<string>(Columns.Sector); }
set { SetColumnValue(Columns.Sector, value); }
}
[XmlAttribute("Sala")]
[Bindable(true)]
public string Sala
{
get { return GetColumnValue<string>(Columns.Sala); }
set { SetColumnValue(Columns.Sala, value); }
}
[XmlAttribute("Cama")]
[Bindable(true)]
public string Cama
{
get { return GetColumnValue<string>(Columns.Cama); }
set { SetColumnValue(Columns.Cama, value); }
}
[XmlAttribute("Embarazo")]
[Bindable(true)]
public string Embarazo
{
get { return GetColumnValue<string>(Columns.Embarazo); }
set { SetColumnValue(Columns.Embarazo, value); }
}
[XmlAttribute("EfectorSolicitante")]
[Bindable(true)]
public string EfectorSolicitante
{
get { return GetColumnValue<string>(Columns.EfectorSolicitante); }
set { SetColumnValue(Columns.EfectorSolicitante, value); }
}
[XmlAttribute("IdSolicitudScreening")]
[Bindable(true)]
public int? IdSolicitudScreening
{
get { return GetColumnValue<int?>(Columns.IdSolicitudScreening); }
set { SetColumnValue(Columns.IdSolicitudScreening, value); }
}
[XmlAttribute("FechaRecibeScreening")]
[Bindable(true)]
public DateTime? FechaRecibeScreening
{
get { return GetColumnValue<DateTime?>(Columns.FechaRecibeScreening); }
set { SetColumnValue(Columns.FechaRecibeScreening, value); }
}
[XmlAttribute("ObservacionesResultados")]
[Bindable(true)]
public string ObservacionesResultados
{
get { return GetColumnValue<string>(Columns.ObservacionesResultados); }
set { SetColumnValue(Columns.ObservacionesResultados, value); }
}
[XmlAttribute("TipoMuestra")]
[Bindable(true)]
public string TipoMuestra
{
get { return GetColumnValue<string>(Columns.TipoMuestra); }
set { SetColumnValue(Columns.TipoMuestra, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.FacOrdenLaboratorioCollection colFacOrdenLaboratorioRecords;
public DalSic.FacOrdenLaboratorioCollection FacOrdenLaboratorioRecords
{
get
{
if(colFacOrdenLaboratorioRecords == null)
{
colFacOrdenLaboratorioRecords = new DalSic.FacOrdenLaboratorioCollection().Where(FacOrdenLaboratorio.Columns.IdEfector, IdProtocolo).Load();
colFacOrdenLaboratorioRecords.ListChanged += new ListChangedEventHandler(colFacOrdenLaboratorioRecords_ListChanged);
}
return colFacOrdenLaboratorioRecords;
}
set
{
colFacOrdenLaboratorioRecords = value;
colFacOrdenLaboratorioRecords.ListChanged += new ListChangedEventHandler(colFacOrdenLaboratorioRecords_ListChanged);
}
}
void colFacOrdenLaboratorioRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colFacOrdenLaboratorioRecords[e.NewIndex].IdEfector = IdProtocolo;
}
}
private DalSic.FacOrdenLaboratorioCollection colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado;
public DalSic.FacOrdenLaboratorioCollection FacOrdenLaboratorioRecordsFromLabResultadoEncabezado
{
get
{
if(colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado == null)
{
colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado = new DalSic.FacOrdenLaboratorioCollection().Where(FacOrdenLaboratorio.Columns.IdProtocolo, IdProtocolo).Load();
colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado.ListChanged += new ListChangedEventHandler(colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado_ListChanged);
}
return colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado;
}
set
{
colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado = value;
colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado.ListChanged += new ListChangedEventHandler(colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado_ListChanged);
}
}
void colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado[e.NewIndex].IdProtocolo = IdProtocolo;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdProtocolo,int varIdEfector,string varApellido,string varNombre,int varEdad,string varUnidadEdad,string varFechaNacimiento,string varSexo,int varNumeroDocumento,string varFecha,DateTime varFecha1,string varDomicilio,int varHc,string varPrioridad,string varOrigen,string varNumero,bool? varHiv,string varSolicitante,string varSector,string varSala,string varCama,string varEmbarazo,string varEfectorSolicitante,int? varIdSolicitudScreening,DateTime? varFechaRecibeScreening,string varObservacionesResultados,string varTipoMuestra)
{
LabResultadoEncabezado item = new LabResultadoEncabezado();
item.IdProtocolo = varIdProtocolo;
item.IdEfector = varIdEfector;
item.Apellido = varApellido;
item.Nombre = varNombre;
item.Edad = varEdad;
item.UnidadEdad = varUnidadEdad;
item.FechaNacimiento = varFechaNacimiento;
item.Sexo = varSexo;
item.NumeroDocumento = varNumeroDocumento;
item.Fecha = varFecha;
item.Fecha1 = varFecha1;
item.Domicilio = varDomicilio;
item.Hc = varHc;
item.Prioridad = varPrioridad;
item.Origen = varOrigen;
item.Numero = varNumero;
item.Hiv = varHiv;
item.Solicitante = varSolicitante;
item.Sector = varSector;
item.Sala = varSala;
item.Cama = varCama;
item.Embarazo = varEmbarazo;
item.EfectorSolicitante = varEfectorSolicitante;
item.IdSolicitudScreening = varIdSolicitudScreening;
item.FechaRecibeScreening = varFechaRecibeScreening;
item.ObservacionesResultados = varObservacionesResultados;
item.TipoMuestra = varTipoMuestra;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdProtocolo,int varIdEfector,string varApellido,string varNombre,int varEdad,string varUnidadEdad,string varFechaNacimiento,string varSexo,int varNumeroDocumento,string varFecha,DateTime varFecha1,string varDomicilio,int varHc,string varPrioridad,string varOrigen,string varNumero,bool? varHiv,string varSolicitante,string varSector,string varSala,string varCama,string varEmbarazo,string varEfectorSolicitante,int? varIdSolicitudScreening,DateTime? varFechaRecibeScreening,string varObservacionesResultados,string varTipoMuestra)
{
LabResultadoEncabezado item = new LabResultadoEncabezado();
item.IdProtocolo = varIdProtocolo;
item.IdEfector = varIdEfector;
item.Apellido = varApellido;
item.Nombre = varNombre;
item.Edad = varEdad;
item.UnidadEdad = varUnidadEdad;
item.FechaNacimiento = varFechaNacimiento;
item.Sexo = varSexo;
item.NumeroDocumento = varNumeroDocumento;
item.Fecha = varFecha;
item.Fecha1 = varFecha1;
item.Domicilio = varDomicilio;
item.Hc = varHc;
item.Prioridad = varPrioridad;
item.Origen = varOrigen;
item.Numero = varNumero;
item.Hiv = varHiv;
item.Solicitante = varSolicitante;
item.Sector = varSector;
item.Sala = varSala;
item.Cama = varCama;
item.Embarazo = varEmbarazo;
item.EfectorSolicitante = varEfectorSolicitante;
item.IdSolicitudScreening = varIdSolicitudScreening;
item.FechaRecibeScreening = varFechaRecibeScreening;
item.ObservacionesResultados = varObservacionesResultados;
item.TipoMuestra = varTipoMuestra;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdProtocoloColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn ApellidoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn EdadColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn UnidadEdadColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn FechaNacimientoColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn SexoColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn NumeroDocumentoColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn Fecha1Column
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn DomicilioColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn HcColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn PrioridadColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn OrigenColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn NumeroColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn HivColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn SolicitanteColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn SectorColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn SalaColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn CamaColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn EmbarazoColumn
{
get { return Schema.Columns[21]; }
}
public static TableSchema.TableColumn EfectorSolicitanteColumn
{
get { return Schema.Columns[22]; }
}
public static TableSchema.TableColumn IdSolicitudScreeningColumn
{
get { return Schema.Columns[23]; }
}
public static TableSchema.TableColumn FechaRecibeScreeningColumn
{
get { return Schema.Columns[24]; }
}
public static TableSchema.TableColumn ObservacionesResultadosColumn
{
get { return Schema.Columns[25]; }
}
public static TableSchema.TableColumn TipoMuestraColumn
{
get { return Schema.Columns[26]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdProtocolo = @"idProtocolo";
public static string IdEfector = @"idEfector";
public static string Apellido = @"apellido";
public static string Nombre = @"nombre";
public static string Edad = @"edad";
public static string UnidadEdad = @"unidadEdad";
public static string FechaNacimiento = @"fechaNacimiento";
public static string Sexo = @"sexo";
public static string NumeroDocumento = @"numeroDocumento";
public static string Fecha = @"fecha";
public static string Fecha1 = @"fecha1";
public static string Domicilio = @"domicilio";
public static string Hc = @"HC";
public static string Prioridad = @"prioridad";
public static string Origen = @"origen";
public static string Numero = @"numero";
public static string Hiv = @"hiv";
public static string Solicitante = @"solicitante";
public static string Sector = @"sector";
public static string Sala = @"sala";
public static string Cama = @"cama";
public static string Embarazo = @"embarazo";
public static string EfectorSolicitante = @"EfectorSolicitante";
public static string IdSolicitudScreening = @"idSolicitudScreening";
public static string FechaRecibeScreening = @"fechaRecibeScreening";
public static string ObservacionesResultados = @"observacionesResultados";
public static string TipoMuestra = @"tipoMuestra";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colFacOrdenLaboratorioRecords != null)
{
foreach (DalSic.FacOrdenLaboratorio item in colFacOrdenLaboratorioRecords)
{
if (item.IdEfector != IdProtocolo)
{
item.IdEfector = IdProtocolo;
}
}
}
if (colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado != null)
{
foreach (DalSic.FacOrdenLaboratorio item in colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado)
{
if (item.IdProtocolo != IdProtocolo)
{
item.IdProtocolo = IdProtocolo;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colFacOrdenLaboratorioRecords != null)
{
colFacOrdenLaboratorioRecords.SaveAll();
}
if (colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado != null)
{
colFacOrdenLaboratorioRecordsFromLabResultadoEncabezado.SaveAll();
}
}
#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.Tracing;
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue https://github.com/dotnet/corefx/issues/4864
using Microsoft.Diagnostics.Tracing.Session;
#endif
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BasicEventSourceTests
{
public class TestEventCounter
{
private sealed class MyEventSource : EventSource
{
private EventCounter _requestCounter;
private EventCounter _errorCounter;
public MyEventSource()
{
_requestCounter = new EventCounter("Request", this);
_errorCounter = new EventCounter("Error", this);
}
public void Request(float elapsed)
{
_requestCounter.WriteMetric(elapsed);
}
public void Error()
{
_errorCounter.WriteMetric(1);
}
}
[Fact]
public void Test_Write_Metric_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_Write_Metric(listener);
}
}
#if USE_ETW
[Fact]
public void Test_Write_Metric_ETW()
{
using (var listener = new EtwListener())
{
Test_Write_Metric(listener);
}
}
#endif
private void Test_Write_Metric(Listener listener)
{
Console.WriteLine("Version of Runtime {0}", Environment.Version);
Console.WriteLine("Version of OS {0}", Environment.OSVersion);
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var logger = new MyEventSource())
{
var tests = new List<SubTest>();
/*************************************************************************/
tests.Add(new SubTest("EventCounter: Log 1 event, explicit poll at end",
delegate ()
{
listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that.
logger.Request(5);
listener.EnableTimer(logger, 0);
},
delegate (List<Event> evts)
{
// There will be two events (request and error) for time 0 and 2 more at 1 second and 2 more when we shut it off.
Assert.Equal(4, evts.Count);
ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[2], "Request", 1, 5, 0, 5, 5);
ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
}));
/*************************************************************************/
tests.Add(new SubTest("EventCounter: Log 2 events, explicit poll at end",
delegate ()
{
listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that.
logger.Request(5);
logger.Request(10);
listener.EnableTimer(logger, 0); // poll
},
delegate (List<Event> evts)
{
Assert.Equal(4, evts.Count);
ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10);
ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
}));
/*************************************************************************/
tests.Add(new SubTest("EventCounter: Log 3 events in two polling periods (explicit polling)",
delegate ()
{
listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */
logger.Request(5);
logger.Request(10);
logger.Error();
listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */
logger.Request(8);
logger.Error();
logger.Error();
listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */
},
delegate (List<Event> evts)
{
Assert.Equal(6, evts.Count);
ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10);
ValidateSingleEventCounter(evts[3], "Error", 1, 1, 0, 1, 1);
ValidateSingleEventCounter(evts[4], "Request", 1, 8, 0, 8, 8);
ValidateSingleEventCounter(evts[5], "Error", 2, 1, 0, 1, 1);
}));
/*************************************************************************/
tests.Add(new SubTest("EventCounter: Log multiple events in multiple periods",
delegate ()
{
listener.EnableTimer(logger, .1); /* Poll every .1 s */
// logs at 0 seconds because of EnableTimer command
Sleep(100);
logger.Request(1);
Sleep(100);
logger.Request(2);
logger.Error();
Sleep(100);
logger.Request(4);
Sleep(100);
logger.Error();
logger.Request(8);
Sleep(100);
logger.Request(16);
Sleep(200);
listener.EnableTimer(logger, 0);
},
delegate (List<Event> evts)
{
int requestCount = 0;
float requestSum = 0;
float requestMin = float.MaxValue;
float requestMax = float.MinValue;
int errorCount = 0;
float errorSum = 0;
float errorMin = float.MaxValue;
float errorMax = float.MinValue;
float timeSum = 0;
for (int j = 0; j < evts.Count; j += 2)
{
var requestPayload = ValidateEventHeaderAndGetPayload(evts[j]);
Assert.Equal("Request", requestPayload["Name"]);
var count = (int)requestPayload["Count"];
requestCount += count;
if (count > 0)
requestSum += (float)requestPayload["Mean"] * count;
requestMin = Math.Min(requestMin, (float)requestPayload["Min"]);
requestMax = Math.Max(requestMax, (float)requestPayload["Max"]);
float requestIntevalSec = (float)requestPayload["IntervalSec"];
var errorPayload = ValidateEventHeaderAndGetPayload(evts[j + 1]);
Assert.Equal("Error", errorPayload["Name"]);
count = (int)errorPayload["Count"];
errorCount += count;
if (count > 0)
errorSum += (float)errorPayload["Mean"] * count;
errorMin = Math.Min(errorMin, (float)errorPayload["Min"]);
errorMax = Math.Max(errorMax, (float)errorPayload["Max"]);
float errorIntevalSec = (float)requestPayload["IntervalSec"];
Assert.Equal(requestIntevalSec, errorIntevalSec);
timeSum += requestIntevalSec;
}
Assert.Equal(requestCount, 5);
Assert.Equal(requestSum, 31);
Assert.Equal(requestMin, 1);
Assert.Equal(requestMax, 16);
Assert.Equal(errorCount, 2);
Assert.Equal(errorSum, 2);
Assert.Equal(errorMin, 1);
Assert.Equal(errorMax, 1);
Assert.True(.4 < timeSum, $"FAILURE: .4 < {timeSum}"); // We should have at least 400 msec
Assert.True(timeSum < 2, $"FAILURE: {timeSum} < 2"); // But well under 2 sec.
// Do all the things that depend on the count of events last so we know everything else is sane
Assert.True(4 <= evts.Count, "We expect two metrices at the begining trigger and two at the end trigger. evts.Count = " + evts.Count);
Assert.True(evts.Count % 2 == 0, "We expect two metrics for every trigger. evts.Count = " + evts.Count);
ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
// We expect the timer to have gone off at least twice, plus the explicit poll at the begining and end.
// Each one fires two events (one for requests, one for errors). so that is (2 + 2)*2 = 8
// We expect about 7 timer requests, but we don't get picky about the exact count
// Putting in a generous buffer, we double7 to say we don't expect more than 14 timer fires
// so that is (2 + 14) * 2 = 32
Assert.True(8 <= evts.Count, $"FAILURE: 8 <= {evts.Count}");
Assert.True(evts.Count <= 32, $"FAILURE: {evts.Count} <= 32");
}));
/*************************************************************************/
#if FEATURE_EVENTCOUNTER_DISPOSE
tests.Add(new SubTest("EventCounter: Dispose()",
delegate ()
{
// Creating and destroying
var myCounter = new EventCounter("counter for a transient object", logger);
myCounter.WriteMetric(10);
listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */
myCounter.Dispose();
listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */
},
delegate (List<Event> evts)
{
// The static counters (Request and Error), should not log any counts and stay at zero.
// The new counter will exist for the first poll but will not exist for the second.
Assert.Equal(5, evts.Count);
ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[2], "counter for a transient object", 1, 10, 0, 10, 10);
ValidateSingleEventCounter(evts[3], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
ValidateSingleEventCounter(evts[4], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity);
}));
#endif
/*************************************************************************/
EventTestHarness.RunTests(tests, listener, logger);
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
// Thread.Sleep has proven unreliable, sometime sleeping much shorter than it should.
// This makes sure it at least sleeps 'msec' at a miniumum.
private static void Sleep(int minMSec)
{
var startTime = DateTime.UtcNow;
for(;;)
{
DateTime endTime = DateTime.UtcNow;
double delta = (endTime - startTime).TotalMilliseconds;
if (delta >= minMSec)
{
Console.WriteLine("Sleep asked to wait {0} msec, actually waited {1:n2} msec Start: {2:mm:ss.fff} End: {3:mm:ss.fff} ", minMSec, delta, startTime, endTime);
break;
}
Thread.Sleep(1);
}
}
private static void ValidateSingleEventCounter(Event evt, string counterName, int count, float mean, float standardDeviation, float min, float max)
{
ValidateEventCounter(counterName, count, mean, standardDeviation, min, max, ValidateEventHeaderAndGetPayload(evt));
}
private static IDictionary<string, object> ValidateEventHeaderAndGetPayload(Event evt)
{
Assert.Equal("EventCounters", evt.EventName);
Assert.Equal(1, evt.PayloadCount);
Assert.NotNull(evt.PayloadNames);
Assert.Equal(1, evt.PayloadNames.Count);
Assert.Equal("Payload", evt.PayloadNames[0]);
var ret = (IDictionary < string, object > ) evt.PayloadValue(0, "Payload");
Assert.NotNull(ret);
return ret;
}
private static void ValidateEventCounter(string counterName, int count, float mean, float standardDeviation, float min, float max, IDictionary<string, object> payloadContent)
{
Assert.Equal(counterName, (string)payloadContent["Name"]);
Assert.Equal(count, (int)payloadContent["Count"]);
if (count != 0)
{
Assert.Equal(mean, (float)payloadContent["Mean"]);
Assert.Equal(standardDeviation, (float)payloadContent["StandardDeviation"]);
}
Assert.Equal(min, (float)payloadContent["Min"]);
Assert.Equal(max, (float)payloadContent["Max"]);
}
}
}
| |
#region Using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Diagnostics;
using TribalWars.Maps.Drawing.Displays;
using TribalWars.Maps.Drawing.Drawers;
using TribalWars.Maps.Drawing.Helpers;
using TribalWars.Maps.Manipulators;
using TribalWars.Maps.Markers;
using TribalWars.Villages;
using TribalWars.Worlds;
#endregion
namespace TribalWars.Maps.Drawing
{
/// <summary>
/// Manages the painting of a TW map
/// </summary>
public sealed class Display : IDisposable
{
#region Fields
private readonly Map _map;
private readonly MarkerManager _markers;
private Rectangle _visibleGameRectangle;
private Rectangle _canvasRectangle;
private Bitmap _background;
private readonly DrawerFactoryBase _drawerFactoryStrategy;
private readonly DisplaySettings _settings;
#endregion
#region Properties
public DisplaySettings Settings
{
get { return _settings; }
}
public DisplayTypes Type
{
get { return _drawerFactoryStrategy.Type; }
}
public VillageDimensions Dimensions
{
get { return _drawerFactoryStrategy.Dimensions; }
}
public bool AllowText
{
get { return _drawerFactoryStrategy.AllowText; }
}
public ZoomInfo Zoom
{
get { return _drawerFactoryStrategy.Zoom; }
}
#endregion
#region Constructors
public Display(DisplaySettings settings, bool isMiniMap, Map map, ref Location location)
: this(settings, map)
{
// Validate zoom or we have a potential divide by zero etc
if (isMiniMap)
{
ZoomInfo zoom = DrawerFactoryBase.CreateMiniMapZoom(location.Zoom);
location = zoom.Validate(location);
_drawerFactoryStrategy = DrawerFactoryBase.CreateMiniMap(location.Zoom);
}
else
{
ZoomInfo zoom = DrawerFactoryBase.CreateZoom(location.Display, location.Zoom);
location = ValidateZoom(zoom, location);
_drawerFactoryStrategy = DrawerFactoryBase.Create(location.Display, location.Zoom, settings.Scenery);
}
// TODO: make this lazy. Setting here = crash
// Is fixed by calling UpdateLocation after Map.Location is set
//_visibleRectangle = GetGameRectangle();
}
/// <summary>
/// Returns the <see cref="Location"/> parameter or an updated
/// one if the zoom level is invalid for the <see cref="Display"/>
/// </summary>
private Location ValidateZoom(ZoomInfo zoom, Location location)
{
if (location.Zoom < zoom.Minimum)
{
return new Location(location.Display, location.Point, zoom.Minimum);
}
if (location.Zoom > zoom.Maximum)
{
// Swap to Shape/Icon
// If this changes also check the hack in Map.GetSpan
if (location.Display == DisplayTypes.Icon)
{
return new Location(DisplayTypes.Shape, location.Point, IconDrawerFactory.MinVillageSide);
}
if (location.Display == DisplayTypes.Shape)
{
return new Location(DisplayTypes.Icon, location.Point, IconDrawerFactory.AutoSwitchFromShapeIndex);
}
return new Location(location.Display, location.Point, zoom.Maximum);
}
return location;
}
private Display(DisplaySettings settings, Map map)
{
_settings = settings;
_map = map;
_markers = map.MarkerManager;
}
#endregion
#region Reset Cache
public void UpdateLocation(Size canvasSize, Location oldLocation, Location newLocation)
{
//if (oldLocation == null || oldLocation.Display != newLocation.Display || oldLocation.Zoom != newLocation.Zoom
// || _background == null || _visibleGameRectangle.IsEmpty || canvasSize != _canvasRectangle.Size)
//{
ResetCache();
_visibleGameRectangle = GetGameRectangle();
//if (_background != null && canvasSize != _background.Size)
//{
// // need fix for when resizing?
//}
//}
//else
//{
// var newRec = GetGameRectangle();
// var calcer = new RegionsToDrawCalculator(_visibleGameRectangle, newRec);
// if (!calcer.HasIntersection)
// {
// ResetCache();
// }
// else
// {
// // we zaten hier:
// // new approach -> create a screenshot of what it should be and of what it is....
// // will be easier to see what exactly is going on with this shit :)
// Rectangle backgroundMove;
// var gameRecsToDraw = calcer.GetNonOverlappingGameRectangles(out backgroundMove);
// backgroundMove.X *= Dimensions.SizeWithSpacing.Width * -1;
// using (var g = Graphics.FromImage(_background))
// {
// // B UG: this scrolls 2x too fast or something?
// g.DrawImageUnscaled(_background, backgroundMove);
// //using (var backgroundBrush = new SolidBrush(Settings.BackgroundColor))
// //{
// // g.FillRectangle(backgroundBrush, _canvasRectangle);
// //}
// foreach (Rectangle gameRecToDraw in gameRecsToDraw)
// {
// //var mapRecToDraw = GetMapRectangle(gameRecToDraw);
// //mapRecToDraw.X = 0;
// //mapRecToDraw.Y = 0;
// //Bitmap drawed = PaintBackground(mapRecToDraw, gameRecToDraw);
// var partialCanvas = new Rectangle(0, 0, gameRecToDraw.Width * Dimensions.SizeWithSpacing.Width, gameRecToDraw.Height * Dimensions.SizeWithSpacing.Height);
// var partialGameRect = gameRecToDraw;
// Offset(ref partialCanvas, ref partialGameRect);
// Bitmap drawed = PaintBackground(partialCanvas, partialGameRect);
// // B UG: this draws the initial stuff, not the new
// //g.DrawImageUnscaled(drawed, new Point(0, 0));
// g.DrawImageUnscaled(drawed, new Point(canvasSize.Width - drawed.Width, 0));
// using (var p = new Pen(Color.Black))
// g.DrawRectangle(p, canvasSize.Width - drawed.Width, 0, canvasSize.Width, canvasSize.Height);
// }
// }
// }
// // _background = newBackground;
// _visibleGameRectangle = GetGameRectangle();
//}
}
/// <summary>
/// Deletes the entire cached image
/// </summary>
public void ResetCache()
{
_background = null;
}
#endregion
#region Painting
private void PaintCachedBackground(Graphics g)
{
// Also draw villages that are only partially visible at left/top
Point mapOffset = GetMapLocation(_visibleGameRectangle.Location);
g.DrawImageUnscaled(_background, mapOffset.X, mapOffset.Y);
//g.DrawImageUnscaled(_background, 0, 0);
}
private Bitmap PaintBackground(Rectangle canvasRectangle, Rectangle gameRectangle)
{
var canvas = new Bitmap(canvasRectangle.Width, canvasRectangle.Height);
using (var g = Graphics.FromImage(canvas))
{
using (var backgroundBrush = new SolidBrush(Settings.BackgroundColor))
{
g.FillRectangle(backgroundBrush, canvasRectangle);
}
var calcVillagesToDisplay = new DisplayVillageCalculator(Dimensions, gameRectangle, canvasRectangle);
foreach (var village in calcVillagesToDisplay.GetVillages())
{
Paint(g, village.GameLocation, new Rectangle(village.MapLocation, Dimensions.Size));
}
var continentDrawer = new ContinentLinesPainter(g, Settings, Dimensions, gameRectangle, canvasRectangle);
continentDrawer.DrawContinentLines();
}
return canvas;
}
/// <summary>
/// To take the _mapOffset into account
/// </summary>
private void Offset(ref Rectangle canvasRectangle, ref Rectangle gameRectangle)
{
canvasRectangle.Width += Dimensions.SizeWithSpacing.Width;
canvasRectangle.Height += Dimensions.SizeWithSpacing.Height;
gameRectangle.Width += 1;
gameRectangle.Height += 1;
}
/// <summary>
/// Paints the canvas
/// </summary>
public void Paint(Graphics g2, Rectangle canvasRectangle)
{
if (_background == null)
{
//Debug.WriteLine("passed for Paint " + fullMap.ToString());
//var timing = Stopwatch.StartNew();
var largerThanCanvas = canvasRectangle;
var largerGameRectangle = GetGameRectangle();
Offset(ref largerThanCanvas, ref largerGameRectangle);
_background = PaintBackground(largerThanCanvas, largerGameRectangle);
_visibleGameRectangle = GetGameRectangle();
_canvasRectangle = canvasRectangle;
//timing.Stop();
//Debug.WriteLine("Painting NEW:{0} in {1}", _map.Location, timing.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture));
}
PaintCachedBackground(g2);
}
/// <summary>
/// Draws a village on the map
/// </summary>
/// <param name="g">The graphics object</param>
/// <param name="game">The game location of the village</param>
/// <param name="mapVillage">Where and how big to draw the village</param>
private void Paint(Graphics g, Point game, Rectangle mapVillage)
{
if (!(game.X >= 0 && game.X < 1000 && game.Y >= 0 && game.Y < 1000))
return;
Village village;
DrawerBase finalCache = null;
if (World.Default.Villages.TryGetValue(game, out village))
{
Marker marker = _markers.GetMarker(Settings, village);
if (marker != null)
{
// Paint village icon/shape
BackgroundDrawerData mainData = World.Default.Views.GetBackgroundDrawerData(village, marker);
if (mainData != null)
{
finalCache = _drawerFactoryStrategy.CreateVillageDrawer(village.Bonus, mainData, marker);
if (finalCache != null)
{
finalCache.PaintVillage(g, mapVillage);
if (_drawerFactoryStrategy.SupportDecorators && village.Type != VillageType.None)
{
// Paint extra village decorators
foreach (DrawerBase decorator in World.Default.Views.GetDecoratorDrawers(_drawerFactoryStrategy, village, mainData))
{
decorator.PaintVillage(g, mapVillage);
}
}
}
}
}
}
if (finalCache == null)
{
PaintNonVillage(g, game, mapVillage);
}
}
/// <summary>
/// Paint grass, mountains, ...
/// </summary>
private void PaintNonVillage(Graphics g, Point game, Rectangle mapVillage)
{
DrawerBase finalCache = _drawerFactoryStrategy.CreateNonVillageDrawer(game, mapVillage);
if (finalCache != null)
{
finalCache.PaintVillage(g, mapVillage);
}
}
#endregion
#region IsVisible
/// <summary>
/// Gets a value indicating whether at least one village is currently visible
/// </summary>
public bool IsVisible(IEnumerable<Village> villages)
{
return villages.Any(village => _visibleGameRectangle.Contains(village.Location));
}
#endregion
#region Game from/to Map Converters
/// <summary>
/// Gets the minimum zoom level that can display villages as big as the parameter.
/// But only change zoom when villages don't fit with current zoom.
/// </summary>
/// <param name="maxVillageSize">Get the zoom for villages this big</param>
/// <param name="tryStayInCurrentZoom">True: Try to respect the current zoom level and only change zoom level when really required</param>
/// <param name="couldSatisfy">HACK to get an IconDisplay to switch to ShapeDisplay with Map.GetSpan</param>
public int GetMinimumZoomLevel(Size maxVillageSize, bool tryStayInCurrentZoom, out bool couldSatisfy)
{
return _drawerFactoryStrategy.GetMinimumZoomLevel(maxVillageSize, tryStayInCurrentZoom, out couldSatisfy);
}
/// <summary>
/// Converts a game location to the map location
/// </summary>
/// <remarks>Assumes the location needs to be converted for the main map</remarks>
public Point GetMapLocation(Point loc)
{
// Get location from game and convert it to location on the map
var villageSize = _drawerFactoryStrategy.Dimensions.SizeWithSpacing;
int off = (loc.X - _map.Location.X) * villageSize.Width;
loc.X = off + _map.CanvasSize.Width / 2;
off = (loc.Y - _map.Location.Y) * villageSize.Height;
loc.Y = off + (_map.CanvasSize.Height / 2);
return loc;
}
/// <summary>
///
/// </summary>
public Rectangle GetMapRectangle(Rectangle gameRectangle)
{
Point leftTop = GetMapLocation(gameRectangle.Location);
Point rightBottom = GetMapLocation(new Point(gameRectangle.Right, gameRectangle.Bottom));
return new Rectangle(leftTop.X, leftTop.Y, rightBottom.X - leftTop.X, rightBottom.Y - leftTop.Y);
}
/// <summary>
/// Converts a map location to the game location
/// </summary>
/// <remarks>Assumes the location needs to be converted for the main map</remarks>
public Point GetGameLocation(Point loc)
{
// Get location from map and convert it to game location
var villageSize = _drawerFactoryStrategy.Dimensions.SizeWithSpacing;
int newx = (loc.X + (_map.Location.X * villageSize.Width) - (_map.CanvasSize.Width / 2)) / villageSize.Width;
int newy = (loc.Y + (_map.Location.Y * villageSize.Height) - (_map.CanvasSize.Height / 2)) / villageSize.Height;
return new Point(newx, newy);
}
/// <summary>
/// Converts map to game location and return the village
/// </summary>
public Village GetGameVillage(Point map)
{
Point game = GetGameLocation(map);
if (World.Default.Villages.ContainsKey(game)) return World.Default.Villages[game];
return null;
}
/// <summary>
/// Converts the UserControl size to the game rectangle it represents
/// </summary>
public Rectangle GetGameRectangle()
{
Size fullMap = _map.CanvasSize;
Point leftTop = GetGameLocation(new Point(0, 0));
Point rightBottom = GetGameLocation(new Point(fullMap.Width, fullMap.Height));
return new Rectangle(leftTop.X, leftTop.Y, rightBottom.X - leftTop.X, rightBottom.Y - leftTop.Y);
}
public Rectangle GetGameRectangle(Rectangle mapRectangle)
{
Point gameLocation = GetGameLocation(mapRectangle.Location);
Point gameSize = GetGameLocation(new Point(mapRectangle.Right, mapRectangle.Bottom));
return new Rectangle(gameLocation, new Size(gameSize.X - gameLocation.X, gameSize.Y - gameLocation.Y));
}
#endregion
#region Other
public void Dispose()
{
}
public override string ToString()
{
return string.Format("Map={0}, Visible={1}, VillageSize={2}", _map, _visibleGameRectangle, _drawerFactoryStrategy != null ? Dimensions.Size.ToString() : "NotInited");
}
#endregion
}
}
| |
using System;
using System.Threading;
namespace M2SA.AppGenome.Threading.Internal
{
/// <summary>
///
/// </summary>
public abstract class WorkItemsGroupBase : IWorkItemsGroup
{
#region Private Fields
/// <summary>
/// Contains the name of this instance of SmartThreadPool.
/// Can be changed by the user.
/// </summary>
private string _name = "WorkItemsGroupBase";
/// <summary>
///
/// </summary>
public WorkItemsGroupBase()
{
IsIdle = true;
}
#endregion
#region IWorkItemsGroup Members
#region Public Methods
/// <summary>
/// Get/Set the name of the SmartThreadPool/WorkItemsGroup instance
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
#endregion
#region Abstract Methods
/// <summary>
///
/// </summary>
public abstract int Concurrency { get; set; }
/// <summary>
///
/// </summary>
public abstract int WaitingCallbacks { get; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public abstract object[] GetStates();
/// <summary>
///
/// </summary>
public abstract WIGStartInfo WIGStartInfo { get; }
/// <summary>
///
/// </summary>
public abstract void Start();
/// <summary>
///
/// </summary>
/// <param name="abortExecution"></param>
public abstract void Cancel(bool abortExecution);
/// <summary>
///
/// </summary>
/// <param name="millisecondsTimeout"></param>
/// <returns></returns>
public abstract bool WaitForIdle(int millisecondsTimeout);
/// <summary>
///
/// </summary>
public abstract event WorkItemsGroupIdleHandler OnIdle;
/// <summary>
///
/// </summary>
/// <param name="workItem"></param>
internal abstract void Enqueue(WorkItem workItem);
/// <summary>
///
/// </summary>
internal virtual void PreQueueWorkItem() { }
#endregion
#region Common Base Methods
/// <summary>
/// Cancel all the work items.
/// Same as Cancel(false)
/// </summary>
public virtual void Cancel()
{
Cancel(false);
}
/// <summary>
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
/// </summary>
public void WaitForIdle()
{
WaitForIdle(Timeout.Infinite);
}
/// <summary>
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
/// </summary>
public bool WaitForIdle(TimeSpan timeout)
{
return WaitForIdle((int)timeout.TotalMilliseconds);
}
/// <summary>
/// IsIdle is true when there are no work items running or queued.
/// </summary>
public bool IsIdle { get; protected set; }
#endregion
#region QueueWorkItem
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback)
{
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="workItemPriority">The priority of the work item</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="workItemInfo">Work item info</param>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state)
{
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="workItemInfo">Work item information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback, state);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute,
WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
#endregion
#region QueueWorkItem(Action<...>)
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
public IWorkItemResult QueueWorkItem(Action action)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
delegate
{
action.Invoke();
return null;
});
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <param name="arg"></param>
/// <returns></returns>
public IWorkItemResult QueueWorkItem<T>(Action<T> action, T arg)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
action.Invoke(arg);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="action"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <returns></returns>
public IWorkItemResult QueueWorkItem<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
action.Invoke(arg1, arg2);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <param name="action"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
/// <returns></returns>
public IWorkItemResult QueueWorkItem<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
action.Invoke(arg1, arg2, arg3);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
/// <param name="action"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
/// <param name="arg4"></param>
/// <returns></returns>
public IWorkItemResult QueueWorkItem<T1, T2, T3, T4>(
Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
action.Invoke(arg1, arg2, arg3, arg4);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
#endregion
#region QueueWorkItem(Func<...>)
/// <summary>
///
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="func"></param>
/// <returns></returns>
public IWorkItemResult<TResult> QueueWorkItem<TResult>(Func<TResult> func)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke();
});
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="func"></param>
/// <param name="arg"></param>
/// <returns></returns>
public IWorkItemResult<TResult> QueueWorkItem<T, TResult>(Func<T, TResult> func, T arg)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="func"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <returns></returns>
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 arg1, T2 arg2)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="func"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
/// <returns></returns>
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, TResult>(
Func<T1, T2, T3, TResult> func, T1 arg1, T2 arg2, T3 arg3)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2, arg3);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="func"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
/// <param name="arg4"></param>
/// <returns></returns>
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, T4, TResult>(
Func<T1, T2, T3, T4, TResult> func, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2, arg3, arg4);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
#endregion
#endregion
}
}
| |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Bandwidth.Net.Api;
using Newtonsoft.Json;
namespace Bandwidth.Net
{
/// <summary>
/// Catapult Api callback event
/// </summary>
/// <example>
/// <code>
/// var callbackEvent = CallbackEvent.CreateFromJson("{\"eventType\": \"sms\"}");
/// switch(callbackEvent.EventType)
/// {
/// case CallbackEventType.Sms:
/// Console.WriteLine($"Sms {callbackEvent.From} -> {callbackEvent.To}: {callbackEvent.Text}");
/// break;
/// }
/// </code>
/// </example>
public class CallbackEvent
{
/// <summary>
/// Event type
/// </summary>
public CallbackEventType EventType { get; set; }
/// <summary>
/// Message direction
/// </summary>
public MessageDirection Direction { get; set; }
/// <summary>
/// From
/// </summary>
public string From { get; set; }
/// <summary>
/// To
/// </summary>
public string To { get; set; }
/// <summary>
/// Id of message
/// </summary>
public string MessageId { get; set; }
/// <summary>
/// Url to message
/// </summary>
public string MessageUri { get; set; }
/// <summary>
/// Text of message or transcription
/// </summary>
public string Text { get; set; }
/// <summary>
/// Application Id
/// </summary>
public string ApplicationId { get; set; }
/// <summary>
/// Time
/// </summary>
public DateTime Time { get; set; }
/// <summary>
/// State
/// </summary>
public CallbackEventState State { get; set; }
/// <summary>
/// Delivery state of message
/// </summary>
public MessageDeliveryState DeliveryState { get; set; }
/// <summary>
/// Delivery code of message
/// </summary>
public int DeliveryCode { get; set; }
/// <summary>
/// Delivery description of message
/// </summary>
public string DeliveryDescription { get; set; }
/// <summary>
/// Urls to attached media files to message
/// </summary>
public string[] Media { get; set; }
/// <summary>
/// Call state
/// </summary>
public CallState CallState { get; set; }
/// <summary>
/// Id of call
/// </summary>
public string CallId { get; set; }
/// <summary>
/// Url to the call
/// </summary>
public string CallUri { get; set; }
/// <summary>
/// Tag
/// </summary>
public string Tag { get; set; }
/// <summary>
/// Status
/// </summary>
public CallbackEventStatus Status { get; set; }
/// <summary>
/// If of conference
/// </summary>
public string ConferenceId { get; set; }
/// <summary>
/// Url to the conference
/// </summary>
public string ConferenceUri { get; set; }
/// <summary>
/// Created time of the conference
/// </summary>
public DateTime CreatedTime { get; set; }
/// <summary>
/// Completed time of the conference
/// </summary>
public DateTime CompletedTime { get; set; }
/// <summary>
/// Active members count of the conference
/// </summary>
public int ActiveMembers { get; set; }
/// <summary>
/// Id of conference member
/// </summary>
public string MemberId { get; set; }
/// <summary>
/// Url to the conference member
/// </summary>
public string MemberUri { get; set; }
/// <summary>
/// Members is on hold in conference and can not hear or speak.
/// </summary>
public bool Hold { get; set; }
/// <summary>
/// Members audio is muted in conference.
/// </summary>
public bool Mute { get; set; }
/// <summary>
/// The digits pressed
/// </summary>
public string Digits { get; set; }
/// <summary>
/// The digit pressed (for DTMF event)
/// </summary>
public string DtmfDigit { get; set; }
/// <summary>
/// Id of gather
/// </summary>
public string GatherId { get; set; }
/// <summary>
/// Reason
/// </summary>
public CallbackEventReason Reason { get; set; }
/// <summary>
/// Cause of call termination
/// </summary>
public string Cause { get; set; }
/// <summary>
/// Id of recording
/// </summary>
public string RecordingId { get; set; }
/// <summary>
/// Url to the recording
/// </summary>
public string RecordingUri { get; set; }
/// <summary>
/// Created time of the recording
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// Completed time of the recording
/// </summary>
public DateTime EndTime { get; set; }
/// <summary>
/// Id of transcription
/// </summary>
public string TranscriptionId { get; set; }
/// <summary>
/// Url to the transcription
/// </summary>
public string TranscriptionUri { get; set; }
/// <summary>
/// Total character count of text.
/// </summary>
public int TextSize { get; set; }
/// <summary>
/// The full URL of the entire text content of the transcription.
/// </summary>
public string TextUrl { get; set; }
/// <summary>
/// Create instance from JSON string
/// </summary>
/// <param name="json">JSON string with callback event data</param>
/// <returns>New instance of CallbackEvent</returns>
public static CallbackEvent CreateFromJson(string json)
=> JsonConvert.DeserializeObject<CallbackEvent>(json, JsonHelpers.GetSerializerSettings());
}
/// <summary>
/// Possible event types
/// </summary>
public enum CallbackEventType
{
/// <summary>
/// Unknown type
/// </summary>
Unknown,
/// <summary>
/// Sms
/// </summary>
Sms,
/// <summary>
/// Mms
/// </summary>
Mms,
/// <summary>
/// Answer call
/// </summary>
Answer,
/// <summary>
/// Playback uadio
/// </summary>
Playback,
/// <summary>
/// Call timeout
/// </summary>
Timeout,
/// <summary>
/// Conference
/// </summary>
Conference,
/// <summary>
/// Play audio to the conference
/// </summary>
ConferencePlayback,
/// <summary>
/// Conference member
/// </summary>
ConferenceMember,
/// <summary>
/// Speak text to the conference
/// </summary>
ConferenceSpeak,
/// <summary>
/// DTMF
/// </summary>
Dtmf,
/// <summary>
/// Gather
/// </summary>
Gather,
/// <summary>
/// Incoming call
/// </summary>
Incomingcall,
/// <summary>
/// Call completed
/// </summary>
Hangup,
/// <summary>
/// Recording
/// </summary>
Recording,
/// <summary>
/// Speak text
/// </summary>
Speak,
/// <summary>
/// Transcription
/// </summary>
Transcription,
/// <summary>
/// Transfer complete
/// </summary>
TransferComplete,
/// <summary>
/// Redirect
/// </summary>
Redirect
}
/// <summary>
/// Possible statuses of calback events
/// </summary>
public enum CallbackEventStatus
{
/// <summary>
/// Started
/// </summary>
Started,
/// <summary>
/// Done
/// </summary>
Done,
/// <summary>
/// Created
/// </summary>
Created,
/// <summary>
/// Completed
/// </summary>
Completed,
/// <summary>
/// Complete
/// </summary>
Complete,
/// <summary>
/// Error
/// </summary>
Error
}
/// <summary>
/// Callback event states
/// </summary>
public enum CallbackEventState
{
/// <summary>
/// Active
/// </summary>
Active,
/// <summary>
/// Completed
/// </summary>
Completed,
/// <summary>
/// Received
/// </summary>
Received,
/// <summary>
/// Queued
/// </summary>
Queued,
/// <summary>
/// Sending
/// </summary>
Sending,
/// <summary>
/// Sent
/// </summary>
Sent,
/// <summary>
/// Complete
/// </summary>
Complete,
/// <summary>
/// Error
/// </summary>
Error,
/// <summary>
/// Start of playback
/// </summary>
PlaybackStart,
/// <summary>
/// End of playback
/// </summary>
PlaybackStop
}
/// <summary>
/// Possible reasons of calback events
/// </summary>
public enum CallbackEventReason
{
/// <summary>
/// Max digits reached
/// </summary>
MaxDigits,
/// <summary>
/// Terminating digit
/// </summary>
TerminatingDigit,
/// <summary>
/// Interdigit timeout
/// </summary>
InterDigitTimeout,
/// <summary>
/// Hung up
/// </summary>
HungUp,
/// <summary>
/// Cancelled
/// </summary>
Cancelled
}
/// <summary>
/// Helper for HttpContent to parse CallbackEvent
/// </summary>
public static class CallbackEventHelpers
{
/// <summary>
/// Read CallbackEvent instance from http content
/// </summary>
/// <param name="content">Content</param>
/// <returns>Callback event data or null if response content is not json</returns>
/// <example>
/// <code>
/// var callbackEvent = await request.Content.ReadAsCallbackEventAsync(); // response is instance of HttpRequestMessage
/// switch(callbackEvent.EventType)
/// {
/// case CallbackEventType.Sms:
/// Console.WriteLine($"Sms {callbackEvent.From} -> {callbackEvent.To}: {callbackEvent.Text}");
/// break;
/// }
/// </code>
/// </example>
public static Task<CallbackEvent> ReadAsCallbackEventAsync(this HttpContent content)
=> content.ReadAsJsonAsync<CallbackEvent>();
}
}
| |
// ==========================================================================
// This software is subject to the provisions of the Zope Public License,
// Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
// WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
// FOR A PARTICULAR PURPOSE.
// ==========================================================================
using System;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
namespace Python.Runtime {
//========================================================================
// Implements a Python type that provides access to CLR namespaces. The
// type behaves like a Python module, and can contain other sub-modules.
//========================================================================
internal class ModuleObject : ExtensionType {
Dictionary<string, ManagedType> cache;
internal string moduleName;
internal IntPtr dict;
protected string _namespace;
public ModuleObject(string name) : base() {
if (name == String.Empty)
{
throw new ArgumentException("Name must not be empty!");
}
moduleName = name;
cache = new Dictionary<string, ManagedType>();
_namespace = name;
dict = Runtime.PyDict_New();
IntPtr pyname = Runtime.PyString_FromString(moduleName);
Runtime.PyDict_SetItemString(dict, "__name__", pyname);
Runtime.PyDict_SetItemString(dict, "__file__", Runtime.PyNone);
Runtime.PyDict_SetItemString(dict, "__doc__", Runtime.PyNone);
Runtime.Decref(pyname);
Marshal.WriteIntPtr(this.pyHandle, ObjectOffset.ob_dict, dict);
InitializeModuleMembers();
}
//===================================================================
// Returns a ClassBase object representing a type that appears in
// this module's namespace or a ModuleObject representing a child
// namespace (or null if the name is not found). This method does
// not increment the Python refcount of the returned object.
//===================================================================
public ManagedType GetAttribute(string name, bool guess) {
ManagedType cached = null;
this.cache.TryGetValue(name, out cached);
if (cached != null) {
return cached;
}
ModuleObject m;
ClassBase c;
Type type;
//if (AssemblyManager.IsValidNamespace(name))
//{
// IntPtr py_mod_name = Runtime.PyString_FromString(name);
// IntPtr modules = Runtime.PyImport_GetModuleDict();
// IntPtr module = Runtime.PyDict_GetItem(modules, py_mod_name);
// if (module != IntPtr.Zero)
// return (ManagedType)this;
// return null;
//}
string qname = (_namespace == String.Empty) ? name :
_namespace + "." + name;
// If the fully-qualified name of the requested attribute is
// a namespace exported by a currently loaded assembly, return
// a new ModuleObject representing that namespace.
if (AssemblyManager.IsValidNamespace(qname)) {
m = new ModuleObject(qname);
StoreAttribute(name, m);
return (ManagedType) m;
}
// Look for a type in the current namespace. Note that this
// includes types, delegates, enums, interfaces and structs.
// Only public namespace members are exposed to Python.
type = AssemblyManager.LookupType(qname);
if (type != null) {
if (!type.IsPublic) {
return null;
}
c = ClassManager.GetClass(type);
StoreAttribute(name, c);
return (ManagedType) c;
}
// This is a little repetitive, but it ensures that the right
// thing happens with implicit assembly loading at a reasonable
// cost. Ask the AssemblyManager to do implicit loading for each
// of the steps in the qualified name, then try it again.
bool fromFile;
if (AssemblyManager.LoadImplicit(qname, out fromFile)) {
bool ignore = name.StartsWith("__");
if (true == fromFile && (!ignore)) {
string deprWarning = String.Format("\nThe module was found, but not in a referenced namespace.\n" +
"Implicit loading is deprecated. Please use clr.AddReference(\"{0}\").", qname);
Exceptions.deprecation(deprWarning);
}
if (AssemblyManager.IsValidNamespace(qname)) {
m = new ModuleObject(qname);
StoreAttribute(name, m);
return (ManagedType) m;
}
type = AssemblyManager.LookupType(qname);
if (type != null) {
if (!type.IsPublic) {
return null;
}
c = ClassManager.GetClass(type);
StoreAttribute(name, c);
return (ManagedType) c;
}
}
// We didn't find the name, so we may need to see if there is a
// generic type with this base name. If so, we'll go ahead and
// return it. Note that we store the mapping of the unmangled
// name to generic type - it is technically possible that some
// future assembly load could contribute a non-generic type to
// the current namespace with the given basename, but unlikely
// enough to complicate the implementation for now.
if (guess) {
string gname = GenericUtil.GenericNameForBaseName(
_namespace, name);
if (gname != null) {
ManagedType o = GetAttribute(gname, false);
if (o != null) {
StoreAttribute(name, o);
return o;
}
}
}
return null;
}
//===================================================================
// Stores an attribute in the instance dict for future lookups.
//===================================================================
private void StoreAttribute(string name, ManagedType ob) {
Runtime.PyDict_SetItemString(dict, name, ob.pyHandle);
cache[name] = ob;
}
//===================================================================
// Preloads all currently-known names for the module namespace. This
// can be called multiple times, to add names from assemblies that
// may have been loaded since the last call to the method.
//===================================================================
public void LoadNames() {
ManagedType m = null;
foreach (string name in AssemblyManager.GetNames(_namespace)) {
this.cache.TryGetValue(name, out m);
if (m == null) {
ManagedType attr = this.GetAttribute(name, true);
if (Runtime.wrap_exceptions) {
if (attr is ExceptionClassObject) {
ExceptionClassObject c = attr as ExceptionClassObject;
if (c != null) {
IntPtr p = attr.pyHandle;
IntPtr r =Exceptions.GetExceptionClassWrapper(p);
Runtime.PyDict_SetItemString(dict, name, r);
Runtime.Incref(r);
}
}
}
}
}
}
/// <summary>
/// Initialize module level functions and attributes
/// </summary>
internal void InitializeModuleMembers()
{
Type funcmarker = typeof(ModuleFunctionAttribute);
Type propmarker = typeof(ModulePropertyAttribute);
Type ftmarker = typeof(ForbidPythonThreadsAttribute);
Type type = this.GetType();
BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
while (type != null)
{
MethodInfo[] methods = type.GetMethods(flags);
for (int i = 0; i < methods.Length; i++)
{
MethodInfo method = methods[i];
object[] attrs = method.GetCustomAttributes(funcmarker, false);
object[] forbid = method.GetCustomAttributes(ftmarker, false);
bool allow_threads = (forbid.Length == 0);
if (attrs.Length > 0)
{
string name = method.Name;
MethodInfo[] mi = new MethodInfo[1];
mi[0] = method;
ModuleFunctionObject m = new ModuleFunctionObject(name, mi, allow_threads);
StoreAttribute(name, m);
}
}
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < properties.Length; i++)
{
PropertyInfo property = properties[i];
object[] attrs = property.GetCustomAttributes(propmarker, false);
if (attrs.Length > 0)
{
string name = property.Name;
ModulePropertyObject p = new ModulePropertyObject(property);
StoreAttribute(name, p);
}
}
type = type.BaseType;
}
}
//====================================================================
// ModuleObject __getattribute__ implementation. Module attributes
// are always either classes or sub-modules representing subordinate
// namespaces. CLR modules implement a lazy pattern - the sub-modules
// and classes are created when accessed and cached for future use.
//====================================================================
public static IntPtr tp_getattro(IntPtr ob, IntPtr key) {
ModuleObject self = (ModuleObject)GetManagedObject(ob);
if (!Runtime.PyString_Check(key)) {
Exceptions.SetError(Exceptions.TypeError, "string expected");
return IntPtr.Zero;
}
IntPtr op = Runtime.PyDict_GetItem(self.dict, key);
if (op != IntPtr.Zero) {
Runtime.Incref(op);
return op;
}
string name = Runtime.GetManagedString(key);
if (name == "__dict__") {
Runtime.Incref(self.dict);
return self.dict;
}
ManagedType attr = self.GetAttribute(name, true);
if (attr == null) {
Exceptions.SetError(Exceptions.AttributeError, name);
return IntPtr.Zero;
}
// XXX - hack required to recognize exception types. These types
// may need to be wrapped in old-style class wrappers in versions
// of Python where new-style classes cannot be used as exceptions.
if (Runtime.wrap_exceptions) {
if (attr is ExceptionClassObject) {
ExceptionClassObject c = attr as ExceptionClassObject;
if (c != null) {
IntPtr p = attr.pyHandle;
IntPtr r = Exceptions.GetExceptionClassWrapper(p);
Runtime.PyDict_SetItemString(self.dict, name, r);
Runtime.Incref(r);
return r;
}
}
}
Runtime.Incref(attr.pyHandle);
return attr.pyHandle;
}
//====================================================================
// ModuleObject __repr__ implementation.
//====================================================================
public static IntPtr tp_repr(IntPtr ob) {
ModuleObject self = (ModuleObject)GetManagedObject(ob);
string s = String.Format("<module '{0}'>", self.moduleName);
return Runtime.PyString_FromString(s);
}
}
/// <summary>
/// The CLR module is the root handler used by the magic import hook
/// to import assemblies. It has a fixed module name "clr" and doesn't
/// provide a namespace.
/// </summary>
internal class CLRModule : ModuleObject
{
protected static bool hacked = false;
protected static bool interactive_preload = true;
internal static bool preload;
// XXX Test performance of new features //
internal static bool _SuppressDocs = false;
internal static bool _SuppressOverloads = false;
public CLRModule() : base("clr") {
_namespace = String.Empty;
// This hackery is required in order to allow a plain Python to
// import the managed runtime via the CLR bootstrapper module.
// The standard Python machinery in control at the time of the
// import requires the module to pass PyModule_Check. :(
if (!hacked)
{
IntPtr type = this.tpHandle;
IntPtr mro = Marshal.ReadIntPtr(type, TypeOffset.tp_mro);
IntPtr ext = Runtime.ExtendTuple(mro, Runtime.PyModuleType);
Marshal.WriteIntPtr(type, TypeOffset.tp_mro, ext);
Runtime.Decref(mro);
hacked = true;
}
}
/// <summary>
/// The initializing of the preload hook has to happen as late as
/// possible since sys.ps1 is created after the CLR module is
/// created.
/// </summary>
internal void InitializePreload() {
if (interactive_preload) {
interactive_preload = false;
if (Runtime.PySys_GetObject("ps1") != IntPtr.Zero) {
preload = true;
} else {
Exceptions.Clear();
preload = false;
}
}
}
[ModuleFunctionAttribute()]
public static bool getPreload() {
return preload;
}
[ModuleFunctionAttribute()]
public static void setPreload(bool preloadFlag)
{
preload = preloadFlag;
}
//[ModulePropertyAttribute]
public static bool SuppressDocs {
get { return _SuppressDocs; }
set { _SuppressDocs = value; }
}
//[ModulePropertyAttribute]
public static bool SuppressOverloads {
get { return _SuppressOverloads; }
set { _SuppressOverloads = value; }
}
[ModuleFunctionAttribute()]
[ForbidPythonThreadsAttribute()]
public static Assembly AddReference(string name)
{
AssemblyManager.UpdatePath();
Assembly assembly = null;
assembly = AssemblyManager.LoadAssemblyPath(name);
if (assembly == null)
{
assembly = AssemblyManager.LoadAssembly(name);
}
if (assembly == null)
{
string msg = String.Format("Unable to find assembly '{0}'.", name);
throw new System.IO.FileNotFoundException(msg);
}
return assembly ;
}
[ModuleFunctionAttribute()]
[ForbidPythonThreadsAttribute()]
public static string FindAssembly(string name)
{
AssemblyManager.UpdatePath();
return AssemblyManager.FindAssembly(name);
}
[ModuleFunctionAttribute()]
public static String[] ListAssemblies(bool verbose)
{
AssemblyName[] assnames = AssemblyManager.ListAssemblies();
String[] names = new String[assnames.Length];
for (int i = 0; i < assnames.Length; i++)
{
if (verbose)
names[i] = assnames[i].FullName;
else
names[i] = assnames[i].Name;
}
return names;
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 LeanIX GmbH
*
* 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 LeanIX.Api.Common;
using LeanIX.Api.Models;
namespace LeanIX.Api {
public class ProjectsApi {
private readonly ApiClient apiClient = ApiClient.GetInstance();
public ApiClient getClient() {
return apiClient;
}
/// <summary>
/// Read all Project
/// </summary>
/// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param>
/// <param name="filter">Full-text filter</param>
/// <returns></returns>
public List<Project> getProjects (bool relations, string filter) {
// create path and map variables
var path = "/projects".Replace("{format}","json");
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
string paramStr = null;
if (relations != null){
paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations);
queryParams.Add("relations", paramStr);
}
if (filter != null){
paramStr = (filter != null && filter is DateTime) ? ((DateTime)(object)filter).ToString("u") : Convert.ToString(filter);
queryParams.Add("filter", paramStr);
}
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (List<Project>) ApiClient.deserialize(response, typeof(List<Project>));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Create a new Project
/// </summary>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public Project createProject (Project body) {
// create path and map variables
var path = "/projects".Replace("{format}","json");
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
if(response != null){
return (Project) ApiClient.deserialize(response, typeof(Project));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read a Project by a given ID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param>
/// <returns></returns>
public Project getProject (string ID, bool relations) {
// create path and map variables
var path = "/projects/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
if (relations != null){
paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations);
queryParams.Add("relations", paramStr);
}
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (Project) ApiClient.deserialize(response, typeof(Project));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Update a Project by a given ID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public Project updateProject (string ID, Project body) {
// create path and map variables
var path = "/projects/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
if(response != null){
return (Project) ApiClient.deserialize(response, typeof(Project));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Delete a Project by a given ID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <returns></returns>
public void deleteProject (string ID) {
// create path and map variables
var path = "/projects/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return ;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read all of relation
/// </summary>
/// <param name="ID">Unique ID</param>
/// <returns></returns>
public List<ServiceHasProject> getServiceHasProjects (string ID) {
// create path and map variables
var path = "/projects/{ID}/serviceHasProjects".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (List<ServiceHasProject>) ApiClient.deserialize(response, typeof(List<ServiceHasProject>));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Create a new relation
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public ServiceHasProject createServiceHasProject (string ID, Project body) {
// create path and map variables
var path = "/projects/{ID}/serviceHasProjects".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
if(response != null){
return (ServiceHasProject) ApiClient.deserialize(response, typeof(ServiceHasProject));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read by relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <returns></returns>
public ServiceHasProject getServiceHasProject (string ID, string relationID) {
// create path and map variables
var path = "/projects/{ID}/serviceHasProjects/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (ServiceHasProject) ApiClient.deserialize(response, typeof(ServiceHasProject));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Update relation by a given relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public ServiceHasProject updateServiceHasProject (string ID, string relationID, Project body) {
// create path and map variables
var path = "/projects/{ID}/serviceHasProjects/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
if(response != null){
return (ServiceHasProject) ApiClient.deserialize(response, typeof(ServiceHasProject));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Delete relation by a given relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <returns></returns>
public void deleteServiceHasProject (string ID, string relationID) {
// create path and map variables
var path = "/projects/{ID}/serviceHasProjects/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return ;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read all of relation
/// </summary>
/// <param name="ID">Unique ID</param>
/// <returns></returns>
public List<ProjectHasProvider> getProjectHasProviders (string ID) {
// create path and map variables
var path = "/projects/{ID}/projectHasProviders".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (List<ProjectHasProvider>) ApiClient.deserialize(response, typeof(List<ProjectHasProvider>));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Create a new relation
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public ProjectHasProvider createProjectHasProvider (string ID, Project body) {
// create path and map variables
var path = "/projects/{ID}/projectHasProviders".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
if(response != null){
return (ProjectHasProvider) ApiClient.deserialize(response, typeof(ProjectHasProvider));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read by relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <returns></returns>
public ProjectHasProvider getProjectHasProvider (string ID, string relationID) {
// create path and map variables
var path = "/projects/{ID}/projectHasProviders/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (ProjectHasProvider) ApiClient.deserialize(response, typeof(ProjectHasProvider));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Update relation by a given relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public ProjectHasProvider updateProjectHasProvider (string ID, string relationID, Project body) {
// create path and map variables
var path = "/projects/{ID}/projectHasProviders/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
if(response != null){
return (ProjectHasProvider) ApiClient.deserialize(response, typeof(ProjectHasProvider));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Delete relation by a given relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <returns></returns>
public void deleteProjectHasProvider (string ID, string relationID) {
// create path and map variables
var path = "/projects/{ID}/projectHasProviders/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return ;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read all of relation
/// </summary>
/// <param name="ID">Unique ID</param>
/// <returns></returns>
public List<ProjectUpdate> getProjectUpdates (string ID) {
// create path and map variables
var path = "/projects/{ID}/projectUpdates".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (List<ProjectUpdate>) ApiClient.deserialize(response, typeof(List<ProjectUpdate>));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Create a new relation
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public ProjectUpdate createProjectUpdate (string ID, Project body) {
// create path and map variables
var path = "/projects/{ID}/projectUpdates".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
if(response != null){
return (ProjectUpdate) ApiClient.deserialize(response, typeof(ProjectUpdate));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read by relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <returns></returns>
public ProjectUpdate getProjectUpdate (string ID, string relationID) {
// create path and map variables
var path = "/projects/{ID}/projectUpdates/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (ProjectUpdate) ApiClient.deserialize(response, typeof(ProjectUpdate));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Update relation by a given relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public ProjectUpdate updateProjectUpdate (string ID, string relationID, Project body) {
// create path and map variables
var path = "/projects/{ID}/projectUpdates/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
if(response != null){
return (ProjectUpdate) ApiClient.deserialize(response, typeof(ProjectUpdate));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Delete relation by a given relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <returns></returns>
public void deleteProjectUpdate (string ID, string relationID) {
// create path and map variables
var path = "/projects/{ID}/projectUpdates/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return ;
}
else {
throw ex;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using Xamarin.iOS.FileExplorer.Config;
using Xamarin.iOS.FileExplorer.Data;
using Xamarin.iOS.FileExplorer.Services.File;
namespace Xamarin.iOS.FileExplorer.ViewModels
{
public class DirectoryContentViewModel
{
private IList<Item<object>> _selectedItems = new List<Item<object>>();
private readonly IList<Item<object>> _allItems = new List<Item<object>>();
private IList<Item<object>> _itemsToDisplay = new List<Item<object>>();
private readonly NSUrl url;
private readonly Configuration configuration = new Configuration();
private readonly FileSpecifications _fileSpecifications;
private readonly IFileService<object> _fileService;
private SortMode sortMode;
private bool isEditing;
public DirectoryContentViewModel(LoadedItem<object> loadedDirectoryItem, FileSpecifications fileSpecifications,
Configuration configuration)
: this(loadedDirectoryItem, fileSpecifications, configuration, new LocalStorageFileService<object>())
{
}
public DirectoryContentViewModel(LoadedItem<object> loadedDirectoryItem, FileSpecifications fileSpecifications,
Configuration configuration, IFileService<object> fileService)
{
url = loadedDirectoryItem.Url;
_fileSpecifications = fileSpecifications;
this.configuration = configuration;
_fileService = fileService;
var filterConfig = configuration.FilteringConfiguration;
var allItems = loadedDirectoryItem.Resource as IEnumerable<Item<object>>;
bool hasAnyFileFIlters = filterConfig.FileFilters.Any();
_allItems =
allItems.Where(
x => !hasAnyFileFIlters || filterConfig.FileFilters.Any(filter => filter.MatchesItem<object>(x))).ToList();
_itemsToDisplay = DirectoryContentViewModel.GetItemsWithAppliedFilterAndSortCriterias(string.Empty, SortMode,_allItems).ToList();
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("ItemsDeleted"), notifiaction =>
{
var deletedItems = notifiaction.Object as IEnumerable<Item<object>>;
if (deletedItems == null)
return;
foreach (var deletedItem in deletedItems)
Remove(deletedItem);
Delegate?.ListChanged(this);
});
}
public SortMode SortMode
{
get { return sortMode; }
set
{
sortMode = value;
_itemsToDisplay = DirectoryContentViewModel.GetItemsWithAppliedFilterAndSortCriterias(SearchQuery, SortMode, _allItems).ToList();
}
}
public bool IsUserInteractionEnabled => _fileService.IsDeletionInProgress;
public string Title => url.LastPathComponent;
public bool IsEditing
{
get { return isEditing; }
set
{
if (isEditing == value)
return;
isEditing = value;
_selectedItems = new List<Item<object>>();
Delegate?.Changed(this);
}
}
private string searchQuery;
public string SearchQuery
{
get { return searchQuery; }
set
{
_itemsToDisplay = GetItemsWithAppliedFilterAndSortCriterias(searchQuery, SortMode, _allItems).ToList();
Delegate?.ListChanged(this);
}
}
public bool IsEditActionHidden
=>
!configuration.ActionsConfiguration.CanChooseFiles && !configuration.ActionsConfiguration.CanChooseDirectories &&
!configuration.ActionsConfiguration.CanRemoveFiles && !configuration.ActionsConfiguration.CanRemoveDirectories;
public string IsEditActionTitle => IsEditing ? "Cancel" : "Select";
public bool IsEditActionEnabled
=> !IsEditActionHidden && !_fileService.IsDeletionInProgress;
public bool IsSelectActionHidden
=> !configuration.ActionsConfiguration.CanChooseFiles && !configuration.ActionsConfiguration.CanChooseDirectories;
public string SelectActionTitle => "Choose";
public bool IsSelectionEnabled => IsEditing;
public bool IsSelectActionEnabled
{
get
{
if (_selectedItems.Count == 0 || IsSelectActionHidden)
return false;
if (!configuration.ActionsConfiguration.CanChooseDirectories && _selectedItems.Any(x => x.Type == ItemType.Directory))
return false;
if (!configuration.ActionsConfiguration.CanChooseFiles && _selectedItems.Any(x => x.Type == ItemType.File))
return false;
bool numberOfSelectedItemsAllowed = configuration.ActionsConfiguration.AllowsMultipleSelection
? _selectedItems.Count > 0
: _selectedItems.Count == 1;
return !_fileService.IsDeletionInProgress && numberOfSelectedItemsAllowed;
}
}
public bool IsDeleteActionHidden
=> !configuration.ActionsConfiguration.CanRemoveDirectories && !configuration.ActionsConfiguration.CanRemoveFiles;
public string DeleteActionTitle => "Delete";
public bool IsDeleteActionEnabled
{
get
{
if (_selectedItems.Count == 0 || IsDeleteActionHidden)
return false;
if (!configuration.ActionsConfiguration.CanRemoveDirectories && _selectedItems.Any(x => x.Type == ItemType.Directory))
return false;
if (!configuration.ActionsConfiguration.CanRemoveFiles && _selectedItems.Any(x => x.Type == ItemType.File))
return false;
return !_fileService.IsDeletionInProgress;
}
}
public IEnumerable<NSIndexPath> IndexPathsOfSelectedCells => _selectedItems.Select(IndexFor);
public void Select(NSIndexPath path)
{
var item = ItemFor(path);
if (IsEditing)
_selectedItems.Add(item);
else
Delegate?.ItemSelected(item);
Delegate?.Changed(this);
}
public void Deselect(NSIndexPath atIndexPath)
{
var item = ItemFor(atIndexPath);
if (IsEditing)
_selectedItems.Remove(item);
else
Delegate?.ItemSelected(item);
Delegate?.Changed(this);
}
public void DeleteItems(IEnumerable<NSIndexPath> atIndexPaths, Action<DeleteResult<object>> onRemovedAction)
{
var items = atIndexPaths.Select(ItemFor).ToList();
_fileService.Delete(items, x =>
{
onRemovedAction(x);
Delegate?.Changed(this);
});
Delegate?.Changed(this);
}
public void ChooseItems(Action<IEnumerable<Item<object>>> pickedItemsAction)
{
pickedItemsAction(_selectedItems);
}
private static IEnumerable<Item<object>> GetItemsWithAppliedFilterAndSortCriterias(string searchQuery,
SortMode sortMode, IEnumerable<Item<object>> items)
{
searchQuery = searchQuery.Trim();
var filteredItems =
items.Where(x => x.Url.LastPathComponent.Contains(searchQuery) || string.IsNullOrWhiteSpace(searchQuery));
if (sortMode == SortMode.Date)
filteredItems = filteredItems.OrderBy(x => x.ModificationDate);
else if (sortMode == SortMode.Name)
filteredItems = filteredItems.OrderBy(x => x.Name);
return filteredItems.ToList();
}
private void Remove(Item<object> item)
{
_itemsToDisplay.Remove(item);
_allItems.Remove(item);
_selectedItems.Remove(item);
}
private NSIndexPath IndexFor(Item<object> item)
{
var itemWithIndex = _allItems.Select((x, index) => new
{
Item = x,
Index = index
}).FirstOrDefault(x => x.Item == item);
if (itemWithIndex == null)
throw new InvalidOperationException("Item does not exist.");
return NSIndexPath.FromItemSection(itemWithIndex.Index, 0);
}
public int NumberOfItems(int section)
{
return _itemsToDisplay.Count();
}
public ItemViewModel ItemViewModelFor(NSIndexPath indexPath)
{
var item = ItemFor(indexPath);
return new ItemViewModel(item, _fileSpecifications.GetFileSpecificationProvider<object>(item));
}
public Item<object> ItemFor(NSIndexPath indexPath)
=> _itemsToDisplay[(int)indexPath.Item];
public IDirectoryContentViewModelDelegate Delegate { get; set; }
public nint NumberOfSections => 1;
}
public interface IDirectoryContentViewModelDelegate
{
void ListChanged(DirectoryContentViewModel viewModel);
void Changed(DirectoryContentViewModel viewModel);
void ItemSelected(Item<object> selectedItem);
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Drawing;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
public class ShadedMapTileRenderer : IMapTileTerrainRenderer
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
//private IConfigSource m_config; // not used currently
public void Initialize(Scene scene, IConfigSource config)
{
m_scene = scene;
// m_config = config; // not used currently
}
public void TerrainToBitmap(DirectBitmap mapbmp)
{
int tc = Environment.TickCount;
m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain (Shaded)");
double[,] hm = m_scene.Heightmap.GetDoubles();
bool ShadowDebugContinue = true;
bool terraincorruptedwarningsaid = false;
float low = 255;
float high = 0;
for (int x = 0; x < 256; x++)
{
for (int y = 0; y < 256; y++)
{
float hmval = (float)hm[x, y];
if (hmval < low)
low = hmval;
if (hmval > high)
high = hmval;
}
}
float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
for (int x = 0; x < 256; x++)
{
for (int y = 0; y < 256; y++)
{
// Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left
int yr = 255 - y;
float heightvalue = (float)hm[x, y];
if (heightvalue > waterHeight)
{
// scale height value
// No, that doesn't scale it:
// heightvalue = low + mid * (heightvalue - low) / mid; => low + (heightvalue - low) * mid / mid = low + (heightvalue - low) * 1 = low + heightvalue - low = heightvalue
if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
heightvalue = 0;
else if (heightvalue > 255f)
heightvalue = 255f;
else if (heightvalue < 0f)
heightvalue = 0f;
Color color = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
mapbmp.Bitmap.SetPixel(x, yr, color);
try
{
//X
// .
//
// Shade the terrain for shadows
if (x < 255 && yr < 255)
{
float hfvalue = (float)hm[x, y];
float hfvaluecompare = 0f;
if ((x + 1 < 256) && (y + 1 < 256))
{
hfvaluecompare = (float)hm[x + 1, y + 1]; // light from north-east => look at land height there
}
if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue))
hfvalue = 0f;
if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
hfvaluecompare = 0f;
float hfdiff = hfvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower
int hfdiffi = 0;
int hfdiffihighlight = 0;
float highlightfactor = 0.18f;
try
{
// hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1;
hfdiffi = Math.Abs((int)(hfdiff * 4.5f)) + 1;
if (hfdiff % 1f != 0)
{
// hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
hfdiffi = hfdiffi + Math.Abs((int)((hfdiff % 1f) * 5f) - 1);
}
hfdiffihighlight = Math.Abs((int)((hfdiff * highlightfactor) * 4.5f)) + 1;
if (hfdiff % 1f != 0)
{
// hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
hfdiffihighlight = hfdiffihighlight + Math.Abs((int)(((hfdiff * highlightfactor) % 1f) * 5f) - 1);
}
}
catch (OverflowException)
{
m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString());
ShadowDebugContinue = false;
}
if (hfdiff > 0.3f)
{
// NE is lower than here
// We have to desaturate and lighten the land at the same time
// we use floats, colors use bytes, so shrink are space down to
// 0-255
if (ShadowDebugContinue)
{
int r = color.R;
int g = color.G;
int b = color.B;
color = Color.FromArgb((r + hfdiffihighlight < 255) ? r + hfdiffihighlight : 255,
(g + hfdiffihighlight < 255) ? g + hfdiffihighlight : 255,
(b + hfdiffihighlight < 255) ? b + hfdiffihighlight : 255);
}
}
else if (hfdiff < -0.3f)
{
// here is lower than NE:
// We have to desaturate and blacken the land at the same time
// we use floats, colors use bytes, so shrink are space down to
// 0-255
if (ShadowDebugContinue)
{
if ((x - 1 > 0) && (yr + 1 < 256))
{
color = mapbmp.Bitmap.GetPixel(x - 1, yr + 1);
int r = color.R;
int g = color.G;
int b = color.B;
color = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0,
(g - hfdiffi > 0) ? g - hfdiffi : 0,
(b - hfdiffi > 0) ? b - hfdiffi : 0);
mapbmp.Bitmap.SetPixel(x-1, yr+1, color);
}
}
}
}
}
catch (ArgumentException)
{
if (!terraincorruptedwarningsaid)
{
m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName);
terraincorruptedwarningsaid = true;
}
color = Color.Black;
mapbmp.Bitmap.SetPixel(x, yr, color);
}
}
else
{
// We're under the water level with the terrain, so paint water instead of land
// Y flip the cordinates
heightvalue = waterHeight - heightvalue;
if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
heightvalue = 0f;
else if (heightvalue > 19f)
heightvalue = 19f;
else if (heightvalue < 0f)
heightvalue = 0f;
heightvalue = 100f - (heightvalue * 100f) / 19f;
try
{
Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255);
mapbmp.Bitmap.SetPixel(x, yr, water);
}
catch (ArgumentException)
{
if (!terraincorruptedwarningsaid)
{
m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName);
terraincorruptedwarningsaid = true;
}
Color black = Color.Black;
mapbmp.Bitmap.SetPixel(x, (256 - y) - 1, black);
}
}
}
}
m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms");
}
}
}
| |
/* $Id$
*
* Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog
* Author: Douglas R. Miles
* E-mail: logicmoo@gmail.com
* WWW: http://www.logicmoo.com
* Copyright (C): 2010-2012 LogicMOO Developement
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*********************************************************/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using SbsSW.SwiPlCs;
using SbsSW.SwiPlCs.Callback;
using SbsSW.SwiPlCs.Exceptions;
namespace Swicli.Library
{
public partial class PrologCLR
{
/// <summary>
/// ?- current_bot(Obj),cli_add_event_handler(Obj,'EachSimEvent',c(A,format(user_error,'EV = ~q.~n',[A])),Out).
/// </summary>
/// <param name="clazzOrInstance"></param>
/// <param name="memberSpec"></param>
/// <param name="closureTerm"></param>
/// <param name="blockOn"></param>
/// <param name="control"></param>
/// <returns></returns>
[NonDet(Arity = 4, ForeignSwitches = (PlForeignSwitches.Nondeterministic | PlForeignSwitches.VarArgs), DelegateType = typeof(DelegateParameterBacktrackVarArgs))]
internal static int cliAddEventHandler(PlTerm term1, int arity, IntPtr control)
{
return cliAddEventHandler0(term1, term1.Shift(1), term1.Shift(2), term1.Shift(3), control);
}
public static int cliAddEventHandler0(PlTerm clazzOrInstance, PlTerm memberSpec, PlTerm closureTerm, PlTerm blockOn, IntPtr control)
{
var handle = control;
FRG fc = (FRG)(libpl.PL_foreign_control(control));
switch (fc)
{
case FRG.PL_FIRST_CALL:
{
object getInstance;
Type c;
if (!GetInstanceAndType(clazzOrInstance, out getInstance, out c)) return PlSucceedOrFail(false);
Type[] paramz = null;
if (!CheckBound(memberSpec, closureTerm)) return PlSucceedOrFail(false);
EventInfo fi = findEventInfo(memberSpec, c, ref paramz, BindingFlagsALL);
if (fi == null)
{
return Embedded.Error("Cant find event {0} on {1}", memberSpec, (object)c ?? clazzOrInstance) ? 3 : 0;
}
ClosureDelegate newClosureDelegate = new ClosureDelegate(fi, getInstance, closureTerm);
var v = NondetContextHandle.ObtainHandle(control, newClosureDelegate);
bool res = v.Setup(new PlTermV(closureTerm, blockOn));
blockOn.FromObject(newClosureDelegate);
bool more = v.HasMore();
if (more)
{
libpl.PL_retry(v.Handle);
return res ? 3 : 0;
}
return res ? 1 : 0;
} break;
case FRG.PL_REDO:
{
var v = NondetContextHandle.FindHandle(control);
bool res = v.Call(new PlTermV(closureTerm, blockOn));
bool more = v.HasMore();
if (more)
{
libpl.PL_retry(v.Handle);
return res ? 3 : 0;
}
return res ? 1 : 0;
} break;
case FRG.PL_CUTTED:
{
var v = NondetContextHandle.FindHandle(control);
bool res = v.Close(new PlTermV(closureTerm, blockOn));
NondetContextHandle.ReleaseHandle(v);
return res ? 1 : 0;
} break;
default:
{
throw new PlException("no frg");
return libpl.PL_fail;
}
break;
}
}
}
public class ClosureDelegate : PrologGenericDelegate, IDisposable, SCCH
{
private object[] Result;
private readonly EventInfo Event;
private readonly object Instance;
private uint closureTerm;
/// <summary>
/// ?- closure(v(V1,V2),format('I was called with ~q ~q ...',[V1,V2]).
/// </summary>
/// <param name="info"></param>
/// <param name="instance"></param>
/// <param name="closureTerm"></param>
public ClosureDelegate(EventInfo info, object instance, PlTerm clousreTerm)
{
Event = info;
Instance = instance;
SetInstanceOfDelegateType(info.EventHandlerType);
PlTerm plC = PlTerm.PlVar();
PrologCLR.PlCall("system", "copy_term", new PlTermV(clousreTerm, plC));
this.closureTerm = libpl.PL_record(clousreTerm.TermRef);
Event.AddEventHandler(instance, Delegate);
}
public override object CallProlog(params object[] paramz)
{
return CallPrologFast(paramz);
}
public override void CallPrologV(params object[] paramz)
{
CallPrologFast(paramz);
}
public override object CallPrologFast(object[] paramz)
{
PrologCLR.RegisterCurrentThread();
var results = paramz;
PlTerm plC = PlTerm.PlVar();
libpl.PL_recorded(closureTerm, plC.TermRef);
PlTerm ctestVars = plC.Arg(0);
PlTerm ctestCode = plC.Arg(1);
PlTerm[] terms = PrologCLR.ToTermArray(ctestVars);
int idx = terms.Length - 1;
int resdex = results.Length - 1;;
while (idx >= 0 && resdex >= 0)
{
terms[idx--].FromObject(results[resdex--]);
}
PrologCLR.PlCall("user", "call", new PlTermV(ctestCode, 1));
return null;
}
#region Implementation of IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
Event.RemoveEventHandler(Instance, Delegate);
if (closureTerm != 0) libpl.PL_erase(closureTerm);
closureTerm = 0;
}
#endregion
#region Implementation of SCCH
public bool Setup(PlTermV a0)
{
return true;
}
public bool Call(PlTermV a0)
{
// throw new NotImplementedException();
return true;
}
public bool Close(PlTermV a0)
{
//throw new NotImplementedException();
return true;
}
public bool HasMore()
{
// throw new NotImplementedException();
return false;
}
#endregion
}
/// <summary>
/// Same as Queue except Dequeue function blocks until there is an object to return.
/// Note: This class does not need to be synchronized
/// </summary>
public class BlockingQueue<T> : Queue<T>
{
private object SyncRoot;
private bool open = true;
/// <summary>
/// Create new BlockingQueue.
/// </summary>
/// <param name="col">The System.Collections.ICollection to copy elements from</param>
public BlockingQueue(IEnumerable<T> col)
: base(col)
{
SyncRoot = new object();
open = true;
}
/// <summary>
/// Create new BlockingQueue.
/// </summary>
/// <param name="capacity">The initial number of elements that the queue can contain</param>
public BlockingQueue(int capacity)
: base(capacity)
{
SyncRoot = new object();
open = true;
}
/// <summary>
/// Create new BlockingQueue.
/// </summary>
public BlockingQueue()
: base()
{
SyncRoot = new object();
open = true;
}
/// <summary>
/// BlockingQueue Destructor (Close queue, resume any waiting thread).
/// </summary>
~BlockingQueue()
{
Close();
}
/// <summary>
/// Remove all objects from the Queue.
/// </summary>
public new void Clear()
{
lock (SyncRoot)
{
base.Clear();
}
}
/// <summary>
/// Remove all objects from the Queue, resume all dequeue threads.
/// </summary>
public void Close()
{
lock (SyncRoot)
{
open = false;
base.Clear();
Monitor.PulseAll(SyncRoot); // resume any waiting threads
}
}
/// <summary>
/// Removes and returns the object at the beginning of the Queue.
/// </summary>
/// <returns>Object in queue.</returns>
public new T Dequeue()
{
return Dequeue(Timeout.Infinite);
}
/// <summary>
/// Removes and returns the object at the beginning of the Queue.
/// </summary>
/// <param name="timeout">time to wait before returning</param>
/// <returns>Object in queue.</returns>
public T Dequeue(TimeSpan timeout)
{
return Dequeue(timeout.Milliseconds);
}
/// <summary>
/// Removes and returns the object at the beginning of the Queue.
/// </summary>
/// <param name="timeout">time to wait before returning (in milliseconds)</param>
/// <returns>Object in queue.</returns>
public T Dequeue(int timeout)
{
lock (SyncRoot)
{
while (open && (base.Count == 0))
{
if (!Monitor.Wait(SyncRoot, timeout))
throw new InvalidOperationException("Timeout");
}
if (open)
return base.Dequeue();
else
throw new InvalidOperationException("Queue Closed");
}
}
public bool Dequeue(int timeout, ref T obj)
{
lock (SyncRoot)
{
while (open && (base.Count == 0))
{
if (!Monitor.Wait(SyncRoot, timeout))
return false;
}
if (open)
{
obj = base.Dequeue();
return true;
}
else
{
obj = default(T);
return false;
}
}
}
/// <summary>
/// Adds an object to the end of the Queue
/// </summary>
/// <param name="obj">Object to put in queue</param>
public new void Enqueue(string name, T obj)
{
lock (SyncRoot)
{
base.Enqueue(obj);
Monitor.Pulse(SyncRoot);
}
}
/// <summary>
/// Open Queue.
/// </summary>
public void Open()
{
lock (SyncRoot)
{
open = true;
}
}
/// <summary>
/// Gets flag indicating if queue has been closed.
/// </summary>
public bool Closed
{
get { return !open; }
}
}
public interface PrologKey
{
string Name { get; }
string Module { get; }
int Arity { get; }
}
public abstract class PrologGenericDelegate
{
public static BlockingQueue<Action> PrologEventQueue = new BlockingQueue<Action>();
static private void PrologEventLoop()
{
Action outgoingPacket = null;
// FIXME: This is kind of ridiculous. Port the HTB code from Simian over ASAP!
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
while (true)
{
if (PrologEventQueue.Dequeue(100, ref outgoingPacket))
{
// Very primitive rate limiting, keeps a fixed buffer of time between each packet
stopwatch.Stop();
if (stopwatch.ElapsedMilliseconds < 10)
{
//Logger.DebugLog(String.Format("Rate limiting, last packet was {0}ms ago", ms));
Thread.Sleep(10 - (int)stopwatch.ElapsedMilliseconds);
}
try
{
outgoingPacket();
}
catch (Exception)
{
}
stopwatch.Start();
}
}
}
public static Thread PrologGenericDelegateThread;
static public void EnsureStated()
{
if (PrologGenericDelegateThread == null)
{
PrologGenericDelegateThread = new Thread(PrologEventLoop);
PrologGenericDelegateThread.Name = "PrologEventSerializer";
PrologGenericDelegateThread.TrySetApartmentState(ApartmentState.STA);
PrologGenericDelegateThread.IsBackground = true;
PrologCLR.RegisterThread(PrologGenericDelegateThread);
PrologGenericDelegateThread.Start();
}
}
#if USE_MUSHDLR
public static TaskQueueHandler PrologEventQueue = new TaskQueueHandler("PrologEventQueue");
#endif
private Type[] ParamTypes;
private bool IsVoid;
private int ParamArity = -1;
/// <summary>
/// prolog predicate arity (invokeMethod.IsStatic ? 0 : 1) + ParamArity + (IsVoid ? 0 : 1);
/// </summary>
public int PrologArity;
public Delegate Delegate;
public Type ReturnType;
private MethodInfo _handlerMethod;
public MethodInfo HandlerMethod
{
get
{
if (_handlerMethod != null) return _handlerMethod;
if (ParamTypes == null) throw new InvalidOperationException("First set instance of DelegateType!");
Type c = GetType();
if (IsVoid)
{
if (ParamArity == 0) return c.GetMethod("GenericFun0");
return c.GetMethod("GenericFun" + ParamArity).MakeGenericMethod(ParamTypes);
}
Type[] typesPlusReturn = new Type[ParamArity + 1];
Array.Copy(ParamTypes, typesPlusReturn, ParamArity);
typesPlusReturn[ParamArity] = ReturnType;
return _handlerMethod = c.GetMethod("GenericFunR" + ParamArity).MakeGenericMethod(typesPlusReturn);
}
}
public void SetInstanceOfDelegateType(Type delegateType)
{
var invokeMethod = delegateType.GetMethod("Invoke");
ReturnType = invokeMethod.ReturnType;
ParameterInfo[] parms = invokeMethod.GetParameters();
IsVoid = ReturnType == typeof(void);
ParamArity = parms.Length;
// For non static we like to send the first argument in from the Origin's value
PrologArity = (invokeMethod.IsStatic ? 0 : 1) + ParamArity + (IsVoid ? 0 : 1);
ParamTypes = new Type[ParamArity];
for (int i = 0; i < ParamArity; i++)
{
ParamTypes[i] = parms[i].ParameterType;
}
Delegate = Delegate.CreateDelegate(delegateType, this, HandlerMethod);
//SyncLock = SyncLock ?? Delegate;
}
//public abstract object CallProlog(params object[] args);
// non-void functions 0-6
public R GenericFunR0<R>()
{
return (R)CallProlog();
}
public R GenericFunR1<A, R>(A a)
{
return (R)CallProlog(a);
}
public R GenericFunR2<A, B, R>(A a, B b)
{
return (R)CallProlog(a, b);
}
public R GenericFunR3<A, B, C, R>(A a, B b, C c)
{
return (R)CallProlog(a, b, c);
}
public R GenericFunR4<A, B, C, D, R>(A a, B b, C c, D d)
{
return (R)CallProlog(a, b, c, d);
}
public R GenericFunR5<A, B, C, D, E, R>(A a, B b, C c, D d, E e)
{
return (R)CallProlog(a, b, c, d, e);
}
public R GenericFunR6<A, B, C, D, E, F, R>(A a, B b, C c, D d, E e, F f)
{
return (R)CallProlog(a, b, c, d, e, f);
}
public R GenericFunR7<A, B, C, D, E, F, G, R>(A a, B b, C c, D d, E e, F f, G g)
{
return (R)CallProlog(a, b, c, d, e, f, g);
}
public R GenericFunR8<A, B, C, D, E, F, G, H, R>(A a, B b, C c, D d, E e, F f, G g, H h)
{
return (R)CallProlog(a, b, c, d, e, f, g, h);
}
// void functions 0-6
public void GenericFun0()
{
CallPrologV();
}
public void GenericFun1<A>(A a)
{
CallPrologV(a);
}
public void GenericFun2<A, B>(A a, B b)
{
CallPrologV(a, b);
}
public void GenericFun3<A, B, C>(A a, B b, C c)
{
CallPrologV(a, b, c);
}
public void GenericFun4<A, B, C, D>(A a, B b, C c, D d)
{
CallPrologV(a, b, c, d);
}
public void GenericFun5<A, B, C, D, E>(A a, B b, C c, D d, E e)
{
CallPrologV(a, b, c, d, e);
}
public void GenericFun6<A, B, C, D, E, F>(A a, B b, C c, D d, E e, F f)
{
CallPrologV(a, b, c, d, e, f);
}
public void GenericFun7<A, B, C, D, E, F, G>(A a, B b, C c, D d, E e, F f, G g)
{
CallPrologV(a, b, c, d, e, f, g);
}
public void GenericFun8<A, B, C, D, E, F, G, H>(A a, B b, C c, D d, E e, F f, G g, H h)
{
CallPrologV(a, b, c, d, e, f, g, h);
}
public virtual void CallPrologV(params object[] paramz)
{
if (!IsUsingGlobalQueue)
{
CallProlog0(paramz);
return;
}
PrologEventQueue.Open();
string threadName = null;// "CallProlog " + Thread.CurrentThread.Name;
PrologEventQueue.Enqueue(threadName, () => CallProlog0(paramz));
EnsureStated();
}
public virtual object CallProlog(params object[] paramz)
{
if (!IsUsingGlobalQueue) return CallProlog0(paramz);
string threadName = null;//"CallProlog " + Thread.CurrentThread.Name;
AutoResetEvent are = new AutoResetEvent(false);
object[] result = new object[1];
PrologEventQueue.Enqueue(threadName, () =>
{
result[0] = CallProlog0(paramz);
are.Set();
});
EnsureStated();
are.WaitOne();
return result[0];
}
private object CallProlog0(object[] paramz)
{
if (IsSyncronous)
{
var syncLock = SyncLock ?? Delegate;
if (syncLock != null)
{
lock (syncLock)
{
return CallPrologFast(paramz);
}
}
}
return CallPrologFast(paramz);
}
public abstract object CallPrologFast(object[] paramz);
static public bool IsUsingGlobalQueue = true;
public bool IsSyncronous = true;
public object SyncLock;
}
}
| |
// <copyright file="JaegerActivityConversionTest.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using OpenTelemetry.Internal;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using Xunit;
namespace OpenTelemetry.Exporter.Jaeger.Implementation.Tests
{
public class JaegerActivityConversionTest
{
static JaegerActivityConversionTest()
{
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = true;
var listener = new ActivityListener
{
ShouldListenTo = _ => true,
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllData,
};
ActivitySource.AddActivityListener(listener);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void JaegerActivityConverterTest_ConvertActivityToJaegerSpan_AllPropertiesSet(bool isRootSpan)
{
var activity = CreateTestActivity(isRootSpan: isRootSpan);
var traceIdAsInt = new Int128(activity.Context.TraceId);
var spanIdAsInt = new Int128(activity.Context.SpanId);
var linkTraceIdAsInt = new Int128(activity.Links.Single().Context.TraceId);
var linkSpanIdAsInt = new Int128(activity.Links.Single().Context.SpanId);
var jaegerSpan = activity.ToJaegerSpan();
Assert.Equal("Name", jaegerSpan.OperationName);
Assert.Equal(2, jaegerSpan.Logs.Count);
Assert.Equal(traceIdAsInt.High, jaegerSpan.TraceIdHigh);
Assert.Equal(traceIdAsInt.Low, jaegerSpan.TraceIdLow);
Assert.Equal(spanIdAsInt.Low, jaegerSpan.SpanId);
Assert.Equal(new Int128(activity.ParentSpanId).Low, jaegerSpan.ParentSpanId);
Assert.Equal(activity.Links.Count(), jaegerSpan.References.Count);
var references = jaegerSpan.References.ToArray();
var jaegerRef = references[0];
Assert.Equal(linkTraceIdAsInt.High, jaegerRef.TraceIdHigh);
Assert.Equal(linkTraceIdAsInt.Low, jaegerRef.TraceIdLow);
Assert.Equal(linkSpanIdAsInt.Low, jaegerRef.SpanId);
Assert.Equal(0x1, jaegerSpan.Flags);
Assert.Equal(activity.StartTimeUtc.ToEpochMicroseconds(), jaegerSpan.StartTime);
Assert.Equal(this.TimeSpanToMicroseconds(activity.Duration), jaegerSpan.Duration);
var tags = jaegerSpan.Tags.ToArray();
var tag = tags[0];
Assert.Equal(JaegerTagType.STRING, tag.VType);
Assert.Equal("stringKey", tag.Key);
Assert.Equal("value", tag.VStr);
tag = tags[1];
Assert.Equal(JaegerTagType.LONG, tag.VType);
Assert.Equal("longKey", tag.Key);
Assert.Equal(1, tag.VLong);
tag = tags[2];
Assert.Equal(JaegerTagType.LONG, tag.VType);
Assert.Equal("longKey2", tag.Key);
Assert.Equal(1, tag.VLong);
tag = tags[3];
Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
Assert.Equal("doubleKey", tag.Key);
Assert.Equal(1, tag.VDouble);
tag = tags[4];
Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
Assert.Equal("doubleKey2", tag.Key);
Assert.Equal(1, tag.VDouble);
tag = tags[5];
Assert.Equal(JaegerTagType.BOOL, tag.VType);
Assert.Equal("boolKey", tag.Key);
Assert.Equal(true, tag.VBool);
var logs = jaegerSpan.Logs.ToArray();
var jaegerLog = logs[0];
Assert.Equal(activity.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);
Assert.Equal(4, jaegerLog.Fields.Count());
var eventFields = jaegerLog.Fields.ToArray();
var eventField = eventFields[0];
Assert.Equal("key", eventField.Key);
Assert.Equal("value", eventField.VStr);
eventField = eventFields[1];
Assert.Equal("string_array", eventField.Key);
Assert.Equal("a", eventField.VStr);
eventField = eventFields[2];
Assert.Equal("string_array", eventField.Key);
Assert.Equal("b", eventField.VStr);
eventField = eventFields[3];
Assert.Equal("event", eventField.Key);
Assert.Equal("Event1", eventField.VStr);
Assert.Equal(activity.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);
jaegerLog = logs[1];
Assert.Equal(2, jaegerLog.Fields.Count());
eventFields = jaegerLog.Fields.ToArray();
eventField = eventFields[0];
Assert.Equal("key", eventField.Key);
Assert.Equal("value", eventField.VStr);
eventField = eventFields[1];
Assert.Equal("event", eventField.Key);
Assert.Equal("Event2", eventField.VStr);
}
[Fact]
public void JaegerActivityConverterTest_ConvertActivityToJaegerSpan_NoAttributes()
{
var activity = CreateTestActivity(setAttributes: false);
var traceIdAsInt = new Int128(activity.Context.TraceId);
var spanIdAsInt = new Int128(activity.Context.SpanId);
var linkTraceIdAsInt = new Int128(activity.Links.Single().Context.TraceId);
var linkSpanIdAsInt = new Int128(activity.Links.Single().Context.SpanId);
var jaegerSpan = activity.ToJaegerSpan();
Assert.Equal("Name", jaegerSpan.OperationName);
Assert.Equal(2, jaegerSpan.Logs.Count);
Assert.Equal(traceIdAsInt.High, jaegerSpan.TraceIdHigh);
Assert.Equal(traceIdAsInt.Low, jaegerSpan.TraceIdLow);
Assert.Equal(spanIdAsInt.Low, jaegerSpan.SpanId);
Assert.Equal(new Int128(activity.ParentSpanId).Low, jaegerSpan.ParentSpanId);
Assert.Equal(activity.Links.Count(), jaegerSpan.References.Count);
var references = jaegerSpan.References.ToArray();
var jaegerRef = references[0];
Assert.Equal(linkTraceIdAsInt.High, jaegerRef.TraceIdHigh);
Assert.Equal(linkTraceIdAsInt.Low, jaegerRef.TraceIdLow);
Assert.Equal(linkSpanIdAsInt.Low, jaegerRef.SpanId);
Assert.Equal(0x1, jaegerSpan.Flags);
Assert.Equal(activity.StartTimeUtc.ToEpochMicroseconds(), jaegerSpan.StartTime);
Assert.Equal(this.TimeSpanToMicroseconds(activity.Duration), jaegerSpan.Duration);
// 2 tags: span.kind & library.name.
Assert.Equal(2, jaegerSpan.Tags.Count);
var logs = jaegerSpan.Logs.ToArray();
var jaegerLog = logs[0];
Assert.Equal(activity.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);
Assert.Equal(4, jaegerLog.Fields.Count());
var eventFields = jaegerLog.Fields.ToArray();
var eventField = eventFields[0];
Assert.Equal("key", eventField.Key);
Assert.Equal("value", eventField.VStr);
eventField = eventFields[3];
Assert.Equal("event", eventField.Key);
Assert.Equal("Event1", eventField.VStr);
Assert.Equal(activity.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);
jaegerLog = logs[1];
Assert.Equal(2, jaegerLog.Fields.Count());
eventFields = jaegerLog.Fields.ToArray();
eventField = eventFields[0];
Assert.Equal("key", eventField.Key);
Assert.Equal("value", eventField.VStr);
eventField = eventFields[1];
Assert.Equal("event", eventField.Key);
Assert.Equal("Event2", eventField.VStr);
}
[Fact]
public void JaegerActivityConverterTest_ConvertActivityToJaegerSpan_NoEvents()
{
var activity = CreateTestActivity(addEvents: false);
var traceIdAsInt = new Int128(activity.Context.TraceId);
var spanIdAsInt = new Int128(activity.Context.SpanId);
var linkTraceIdAsInt = new Int128(activity.Links.Single().Context.TraceId);
var linkSpanIdAsInt = new Int128(activity.Links.Single().Context.SpanId);
var jaegerSpan = activity.ToJaegerSpan();
Assert.Equal("Name", jaegerSpan.OperationName);
Assert.Empty(jaegerSpan.Logs);
Assert.Equal(traceIdAsInt.High, jaegerSpan.TraceIdHigh);
Assert.Equal(traceIdAsInt.Low, jaegerSpan.TraceIdLow);
Assert.Equal(spanIdAsInt.Low, jaegerSpan.SpanId);
Assert.Equal(new Int128(activity.ParentSpanId).Low, jaegerSpan.ParentSpanId);
Assert.Equal(activity.Links.Count(), jaegerSpan.References.Count);
var references = jaegerSpan.References.ToArray();
var jaegerRef = references[0];
Assert.Equal(linkTraceIdAsInt.High, jaegerRef.TraceIdHigh);
Assert.Equal(linkTraceIdAsInt.Low, jaegerRef.TraceIdLow);
Assert.Equal(linkSpanIdAsInt.Low, jaegerRef.SpanId);
Assert.Equal(0x1, jaegerSpan.Flags);
Assert.Equal(activity.StartTimeUtc.ToEpochMicroseconds(), jaegerSpan.StartTime);
Assert.Equal(this.TimeSpanToMicroseconds(activity.Duration), jaegerSpan.Duration);
var tags = jaegerSpan.Tags.ToArray();
var tag = tags[0];
Assert.Equal(JaegerTagType.STRING, tag.VType);
Assert.Equal("stringKey", tag.Key);
Assert.Equal("value", tag.VStr);
tag = tags[1];
Assert.Equal(JaegerTagType.LONG, tag.VType);
Assert.Equal("longKey", tag.Key);
Assert.Equal(1, tag.VLong);
tag = tags[2];
Assert.Equal(JaegerTagType.LONG, tag.VType);
Assert.Equal("longKey2", tag.Key);
Assert.Equal(1, tag.VLong);
tag = tags[3];
Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
Assert.Equal("doubleKey", tag.Key);
Assert.Equal(1, tag.VDouble);
tag = tags[4];
Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
Assert.Equal("doubleKey2", tag.Key);
Assert.Equal(1, tag.VDouble);
tag = tags[5];
Assert.Equal(JaegerTagType.BOOL, tag.VType);
Assert.Equal("boolKey", tag.Key);
Assert.Equal(true, tag.VBool);
}
[Fact]
public void JaegerActivityConverterTest_ConvertActivityToJaegerSpan_NoLinks()
{
var activity = CreateTestActivity(addLinks: false, ticksToAdd: 8000);
var traceIdAsInt = new Int128(activity.Context.TraceId);
var spanIdAsInt = new Int128(activity.Context.SpanId);
var jaegerSpan = activity.ToJaegerSpan();
Assert.Equal("Name", jaegerSpan.OperationName);
Assert.Equal(2, jaegerSpan.Logs.Count);
Assert.Equal(traceIdAsInt.High, jaegerSpan.TraceIdHigh);
Assert.Equal(traceIdAsInt.Low, jaegerSpan.TraceIdLow);
Assert.Equal(spanIdAsInt.Low, jaegerSpan.SpanId);
Assert.Equal(new Int128(activity.ParentSpanId).Low, jaegerSpan.ParentSpanId);
Assert.Empty(jaegerSpan.References);
Assert.Equal(0x1, jaegerSpan.Flags);
Assert.Equal(activity.StartTimeUtc.ToEpochMicroseconds(), jaegerSpan.StartTime);
Assert.Equal(this.TimeSpanToMicroseconds(activity.Duration), jaegerSpan.Duration);
var tags = jaegerSpan.Tags.ToArray();
var tag = tags[0];
Assert.Equal(JaegerTagType.STRING, tag.VType);
Assert.Equal("stringKey", tag.Key);
Assert.Equal("value", tag.VStr);
tag = tags[1];
Assert.Equal(JaegerTagType.LONG, tag.VType);
Assert.Equal("longKey", tag.Key);
Assert.Equal(1, tag.VLong);
tag = tags[2];
Assert.Equal(JaegerTagType.LONG, tag.VType);
Assert.Equal("longKey2", tag.Key);
Assert.Equal(1, tag.VLong);
tag = tags[3];
Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
Assert.Equal("doubleKey", tag.Key);
Assert.Equal(1, tag.VDouble);
tag = tags[4];
Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
Assert.Equal("doubleKey2", tag.Key);
Assert.Equal(1, tag.VDouble);
tag = tags[5];
Assert.Equal(JaegerTagType.BOOL, tag.VType);
Assert.Equal("boolKey", tag.Key);
Assert.Equal(true, tag.VBool);
tag = tags[6];
Assert.Equal(JaegerTagType.LONG, tag.VType);
Assert.Equal("int_array", tag.Key);
Assert.Equal(1, tag.VLong);
tag = tags[8];
Assert.Equal(JaegerTagType.BOOL, tag.VType);
Assert.Equal("bool_array", tag.Key);
Assert.Equal(true, tag.VBool);
tag = tags[10];
Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
Assert.Equal("double_array", tag.Key);
Assert.Equal(1, tag.VDouble);
tag = tags[12];
Assert.Equal(JaegerTagType.STRING, tag.VType);
Assert.Equal("string_array", tag.Key);
Assert.Equal("a", tag.VStr);
// The second to last tag should be span.kind in this case
tag = tags[tags.Length - 2];
Assert.Equal(JaegerTagType.STRING, tag.VType);
Assert.Equal("span.kind", tag.Key);
Assert.Equal("client", tag.VStr);
// The last tag should be library.name in this case
tag = tags[tags.Length - 1];
Assert.Equal(JaegerTagType.STRING, tag.VType);
Assert.Equal("otel.library.name", tag.Key);
Assert.Equal(nameof(CreateTestActivity), tag.VStr);
var logs = jaegerSpan.Logs.ToArray();
var jaegerLog = logs[0];
Assert.Equal(activity.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);
Assert.Equal(4, jaegerLog.Fields.Count());
var eventFields = jaegerLog.Fields.ToArray();
var eventField = eventFields[0];
Assert.Equal("key", eventField.Key);
Assert.Equal("value", eventField.VStr);
eventField = eventFields[3];
Assert.Equal("event", eventField.Key);
Assert.Equal("Event1", eventField.VStr);
Assert.Equal(activity.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);
jaegerLog = logs[1];
Assert.Equal(2, jaegerLog.Fields.Count());
eventFields = jaegerLog.Fields.ToArray();
eventField = eventFields[0];
Assert.Equal("key", eventField.Key);
Assert.Equal("value", eventField.VStr);
eventField = eventFields[1];
Assert.Equal("event", eventField.Key);
Assert.Equal("Event2", eventField.VStr);
}
[Fact]
public void JaegerActivityConverterTest_GenerateJaegerSpan_RemoteEndpointOmittedByDefault()
{
// Arrange
var span = CreateTestActivity();
// Act
var jaegerSpan = span.ToJaegerSpan();
// Assert
Assert.DoesNotContain(jaegerSpan.Tags, t => t.Key == "peer.service");
}
[Fact]
public void JaegerActivityConverterTest_GenerateJaegerSpan_RemoteEndpointResolution()
{
// Arrange
var span = CreateTestActivity(
additionalAttributes: new Dictionary<string, object>
{
["net.peer.name"] = "RemoteServiceName",
});
// Act
var jaegerSpan = span.ToJaegerSpan();
// Assert
Assert.Contains(jaegerSpan.Tags, t => t.Key == "peer.service");
Assert.Equal("RemoteServiceName", jaegerSpan.Tags.First(t => t.Key == "peer.service").VStr);
}
[Fact]
public void JaegerActivityConverterTest_GenerateJaegerSpan_PeerServiceNameIgnoredForServerSpan()
{
// Arrange
var span = CreateTestActivity(
additionalAttributes: new Dictionary<string, object>
{
["http.host"] = "DiscardedRemoteServiceName",
},
kind: ActivityKind.Server);
// Act
var jaegerSpan = span.ToJaegerSpan();
// Assert
Assert.Null(jaegerSpan.PeerServiceName);
Assert.Empty(jaegerSpan.Tags.Where(t => t.Key == "peer.service"));
}
[Theory]
[MemberData(nameof(RemoteEndpointPriorityTestCase.GetTestCases), MemberType = typeof(RemoteEndpointPriorityTestCase))]
public void JaegerActivityConverterTest_GenerateJaegerSpan_RemoteEndpointResolutionPriority(RemoteEndpointPriorityTestCase testCase)
{
// Arrange
var activity = CreateTestActivity(additionalAttributes: testCase.RemoteEndpointAttributes);
// Act
var jaegerSpan = activity.ToJaegerSpan();
// Assert
var tags = jaegerSpan.Tags.Where(t => t.Key == "peer.service");
Assert.Single(tags);
var tag = tags.First();
Assert.Equal(testCase.ExpectedResult, tag.VStr);
}
[Fact]
public void JaegerActivityConverterTest_NullTagValueTest()
{
// Arrange
var activity = CreateTestActivity(additionalAttributes: new Dictionary<string, object> { ["nullTag"] = null });
// Act
var jaegerSpan = activity.ToJaegerSpan();
// Assert
Assert.DoesNotContain(jaegerSpan.Tags, t => t.Key == "nullTag");
}
[Theory]
[InlineData(StatusCode.Unset, "unset")]
[InlineData(StatusCode.Ok, "Ok")]
[InlineData(StatusCode.Error, "ERROR")]
[InlineData(StatusCode.Unset, "iNvAlId")]
public void JaegerActivityConverterTest_Status_ErrorFlagTest(StatusCode expectedStatusCode, string statusCodeTagValue)
{
// Arrange
var activity = CreateTestActivity();
activity.SetTag(SpanAttributeConstants.StatusCodeKey, statusCodeTagValue);
// Act
var jaegerSpan = activity.ToJaegerSpan();
// Assert
Assert.Equal(expectedStatusCode, activity.GetStatus().StatusCode);
if (expectedStatusCode == StatusCode.Unset)
{
Assert.DoesNotContain(jaegerSpan.Tags, t => t.Key == SpanAttributeConstants.StatusCodeKey);
}
else
{
Assert.Equal(
StatusHelper.GetTagValueForStatusCode(expectedStatusCode),
jaegerSpan.Tags.FirstOrDefault(t => t.Key == SpanAttributeConstants.StatusCodeKey).VStr);
}
if (expectedStatusCode == StatusCode.Error)
{
Assert.Contains(jaegerSpan.Tags, t => t.Key == JaegerActivityExtensions.JaegerErrorFlagTagName && t.VType == JaegerTagType.BOOL && (t.VBool ?? false));
}
else
{
Assert.DoesNotContain(jaegerSpan.Tags, t => t.Key == JaegerActivityExtensions.JaegerErrorFlagTagName);
}
}
internal static Activity CreateTestActivity(
bool setAttributes = true,
Dictionary<string, object> additionalAttributes = null,
bool addEvents = true,
bool addLinks = true,
Resource resource = null,
ActivityKind kind = ActivityKind.Client,
bool isRootSpan = false,
Status? status = null,
long ticksToAdd = 60 * TimeSpan.TicksPerSecond)
{
var startTimestamp = DateTime.UtcNow;
var endTimestamp = startTimestamp.AddTicks(ticksToAdd);
var eventTimestamp = DateTime.UtcNow;
var traceId = ActivityTraceId.CreateFromString("e8ea7e9ac72de94e91fabc613f9686b2".AsSpan());
var parentSpanId = isRootSpan ? default : ActivitySpanId.CreateFromBytes(new byte[] { 12, 23, 34, 45, 56, 67, 78, 89 });
var attributes = new Dictionary<string, object>
{
{ "stringKey", "value" },
{ "longKey", 1L },
{ "longKey2", 1 },
{ "doubleKey", 1D },
{ "doubleKey2", 1F },
{ "boolKey", true },
{ "int_array", new int[] { 1, 2 } },
{ "bool_array", new bool[] { true, false } },
{ "double_array", new double[] { 1.0, 1.1 } },
{ "string_array", new string[] { "a", "b" } },
};
if (additionalAttributes != null)
{
foreach (var attribute in additionalAttributes)
{
attributes.Add(attribute.Key, attribute.Value);
}
}
var events = new List<ActivityEvent>
{
new ActivityEvent(
"Event1",
eventTimestamp,
new ActivityTagsCollection(new Dictionary<string, object>
{
{ "key", "value" },
{ "string_array", new string[] { "a", "b" } },
})),
new ActivityEvent(
"Event2",
eventTimestamp,
new ActivityTagsCollection(new Dictionary<string, object>
{
{ "key", "value" },
})),
};
var linkedSpanId = ActivitySpanId.CreateFromString("888915b6286b9c41".AsSpan());
var activitySource = new ActivitySource(nameof(CreateTestActivity));
var tags = setAttributes ?
attributes
: null;
var links = addLinks ?
new[]
{
new ActivityLink(new ActivityContext(
traceId,
linkedSpanId,
ActivityTraceFlags.Recorded)),
}
: null;
var activity = activitySource.StartActivity(
"Name",
kind,
parentContext: new ActivityContext(traceId, parentSpanId, ActivityTraceFlags.Recorded),
tags,
links,
startTime: startTimestamp);
if (addEvents)
{
foreach (var evnt in events)
{
activity.AddEvent(evnt);
}
}
if (status.HasValue)
{
activity.SetStatus(status.Value);
}
activity.SetEndTime(endTimestamp);
activity.Stop();
return activity;
}
private long TimeSpanToMicroseconds(TimeSpan timeSpan)
{
return timeSpan.Ticks / (TimeSpan.TicksPerMillisecond / 1000);
}
public class RemoteEndpointPriorityTestCase
{
public string Name { get; set; }
public string ExpectedResult { get; set; }
public Dictionary<string, object> RemoteEndpointAttributes { get; set; }
public static IEnumerable<object[]> GetTestCases()
{
yield return new object[]
{
new RemoteEndpointPriorityTestCase
{
Name = "Highest priority name = net.peer.name",
ExpectedResult = "RemoteServiceName",
RemoteEndpointAttributes = new Dictionary<string, object>
{
["http.host"] = "DiscardedRemoteServiceName",
["net.peer.name"] = "RemoteServiceName",
["peer.hostname"] = "DiscardedRemoteServiceName",
},
},
};
yield return new object[]
{
new RemoteEndpointPriorityTestCase
{
Name = "Highest priority name = SemanticConventions.AttributePeerService",
ExpectedResult = "RemoteServiceName",
RemoteEndpointAttributes = new Dictionary<string, object>
{
[SemanticConventions.AttributePeerService] = "RemoteServiceName",
["http.host"] = "DiscardedRemoteServiceName",
["net.peer.name"] = "DiscardedRemoteServiceName",
["net.peer.port"] = "1234",
["peer.hostname"] = "DiscardedRemoteServiceName",
},
},
};
yield return new object[]
{
new RemoteEndpointPriorityTestCase
{
Name = "Only has net.peer.name and net.peer.port",
ExpectedResult = "RemoteServiceName:1234",
RemoteEndpointAttributes = new Dictionary<string, object>
{
["net.peer.name"] = "RemoteServiceName",
["net.peer.port"] = "1234",
},
},
};
yield return new object[]
{
new RemoteEndpointPriorityTestCase
{
Name = "net.peer.port is an int",
ExpectedResult = "RemoteServiceName:1234",
RemoteEndpointAttributes = new Dictionary<string, object>
{
["net.peer.name"] = "RemoteServiceName",
["net.peer.port"] = 1234,
},
},
};
yield return new object[]
{
new RemoteEndpointPriorityTestCase
{
Name = "Has net.peer.name and net.peer.port",
ExpectedResult = "RemoteServiceName:1234",
RemoteEndpointAttributes = new Dictionary<string, object>
{
["http.host"] = "DiscardedRemoteServiceName",
["net.peer.name"] = "RemoteServiceName",
["net.peer.port"] = "1234",
["peer.hostname"] = "DiscardedRemoteServiceName",
},
},
};
yield return new object[]
{
new RemoteEndpointPriorityTestCase
{
Name = "Has net.peer.ip and net.peer.port",
ExpectedResult = "1.2.3.4:1234",
RemoteEndpointAttributes = new Dictionary<string, object>
{
["http.host"] = "DiscardedRemoteServiceName",
["net.peer.ip"] = "1.2.3.4",
["net.peer.port"] = "1234",
["peer.hostname"] = "DiscardedRemoteServiceName",
},
},
};
yield return new object[]
{
new RemoteEndpointPriorityTestCase
{
Name = "Has net.peer.name, net.peer.ip, and net.peer.port",
ExpectedResult = "RemoteServiceName:1234",
RemoteEndpointAttributes = new Dictionary<string, object>
{
["http.host"] = "DiscardedRemoteServiceName",
["net.peer.name"] = "RemoteServiceName",
["net.peer.ip"] = "1.2.3.4",
["net.peer.port"] = "1234",
["peer.hostname"] = "DiscardedRemoteServiceName",
},
},
};
}
public override string ToString()
{
return this.Name;
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class RecordingProgressDecoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 102;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private RecordingProgressDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public RecordingProgressDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public RecordingProgressDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int RecordingIdId()
{
return 1;
}
public static int RecordingIdSinceVersion()
{
return 0;
}
public static int RecordingIdEncodingOffset()
{
return 0;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long RecordingId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int StartPositionId()
{
return 2;
}
public static int StartPositionSinceVersion()
{
return 0;
}
public static int StartPositionEncodingOffset()
{
return 8;
}
public static int StartPositionEncodingLength()
{
return 8;
}
public static string StartPositionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long StartPositionNullValue()
{
return -9223372036854775808L;
}
public static long StartPositionMinValue()
{
return -9223372036854775807L;
}
public static long StartPositionMaxValue()
{
return 9223372036854775807L;
}
public long StartPosition()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int PositionId()
{
return 3;
}
public static int PositionSinceVersion()
{
return 0;
}
public static int PositionEncodingOffset()
{
return 16;
}
public static int PositionEncodingLength()
{
return 8;
}
public static string PositionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long PositionNullValue()
{
return -9223372036854775808L;
}
public static long PositionMinValue()
{
return -9223372036854775807L;
}
public static long PositionMaxValue()
{
return 9223372036854775807L;
}
public long Position()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[RecordingProgress](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("RecordingId=");
builder.Append(RecordingId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='startPosition', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("StartPosition=");
builder.Append(StartPosition());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='position', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Position=");
builder.Append(Position());
Limit(originalLimit);
return builder;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HPSF.Extractor
{
using System;
using NUnit.Framework;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.FileSystem;
using System.IO;
using NPOI.HSSF.Extractor;
using NPOI.HPSF.Extractor;
using TestCases.HSSF;
using NPOI.HPSF;
[TestFixture]
public class TestHPSFPropertiesExtractor
{
private static POIDataSamples _samples = POIDataSamples.GetHPSFInstance();
[Test]
public void TestNormalProperties()
{
POIFSFileSystem fs = new POIFSFileSystem(_samples.OpenResourceAsStream("TestMickey.doc"));
HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs);
String text = ext.Text;
// Check each bit in turn
String sinfText = ext.SummaryInformationText;
String dinfText = ext.DocumentSummaryInformationText;
Assert.IsTrue(sinfText.IndexOf("TEMPLATE = Normal") > -1);
Assert.IsTrue(sinfText.IndexOf("SUBJECT = sample subject") > -1);
Assert.IsTrue(dinfText.IndexOf("MANAGER = sample manager") > -1);
Assert.IsTrue(dinfText.IndexOf("COMPANY = sample company") > -1);
// Now overall
text = ext.Text;
Assert.IsTrue(text.IndexOf("TEMPLATE = Normal") > -1);
Assert.IsTrue(text.IndexOf("SUBJECT = sample subject") > -1);
Assert.IsTrue(text.IndexOf("MANAGER = sample manager") > -1);
Assert.IsTrue(text.IndexOf("COMPANY = sample company") > -1);
}
[Test]
public void TestNormalUnicodeProperties()
{
POIFSFileSystem fs = new POIFSFileSystem(_samples.OpenResourceAsStream("TestUnicode.xls"));
HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs);
string text = ext.Text;
// Check each bit in turn
String sinfText = ext.SummaryInformationText;
String dinfText = ext.DocumentSummaryInformationText;
Assert.IsTrue(sinfText.IndexOf("AUTHOR = marshall") > -1);
Assert.IsTrue(sinfText.IndexOf("TITLE = Titel: \u00c4h") > -1);
Assert.IsTrue(dinfText.IndexOf("COMPANY = Schreiner") > -1);
Assert.IsTrue(dinfText.IndexOf("SCALE = False") > -1);
// Now overall
text = ext.Text;
Assert.IsTrue(text.IndexOf("AUTHOR = marshall") > -1);
Assert.IsTrue(text.IndexOf("TITLE = Titel: \u00c4h") > -1);
Assert.IsTrue(text.IndexOf("COMPANY = Schreiner") > -1);
Assert.IsTrue(text.IndexOf("SCALE = False") > -1);
}
[Test]
public void TestCustomProperties()
{
POIFSFileSystem fs = new POIFSFileSystem(
_samples.OpenResourceAsStream("TestMickey.doc")
);
HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs);
// Custom properties are part of the document info stream
String dinfText = ext.DocumentSummaryInformationText;
Assert.IsTrue(dinfText.IndexOf("Client = sample client") > -1);
Assert.IsTrue(dinfText.IndexOf("Division = sample division") > -1);
String text = ext.Text;
Assert.IsTrue(text.IndexOf("Client = sample client") > -1);
Assert.IsTrue(text.IndexOf("Division = sample division") > -1);
}
[Test]
public void TestConstructors()
{
POIFSFileSystem fs;
HSSFWorkbook wb;
try
{
fs = new POIFSFileSystem(_samples.OpenResourceAsStream("TestUnicode.xls"));
wb = new HSSFWorkbook(fs);
}
catch (IOException e)
{
throw new Exception("TestConstructors", e);
}
ExcelExtractor excelExt = new ExcelExtractor(wb);
String fsText;
HPSFPropertiesExtractor fsExt = new HPSFPropertiesExtractor(fs);
fsExt.SetFilesystem(null); // Don't close re-used test resources!
try
{
fsText = fsExt.Text;
}
finally
{
fsExt.Close();
}
String hwText;
HPSFPropertiesExtractor hwExt = new HPSFPropertiesExtractor(wb);
hwExt.SetFilesystem(null); // Don't close re-used test resources!
try
{
hwText = hwExt.Text;
}
finally
{
hwExt.Close();
}
String eeText;
HPSFPropertiesExtractor eeExt = new HPSFPropertiesExtractor(excelExt);
eeExt.SetFilesystem(null); // Don't close re-used test resources!
try
{
eeText = eeExt.Text;
}
finally
{
eeExt.Close();
}
Assert.AreEqual(fsText, hwText);
Assert.AreEqual(fsText, eeText);
Assert.IsTrue(fsText.IndexOf("AUTHOR = marshall") > -1);
Assert.IsTrue(fsText.IndexOf("TITLE = Titel: \u00c4h") > -1);
// Finally tidy
wb.Close();
}
[Test]
public void Test42726()
{
HPSFPropertiesExtractor ex = new HPSFPropertiesExtractor(HSSFTestDataSamples.OpenSampleWorkbook("42726.xls"));
String txt = ex.Text;
Assert.IsTrue(txt.IndexOf("PID_AUTHOR") != -1);
Assert.IsTrue(txt.IndexOf("PID_EDITTIME") != -1);
Assert.IsTrue(txt.IndexOf("PID_REVNUMBER") != -1);
Assert.IsTrue(txt.IndexOf("PID_THUMBNAIL") != -1);
}
[Test]
public void TestThumbnail()
{
POIFSFileSystem fs = new POIFSFileSystem(_samples.OpenResourceAsStream("TestThumbnail.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
Thumbnail thumbnail = new Thumbnail(wb.SummaryInformation.Thumbnail);
Assert.AreEqual(-1, thumbnail.ClipboardFormatTag);
Assert.AreEqual(3, thumbnail.GetClipboardFormat());
Assert.IsNotNull(thumbnail.GetThumbnailAsWMF());
//wb.Close();
}
[Test]
public void Test52258()
{
POIFSFileSystem fs = new POIFSFileSystem(_samples.OpenResourceAsStream("TestVisioWithCodepage.vsd"));
HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs);
try
{
Assert.IsNotNull(ext.DocSummaryInformation);
Assert.IsNotNull(ext.DocumentSummaryInformationText);
Assert.IsNotNull(ext.SummaryInformation);
Assert.IsNotNull(ext.SummaryInformationText);
Assert.IsNotNull(ext.Text);
}
finally
{
ext.Close();
}
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
/// <summary>
/// Defines a particular format for text, including font face, size, and style attributes.
/// </summary>
public sealed partial class Font : MarshalByRefObject, ICloneable, IDisposable, ISerializable
{
private IntPtr _nativeFont;
private float _fontSize;
private FontStyle _fontStyle;
private FontFamily _fontFamily;
private GraphicsUnit _fontUnit;
private byte _gdiCharSet = SafeNativeMethods.DEFAULT_CHARSET;
private bool _gdiVerticalFont;
private string _systemFontName = "";
private string _originalFontName;
// Return value is in Unit (the unit the font was created in)
/// <summary>
/// Gets the size of this <see cref='Font'/>.
/// </summary>
public float Size => _fontSize;
/// <summary>
/// Gets style information for this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public FontStyle Style => _fontStyle;
/// <summary>
/// Gets a value indicating whether this <see cref='System.Drawing.Font'/> is bold.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Bold => (Style & FontStyle.Bold) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is Italic.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Italic => (Style & FontStyle.Italic) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is strikeout (has a line through it).
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Strikeout => (Style & FontStyle.Strikeout) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is underlined.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Underline => (Style & FontStyle.Underline) != 0;
/// <summary>
/// Gets the <see cref='Drawing.FontFamily'/> of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public FontFamily FontFamily => _fontFamily;
/// <summary>
/// Gets the face name of this <see cref='Font'/> .
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
#if !NETCORE
[Editor ("System.Drawing.Design.FontNameEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))]
[TypeConverter (typeof (FontConverter.FontNameConverter))]
#endif
public string Name => FontFamily.Name;
/// <summary>
/// Gets the unit of measure for this <see cref='Font'/>.
/// </summary>
#if !NETCORE
[TypeConverter (typeof (FontConverter.FontUnitConverter))]
#endif
public GraphicsUnit Unit => _fontUnit;
/// <summary>
/// Returns the GDI char set for this instance of a font. This will only
/// be valid if this font was created from a classic GDI font definition,
/// like a LOGFONT or HFONT, or it was passed into the constructor.
///
/// This is here for compatibility with native Win32 intrinsic controls
/// on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public byte GdiCharSet => _gdiCharSet;
/// <summary>
/// Determines if this font was created to represent a GDI vertical font. This will only be valid if this font
/// was created from a classic GDIfont definition, like a LOGFONT or HFONT, or it was passed into the constructor.
///
/// This is here for compatibility with native Win32 intrinsic controls on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool GdiVerticalFont => _gdiVerticalFont;
/// <summary>
/// This property is required by the framework and not intended to be used directly.
/// </summary>
[Browsable(false)]
public string OriginalFontName => _originalFontName;
/// <summary>
/// Gets the name of this <see cref='Drawing.SystemFont'/>.
/// </summary>
[Browsable(false)]
public string SystemFontName => _systemFontName;
/// <summary>
/// Returns true if this <see cref='Font'/> is a SystemFont.
/// </summary>
[Browsable(false)]
public bool IsSystemFont => !string.IsNullOrEmpty(_systemFontName);
/// <summary>
/// Gets the height of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public int Height => (int)Math.Ceiling(GetHeight());
/// <summary>
/// Get native GDI+ object pointer. This property triggers the creation of the GDI+ native object if not initialized yet.
/// </summary>
internal IntPtr NativeFont => _nativeFont;
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
~Font() => Dispose(false);
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_nativeFont != IntPtr.Zero)
{
try
{
#if DEBUG
int status =
#endif
Gdip.GdipDeleteFont(new HandleRef(this, _nativeFont));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex) when (!ClientUtils.IsCriticalException(ex))
{
}
finally
{
_nativeFont = IntPtr.Zero;
}
}
}
/// <summary>
/// Returns the height of this Font in the specified graphics context.
/// </summary>
public float GetHeight(Graphics graphics)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
float height;
int status = Gdip.GdipGetFontHeight(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), out height);
Gdip.CheckStatus(status);
return height;
}
public float GetHeight(float dpi)
{
float size;
int status = Gdip.GdipGetFontHeightGivenDPI(new HandleRef(this, NativeFont), dpi, out size);
Gdip.CheckStatus(status);
return size;
}
/// <summary>
/// Returns a value indicating whether the specified object is a <see cref='Font'/> equivalent to this
/// <see cref='Font'/>.
/// </summary>
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
if (!(obj is Font font))
{
return false;
}
// Note: If this and/or the passed-in font are disposed, this method can still return true since we check for cached properties
// here.
// We need to call properties on the passed-in object since it could be a proxy in a remoting scenario and proxies don't
// have access to private/internal fields.
return font.FontFamily.Equals(FontFamily) &&
font.GdiVerticalFont == GdiVerticalFont &&
font.GdiCharSet == GdiCharSet &&
font.Style == Style &&
font.Size == Size &&
font.Unit == Unit;
}
/// <summary>
/// Gets the hash code for this <see cref='Font'/>.
/// </summary>
public override int GetHashCode()
{
return unchecked((int)((((uint)_fontStyle << 13) | ((uint)_fontStyle >> 19)) ^
(((uint)_fontUnit << 26) | ((uint)_fontUnit >> 6)) ^
(((uint)_fontSize << 7) | ((uint)_fontSize >> 25))));
}
/// <summary>
/// Returns a human-readable string representation of this <see cref='Font'/>.
/// </summary>
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2}, Units={3}, GdiCharSet={4}, GdiVerticalFont={5}]",
GetType().Name,
FontFamily.Name,
_fontSize,
(int)_fontUnit,
_gdiCharSet,
_gdiVerticalFont);
}
// This is used by SystemFonts when constructing a system Font objects.
internal void SetSystemFontName(string systemFontName) => _systemFontName = systemFontName;
}
}
| |
using UnityEngine;
using System;
using Cinemachine.Utility;
using UnityEngine.Serialization;
namespace Cinemachine
{
/// <summary>
/// A Cinemachine Virtual Camera Body component that constrains camera motion
/// to a CinemachinePath. The camera can move along the path.
///
/// This behaviour can operate in two modes: manual positioning, and Auto-Dolly positioning.
/// In Manual mode, the camera's position is specified by animating the Path Position field.
/// In Auto-Dolly mode, the Path Position field is animated automatically every frame by finding
/// the position on the path that's closest to the virtual camera's Follow target.
/// </summary>
[DocumentationSorting(7, DocumentationSortingAttribute.Level.UserRef)]
[AddComponentMenu("")] // Don't display in add component menu
[RequireComponent(typeof(CinemachinePipeline))]
[SaveDuringPlay]
public class CinemachineTrackedDolly : CinemachineComponentBase
{
/// <summary>The path to which the camera will be constrained. This must be non-null.</summary>
[Tooltip("The path to which the camera will be constrained. This must be non-null.")]
public CinemachinePathBase m_Path;
/// <summary>The position along the path at which the camera will be placed.
/// This can be animated directly, or set automatically by the Auto-Dolly feature
/// to get as close as possible to the Follow target.</summary>
[Tooltip("The position along the path at which the camera will be placed. This can be animated directly, or set automatically by the Auto-Dolly feature to get as close as possible to the Follow target. The value is interpreted according to the Position Units setting.")]
public float m_PathPosition;
/// <summary>How to interpret the Path Position</summary>
[Tooltip("How to interpret Path Position. If set to Path Units, values are as follows: 0 represents the first waypoint on the path, 1 is the second, and so on. Values in-between are points on the path in between the waypoints. If set to Distance, then Path Position represents distance along the path.")]
public CinemachinePathBase.PositionUnits m_PositionUnits = CinemachinePathBase.PositionUnits.PathUnits;
/// <summary>Where to put the camera realtive to the path postion. X is perpendicular to the path, Y is up, and Z is parallel to the path.</summary>
[Tooltip("Where to put the camera relative to the path position. X is perpendicular to the path, Y is up, and Z is parallel to the path. This allows the camera to be offset from the path itself (as if on a tripod, for example).")]
public Vector3 m_PathOffset = Vector3.zero;
/// <summary>How aggressively the camera tries to maintain the offset perpendicular to the path.
/// Small numbers are more responsive, rapidly translating the camera to keep the target's
/// x-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in a direction perpendicular to the path. Small numbers are more responsive, rapidly translating the camera to keep the target's x-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_XDamping = 0f;
/// <summary>How aggressively the camera tries to maintain the offset in the path-local up direction.
/// Small numbers are more responsive, rapidly translating the camera to keep the target's
/// y-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in the path-local up direction. Small numbers are more responsive, rapidly translating the camera to keep the target's y-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_YDamping = 0f;
/// <summary>How aggressively the camera tries to maintain the offset parallel to the path.
/// Small numbers are more responsive, rapidly translating the camera to keep the
/// target's z-axis offset. Larger numbers give a more heavy slowly responding camera.
/// Using different settings per axis can yield a wide range of camera behaviors</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to maintain its position in a direction parallel to the path. Small numbers are more responsive, rapidly translating the camera to keep the target's z-axis offset. Larger numbers give a more heavy slowly responding camera. Using different settings per axis can yield a wide range of camera behaviors.")]
public float m_ZDamping = 1f;
/// <summary>Different ways to set the camera's up vector</summary>
[DocumentationSorting(7.1f, DocumentationSortingAttribute.Level.UserRef)]
public enum CameraUpMode
{
/// <summary>Leave the camera's up vector alone. It will be set according to the Brain's WorldUp.</summary>
Default,
/// <summary>Take the up vector from the path's up vector at the current point</summary>
Path,
/// <summary>Take the up vector from the path's up vector at the current point, but with the roll zeroed out</summary>
PathNoRoll,
/// <summary>Take the up vector from the Follow target's up vector</summary>
FollowTarget,
/// <summary>Take the up vector from the Follow target's up vector, but with the roll zeroed out</summary>
FollowTargetNoRoll,
};
/// <summary>How to set the virtual camera's Up vector. This will affect the screen composition.</summary>
[Tooltip("How to set the virtual camera's Up vector. This will affect the screen composition, because the camera Aim behaviours will always try to respect the Up direction.")]
public CameraUpMode m_CameraUp = CameraUpMode.Default;
/// <summary>"How aggressively the camera tries to track the target rotation's X angle.
/// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to track the target rotation's X angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")]
public float m_PitchDamping = 0;
/// <summary>How aggressively the camera tries to track the target rotation's Y angle.
/// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to track the target rotation's Y angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")]
public float m_YawDamping = 0;
/// <summary>How aggressively the camera tries to track the target rotation's Z angle.
/// Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.</summary>
[Range(0f, 20f)]
[Tooltip("How aggressively the camera tries to track the target rotation's Z angle. Small numbers are more responsive. Larger numbers give a more heavy slowly responding camera.")]
public float m_RollDamping = 0f;
/// <summary>Controls how automatic dollying occurs</summary>
[DocumentationSorting(7.2f, DocumentationSortingAttribute.Level.UserRef)]
[Serializable]
public struct AutoDolly
{
/// <summary>If checked, will enable automatic dolly, which chooses a path position
/// that is as close as possible to the Follow target.</summary>
[Tooltip("If checked, will enable automatic dolly, which chooses a path position that is as close as possible to the Follow target. Note: this can have significant performance impact")]
public bool m_Enabled;
/// <summary>Offset, in current position units, from the closest point on the path to the follow target.</summary>
[Tooltip("Offset, in current position units, from the closest point on the path to the follow target")]
public float m_PositionOffset;
/// <summary>Search up to how many waypoints on either side of the current position. Use 0 for Entire path</summary>
[Tooltip("Search up to how many waypoints on either side of the current position. Use 0 for Entire path.")]
public int m_SearchRadius;
/// <summary>We search between waypoints by dividing the segment into this many straight pieces.
/// The higher the number, the more accurate the result, but performance is
/// proportionally slower for higher numbers</summary>
[FormerlySerializedAs("m_StepsPerSegment")]
[Tooltip("We search between waypoints by dividing the segment into this many straight pieces. The higher the number, the more accurate the result, but performance is proportionally slower for higher numbers")]
public int m_SearchResolution;
/// <summary>Constructor with specific field values</summary>
public AutoDolly(bool enabled, float positionOffset, int searchRadius, int stepsPerSegment)
{
m_Enabled = enabled;
m_PositionOffset = positionOffset;
m_SearchRadius = searchRadius;
m_SearchResolution = stepsPerSegment;
}
};
/// <summary>Controls how automatic dollying occurs</summary>
[Tooltip("Controls how automatic dollying occurs. A Follow target is necessary to use this feature.")]
public AutoDolly m_AutoDolly = new AutoDolly(false, 0, 2, 5);
/// <summary>True if component is enabled and has a path</summary>
public override bool IsValid { get { return enabled && m_Path != null; } }
/// <summary>Get the Cinemachine Pipeline stage that this component implements.
/// Always returns the Body stage</summary>
public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } }
/// <summary>Positions the virtual camera according to the transposer rules.</summary>
/// <param name="curState">The current camera state</param>
/// <param name="deltaTime">Used for damping. If less that 0, no damping is done.</param>
public override void MutateCameraState(ref CameraState curState, float deltaTime)
{
// Init previous frame state info
if (deltaTime < 0)
{
m_PreviousPathPosition = m_PathPosition;
m_PreviousCameraPosition = curState.RawPosition;
}
if (!IsValid)
return;
//UnityEngine.Profiling.Profiler.BeginSample("CinemachineTrackedDolly.MutateCameraState");
// Get the new ideal path base position
if (m_AutoDolly.m_Enabled && FollowTarget != null)
{
float prevPos = m_PreviousPathPosition;
if (m_PositionUnits == CinemachinePathBase.PositionUnits.Distance)
prevPos = m_Path.GetPathPositionFromDistance(prevPos);
// This works in path units
m_PathPosition = m_Path.FindClosestPoint(
FollowTarget.transform.position,
Mathf.FloorToInt(prevPos),
(deltaTime < 0 || m_AutoDolly.m_SearchRadius <= 0)
? -1 : m_AutoDolly.m_SearchRadius,
m_AutoDolly.m_SearchResolution);
if (m_PositionUnits == CinemachinePathBase.PositionUnits.Distance)
m_PathPosition = m_Path.GetPathDistanceFromPosition(m_PathPosition);
// Apply the path position offset
m_PathPosition += m_AutoDolly.m_PositionOffset;
}
float newPathPosition = m_PathPosition;
if (deltaTime >= 0)
{
// Normalize previous position to find the shortest path
float maxUnit = m_Path.MaxUnit(m_PositionUnits);
if (maxUnit > 0)
{
float prev = m_Path.NormalizeUnit(m_PreviousPathPosition, m_PositionUnits);
float next = m_Path.NormalizeUnit(newPathPosition, m_PositionUnits);
if (m_Path.Looped && Mathf.Abs(next - prev) > maxUnit / 2)
{
if (next > prev)
prev += maxUnit;
else
prev -= maxUnit;
}
m_PreviousPathPosition = prev;
newPathPosition = next;
}
// Apply damping along the path direction
float offset = m_PreviousPathPosition - newPathPosition;
offset = Damper.Damp(offset, m_ZDamping, deltaTime);
newPathPosition = m_PreviousPathPosition - offset;
}
m_PreviousPathPosition = newPathPosition;
Quaternion newPathOrientation = m_Path.EvaluateOrientationAtUnit(newPathPosition, m_PositionUnits);
// Apply the offset to get the new camera position
Vector3 newCameraPos = m_Path.EvaluatePositionAtUnit(newPathPosition, m_PositionUnits);
Vector3 offsetX = newPathOrientation * Vector3.right;
Vector3 offsetY = newPathOrientation * Vector3.up;
Vector3 offsetZ = newPathOrientation * Vector3.forward;
newCameraPos += m_PathOffset.x * offsetX;
newCameraPos += m_PathOffset.y * offsetY;
newCameraPos += m_PathOffset.z * offsetZ;
// Apply damping to the remaining directions
if (deltaTime >= 0)
{
Vector3 currentCameraPos = m_PreviousCameraPosition;
Vector3 delta = (currentCameraPos - newCameraPos);
Vector3 delta1 = Vector3.Dot(delta, offsetY) * offsetY;
Vector3 delta0 = delta - delta1;
delta0 = Damper.Damp(delta0, m_XDamping, deltaTime);
delta1 = Damper.Damp(delta1, m_YDamping, deltaTime);
newCameraPos = currentCameraPos - (delta0 + delta1);
}
curState.RawPosition = m_PreviousCameraPosition = newCameraPos;
// Set the orientation and up
Quaternion newOrientation
= GetTargetOrientationAtPathPoint(newPathOrientation, curState.ReferenceUp);
if (deltaTime < 0)
m_PreviousOrientation = newOrientation;
else
{
if (deltaTime >= 0)
{
Vector3 relative = (Quaternion.Inverse(m_PreviousOrientation)
* newOrientation).eulerAngles;
for (int i = 0; i < 3; ++i)
if (relative[i] > 180)
relative[i] -= 360;
relative = Damper.Damp(relative, AngularDamping, deltaTime);
newOrientation = m_PreviousOrientation * Quaternion.Euler(relative);
}
m_PreviousOrientation = newOrientation;
}
curState.RawOrientation = newOrientation;
curState.ReferenceUp = curState.RawOrientation * Vector3.up;
//UnityEngine.Profiling.Profiler.EndSample();
}
/// <summary>API for the editor, to process a position drag from the user.
/// This implementation adds the delta to the follow offset.</summary>
/// <param name="delta">The amount dragged this frame</param>
public override void OnPositionDragged(Vector3 delta)
{
Quaternion targetOrientation = m_Path.EvaluateOrientationAtUnit(m_PathPosition, m_PositionUnits);
Vector3 localOffset = Quaternion.Inverse(targetOrientation) * delta;
m_PathOffset += localOffset;
}
private Quaternion GetTargetOrientationAtPathPoint(Quaternion pathOrientation, Vector3 up)
{
switch (m_CameraUp)
{
default:
case CameraUpMode.Default: break;
case CameraUpMode.Path: return pathOrientation;
case CameraUpMode.PathNoRoll:
return Quaternion.LookRotation(pathOrientation * Vector3.forward, up);
case CameraUpMode.FollowTarget:
if (FollowTarget != null)
return FollowTarget.rotation;
break;
case CameraUpMode.FollowTargetNoRoll:
if (FollowTarget != null)
return Quaternion.LookRotation(FollowTarget.rotation * Vector3.forward, up);
break;
}
return Quaternion.LookRotation(transform.rotation * Vector3.forward, up);
}
private Vector3 AngularDamping
{
get
{
switch (m_CameraUp)
{
case CameraUpMode.PathNoRoll:
case CameraUpMode.FollowTargetNoRoll:
return new Vector3(m_PitchDamping, m_YawDamping, 0);
case CameraUpMode.Default:
return Vector3.zero;
default:
return new Vector3(m_PitchDamping, m_YawDamping, m_RollDamping);
}
}
}
private float m_PreviousPathPosition = 0;
Quaternion m_PreviousOrientation = Quaternion.identity;
private Vector3 m_PreviousCameraPosition = Vector3.zero;
}
}
| |
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.RabbitMqTransport.Integration
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Contexts;
using GreenPipes;
using Logging;
using RabbitMQ.Client;
using Specifications;
using Topology;
using Util;
/// <summary>
/// Caches the models for sending that have already been created, so that the model
/// is retained and configured using an existing connection
/// </summary>
public class RabbitMqModelCache :
IModelCache
{
static readonly ILog _log = Logger.Get<RabbitMqModelCache>();
readonly ITaskScope _cacheTaskScope;
readonly IRabbitMqHost _host;
readonly IRabbitMqTopology _topology;
readonly object _scopeLock = new object();
ModelScope _scope;
public RabbitMqModelCache(IRabbitMqHost host, IRabbitMqTopology topology)
{
_host = host;
_topology = topology;
_cacheTaskScope = host.Supervisor.CreateScope($"{TypeMetadataCache<RabbitMqModelCache>.ShortName}", CloseScope);
}
public Task Send(IPipe<ModelContext> connectionPipe, CancellationToken cancellationToken)
{
ModelScope newScope = null;
ModelScope existingScope;
lock (_scopeLock)
{
existingScope = _scope;
if (existingScope == null || existingScope.IsShuttingDown)
{
newScope = new ModelScope(_cacheTaskScope);
_scope = newScope;
}
}
if (existingScope != null)
return SendUsingExistingModel(connectionPipe, existingScope, cancellationToken);
return SendUsingNewModel(connectionPipe, newScope, cancellationToken);
}
public async Task Close()
{
Interlocked.Exchange(ref _scope, null);
_cacheTaskScope.Stop(new StopEventArgs("Closed by owner"));
}
Task CloseScope()
{
return TaskUtil.Completed;
}
async Task SendUsingNewModel(IPipe<ModelContext> modelPipe, ModelScope scope, CancellationToken cancellationToken)
{
IPipe<ConnectionContext> connectionPipe = Pipe.ExecuteAsync<ConnectionContext>(async connectionContext =>
{
IModel model = null;
try
{
if (_log.IsDebugEnabled)
_log.DebugFormat("Creating model: {0}", connectionContext.HostSettings.ToDebugString());
model = await connectionContext.CreateModel().ConfigureAwait(false);
EventHandler<ShutdownEventArgs> modelShutdown = null;
modelShutdown = (obj, reason) =>
{
model.ModelShutdown -= modelShutdown;
Interlocked.CompareExchange(ref _scope, null, scope);
scope.Shutdown(reason.ReplyText);
};
model.ModelShutdown += modelShutdown;
var modelContext = new RabbitMqModelContext(connectionContext, model, _cacheTaskScope, _host, _topology);
scope.Created(modelContext);
}
catch (Exception ex)
{
Interlocked.CompareExchange(ref _scope, null, scope);
scope.CreateFaulted(ex);
model?.Dispose();
throw;
}
await SendUsingExistingModel(modelPipe, scope, cancellationToken).ConfigureAwait(false);
});
try
{
await _host.ConnectionCache.Send(connectionPipe, _cacheTaskScope.StoppedToken).ConfigureAwait(false);
}
catch (Exception exception)
{
if (_log.IsDebugEnabled)
_log.Debug("The connection threw an exception", exception);
Interlocked.CompareExchange(ref _scope, null, scope);
scope.CreateFaulted(exception);
throw;
}
}
async Task SendUsingExistingModel(IPipe<ModelContext> modelPipe, ModelScope scope, CancellationToken cancellationToken)
{
try
{
using (var context = await scope.Attach(cancellationToken).ConfigureAwait(false))
{
// if (_log.IsDebugEnabled)
// _log.DebugFormat("Using model: {0}", ((ModelContext)context).ConnectionContext.HostSettings.ToDebugString());
await modelPipe.Send(context).ConfigureAwait(false);
}
}
catch (Exception exception)
{
if (_log.IsDebugEnabled)
_log.Debug("The model usage threw an exception", exception);
Interlocked.CompareExchange(ref _scope, null, scope);
scope.CreateFaulted(exception);
throw;
}
}
class ModelScope
{
readonly TaskCompletionSource<RabbitMqModelContext> _modelContext;
readonly ITaskScope _taskScope;
public ModelScope(ITaskScope supervisor)
{
_modelContext = new TaskCompletionSource<RabbitMqModelContext>();
_taskScope = supervisor.CreateScope("ModelScope", CloseContext);
}
public bool IsShuttingDown => _taskScope.StoppingToken.IsCancellationRequested;
public void Created(RabbitMqModelContext connectionContext)
{
_modelContext.TrySetResult(connectionContext);
_taskScope.SetReady();
}
public void CreateFaulted(Exception exception)
{
_modelContext.TrySetException(exception);
_taskScope.SetNotReady(exception);
_taskScope.Stop(new StopEventArgs($"Model faulted: {exception.Message}"));
}
public async Task<SharedModelContext> Attach(CancellationToken cancellationToken)
{
var modelContext = await _modelContext.Task.ConfigureAwait(false);
return new SharedModelContext(modelContext, cancellationToken, _taskScope);
}
public void Shutdown(string reason)
{
_taskScope.Stop(new StopEventArgs(reason));
}
async Task CloseContext()
{
if (_modelContext.Task.Status == TaskStatus.RanToCompletion)
{
try
{
var modelContext = await _modelContext.Task.ConfigureAwait(false);
if (_log.IsDebugEnabled)
_log.DebugFormat("Disposing model: {0}", ((ModelContext)modelContext).ConnectionContext.HostSettings.ToDebugString());
modelContext.Dispose();
}
catch (Exception exception)
{
if (_log.IsWarnEnabled)
_log.Warn("The model failed to be disposed", exception);
}
}
}
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// String.System.IConvertible.ToByte(IFormatProvider provider)
/// This method supports the .NET Framework infrastructure and is
/// not intended to be used directly from your code.
/// Converts the value of the current String object to an 8-bit unsigned integer.
/// </summary>
class IConvertibleToByte
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
public static int Main()
{
IConvertibleToByte iege = new IConvertibleToByte();
TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToByte(IFormatProvider)");
if (iege.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive test scenarioes
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Random numeric string";
const string c_TEST_ID = "P001";
string strSrc;
IFormatProvider provider;
byte b;
bool expectedValue = true;
bool actualValue = false;
b = TestLibrary.Generator.GetByte(-55);
strSrc = b.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (b == ((IConvertible)strSrc).ToByte(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Positive sign";
const string c_TEST_ID = "P002";
string strSrc;
IFormatProvider provider;
NumberFormatInfo ni = new NumberFormatInfo();
byte b;
bool expectedValue = true;
bool actualValue = false;
b = TestLibrary.Generator.GetByte(-55);
ni.PositiveSign = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSrc = ni.PositiveSign + b.ToString();
provider = (IFormatProvider)ni;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (b == ((IConvertible)strSrc).ToByte(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: string is Byte.MaxValue";
const string c_TEST_ID = "P003";
string strSrc;
IFormatProvider provider;
bool expectedValue = true;
bool actualValue = false;
strSrc = byte.MaxValue.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (byte.MaxValue == ((IConvertible)strSrc).ToByte(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: string is Byte.MinValue";
const string c_TEST_ID = "P004";
string strSrc;
IFormatProvider provider;
bool expectedValue = true;
bool actualValue = false;
strSrc = byte.MinValue.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (byte.MinValue == ((IConvertible)strSrc).ToByte(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
#endregion // end for positive test scenarioes
#region Negative test scenarios
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed";
const string c_TEST_ID = "N001";
string strSrc;
IFormatProvider provider;
strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN);
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToByte(provider);
TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue";
const string c_TEST_ID = "N002";
string strSrc;
IFormatProvider provider;
int i;
i = byte.MaxValue + 1 + TestLibrary.Generator.GetByte(-55);
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToByte(provider);
TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue";
const string c_TEST_ID = "N003";
string strSrc;
IFormatProvider provider;
int i;
// new update 8-14-2006 Noter(v-yaduoj)
i = -1*TestLibrary.Generator.GetByte(-55) - 1;
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToByte(provider);
TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
#endregion
private string GetDataString(string strSrc, IFormatProvider provider)
{
string str1, str2, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str2 = (null == provider) ? "null" : provider.ToString();
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Format provider string]\n {0}", str2);
return str;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Diagnostics;
using System.Text;
namespace System
{
// 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]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class Version : ICloneable, IComparable, IComparable<Version>, IEquatable<Version>, ISpanFormattable
{
// AssemblyName depends on the order staying the same
private readonly int _Major; // Do not rename (binary serialization)
private readonly int _Minor; // Do not rename (binary serialization)
private readonly int _Build = -1; // Do not rename (binary serialization)
private readonly int _Revision = -1; // Do not rename (binary serialization)
public Version(int major, int minor, int build, int revision)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
if (revision < 0)
throw new ArgumentOutOfRangeException(nameof(revision), SR.ArgumentOutOfRange_Version);
_Major = major;
_Minor = minor;
_Build = build;
_Revision = revision;
}
public Version(int major, int minor, int build)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
_Major = major;
_Minor = minor;
_Build = build;
}
public Version(int major, int minor)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
_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;
}
public object Clone()
{
return new Version(this);
}
// 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 int CompareTo(Object version)
{
if (version == null)
{
return 1;
}
Version v = version as Version;
if (v == null)
{
throw new ArgumentException(SR.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() =>
ToString(DefaultFormatFieldCount);
public string ToString(int fieldCount) =>
fieldCount == 0 ? string.Empty :
fieldCount == 1 ? _Major.ToString() :
StringBuilderCache.GetStringAndRelease(ToCachedStringBuilder(fieldCount));
public bool TryFormat(Span<char> destination, out int charsWritten) =>
TryFormat(destination, DefaultFormatFieldCount, out charsWritten);
public bool TryFormat(Span<char> destination, int fieldCount, out int charsWritten)
{
if (fieldCount == 0)
{
charsWritten = 0;
return true;
}
else if (fieldCount == 1)
{
return _Major.TryFormat(destination, out charsWritten);
}
StringBuilder sb = ToCachedStringBuilder(fieldCount);
if (sb.Length <= destination.Length)
{
sb.CopyTo(0, destination, sb.Length);
StringBuilderCache.Release(sb);
charsWritten = sb.Length;
return true;
}
StringBuilderCache.Release(sb);
charsWritten = 0;
return false;
}
bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider provider)
{
// format and provider are ignored.
return TryFormat(destination, out charsWritten);
}
private int DefaultFormatFieldCount =>
_Build == -1 ? 2 :
_Revision == -1 ? 3 :
4;
private StringBuilder ToCachedStringBuilder(int fieldCount)
{
// 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.
if (fieldCount == 2)
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(_Major);
sb.Append('.');
sb.Append(_Minor);
return sb;
}
else
{
if (_Build == -1)
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), nameof(fieldCount));
}
if (fieldCount == 3)
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(_Major);
sb.Append('.');
sb.Append(_Minor);
sb.Append('.');
sb.Append(_Build);
return sb;
}
if (_Revision == -1)
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), nameof(fieldCount));
}
if (fieldCount == 4)
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(_Major);
sb.Append('.');
sb.Append(_Minor);
sb.Append('.');
sb.Append(_Build);
sb.Append('.');
sb.Append(_Revision);
return sb;
}
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), nameof(fieldCount));
}
}
public static Version Parse(string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
return ParseVersion(input.AsSpan(), throwOnFailure: true);
}
public static Version Parse(ReadOnlySpan<char> input) =>
ParseVersion(input, throwOnFailure: true);
public static bool TryParse(string input, out Version result)
{
if (input == null)
{
result = null;
return false;
}
return (result = ParseVersion(input.AsSpan(), throwOnFailure: false)) != null;
}
public static bool TryParse(ReadOnlySpan<char> input, out Version result) =>
(result = ParseVersion(input, throwOnFailure: false)) != null;
private static Version ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure)
{
// Find the separator between major and minor. It must exist.
int majorEnd = input.IndexOf('.');
if (majorEnd < 0)
{
if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
return null;
}
// Find the ends of the optional minor and build portions.
// We musn't have any separators after build.
int buildEnd = -1;
int minorEnd = input.Slice(majorEnd + 1).IndexOf('.');
if (minorEnd != -1)
{
minorEnd += (majorEnd + 1);
buildEnd = input.Slice(minorEnd + 1).IndexOf('.');
if (buildEnd != -1)
{
buildEnd += (minorEnd + 1);
if (input.Slice(buildEnd + 1).IndexOf('.') != -1)
{
if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
return null;
}
}
}
int minor, build, revision;
// Parse the major version
if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out int major))
{
return null;
}
if (minorEnd != -1)
{
// If there's more than a major and minor, parse the minor, too.
if (!TryParseComponent(input.Slice(majorEnd + 1, minorEnd - majorEnd - 1), nameof(input), throwOnFailure, out minor))
{
return null;
}
if (buildEnd != -1)
{
// major.minor.build.revision
return
TryParseComponent(input.Slice(minorEnd + 1, buildEnd - minorEnd - 1), nameof(build), throwOnFailure, out build) &&
TryParseComponent(input.Slice(buildEnd + 1), nameof(revision), throwOnFailure, out revision) ?
new Version(major, minor, build, revision) :
null;
}
else
{
// major.minor.build
return TryParseComponent(input.Slice(minorEnd + 1), nameof(build), throwOnFailure, out build) ?
new Version(major, minor, build) :
null;
}
}
else
{
// major.minor
return TryParseComponent(input.Slice(majorEnd + 1), nameof(input), throwOnFailure, out minor) ?
new Version(major, minor) :
null;
}
}
private static bool TryParseComponent(ReadOnlySpan<char> component, string componentName, bool throwOnFailure, out int parsedComponent)
{
if (throwOnFailure)
{
if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0)
{
throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version);
}
return true;
}
return int.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent) && parsedComponent >= 0;
}
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));
return (v1.CompareTo(v2) < 0);
}
public static bool operator <=(Version v1, Version v2)
{
if ((Object)v1 == null)
throw new ArgumentNullException(nameof(v1));
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);
}
}
}
| |
// 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,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Uwp.Interpreter {
class PythonUwpInterpreter : IPythonInterpreter, IPythonInterpreterWithProjectReferences2, IDisposable {
readonly Version _langVersion;
private PythonInterpreterFactoryWithDatabase _factory;
private PythonTypeDatabase _typeDb;
private HashSet<ProjectReference> _references;
public PythonUwpInterpreter(PythonInterpreterFactoryWithDatabase factory) {
_langVersion = factory.Configuration.Version;
_factory = factory;
_typeDb = _factory.GetCurrentDatabase();
_factory.NewDatabaseAvailable += OnNewDatabaseAvailable;
}
private void OnNewDatabaseAvailable(object sender, EventArgs e) {
var factory = _factory;
if (factory == null) {
// We have been disposed already, so ignore this event
return;
}
var evt = ModuleNamesChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
#region IPythonInterpreter Members
public IPythonType GetBuiltinType(BuiltinTypeId id) {
if (id == BuiltinTypeId.Unknown) {
return null;
}
if (_typeDb == null) {
throw new KeyNotFoundException(string.Format("{0} ({1})", id, (int)id));
}
var name = GetBuiltinTypeName(id, _typeDb.LanguageVersion);
var res = _typeDb.BuiltinModule.GetAnyMember(name) as IPythonType;
if (res == null) {
throw new KeyNotFoundException(string.Format("{0} ({1})", id, (int)id));
}
return res;
}
public IList<string> GetModuleNames() {
if (_typeDb == null) {
return new string[0];
}
return new List<string>(_typeDb.GetModuleNames());
}
public IPythonModule ImportModule(string name) {
if (_typeDb == null) {
return null;
}
return _typeDb.GetModule(name);
}
public IModuleContext CreateModuleContext() {
return null;
}
public void Initialize(PythonAnalyzer state) {
}
public event EventHandler ModuleNamesChanged;
public Task AddReferenceAsync(ProjectReference reference, CancellationToken cancellationToken = default(CancellationToken)) {
if (reference == null) {
return MakeExceptionTask(new ArgumentNullException("reference"));
}
if (_references == null) {
_references = new HashSet<ProjectReference>();
// If we needed to set _references, then we also need to clone
// _typeDb to avoid adding modules to the shared database.
if (_typeDb != null) {
_typeDb = _typeDb.Clone();
}
}
switch (reference.Kind) {
case ProjectReferenceKind.ExtensionModule:
_references.Add(reference);
string filename;
try {
filename = Path.GetFileNameWithoutExtension(reference.Name);
} catch (Exception e) {
return MakeExceptionTask(e);
}
if (_typeDb != null) {
return Task.Factory.StartNew(EmptyTask);
}
break;
}
return Task.Factory.StartNew(EmptyTask);
}
public void RemoveReference(ProjectReference reference) {
switch (reference.Kind) {
case ProjectReferenceKind.ExtensionModule:
if (_references != null && _references.Remove(reference) && _typeDb != null) {
RaiseModulesChanged(null);
}
break;
}
}
public IEnumerable<ProjectReference> GetReferences() {
return _references != null ? _references : Enumerable.Empty<ProjectReference>();
}
private static Task MakeExceptionTask(Exception e) {
var res = new TaskCompletionSource<Task>();
res.SetException(e);
return res.Task;
}
private static void EmptyTask() {
}
private void RaiseModulesChanged(Task task) {
if (task != null && task.Exception != null) {
throw task.Exception;
}
var modNamesChanged = ModuleNamesChanged;
if (modNamesChanged != null) {
modNamesChanged(this, EventArgs.Empty);
}
}
public static string GetBuiltinTypeName(BuiltinTypeId id, Version languageVersion) {
string name;
switch (id) {
case BuiltinTypeId.Bool: name = "bool"; break;
case BuiltinTypeId.Complex: name = "complex"; break;
case BuiltinTypeId.Dict: name = "dict"; break;
case BuiltinTypeId.Float: name = "float"; break;
case BuiltinTypeId.Int: name = "int"; break;
case BuiltinTypeId.List: name = "list"; break;
case BuiltinTypeId.Long: name = languageVersion.Major == 3 ? "int" : "long"; break;
case BuiltinTypeId.Object: name = "object"; break;
case BuiltinTypeId.Set: name = "set"; break;
case BuiltinTypeId.Str: name = "str"; break;
case BuiltinTypeId.Unicode: name = languageVersion.Major == 3 ? "str" : "unicode"; break;
case BuiltinTypeId.Bytes: name = languageVersion.Major == 3 ? "bytes" : "str"; break;
case BuiltinTypeId.Tuple: name = "tuple"; break;
case BuiltinTypeId.Type: name = "type"; break;
case BuiltinTypeId.BuiltinFunction: name = "builtin_function"; break;
case BuiltinTypeId.BuiltinMethodDescriptor: name = "builtin_method_descriptor"; break;
case BuiltinTypeId.DictKeys: name = "dict_keys"; break;
case BuiltinTypeId.DictValues: name = "dict_values"; break;
case BuiltinTypeId.DictItems: name = "dict_items"; break;
case BuiltinTypeId.Function: name = "function"; break;
case BuiltinTypeId.Generator: name = "generator"; break;
case BuiltinTypeId.NoneType: name = "NoneType"; break;
case BuiltinTypeId.Ellipsis: name = "ellipsis"; break;
case BuiltinTypeId.Module: name = "module_type"; break;
case BuiltinTypeId.ListIterator: name = "list_iterator"; break;
case BuiltinTypeId.TupleIterator: name = "tuple_iterator"; break;
case BuiltinTypeId.SetIterator: name = "set_iterator"; break;
case BuiltinTypeId.StrIterator: name = "str_iterator"; break;
case BuiltinTypeId.UnicodeIterator: name = languageVersion.Major == 3 ? "str_iterator" : "unicode_iterator"; break;
case BuiltinTypeId.BytesIterator: name = languageVersion.Major == 3 ? "bytes_iterator" : "str_iterator"; break;
case BuiltinTypeId.CallableIterator: name = "callable_iterator"; break;
case BuiltinTypeId.Property: name = "property"; break;
case BuiltinTypeId.ClassMethod: name = "classmethod"; break;
case BuiltinTypeId.StaticMethod: name = "staticmethod"; break;
case BuiltinTypeId.FrozenSet: name = "frozenset"; break;
case BuiltinTypeId.Unknown:
default:
return null;
}
return name;
}
#endregion
public void Dispose() {
_typeDb = null;
var factory = _factory;
_factory = null;
if (factory != null) {
factory.NewDatabaseAvailable -= OnNewDatabaseAvailable;
}
}
}
}
| |
using Lucene.Net.Documents;
namespace Lucene.Net.Search
{
using NUnit.Framework;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
/*
* 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 Field = Field;
using FieldInvertState = Lucene.Net.Index.FieldInvertState;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Term = Lucene.Net.Index.Term;
/// <summary>
/// Similarity unit test.
///
///
/// </summary>
[TestFixture]
public class TestSimilarity : LuceneTestCase
{
public class SimpleSimilarity : DefaultSimilarity
{
public override float QueryNorm(float sumOfSquaredWeights)
{
return 1.0f;
}
public override float Coord(int overlap, int maxOverlap)
{
return 1.0f;
}
public override float LengthNorm(FieldInvertState state)
{
return state.Boost;
}
public override float Tf(float freq)
{
return freq;
}
public override float SloppyFreq(int distance)
{
return 2.0f;
}
public override float Idf(long docFreq, long numDocs)
{
return 1.0f;
}
public override Explanation IdfExplain(CollectionStatistics collectionStats, TermStatistics[] stats)
{
return new Explanation(1.0f, "Inexplicable");
}
}
[Test]
public virtual void TestSimilarity_Mem()
{
Directory store = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), store, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetSimilarity(new SimpleSimilarity()));
Document d1 = new Document();
d1.Add(NewTextField("field", "a c", Field.Store.YES));
Document d2 = new Document();
d2.Add(NewTextField("field", "a b c", Field.Store.YES));
writer.AddDocument(d1);
writer.AddDocument(d2);
IndexReader reader = writer.Reader;
writer.Dispose();
IndexSearcher searcher = NewSearcher(reader);
searcher.Similarity = new SimpleSimilarity();
Term a = new Term("field", "a");
Term b = new Term("field", "b");
Term c = new Term("field", "c");
searcher.Search(new TermQuery(b), new CollectorAnonymousInnerClassHelper(this));
BooleanQuery bq = new BooleanQuery();
bq.Add(new TermQuery(a), BooleanClause.Occur.SHOULD);
bq.Add(new TermQuery(b), BooleanClause.Occur.SHOULD);
//System.out.println(bq.toString("field"));
searcher.Search(bq, new CollectorAnonymousInnerClassHelper2(this));
PhraseQuery pq = new PhraseQuery();
pq.Add(a);
pq.Add(c);
//System.out.println(pq.toString("field"));
searcher.Search(pq, new CollectorAnonymousInnerClassHelper3(this));
pq.Slop = 2;
//System.out.println(pq.toString("field"));
searcher.Search(pq, new CollectorAnonymousInnerClassHelper4(this));
reader.Dispose();
store.Dispose();
}
private class CollectorAnonymousInnerClassHelper : Collector
{
private readonly TestSimilarity OuterInstance;
public CollectorAnonymousInnerClassHelper(TestSimilarity outerInstance)
{
this.OuterInstance = outerInstance;
}
private Scorer scorer;
public override Scorer Scorer
{
set
{
this.scorer = value;
}
}
public override void Collect(int doc)
{
Assert.AreEqual(1.0f, scorer.Score(), 0);
}
public override AtomicReaderContext NextReader
{
set
{
}
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
private class CollectorAnonymousInnerClassHelper2 : Collector
{
private readonly TestSimilarity OuterInstance;
public CollectorAnonymousInnerClassHelper2(TestSimilarity outerInstance)
{
this.OuterInstance = outerInstance;
@base = 0;
}
private int @base;
private Scorer scorer;
public override Scorer Scorer
{
set
{
this.scorer = value;
}
}
public override void Collect(int doc)
{
//System.out.println("Doc=" + doc + " score=" + score);
Assert.AreEqual((float)doc + @base + 1, scorer.Score(), 0);
}
public override AtomicReaderContext NextReader
{
set
{
@base = value.DocBase;
}
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
private class CollectorAnonymousInnerClassHelper3 : Collector
{
private readonly TestSimilarity OuterInstance;
public CollectorAnonymousInnerClassHelper3(TestSimilarity outerInstance)
{
this.OuterInstance = outerInstance;
}
private Scorer scorer;
public override Scorer Scorer
{
set
{
this.scorer = value;
}
}
public override void Collect(int doc)
{
//System.out.println("Doc=" + doc + " score=" + score);
Assert.AreEqual(1.0f, scorer.Score(), 0);
}
public override AtomicReaderContext NextReader
{
set
{
}
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
private class CollectorAnonymousInnerClassHelper4 : Collector
{
private readonly TestSimilarity OuterInstance;
public CollectorAnonymousInnerClassHelper4(TestSimilarity outerInstance)
{
this.OuterInstance = outerInstance;
}
private Scorer scorer;
public override Scorer Scorer
{
set
{
this.scorer = value;
}
}
public override void Collect(int doc)
{
//System.out.println("Doc=" + doc + " score=" + score);
Assert.AreEqual(2.0f, scorer.Score(), 0);
}
public override AtomicReaderContext NextReader
{
set
{
}
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
namespace InControl
{
public sealed class AutoDiscover : Attribute
{
}
public class UnityInputDeviceProfile
{
public string Name { get; protected set; }
public string Meta { get; protected set; }
public InputControlMapping[] AnalogMappings { get; protected set; }
public InputControlMapping[] ButtonMappings { get; protected set; }
protected string[] SupportedPlatforms;
protected string[] JoystickNames;
protected string RegexName;
static HashSet<Type> hideList = new HashSet<Type>();
float sensitivity;
float lowerDeadZone;
float upperDeadZone;
public UnityInputDeviceProfile()
{
Name = "";
Meta = "";
sensitivity = 1.0f;
lowerDeadZone = 0.2f;
upperDeadZone = 0.9f;
}
public float Sensitivity
{
get { return sensitivity; }
protected set { sensitivity = Mathf.Clamp01( value ); }
}
public float LowerDeadZone
{
get { return lowerDeadZone; }
protected set { lowerDeadZone = Mathf.Clamp01( value ); }
}
public float UpperDeadZone
{
get { return upperDeadZone; }
protected set { upperDeadZone = Mathf.Clamp01( value ); }
}
public bool IsSupportedOnThisPlatform
{
get
{
if (SupportedPlatforms == null || SupportedPlatforms.Length == 0)
{
return true;
}
foreach (var platform in SupportedPlatforms)
{
if (InputManager.Platform.Contains( platform.ToUpper() ))
{
return true;
}
}
return false;
}
}
public bool IsJoystick
{
get
{
return (RegexName != null) || (JoystickNames != null && JoystickNames.Length > 0);
}
}
public bool IsNotJoystick
{
get { return !IsJoystick; }
}
public bool HasJoystickName( string joystickName )
{
if (IsNotJoystick)
{
return false;
}
if (JoystickNames == null)
{
return false;
}
return JoystickNames.Contains( joystickName, StringComparer.OrdinalIgnoreCase );
}
public bool HasRegexName( string joystickName )
{
if (IsNotJoystick)
{
return false;
}
if (RegexName == null)
{
return false;
}
return Regex.IsMatch( joystickName, RegexName, RegexOptions.IgnoreCase );
}
public bool HasJoystickOrRegexName( string joystickName )
{
return HasJoystickName( joystickName ) || HasRegexName( joystickName );
}
public static void Hide( Type type )
{
hideList.Add( type );
}
public bool IsHidden
{
get { return hideList.Contains( GetType() ); }
}
#region InputControlSource Helpers
protected static InputControlSource Button( int index )
{
return new UnityButtonSource( index );
}
protected static InputControlSource Analog( int index )
{
return new UnityAnalogSource( index );
}
protected static InputControlSource KeyCodeButton( KeyCode keyCode )
{
return new UnityKeyCodeSource( keyCode );
}
protected static InputControlSource KeyCodeAxis( KeyCode negativeKeyCode, KeyCode positiveKeyCode )
{
return new UnityKeyCodeAxisSource( negativeKeyCode, positiveKeyCode );
}
protected static InputControlSource Button0 = Button( 0 );
protected static InputControlSource Button1 = Button( 1 );
protected static InputControlSource Button2 = Button( 2 );
protected static InputControlSource Button3 = Button( 3 );
protected static InputControlSource Button4 = Button( 4 );
protected static InputControlSource Button5 = Button( 5 );
protected static InputControlSource Button6 = Button( 6 );
protected static InputControlSource Button7 = Button( 7 );
protected static InputControlSource Button8 = Button( 8 );
protected static InputControlSource Button9 = Button( 9 );
protected static InputControlSource Button10 = Button( 10 );
protected static InputControlSource Button11 = Button( 11 );
protected static InputControlSource Button12 = Button( 12 );
protected static InputControlSource Button13 = Button( 13 );
protected static InputControlSource Button14 = Button( 14 );
protected static InputControlSource Button15 = Button( 15 );
protected static InputControlSource Button16 = Button( 16 );
protected static InputControlSource Button17 = Button( 17 );
protected static InputControlSource Button18 = Button( 18 );
protected static InputControlSource Button19 = Button( 19 );
protected static InputControlSource Analog0 = Analog( 0 );
protected static InputControlSource Analog1 = Analog( 1 );
protected static InputControlSource Analog2 = Analog( 2 );
protected static InputControlSource Analog3 = Analog( 3 );
protected static InputControlSource Analog4 = Analog( 4 );
protected static InputControlSource Analog5 = Analog( 5 );
protected static InputControlSource Analog6 = Analog( 6 );
protected static InputControlSource Analog7 = Analog( 7 );
protected static InputControlSource Analog8 = Analog( 8 );
protected static InputControlSource Analog9 = Analog( 9 );
protected static InputControlSource Analog10 = Analog( 10 );
protected static InputControlSource Analog11 = Analog( 11 );
protected static InputControlSource Analog12 = Analog( 12 );
protected static InputControlSource Analog13 = Analog( 13 );
protected static InputControlSource Analog14 = Analog( 14 );
protected static InputControlSource Analog15 = Analog( 15 );
protected static InputControlSource Analog16 = Analog( 16 );
protected static InputControlSource Analog17 = Analog( 17 );
protected static InputControlSource Analog18 = Analog( 18 );
protected static InputControlSource Analog19 = Analog( 19 );
protected static InputControlSource MouseButton0 = new UnityMouseButtonSource( 0 );
protected static InputControlSource MouseButton1 = new UnityMouseButtonSource( 1 );
protected static InputControlSource MouseButton2 = new UnityMouseButtonSource( 2 );
protected static InputControlSource MouseXAxis = new UnityMouseAxisSource( "x" );
protected static InputControlSource MouseYAxis = new UnityMouseAxisSource( "y" );
protected static InputControlSource MouseScrollWheel = new UnityMouseAxisSource( "z" );
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public abstract class HttpClientHandlerTest_TrailingHeaders_Test : HttpClientHandlerTestBase
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetAsyncDefaultCompletionOption_TrailingHeaders_Available(bool includeTrailerHeader)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
(includeTrailerHeader ? "Trailer: MyCoolTrailerHeader, Hello\r\n" : "") +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"MyCoolTrailerHeader: amazingtrailer\r\n" +
"Hello: World\r\n" +
"\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("chunked", response.Headers.GetValues("Transfer-Encoding"));
// Check the Trailer header.
if (includeTrailerHeader)
{
Assert.Contains("MyCoolTrailerHeader", response.Headers.GetValues("Trailer"));
Assert.Contains("Hello", response.Headers.GetValues("Trailer"));
}
Assert.Contains("amazingtrailer", response.TrailingHeaders.GetValues("MyCoolTrailerHeader"));
Assert.Contains("World", response.TrailingHeaders.GetValues("Hello"));
string data = await response.Content.ReadAsStringAsync();
Assert.Contains("data", data);
// Trailers should not be part of the content data.
Assert.DoesNotContain("MyCoolTrailerHeader", data);
Assert.DoesNotContain("amazingtrailer", data);
Assert.DoesNotContain("Hello", data);
Assert.DoesNotContain("World", data);
}
}
});
}
[Fact]
public async Task GetAsyncResponseHeadersReadOption_TrailingHeaders_Available()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
"Trailer: MyCoolTrailerHeader\r\n" +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"MyCoolTrailerHeader: amazingtrailer\r\n" +
"Hello: World\r\n" +
"\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("chunked", response.Headers.GetValues("Transfer-Encoding"));
Assert.Contains("MyCoolTrailerHeader", response.Headers.GetValues("Trailer"));
// Pending read on the response content.
var trailingHeaders = response.TrailingHeaders;
Assert.Empty(trailingHeaders);
Stream stream = await response.Content.ReadAsStreamAsync();
Byte[] data = new Byte[100];
// Read some data, preferably whole body.
int readBytes = await stream.ReadAsync(data, 0, 4);
// Intermediate test - haven't reached stream EOF yet.
Assert.Empty(response.TrailingHeaders);
if (readBytes == 4)
{
// If we consumed whole content, check content.
Assert.Contains("data", System.Text.Encoding.Default.GetString(data));
}
// Read data until EOF is reached
while (stream.Read(data, 0, data.Length) != 0);
Assert.Same(trailingHeaders, response.TrailingHeaders);
Assert.Contains("amazingtrailer", response.TrailingHeaders.GetValues("MyCoolTrailerHeader"));
Assert.Contains("World", response.TrailingHeaders.GetValues("Hello"));
}
}
});
}
[Theory]
[InlineData("Age", "1")]
[InlineData("Authorization", "Basic YWxhZGRpbjpvcGVuc2VzYW1l")]
[InlineData("Cache-Control", "no-cache")]
[InlineData("Content-Encoding", "gzip")]
[InlineData("Content-Length", "22")]
[InlineData("Content-type", "foo/bar")]
[InlineData("Content-Range", "bytes 200-1000/67589")]
[InlineData("Date", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("Expect", "100-continue")]
[InlineData("Expires", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("Host", "foo")]
[InlineData("If-Match", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("If-Modified-Since", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("If-None-Match", "*")]
[InlineData("If-Range", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("If-Unmodified-Since", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("Location", "/index.html")]
[InlineData("Max-Forwards","2")]
[InlineData("Pragma", "no-cache")]
[InlineData("Range", "5/10")]
[InlineData("Retry-After", "20")]
[InlineData("Set-Cookie", "foo=bar")]
[InlineData("TE", "boo")]
[InlineData("Transfer-Encoding", "chunked")]
[InlineData("Transfer-Encoding", "gzip")]
[InlineData("Vary", "*")]
[InlineData("Warning", "300 - \"Be Warned!\"")]
public async Task GetAsync_ForbiddenTrailingHeaders_Ignores(string name, string value)
{
await LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
HttpResponseMessage response = await client.GetAsync(url);
Assert.Contains("amazingtrailer", response.TrailingHeaders.GetValues("MyCoolTrailerHeader"));
Assert.False(response.TrailingHeaders.TryGetValues(name, out IEnumerable<string> values));
Assert.Contains("Loopback", response.TrailingHeaders.GetValues("Server"));
}
}, server => server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
$"Trailer: Set-Cookie, MyCoolTrailerHeader, {name}, Hello\r\n" +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"Set-Cookie: yummy\r\n" +
"MyCoolTrailerHeader: amazingtrailer\r\n" +
$"{name}: {value}\r\n" +
"Server: Loopback\r\n" +
$"{name}: {value}\r\n" +
"\r\n"));
}
[Fact]
public async Task GetAsync_NoTrailingHeaders_EmptyCollection()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
"Trailer: MyCoolTrailerHeader\r\n" +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("chunked", response.Headers.GetValues("Transfer-Encoding"));
Assert.NotNull(response.TrailingHeaders);
Assert.Equal(0, response.TrailingHeaders.Count());
Assert.Same(response.TrailingHeaders, response.TrailingHeaders);
}
}
});
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Collections;
using System.IO;
using log4net.Core;
using log4net.Layout.Pattern;
using log4net.Util;
using log4net.Util.PatternStringConverters;
using AppDomainPatternConverter=log4net.Layout.Pattern.AppDomainPatternConverter;
using DatePatternConverter=log4net.Layout.Pattern.DatePatternConverter;
using IdentityPatternConverter=log4net.Layout.Pattern.IdentityPatternConverter;
using PropertyPatternConverter=log4net.Layout.Pattern.PropertyPatternConverter;
using UserNamePatternConverter=log4net.Layout.Pattern.UserNamePatternConverter;
using UtcDatePatternConverter=log4net.Layout.Pattern.UtcDatePatternConverter;
namespace log4net.Layout
{
/// <summary>
/// A flexible layout configurable with pattern string.
/// </summary>
/// <remarks>
/// <para>
/// The goal of this class is to <see cref="M:PatternLayout.Format(TextWriter,LoggingEvent)"/> a
/// <see cref="LoggingEvent"/> as a string. The results
/// depend on the <i>conversion pattern</i>.
/// </para>
/// <para>
/// The conversion pattern is closely related to the conversion
/// pattern of the printf function in C. A conversion pattern is
/// composed of literal text and format control expressions called
/// <i>conversion specifiers</i>.
/// </para>
/// <para>
/// <i>You are free to insert any literal text within the conversion
/// pattern.</i>
/// </para>
/// <para>
/// Each conversion specifier starts with a percent sign (%) and is
/// followed by optional <i>format modifiers</i> and a <i>conversion
/// pattern name</i>. The conversion pattern name specifies the type of
/// data, e.g. logger, level, date, thread name. The format
/// modifiers control such things as field width, padding, left and
/// right justification. The following is a simple example.
/// </para>
/// <para>
/// Let the conversion pattern be <b>"%-5level [%thread]: %message%newline"</b> and assume
/// that the log4net environment was set to use a PatternLayout. Then the
/// statements
/// </para>
/// <code lang="C#">
/// ILog log = LogManager.GetLogger(typeof(TestApp));
/// log.Debug("Message 1");
/// log.Warn("Message 2");
/// </code>
/// <para>would yield the output</para>
/// <code>
/// DEBUG [main]: Message 1
/// WARN [main]: Message 2
/// </code>
/// <para>
/// Note that there is no explicit separator between text and
/// conversion specifiers. The pattern parser knows when it has reached
/// the end of a conversion specifier when it reads a conversion
/// character. In the example above the conversion specifier
/// <b>%-5level</b> means the level of the logging event should be left
/// justified to a width of five characters.
/// </para>
/// <para>
/// The recognized conversion pattern names are:
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Conversion Pattern Name</term>
/// <description>Effect</description>
/// </listheader>
/// <item>
/// <term>a</term>
/// <description>Equivalent to <b>appdomain</b></description>
/// </item>
/// <item>
/// <term>appdomain</term>
/// <description>
/// Used to output the friendly name of the AppDomain where the
/// logging event was generated.
/// </description>
/// </item>
/// <item>
/// <term>aspnet-cache</term>
/// <description>
/// <para>
/// Used to output all cache items in the case of <b>%aspnet-cache</b> or just one named item if used as <b>%aspnet-cache{key}</b>
/// </para>
/// <para>
/// This pattern is not available for Compact Framework or Client Profile assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>aspnet-context</term>
/// <description>
/// <para>
/// Used to output all context items in the case of <b>%aspnet-context</b> or just one named item if used as <b>%aspnet-context{key}</b>
/// </para>
/// <para>
/// This pattern is not available for Compact Framework or Client Profile assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>aspnet-request</term>
/// <description>
/// <para>
/// Used to output all request parameters in the case of <b>%aspnet-request</b> or just one named param if used as <b>%aspnet-request{key}</b>
/// </para>
/// <para>
/// This pattern is not available for Compact Framework or Client Profile assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>aspnet-session</term>
/// <description>
/// <para>
/// Used to output all session items in the case of <b>%aspnet-session</b> or just one named item if used as <b>%aspnet-session{key}</b>
/// </para>
/// <para>
/// This pattern is not available for Compact Framework or Client Profile assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>c</term>
/// <description>Equivalent to <b>logger</b></description>
/// </item>
/// <item>
/// <term>C</term>
/// <description>Equivalent to <b>type</b></description>
/// </item>
/// <item>
/// <term>class</term>
/// <description>Equivalent to <b>type</b></description>
/// </item>
/// <item>
/// <term>d</term>
/// <description>Equivalent to <b>date</b></description>
/// </item>
/// <item>
/// <term>date</term>
/// <description>
/// <para>
/// Used to output the date of the logging event in the local time zone.
/// To output the date in universal time use the <c>%utcdate</c> pattern.
/// The date conversion
/// specifier may be followed by a <i>date format specifier</i> enclosed
/// between braces. For example, <b>%date{HH:mm:ss,fff}</b> or
/// <b>%date{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
/// given then ISO8601 format is
/// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>).
/// </para>
/// <para>
/// The date format specifier admits the same syntax as the
/// time pattern string of the <see cref="M:DateTime.ToString(string)"/>.
/// </para>
/// <para>
/// For better results it is recommended to use the log4net date
/// formatters. These can be specified using one of the strings
/// "ABSOLUTE", "DATE" and "ISO8601" for specifying
/// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
/// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
/// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example,
/// <b>%date{ISO8601}</b> or <b>%date{ABSOLUTE}</b>.
/// </para>
/// <para>
/// These dedicated date formatters perform significantly
/// better than <see cref="M:DateTime.ToString(string)"/>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>exception</term>
/// <description>
/// <para>
/// Used to output the exception passed in with the log message.
/// </para>
/// <para>
/// If an exception object is stored in the logging event
/// it will be rendered into the pattern output with a
/// trailing newline.
/// If there is no exception then nothing will be output
/// and no trailing newline will be appended.
/// It is typical to put a newline before the exception
/// and to have the exception as the last data in the pattern.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>F</term>
/// <description>Equivalent to <b>file</b></description>
/// </item>
/// <item>
/// <term>file</term>
/// <description>
/// <para>
/// Used to output the file name where the logging request was
/// issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>identity</term>
/// <description>
/// <para>
/// Used to output the user name for the currently active user
/// (Principal.Identity.Name).
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>l</term>
/// <description>Equivalent to <b>location</b></description>
/// </item>
/// <item>
/// <term>L</term>
/// <description>Equivalent to <b>line</b></description>
/// </item>
/// <item>
/// <term>location</term>
/// <description>
/// <para>
/// Used to output location information of the caller which generated
/// the logging event.
/// </para>
/// <para>
/// The location information depends on the CLI implementation but
/// usually consists of the fully qualified name of the calling
/// method followed by the callers source the file name and line
/// number between parentheses.
/// </para>
/// <para>
/// The location information can be very useful. However, its
/// generation is <b>extremely</b> slow. Its use should be avoided
/// unless execution speed is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>level</term>
/// <description>
/// <para>
/// Used to output the level of the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>line</term>
/// <description>
/// <para>
/// Used to output the line number from where the logging request
/// was issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>logger</term>
/// <description>
/// <para>
/// Used to output the logger of the logging event. The
/// logger conversion specifier can be optionally followed by
/// <i>precision specifier</i>, that is a decimal constant in
/// brackets.
/// </para>
/// <para>
/// If a precision specifier is given, then only the corresponding
/// number of right most components of the logger name will be
/// printed. By default the logger name is printed in full.
/// </para>
/// <para>
/// For example, for the logger name "a.b.c" the pattern
/// <b>%logger{2}</b> will output "b.c".
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>m</term>
/// <description>Equivalent to <b>message</b></description>
/// </item>
/// <item>
/// <term>M</term>
/// <description>Equivalent to <b>method</b></description>
/// </item>
/// <item>
/// <term>message</term>
/// <description>
/// <para>
/// Used to output the application supplied message associated with
/// the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>mdc</term>
/// <description>
/// <para>
/// The MDC (old name for the ThreadContext.Properties) is now part of the
/// combined event properties. This pattern is supported for compatibility
/// but is equivalent to <b>property</b>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>method</term>
/// <description>
/// <para>
/// Used to output the method name where the logging request was
/// issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>n</term>
/// <description>Equivalent to <b>newline</b></description>
/// </item>
/// <item>
/// <term>newline</term>
/// <description>
/// <para>
/// Outputs the platform dependent line separator character or
/// characters.
/// </para>
/// <para>
/// This conversion pattern offers the same performance as using
/// non-portable line separator strings such as "\n", or "\r\n".
/// Thus, it is the preferred way of specifying a line separator.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>ndc</term>
/// <description>
/// <para>
/// Used to output the NDC (nested diagnostic context) associated
/// with the thread that generated the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>p</term>
/// <description>Equivalent to <b>level</b></description>
/// </item>
/// <item>
/// <term>P</term>
/// <description>Equivalent to <b>property</b></description>
/// </item>
/// <item>
/// <term>properties</term>
/// <description>Equivalent to <b>property</b></description>
/// </item>
/// <item>
/// <term>property</term>
/// <description>
/// <para>
/// Used to output the an event specific property. The key to
/// lookup must be specified within braces and directly following the
/// pattern specifier, e.g. <b>%property{user}</b> would include the value
/// from the property that is keyed by the string 'user'. Each property value
/// that is to be included in the log must be specified separately.
/// Properties are added to events by loggers or appenders. By default
/// the <c>log4net:HostName</c> property is set to the name of machine on
/// which the event was originally logged.
/// </para>
/// <para>
/// If no key is specified, e.g. <b>%property</b> then all the keys and their
/// values are printed in a comma separated list.
/// </para>
/// <para>
/// The properties of an event are combined from a number of different
/// contexts. These are listed below in the order in which they are searched.
/// </para>
/// <list type="definition">
/// <item>
/// <term>the event properties</term>
/// <description>
/// The event has <see cref="LoggingEvent.Properties"/> that can be set. These
/// properties are specific to this event only.
/// </description>
/// </item>
/// <item>
/// <term>the thread properties</term>
/// <description>
/// The <see cref="ThreadContext.Properties"/> that are set on the current
/// thread. These properties are shared by all events logged on this thread.
/// </description>
/// </item>
/// <item>
/// <term>the global properties</term>
/// <description>
/// The <see cref="GlobalContext.Properties"/> that are set globally. These
/// properties are shared by all the threads in the AppDomain.
/// </description>
/// </item>
/// </list>
///
/// </description>
/// </item>
/// <item>
/// <term>r</term>
/// <description>Equivalent to <b>timestamp</b></description>
/// </item>
/// <item>
/// <term>stacktrace</term>
/// <description>
/// <para>
/// Used to output the stack trace of the logging event
/// The stack trace level specifier may be enclosed
/// between braces. For example, <b>%stacktrace{level}</b>.
/// If no stack trace level specifier is given then 1 is assumed
/// </para>
/// <para>
/// Output uses the format:
/// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1
/// </para>
/// <para>
/// This pattern is not available for Compact Framework assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>stacktracedetail</term>
/// <description>
/// <para>
/// Used to output the stack trace of the logging event
/// The stack trace level specifier may be enclosed
/// between braces. For example, <b>%stacktracedetail{level}</b>.
/// If no stack trace level specifier is given then 1 is assumed
/// </para>
/// <para>
/// Output uses the format:
/// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...)
/// </para>
/// <para>
/// This pattern is not available for Compact Framework assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>t</term>
/// <description>Equivalent to <b>thread</b></description>
/// </item>
/// <item>
/// <term>timestamp</term>
/// <description>
/// <para>
/// Used to output the number of milliseconds elapsed since the start
/// of the application until the creation of the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>thread</term>
/// <description>
/// <para>
/// Used to output the name of the thread that generated the
/// logging event. Uses the thread number if no name is available.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>type</term>
/// <description>
/// <para>
/// Used to output the fully qualified type name of the caller
/// issuing the logging request. This conversion specifier
/// can be optionally followed by <i>precision specifier</i>, that
/// is a decimal constant in brackets.
/// </para>
/// <para>
/// If a precision specifier is given, then only the corresponding
/// number of right most components of the class name will be
/// printed. By default the class name is output in fully qualified form.
/// </para>
/// <para>
/// For example, for the class name "log4net.Layout.PatternLayout", the
/// pattern <b>%type{1}</b> will output "PatternLayout".
/// </para>
/// <para>
/// <b>WARNING</b> Generating the caller class information is
/// slow. Thus, its use should be avoided unless execution speed is
/// not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>u</term>
/// <description>Equivalent to <b>identity</b></description>
/// </item>
/// <item>
/// <term>username</term>
/// <description>
/// <para>
/// Used to output the WindowsIdentity for the currently
/// active user.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller WindowsIdentity information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>utcdate</term>
/// <description>
/// <para>
/// Used to output the date of the logging event in universal time.
/// The date conversion
/// specifier may be followed by a <i>date format specifier</i> enclosed
/// between braces. For example, <b>%utcdate{HH:mm:ss,fff}</b> or
/// <b>%utcdate{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
/// given then ISO8601 format is
/// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>).
/// </para>
/// <para>
/// The date format specifier admits the same syntax as the
/// time pattern string of the <see cref="M:DateTime.ToString(string)"/>.
/// </para>
/// <para>
/// For better results it is recommended to use the log4net date
/// formatters. These can be specified using one of the strings
/// "ABSOLUTE", "DATE" and "ISO8601" for specifying
/// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
/// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
/// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example,
/// <b>%utcdate{ISO8601}</b> or <b>%utcdate{ABSOLUTE}</b>.
/// </para>
/// <para>
/// These dedicated date formatters perform significantly
/// better than <see cref="M:DateTime.ToString(string)"/>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>w</term>
/// <description>Equivalent to <b>username</b></description>
/// </item>
/// <item>
/// <term>x</term>
/// <description>Equivalent to <b>ndc</b></description>
/// </item>
/// <item>
/// <term>X</term>
/// <description>Equivalent to <b>mdc</b></description>
/// </item>
/// <item>
/// <term>%</term>
/// <description>
/// <para>
/// The sequence %% outputs a single percent sign.
/// </para>
/// </description>
/// </item>
/// </list>
/// <para>
/// The single letter patterns are deprecated in favor of the
/// longer more descriptive pattern names.
/// </para>
/// <para>
/// By default the relevant information is output as is. However,
/// with the aid of format modifiers it is possible to change the
/// minimum field width, the maximum field width and justification.
/// </para>
/// <para>
/// The optional format modifier is placed between the percent sign
/// and the conversion pattern name.
/// </para>
/// <para>
/// The first optional format modifier is the <i>left justification
/// flag</i> which is just the minus (-) character. Then comes the
/// optional <i>minimum field width</i> modifier. This is a decimal
/// constant that represents the minimum number of characters to
/// output. If the data item requires fewer characters, it is padded on
/// either the left or the right until the minimum width is
/// reached. The default is to pad on the left (right justify) but you
/// can specify right padding with the left justification flag. The
/// padding character is space. If the data item is larger than the
/// minimum field width, the field is expanded to accommodate the
/// data. The value is never truncated.
/// </para>
/// <para>
/// This behavior can be changed using the <i>maximum field
/// width</i> modifier which is designated by a period followed by a
/// decimal constant. If the data item is longer than the maximum
/// field, then the extra characters are removed from the
/// <i>beginning</i> of the data item and not from the end. For
/// example, it the maximum field width is eight and the data item is
/// ten characters long, then the first two characters of the data item
/// are dropped. This behavior deviates from the printf function in C
/// where truncation is done from the end.
/// </para>
/// <para>
/// Below are various format modifier examples for the logger
/// conversion specifier.
/// </para>
/// <div class="tablediv">
/// <table class="dtTABLE" cellspacing="0">
/// <tr>
/// <th>Format modifier</th>
/// <th>left justify</th>
/// <th>minimum width</th>
/// <th>maximum width</th>
/// <th>comment</th>
/// </tr>
/// <tr>
/// <td align="center">%20logger</td>
/// <td align="center">false</td>
/// <td align="center">20</td>
/// <td align="center">none</td>
/// <td>
/// <para>
/// Left pad with spaces if the logger name is less than 20
/// characters long.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%-20logger</td>
/// <td align="center">true</td>
/// <td align="center">20</td>
/// <td align="center">none</td>
/// <td>
/// <para>
/// Right pad with spaces if the logger
/// name is less than 20 characters long.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%.30logger</td>
/// <td align="center">NA</td>
/// <td align="center">none</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Truncate from the beginning if the logger
/// name is longer than 30 characters.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center"><nobr>%20.30logger</nobr></td>
/// <td align="center">false</td>
/// <td align="center">20</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Left pad with spaces if the logger name is shorter than 20
/// characters. However, if logger name is longer than 30 characters,
/// then truncate from the beginning.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%-20.30logger</td>
/// <td align="center">true</td>
/// <td align="center">20</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Right pad with spaces if the logger name is shorter than 20
/// characters. However, if logger name is longer than 30 characters,
/// then truncate from the beginning.
/// </para>
/// </td>
/// </tr>
/// </table>
/// </div>
/// <para>
/// <b>Note about caller location information.</b><br />
/// The following patterns <c>%type %file %line %method %location %class %C %F %L %l %M</c>
/// all generate caller location information.
/// Location information uses the <c>System.Diagnostics.StackTrace</c> class to generate
/// a call stack. The caller's information is then extracted from this stack.
/// </para>
/// <note type="caution">
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class is not supported on the
/// .NET Compact Framework 1.0 therefore caller location information is not
/// available on that framework.
/// </para>
/// </note>
/// <note type="caution">
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds:
/// </para>
/// <para>
/// "StackTrace information will be most informative with Debug build configurations.
/// By default, Debug builds include debug symbols, while Release builds do not. The
/// debug symbols contain most of the file, method name, line number, and column
/// information used in constructing StackFrame and StackTrace objects. StackTrace
/// might not report as many method calls as expected, due to code transformations
/// that occur during optimization."
/// </para>
/// <para>
/// This means that in a Release build the caller information may be incomplete or may
/// not exist at all! Therefore caller location information cannot be relied upon in a Release build.
/// </para>
/// </note>
/// <para>
/// Additional pattern converters may be registered with a specific <see cref="PatternLayout"/>
/// instance using the <see cref="M:AddConverter(string, Type)"/> method.
/// </para>
/// </remarks>
/// <example>
/// This is a more detailed pattern.
/// <code><b>%timestamp [%thread] %level %logger %ndc - %message%newline</b></code>
/// </example>
/// <example>
/// A similar pattern except that the relative time is
/// right padded if less than 6 digits, thread name is right padded if
/// less than 15 characters and truncated if longer and the logger
/// name is left padded if shorter than 30 characters and truncated if
/// longer.
/// <code><b>%-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline</b></code>
/// </example>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Douglas de la Torre</author>
/// <author>Daniel Cazzulino</author>
public class PatternLayout : LayoutSkeleton
{
#region Constants
/// <summary>
/// Default pattern string for log output.
/// </summary>
/// <remarks>
/// <para>
/// Default pattern string for log output.
/// Currently set to the string <b>"%message%newline"</b>
/// which just prints the application supplied message.
/// </para>
/// </remarks>
public const string DefaultConversionPattern ="%message%newline";
/// <summary>
/// A detailed conversion pattern
/// </summary>
/// <remarks>
/// <para>
/// A conversion pattern which includes Time, Thread, Logger, and Nested Context.
/// Current value is <b>%timestamp [%thread] %level %logger %ndc - %message%newline</b>.
/// </para>
/// </remarks>
public const string DetailConversionPattern = "%timestamp [%thread] %level %logger %ndc - %message%newline";
#endregion
#region Static Fields
/// <summary>
/// Internal map of converter identifiers to converter types.
/// </summary>
/// <remarks>
/// <para>
/// This static map is overridden by the m_converterRegistry instance map
/// </para>
/// </remarks>
private static Hashtable s_globalRulesRegistry;
#endregion Static Fields
#region Member Variables
/// <summary>
/// the pattern
/// </summary>
private string m_pattern;
/// <summary>
/// the head of the pattern converter chain
/// </summary>
private PatternConverter m_head;
/// <summary>
/// patterns defined on this PatternLayout only
/// </summary>
private Hashtable m_instanceRulesRegistry = new Hashtable();
#endregion
#region Static Constructor
/// <summary>
/// Initialize the global registry
/// </summary>
/// <remarks>
/// <para>
/// Defines the builtin global rules.
/// </para>
/// </remarks>
static PatternLayout()
{
s_globalRulesRegistry = new Hashtable(45);
s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter));
s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter));
s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter));
// .NET Compact Framework has no support for ASP.NET
#if !NETCF && !CLIENT_PROFILE
s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter));
s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter));
s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter));
s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter));
#endif
s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter));
s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter));
s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("d", typeof(DatePatternConverter));
s_globalRulesRegistry.Add("date", typeof(DatePatternConverter));
s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter));
s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter));
s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter));
s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter));
s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter));
s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter));
s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter));
s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter));
s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter));
s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter));
s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter));
s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter));
s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter));
s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter));
s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter));
#if !NETCF
s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter));
s_globalRulesRegistry.Add("stacktracedetail", typeof(StackTraceDetailPatternConverter));
#endif
s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter));
s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter));
// For backwards compatibility the NDC patterns
s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter));
s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter));
// For backwards compatibility the MDC patterns just do a property lookup
s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter));
s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter));
s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter));
s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter));
s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter));
s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter));
}
#endregion Static Constructor
#region Constructors
/// <summary>
/// Constructs a PatternLayout using the DefaultConversionPattern
/// </summary>
/// <remarks>
/// <para>
/// The default pattern just produces the application supplied message.
/// </para>
/// <para>
/// Note to Inheritors: This constructor calls the virtual method
/// <see cref="CreatePatternParser"/>. If you override this method be
/// aware that it will be called before your is called constructor.
/// </para>
/// <para>
/// As per the <see cref="IOptionHandler"/> contract the <see cref="ActivateOptions"/>
/// method must be called after the properties on this object have been
/// configured.
/// </para>
/// </remarks>
public PatternLayout() : this(DefaultConversionPattern)
{
}
/// <summary>
/// Constructs a PatternLayout using the supplied conversion pattern
/// </summary>
/// <param name="pattern">the pattern to use</param>
/// <remarks>
/// <para>
/// Note to Inheritors: This constructor calls the virtual method
/// <see cref="CreatePatternParser"/>. If you override this method be
/// aware that it will be called before your is called constructor.
/// </para>
/// <para>
/// When using this constructor the <see cref="ActivateOptions"/> method
/// need not be called. This may not be the case when using a subclass.
/// </para>
/// </remarks>
public PatternLayout(string pattern)
{
// By default we do not process the exception
IgnoresException = true;
m_pattern = pattern;
if (m_pattern == null)
{
m_pattern = DefaultConversionPattern;
}
ActivateOptions();
}
#endregion
/// <summary>
/// The pattern formatting string
/// </summary>
/// <remarks>
/// <para>
/// The <b>ConversionPattern</b> option. This is the string which
/// controls formatting and consists of a mix of literal content and
/// conversion specifiers.
/// </para>
/// </remarks>
public string ConversionPattern
{
get { return m_pattern; }
set { m_pattern = value; }
}
/// <summary>
/// Create the pattern parser instance
/// </summary>
/// <param name="pattern">the pattern to parse</param>
/// <returns>The <see cref="PatternParser"/> that will format the event</returns>
/// <remarks>
/// <para>
/// Creates the <see cref="PatternParser"/> used to parse the conversion string. Sets the
/// global and instance rules on the <see cref="PatternParser"/>.
/// </para>
/// </remarks>
virtual protected PatternParser CreatePatternParser(string pattern)
{
PatternParser patternParser = new PatternParser(pattern);
// Add all the builtin patterns
foreach(DictionaryEntry entry in s_globalRulesRegistry)
{
ConverterInfo converterInfo = new ConverterInfo();
converterInfo.Name = (string)entry.Key;
converterInfo.Type = (Type)entry.Value;
patternParser.PatternConverters[entry.Key] = converterInfo;
}
// Add the instance patterns
foreach(DictionaryEntry entry in m_instanceRulesRegistry)
{
patternParser.PatternConverters[entry.Key] = entry.Value;
}
return patternParser;
}
#region Implementation of IOptionHandler
/// <summary>
/// Initialize layout options
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
m_head = CreatePatternParser(m_pattern).Parse();
PatternConverter curConverter = m_head;
while(curConverter != null)
{
PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter;
if (layoutConverter != null)
{
if (!layoutConverter.IgnoresException)
{
// Found converter that handles the exception
this.IgnoresException = false;
break;
}
}
curConverter = curConverter.Next;
}
}
#endregion
#region Override implementation of LayoutSkeleton
/// <summary>
/// Produces a formatted string as specified by the conversion pattern.
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <param name="writer">The TextWriter to write the formatted event to</param>
/// <remarks>
/// <para>
/// Parse the <see cref="LoggingEvent"/> using the patter format
/// specified in the <see cref="ConversionPattern"/> property.
/// </para>
/// </remarks>
override public void Format(TextWriter writer, LoggingEvent loggingEvent)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
PatternConverter c = m_head;
// loop through the chain of pattern converters
while(c != null)
{
c.Format(writer, loggingEvent);
c = c.Next;
}
}
#endregion
/// <summary>
/// Add a converter to this PatternLayout
/// </summary>
/// <param name="converterInfo">the converter info</param>
/// <remarks>
/// <para>
/// This version of the method is used by the configurator.
/// Programmatic users should use the alternative <see cref="M:AddConverter(string,Type)"/> method.
/// </para>
/// </remarks>
public void AddConverter(ConverterInfo converterInfo)
{
if (converterInfo == null) throw new ArgumentNullException("converterInfo");
if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type))
{
throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo");
}
m_instanceRulesRegistry[converterInfo.Name] = converterInfo;
}
/// <summary>
/// Add a converter to this PatternLayout
/// </summary>
/// <param name="name">the name of the conversion pattern for this converter</param>
/// <param name="type">the type of the converter</param>
/// <remarks>
/// <para>
/// Add a named pattern converter to this instance. This
/// converter will be used in the formatting of the event.
/// This method must be called before <see cref="ActivateOptions"/>.
/// </para>
/// <para>
/// The <paramref name="type"/> specified must extend the
/// <see cref="PatternConverter"/> type.
/// </para>
/// </remarks>
public void AddConverter(string name, Type type)
{
if (name == null) throw new ArgumentNullException("name");
if (type == null) throw new ArgumentNullException("type");
ConverterInfo converterInfo = new ConverterInfo();
converterInfo.Name = name;
converterInfo.Type = type;
AddConverter(converterInfo);
}
}
}
| |
#region Copyright & License
//
// Copyright 2001-2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Configuration;
using System.Diagnostics;
namespace log4net.Util
{
/// <summary>
/// Outputs log statements from within the log4net assembly.
/// </summary>
/// <remarks>
/// <para>
/// Log4net components cannot make log4net logging calls. However, it is
/// sometimes useful for the user to learn about what log4net is
/// doing.
/// </para>
/// <para>
/// All log4net internal debug calls go to the standard output stream
/// whereas internal error messages are sent to the standard error output
/// stream.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class LogLog
{
#region Private Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LogLog" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Uses a private access modifier to prevent instantiation of this class.
/// </para>
/// </remarks>
private LogLog()
{
}
#endregion Private Instance Constructors
#region Static Constructor
/// <summary>
/// Static constructor that initializes logging by reading
/// settings from the application configuration file.
/// </summary>
/// <remarks>
/// <para>
/// The <c>log4net.Internal.Debug</c> application setting
/// controls internal debugging. This setting should be set
/// to <c>true</c> to enable debugging.
/// </para>
/// <para>
/// The <c>log4net.Internal.Quiet</c> application setting
/// suppresses all internal logging including error messages.
/// This setting should be set to <c>true</c> to enable message
/// suppression.
/// </para>
/// </remarks>
static LogLog()
{
#if !NETCF
try
{
InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Debug"), false);
QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Quiet"), false);
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not
// parse correctly.
//
// We will leave debug OFF and print an Error message
Error("LogLog: Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
#endif
}
#endregion Static Constructor
#region Public Static Properties
/// <summary>
/// Gets or sets a value indicating whether log4net internal logging
/// is enabled or disabled.
/// </summary>
/// <value>
/// <c>true</c> if log4net internal logging is enabled, otherwise
/// <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c>, internal debug level logging will be
/// displayed.
/// </para>
/// <para>
/// This value can be set by setting the application setting
/// <c>log4net.Internal.Debug</c> in the application configuration
/// file.
/// </para>
/// <para>
/// The default value is <c>false</c>, i.e. debugging is
/// disabled.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// The following example enables internal debugging using the
/// application configuration file :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net.Internal.Debug" value="true" />
/// </appSettings>
/// </configuration>
/// </code>
/// </example>
public static bool InternalDebugging
{
get { return s_debugEnabled; }
set { s_debugEnabled = value; }
}
/// <summary>
/// Gets or sets a value indicating whether log4net should generate no output
/// from internal logging, not even for errors.
/// </summary>
/// <value>
/// <c>true</c> if log4net should generate no output at all from internal
/// logging, otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c> will cause internal logging at all levels to be
/// suppressed. This means that no warning or error reports will be logged.
/// This option overrides the <see cref="InternalDebugging"/> setting and
/// disables all debug also.
/// </para>
/// <para>This value can be set by setting the application setting
/// <c>log4net.Internal.Quiet</c> in the application configuration file.
/// </para>
/// <para>
/// The default value is <c>false</c>, i.e. internal logging is not
/// disabled.
/// </para>
/// </remarks>
/// <example>
/// The following example disables internal logging using the
/// application configuration file :
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net.Internal.Quiet" value="true" />
/// </appSettings>
/// </configuration>
/// </code>
/// </example>
public static bool QuietMode
{
get { return s_quietMode; }
set { s_quietMode = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Test if LogLog.Debug is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Debug is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Debug is enabled for output.
/// </para>
/// </remarks>
public static bool IsDebugEnabled
{
get { return s_debugEnabled && !s_quietMode; }
}
/// <summary>
/// Writes log4net internal debug messages to the
/// standard output stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net: ".
/// </para>
/// </remarks>
public static void Debug(string message)
{
if (IsDebugEnabled)
{
EmitOutLine(PREFIX + message);
}
}
/// <summary>
/// Writes log4net internal debug messages to the
/// standard output stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net: ".
/// </para>
/// </remarks>
public static void Debug(string message, Exception exception)
{
if (IsDebugEnabled)
{
EmitOutLine(PREFIX + message);
if (exception != null)
{
EmitOutLine(exception.ToString());
}
}
}
/// <summary>
/// Test if LogLog.Warn is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Warn is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Warn is enabled for output.
/// </para>
/// </remarks>
public static bool IsWarnEnabled
{
get { return !s_quietMode; }
}
/// <summary>
/// Writes log4net internal warning messages to the
/// standard error stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal warning messages are prepended with
/// the string "log4net:WARN ".
/// </para>
/// </remarks>
public static void Warn(string message)
{
if (IsWarnEnabled)
{
EmitErrorLine(WARN_PREFIX + message);
}
}
/// <summary>
/// Writes log4net internal warning messages to the
/// standard error stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal warning messages are prepended with
/// the string "log4net:WARN ".
/// </para>
/// </remarks>
public static void Warn(string message, Exception exception)
{
if (IsWarnEnabled)
{
EmitErrorLine(WARN_PREFIX + message);
if (exception != null)
{
EmitErrorLine(exception.ToString());
}
}
}
/// <summary>
/// Test if LogLog.Error is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Error is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Error is enabled for output.
/// </para>
/// </remarks>
public static bool IsErrorEnabled
{
get { return !s_quietMode; }
}
/// <summary>
/// Writes log4net internal error messages to the
/// standard error stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal error messages are prepended with
/// the string "log4net:ERROR ".
/// </para>
/// </remarks>
public static void Error(string message)
{
if (IsErrorEnabled)
{
EmitErrorLine(ERR_PREFIX + message);
}
}
/// <summary>
/// Writes log4net internal error messages to the
/// standard error stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net:ERROR ".
/// </para>
/// </remarks>
public static void Error(string message, Exception exception)
{
if (IsErrorEnabled)
{
EmitErrorLine(ERR_PREFIX + message);
if (exception != null)
{
EmitErrorLine(exception.ToString());
}
}
}
#endregion Public Static Methods
/// <summary>
/// Writes output to the standard output stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// Writes to both Console.Out and System.Diagnostics.Trace.
/// Note that the System.Diagnostics.Trace is not supported
/// on the Compact Framework.
/// </para>
/// <para>
/// If the AppDomain is not configured with a config file then
/// the call to System.Diagnostics.Trace may fail. This is only
/// an issue if you are programmatically creating your own AppDomains.
/// </para>
/// </remarks>
private static void EmitOutLine(string message)
{
try
{
#if NETCF
Console.WriteLine(message);
//System.Diagnostics.Debug.WriteLine(message);
#else
Console.Out.WriteLine(message);
Trace.WriteLine(message);
#endif
}
catch
{
// Ignore exception, what else can we do? Not really a good idea to propagate back to the caller
}
}
/// <summary>
/// Writes output to the standard error stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// Writes to both Console.Error and System.Diagnostics.Trace.
/// Note that the System.Diagnostics.Trace is not supported
/// on the Compact Framework.
/// </para>
/// <para>
/// If the AppDomain is not configured with a config file then
/// the call to System.Diagnostics.Trace may fail. This is only
/// an issue if you are programmatically creating your own AppDomains.
/// </para>
/// </remarks>
private static void EmitErrorLine(string message)
{
try
{
#if NETCF
Console.WriteLine(message);
//System.Diagnostics.Debug.WriteLine(message);
#else
Console.Error.WriteLine(message);
Trace.WriteLine(message);
#endif
}
catch
{
// Ignore exception, what else can we do? Not really a good idea to propagate back to the caller
}
}
#region Private Static Fields
/// <summary>
/// Default debug level
/// </summary>
private static bool s_debugEnabled = false;
/// <summary>
/// In quietMode not even errors generate any output.
/// </summary>
private static bool s_quietMode = false;
private const string PREFIX = "log4net: ";
private const string ERR_PREFIX = "log4net:ERROR ";
private const string WARN_PREFIX = "log4net:WARN ";
#endregion Private Static Fields
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using static Interop.Libsodium;
namespace NSec.Cryptography
{
//
// A message authentication code (MAC) algorithm
//
// Candidates
//
// | Algorithm | Reference | Key Size | Customization | MAC Size |
// | ------------ | --------------- | -------- | ------------- | -------- |
// | AES-CMAC | RFC 4493 | 16 | no | 16 |
// | BLAKE2b | RFC 7693 | 0..64 | no | 1..64 |
// | HMAC-SHA-256 | RFC 2104 | any | no | 32 |
// | HMAC-SHA-512 | RFC 2104 | any | no | 64 |
// | KMAC128 | NIST SP 800-185 | any | yes | any |
// | KMAC256 | NIST SP 800-185 | any | yes | any |
// | KMACXOF128 | NIST SP 800-185 | any | yes | any |
// | KMACXOF256 | NIST SP 800-185 | any | yes | any |
//
public abstract class MacAlgorithm : Algorithm
{
private static Blake2bMac? s_Blake2b_128;
private static Blake2bMac? s_Blake2b_256;
private static Blake2bMac? s_Blake2b_512;
private static HmacSha256? s_HmacSha256;
private static HmacSha256? s_HmacSha256_128;
private static HmacSha512? s_HmacSha512;
private static HmacSha512? s_HmacSha512_256;
private readonly int _keySize;
private readonly int _macSize;
private protected MacAlgorithm(
int keySize,
int macSize)
{
Debug.Assert(keySize > 0);
Debug.Assert(macSize > 0);
_keySize = keySize;
_macSize = macSize;
}
public static Blake2bMac Blake2b_128
{
get
{
Blake2bMac? instance = s_Blake2b_128;
if (instance == null)
{
Interlocked.CompareExchange(ref s_Blake2b_128, new Blake2bMac(crypto_generichash_blake2b_KEYBYTES, 128 / 8), null);
instance = s_Blake2b_128;
}
return instance;
}
}
public static Blake2bMac Blake2b_256
{
get
{
Blake2bMac? instance = s_Blake2b_256;
if (instance == null)
{
Interlocked.CompareExchange(ref s_Blake2b_256, new Blake2bMac(crypto_generichash_blake2b_KEYBYTES, 256 / 8), null);
instance = s_Blake2b_256;
}
return instance;
}
}
public static Blake2bMac Blake2b_512
{
get
{
Blake2bMac? instance = s_Blake2b_512;
if (instance == null)
{
Interlocked.CompareExchange(ref s_Blake2b_512, new Blake2bMac(crypto_generichash_blake2b_KEYBYTES, 512 / 8), null);
instance = s_Blake2b_512;
}
return instance;
}
}
public static HmacSha256 HmacSha256
{
get
{
HmacSha256? instance = s_HmacSha256;
if (instance == null)
{
Interlocked.CompareExchange(ref s_HmacSha256, new HmacSha256(crypto_hash_sha256_BYTES, 256 / 8), null);
instance = s_HmacSha256;
}
return instance;
}
}
public static HmacSha256 HmacSha256_128
{
get
{
HmacSha256? instance = s_HmacSha256_128;
if (instance == null)
{
Interlocked.CompareExchange(ref s_HmacSha256_128, new HmacSha256(crypto_hash_sha256_BYTES, 128 / 8), null);
instance = s_HmacSha256_128;
}
return instance;
}
}
public static HmacSha512 HmacSha512
{
get
{
HmacSha512? instance = s_HmacSha512;
if (instance == null)
{
Interlocked.CompareExchange(ref s_HmacSha512, new HmacSha512(crypto_hash_sha512_BYTES, 512 / 8), null);
instance = s_HmacSha512;
}
return instance;
}
}
public static HmacSha512 HmacSha512_256
{
get
{
HmacSha512? instance = s_HmacSha512_256;
if (instance == null)
{
Interlocked.CompareExchange(ref s_HmacSha512_256, new HmacSha512(crypto_hash_sha512_BYTES, 256 / 8), null);
instance = s_HmacSha512_256;
}
return instance;
}
}
public int KeySize => _keySize;
public int MacSize => _macSize;
public byte[] Mac(
Key key,
ReadOnlySpan<byte> data)
{
if (key == null)
{
throw Error.ArgumentNull_Key(nameof(key));
}
if (key.Algorithm != this)
{
throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key));
}
byte[] mac = new byte[_macSize];
MacCore(key.Handle, data, mac);
return mac;
}
public void Mac(
Key key,
ReadOnlySpan<byte> data,
Span<byte> mac)
{
if (key == null)
{
throw Error.ArgumentNull_Key(nameof(key));
}
if (key.Algorithm != this)
{
throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key));
}
if (mac.Length != _macSize)
{
throw Error.Argument_MacLength(nameof(mac), _macSize);
}
MacCore(key.Handle, data, mac);
}
public bool Verify(
Key key,
ReadOnlySpan<byte> data,
ReadOnlySpan<byte> mac)
{
if (key == null)
{
throw Error.ArgumentNull_Key(nameof(key));
}
if (key.Algorithm != this)
{
throw Error.Argument_KeyAlgorithmMismatch(nameof(key), nameof(key));
}
Span<byte> temp = stackalloc byte[_macSize];
MacCore(key.Handle, data, temp);
return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(temp, mac);
}
internal abstract void FinalizeCore(
ref IncrementalMacState state,
Span<byte> mac);
internal sealed override int GetKeySize()
{
return _keySize;
}
internal sealed override int GetPublicKeySize()
{
throw Error.InvalidOperation_InternalError();
}
internal abstract override int GetSeedSize();
internal abstract void InitializeCore(
SecureMemoryHandle keyHandle,
out IncrementalMacState state);
internal abstract void UpdateCore(
ref IncrementalMacState state,
ReadOnlySpan<byte> data);
private protected abstract void MacCore(
SecureMemoryHandle keyHandle,
ReadOnlySpan<byte> data,
Span<byte> mac);
}
}
| |
// 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.Arm\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Add_Vector128_Single()
{
var test = new SimpleBinaryOpTest__Add_Vector128_Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__Add_Vector128_Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
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>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__Add_Vector128_Single testClass)
{
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__Add_Vector128_Single testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(pFld1)),
AdvSimd.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = 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 Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__Add_Vector128_Single()
{
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>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleBinaryOpTest__Add_Vector128_Single()
{
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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Add(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(pClsVar1)),
AdvSimd.LoadVector128((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__Add_Vector128_Single();
var result = AdvSimd.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__Add_Vector128_Single();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(pFld1)),
AdvSimd.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(pFld1)),
AdvSimd.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Add(
AdvSimd.LoadVector128((Single*)(&test._fld1)),
AdvSimd.LoadVector128((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(left[0] + right[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(left[i] + right[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/**
*
* Luke Church, 2011
* luke@church.name
*
*/
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Data.SQLite;
namespace net.riversofdata.dhlogger
{
public class Log : IDisposable
{
private const string URL = "https://dataharvestapp.appspot.com/rpc";
private const int MAX_DATA_LENGTH = 750000;
private const int MAX_NAME_LENGTH = 256;
private const String AppFolderName = "dh-logLib-Cache";
private const String dbFileName = "UsabilityLog.db";
private const String tableName = "LOGITEMS";
private SQLiteConnection conn;
/// <summary>
///
/// This mutex guards transactions on the DB
///
/// This is not actually necessary as SQLLite should enforce ACID,
/// but rather another defensive programming mechanism
/// </summary>
private object dbMutex = new object();
#region State holders
private string appName;
/// <summary>
/// The name of the application associated with the log entries
/// </summary>
public string AppName {
get
{
return appName;
}
set
{
if (!ValidateTextContent(value))
throw new ArgumentException(
"App name must only be letters, numbers or -");
if (!ValidateLength(value))
throw new ArgumentException("App Name must be 256 chars or less");
appName = value;
}
}
private string userID;
/// <summary>
/// A Guid string for the user associated with the log entries
/// </summary>
public string UserID {
get
{
return userID;
}
set
{
if (!ValidateTextContent(value))
throw new ArgumentException(
"User ID name must only be letters, numbers or -");
if (!ValidateLength(value))
throw new ArgumentException("UserID must be 256 chars or less");
userID = value;
}
}
private string sessionID;
/// <summary>
/// A Guid string for the session that the user is engaging with
/// </summary>
public string SessionID {
get
{
return sessionID;
}
set
{
if (!ValidateTextContent(value))
throw new ArgumentException(
"Session ID name must only be letters, numbers or -");
if (!ValidateLength(value))
throw new ArgumentException("Session ID must be 256 chars or less");
sessionID = value;
}
}
#endregion
/// <summary>
/// An object used to guard the uploadedItemsCount
/// </summary>
private Object uploadedItemsMutex = new object();
private long uploadedItemsCount = 0;
/// <summary>
/// The number of items that this log entity has successfully uploaded
/// This may be greater than the number of calls due to splitting of large entries
/// </summary>
public long UploadedItems
{
get
{
lock (uploadedItemsMutex)
{
return uploadedItemsCount;
}
}
private set
{
lock (uploadedItemsMutex)
{
uploadedItemsCount = value;
}
}
}
System.Diagnostics.Stopwatch sw;
private Thread uploaderThread;
private Queue<Dictionary<String, String>> items;
private const int DELAY_MS = 1000;
#region Public API
/// <summary>
/// Create a new log instance
/// </summary>
/// <param name="appName">The name of the application associated with this log</param>
/// <param name="userID">A statistically unique string associated with the user, e.g. a GUID</param>
/// <param name="sessionID">A statistically unique string associated with the session, e.g. a GUID</param>
public Log (string appName, string userID, string sessionID)
{
string dataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullFolderName = dataFolder + "\\" + AppFolderName;
if (!Directory.Exists(fullFolderName))
Directory.CreateDirectory(fullFolderName);
string connString = "Data Source=" + fullFolderName + "\\" + dbFileName;
conn = new System.Data.SQLite.SQLiteConnection(connString);
conn.Open();
//See if we already have the table, if not, create it
lock (dbMutex)
{
SQLiteCommand cmd = new SQLiteCommand(conn);
cmd.CommandText = "SELECT name FROM sqlite_master WHERE name='" + tableName + "'";
SQLiteDataReader rdr = cmd.ExecuteReader();
if (!rdr.HasRows)
{
SQLiteCommand createTable = new SQLiteCommand(conn);
createTable.CommandText
= "CREATE TABLE '" + tableName + @"' (
'EntryID' String,
'AppName' String,
'UserID' String,
'SessionID' String,
'Tag' String,
'Priority' String,
'Text' String,
'DateTime' String,
'MicroTime' String
);";
System.Diagnostics.Debug.WriteLine("About to Exec: " + createTable.CommandText);
SQLiteTransaction trans = conn.BeginTransaction();
createTable.ExecuteNonQuery();
trans.Commit();
}
}
AppName = appName;
UserID = userID;
SessionID = sessionID;
this.sw = new System.Diagnostics.Stopwatch();
sw.Start();
items = new Queue<Dictionary<string, string>>();
uploaderThread = new Thread(new ThreadStart(UploaderExec));
uploaderThread.IsBackground = true;
uploaderThread.Start();
}
/// <summary>
/// Log an item at debug priority
/// </summary>
/// <param name="tag">Tag associated with the log item</param>
/// <param name="text">Text to log</param>
public void Debug(string tag, string text)
{
ValidateInput(tag, text);
PrepAndPushItem(tag, "Debug", text);
}
/// <summary>
/// Log an item at error priority
/// </summary>
/// <param name="tag">Tag associated with the log item</param>
/// <param name="text">Text to log</param>
public void Error(string tag, string text)
{
ValidateInput(tag, text);
PrepAndPushItem(tag, "Error", text);
}
/// <summary>
/// Log an item at info priority
/// </summary>
/// <param name="tag">Tag associated with the log item</param>
/// <param name="text">Text to log</param>
public void Info(string tag, string text)
{
ValidateInput(tag, text);
PrepAndPushItem(tag, "Info", text);
}
/// <summary>
/// Log an item at verbose priority
/// </summary>
/// <param name="tag">Tag associated with the log item</param>
/// <param name="text">Text to log</param>
public void Verbose(string tag, string text)
{
ValidateInput(tag, text);
PrepAndPushItem(tag, "Verbose", text);
}
#endregion
/// <summary>
/// Methods that preps a write request
/// This method calls recursively up to once if the text is too large and needs
/// splitting
/// </summary>
/// <param name="tag"></param>
/// <param name="priority"></param>
/// <param name="text"></param>
private void PrepAndPushItem(string tag, string priority, string text)
{
//We don't need to validate the content of text as it's going to get base64
//encoded
System.Diagnostics.Debug.Assert(ValidateTextContent(tag));
System.Diagnostics.Debug.Assert(ValidateTextContent(priority));
List<String> splitText = SplitText(text);
if (splitText.Count > 1)
{
//Add a GUID and a serial to the Tag (We've reserved enough space for this)
//Recursive call the write with the split text
Guid g = Guid.NewGuid();
for (int i = 0; i < splitText.Count; i++)
{
PrepAndPushItem(
tag + "-" + g.ToString() + "-" + i.ToString(),
priority,
splitText[i]);
}
return;
}
text = splitText[0];
byte[] byteRepresentation = System.Text.Encoding.UTF8.GetBytes(text);
string safeStr = System.Convert.ToBase64String(byteRepresentation);
//Destroy the original representations to ensure runtime errors if used later in this method
text = null;
string dateTime = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss");
string microTime = sw.ElapsedMilliseconds.ToString();
Dictionary<String, String> item = new Dictionary<String, String>();
item.Add("Tag", tag);
item.Add("Priority", priority);
item.Add("AppIdent", AppName);
item.Add("UserID", UserID);
item.Add("SessionID", SessionID);
item.Add("DateTime", dateTime);
item.Add("MicroTime", microTime);
item.Add("Data", safeStr);
PushItem(item);
}
/// <summary>
/// ASync add the log item onto the queue to be pushed to the db
/// </summary>
/// <param name="item">
/// A <see cref="Dictionary<String, String>"/>
/// </param>
private void PushItem(Dictionary<String, String> item)
{
SQLiteCommand insertItem = new SQLiteCommand(conn);
insertItem.CommandText
= "INSERT INTO " + tableName +
@" (EntryID, AppName, UserID, SessionID, Tag, Priority, Text, DateTime, MicroTime)
VALUES ('" + Guid.NewGuid() + "', '" +
item["AppIdent"] + "', '" +
item["UserID"] + "', '" +
item["SessionID"] + "', '" +
item["Tag"] + "', '" +
item["Priority"] + "', '" +
item["Data"] + "', '" +
item["DateTime"] + "', '" +
item["MicroTime"] + "')";
System.Diagnostics.Debug.WriteLine("About to Exec: " + insertItem.CommandText);
lock (dbMutex)
{
SQLiteTransaction trans = conn.BeginTransaction();
insertItem.ExecuteNonQuery();
trans.Commit();
}
}
#region Uploader Thread methods
/// <summary>
/// Core thread method for handling the upload
/// </summary>
private void UploaderExec()
{
while (true)
{
Thread.Sleep(DELAY_MS);
//Pull a list of the entries from the db
//We don't need a transaction for this, it's only a read at this point
SQLiteCommand cmd = new SQLiteCommand(conn);
cmd.CommandText = "SELECT * FROM " + tableName;
System.Diagnostics.Debug.WriteLine("About to exec: " + cmd.CommandText);
List<Dictionary<String, String>> items = new List<Dictionary<string, string>>();
lock (dbMutex)
{
SQLiteDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//Build the dictionary back from the DB
Dictionary<String, String> item = new Dictionary<String, String>();
//Table names
//(EntryID, AppName, UserID, SessionID, Tag, Priority, Text, DateTime, MicroTime)
item.Add("EntryID", (string)rdr["EntryID"]);
item.Add("Tag", (string)rdr["Tag"]);
item.Add("Priority", (string)rdr["Priority"]);
item.Add("AppIdent", (string)rdr["AppName"]);
item.Add("UserID", (string)rdr["UserID"]);
item.Add("SessionID", (string)rdr["SessionID"]);
item.Add("DateTime", (string)rdr["DateTime"]);
item.Add("MicroTime", (string)rdr["MicroTime"]);
item.Add("Data", (string)rdr["Text"]);
items.Add(item);
}
}
List<Dictionary<String, String>> failedItems = new List<Dictionary<String, String>>();
foreach (Dictionary<String, String> item in items)
if (!UploadItem(item))
failedItems.Add(item);
//Now delete all the items other than the failed ones
List<String> IDsToDelete = new List<string>();
foreach (Dictionary<String, String> item in items)
if (!failedItems.Contains(item))
IDsToDelete.Add(item["EntryID"]);
if (IDsToDelete.Count > 0)
{
SQLiteCommand deleteItems = new SQLiteCommand(conn);
deleteItems.CommandText
= "DELETE FROM " + tableName + " WHERE EntryID IN (";
for (int i = 0; i < IDsToDelete.Count; i++)
{
deleteItems.CommandText += "'" + IDsToDelete[i] + "'";
if (i < IDsToDelete.Count - 1)
deleteItems.CommandText += ",";
}
deleteItems.CommandText += ")";
System.Diagnostics.Debug.WriteLine("About to Exec: " + deleteItems.CommandText);
lock (dbMutex)
{
SQLiteTransaction trans = conn.BeginTransaction();
deleteItems.ExecuteNonQuery();
trans.Commit();
}
}
}
}
/// <summary>
/// Code to transfer an item iver the network
/// </summary>
/// <param name="item"></param>
/// <returns>true if success, false otherwise</returns>
private bool UploadItem(Dictionary<String, String> item)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append("[\"BasicStore\", {");
bool first = true;
foreach (string key in item.Keys)
{
if (!first)
sb.Append(",");
else
first = false;
sb.Append("\"");
sb.Append(key);
sb.Append("\" : \"");
sb.Append(item[key]);
sb.Append("\"");
}
sb.Append("}]");
System.Diagnostics.Debug.WriteLine(sb.ToString());
WebRequest request = WebRequest.Create (URL);
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes (sb.ToString());
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
WebResponse response = request.GetResponse ();
if (((HttpWebResponse)response).StatusCode != HttpStatusCode.OK)
throw new Exception(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
System.Diagnostics.Debug.WriteLine (responseFromServer);
reader.Close ();
dataStream.Close ();
response.Close ();
UploadedItems += long.Parse(responseFromServer);
return true;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
return false;
}
}
#endregion
#region Helper methods
/// <summary>
/// Split a string into shorter strings as defined by the const
/// params
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private List<String> SplitText(String text)
{
int len = text.Length;
List<String> ret = new List<string>();
int added = 0;
for (int i = 0; i < len / (MAX_DATA_LENGTH+1); i++)
{
ret.Add(text.Substring(i*MAX_DATA_LENGTH, MAX_DATA_LENGTH));
added += MAX_DATA_LENGTH;
}
ret.Add(text.Substring(added));
#if DEBUG
int totalTextCount = 0;
foreach (String str in ret)
totalTextCount += str.Length;
System.Diagnostics.Debug.Assert(totalTextCount == len);
#endif
return ret;
}
/// <summary>
/// Do input validation tests
/// </summary>
/// <param name="tag"></param>
/// <param name="text"></param>
private void ValidateInput(string tag, string text)
{
if (tag == null)
throw new ArgumentNullException("Tag must not be null");
if (text == null)
throw new ArgumentNullException("Text must not be null");
if (!ValidateLength(tag))
throw new ArgumentException("Tag must be 256 chars or less");
if (!ValidateTextContent(tag))
throw new ArgumentException(
"Tag must only be letters, numbers or '-', '.'");
}
/// <summary>
/// Ensure that the text that is being sent is only alphanumeric
/// and hypen
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private bool ValidateTextContent(string str)
{
char[] chars = str.ToCharArray();
foreach (char ch in chars)
{
if (!(char.IsLetterOrDigit(ch) || ch == '-' || ch=='.'))
return false;
}
return true;
}
/// <summary>
/// Ensure that the names and tags fit within the safe window after
/// we've put a GUID and a serial on the end of them
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private bool ValidateLength(string str)
{
if (str == null)
return false;
if (str.Length > MAX_NAME_LENGTH)
return false;
else
return true;
}
#endregion
#region IDisposable Members
public void Dispose()
{
try
{
uploaderThread.Abort();
conn.Close();
conn.Dispose();
}
catch (Exception)
{
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
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.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Resources
{
/// <summary>
/// Operations for managing resource groups.
/// </summary>
internal partial class ResourceGroupOperations : IServiceOperations<ResourceManagementClient>, IResourceGroupOperations
{
/// <summary>
/// Initializes a new instance of the ResourceGroupOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ResourceGroupOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Begin deleting resource group.To determine whether the operation
/// has finished processing the request, call
/// GetLongRunningOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be deleted. The name is
/// case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> BeginDeletingAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
// 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);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", 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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && 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
LongRunningOperationResponse result = null;
// Deserialize Response
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Conflict)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Checks whether resource group exists.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to check. The name is case
/// insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupExistsResult> CheckExistenceAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
// 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);
TracingAdapter.Enter(invocationId, this, "CheckExistenceAsync", 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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Head;
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.NoContent && statusCode != HttpStatusCode.NotFound)
{
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
ResourceGroupExistsResult result = null;
// Deserialize Response
result = new ResourceGroupExistsResult();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Exists = true;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be created or updated.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create or update resource
/// group service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupCreateOrUpdateResult> CreateOrUpdateAsync(string resourceGroupName, ResourceGroup parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// 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("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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject resourceGroupValue = new JObject();
requestDoc = resourceGroupValue;
resourceGroupValue["location"] = parameters.Location;
if (parameters.Properties != null)
{
resourceGroupValue["properties"] = JObject.Parse(parameters.Properties);
}
if (parameters.Tags != null)
{
if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
resourceGroupValue["tags"] = tagsDictionary;
}
}
if (parameters.ProvisioningState != null)
{
resourceGroupValue["provisioningState"] = parameters.ProvisioningState;
}
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
ResourceGroupCreateOrUpdateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupCreateOrUpdateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
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 resource group and all of its resources.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be deleted. The name is
/// case insensitive.
/// </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, CancellationToken cancellationToken)
{
ResourceManagementClient 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("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse response = await client.ResourceGroups.BeginDeletingAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupGetResult> GetAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
// 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);
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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.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
ResourceGroupGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a collection of resource groups.
/// </summary>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all resource
/// groups.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource groups.
/// </returns>
public async Task<ResourceGroupListResult> ListAsync(ResourceGroupListParameters parameters, 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>();
tracingParameters.Add("parameters", parameters);
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";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.TagName != null)
{
odataFilter.Add("tagname eq '" + Uri.EscapeDataString(parameters.TagName) + "'");
}
if (parameters != null && parameters.TagValue != null)
{
odataFilter.Add("tagvalue eq '" + Uri.EscapeDataString(parameters.TagValue) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
if (parameters != null && parameters.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()));
}
queryParameters.Add("api-version=2015-11-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.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
ResourceGroupListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupListResult();
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))
{
ResourceGroupExtended resourceGroupJsonFormatInstance = new ResourceGroupExtended();
result.ResourceGroups.Add(resourceGroupJsonFormatInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupJsonFormatInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupJsonFormatInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupJsonFormatInstance.Location = locationInstance;
}
JToken propertiesValue2 = valueValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupJsonFormatInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupJsonFormatInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = valueValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
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>
/// Get a list of deployments.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource groups.
/// </returns>
public async Task<ResourceGroupListResult> 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
// 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
ResourceGroupListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupListResult();
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))
{
ResourceGroupExtended resourceGroupJsonFormatInstance = new ResourceGroupExtended();
result.ResourceGroups.Add(resourceGroupJsonFormatInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupJsonFormatInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupJsonFormatInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupJsonFormatInstance.Location = locationInstance;
}
JToken propertiesValue2 = valueValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupJsonFormatInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupJsonFormatInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = valueValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
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>
/// Resource groups can be updated through a simple PATCH operation to
/// a group address. The format of the request is the same as that for
/// creating a resource groups, though if a field is unspecified
/// current value will be carried over.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be created or updated.
/// The name is case insensitive.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the update state resource group
/// service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupPatchResult> PatchAsync(string resourceGroupName, ResourceGroup parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// 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("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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject resourceGroupValue = new JObject();
requestDoc = resourceGroupValue;
resourceGroupValue["location"] = parameters.Location;
if (parameters.Properties != null)
{
resourceGroupValue["properties"] = JObject.Parse(parameters.Properties);
}
if (parameters.Tags != null)
{
if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
resourceGroupValue["tags"] = tagsDictionary;
}
}
if (parameters.ProvisioningState != null)
{
resourceGroupValue["provisioningState"] = parameters.ProvisioningState;
}
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
ResourceGroupPatchResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupPatchResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
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 Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace Lucene.Net.Index
{
/*
* 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 InfoStream = Lucene.Net.Util.InfoStream;
using ThreadState = Lucene.Net.Index.DocumentsWriterPerThreadPool.ThreadState;
/// <summary>
/// This class controls <see cref="DocumentsWriterPerThread"/> flushing during
/// indexing. It tracks the memory consumption per
/// <see cref="DocumentsWriterPerThread"/> and uses a configured <see cref="flushPolicy"/> to
/// decide if a <see cref="DocumentsWriterPerThread"/> must flush.
/// <para/>
/// In addition to the <see cref="flushPolicy"/> the flush control might set certain
/// <see cref="DocumentsWriterPerThread"/> as flush pending iff a
/// <see cref="DocumentsWriterPerThread"/> exceeds the
/// <see cref="IndexWriterConfig.RAMPerThreadHardLimitMB"/> to prevent address
/// space exhaustion.
/// </summary>
internal sealed class DocumentsWriterFlushControl
{
private readonly long hardMaxBytesPerDWPT;
private long activeBytes = 0;
private long flushBytes = 0;
private volatile int numPending = 0;
private int numDocsSinceStalled = 0; // only with assert
internal readonly AtomicBoolean flushDeletes = new AtomicBoolean(false);
private bool fullFlush = false;
private readonly Queue<DocumentsWriterPerThread> flushQueue = new Queue<DocumentsWriterPerThread>();
// only for safety reasons if a DWPT is close to the RAM limit
private readonly LinkedList<BlockedFlush> blockedFlushes = new LinkedList<BlockedFlush>();
private readonly IdentityHashMap<DocumentsWriterPerThread, long?> flushingWriters = new IdentityHashMap<DocumentsWriterPerThread, long?>();
internal double maxConfiguredRamBuffer = 0;
internal long peakActiveBytes = 0; // only with assert
internal long peakFlushBytes = 0; // only with assert
internal long peakNetBytes = 0; // only with assert
internal long peakDelta = 0; // only with assert
internal readonly DocumentsWriterStallControl stallControl;
private readonly DocumentsWriterPerThreadPool perThreadPool;
private readonly FlushPolicy flushPolicy;
private bool closed = false;
private readonly DocumentsWriter documentsWriter;
private readonly LiveIndexWriterConfig config;
private readonly BufferedUpdatesStream bufferedUpdatesStream;
private readonly InfoStream infoStream;
internal DocumentsWriterFlushControl(DocumentsWriter documentsWriter, LiveIndexWriterConfig config, BufferedUpdatesStream bufferedUpdatesStream)
{
this.infoStream = config.InfoStream;
this.stallControl = new DocumentsWriterStallControl();
this.perThreadPool = documentsWriter.perThreadPool;
this.flushPolicy = documentsWriter.flushPolicy;
this.config = config;
this.hardMaxBytesPerDWPT = config.RAMPerThreadHardLimitMB * 1024 * 1024;
this.documentsWriter = documentsWriter;
this.bufferedUpdatesStream = bufferedUpdatesStream;
}
public long ActiveBytes
{
get
{
lock (this)
{
return activeBytes;
}
}
}
public long FlushBytes
{
get
{
lock (this)
{
return flushBytes;
}
}
}
public long NetBytes
{
get
{
lock (this)
{
return flushBytes + activeBytes;
}
}
}
private long StallLimitBytes
{
get
{
double maxRamMB = config.RAMBufferSizeMB;
return maxRamMB != IndexWriterConfig.DISABLE_AUTO_FLUSH ? (long)(2 * (maxRamMB * 1024 * 1024)) : long.MaxValue;
}
}
private bool AssertMemory()
{
double maxRamMB = config.RAMBufferSizeMB;
if (maxRamMB != IndexWriterConfig.DISABLE_AUTO_FLUSH)
{
// for this assert we must be tolerant to ram buffer changes!
maxConfiguredRamBuffer = Math.Max(maxRamMB, maxConfiguredRamBuffer);
long ram = flushBytes + activeBytes;
long ramBufferBytes = (long)(maxConfiguredRamBuffer * 1024 * 1024);
// take peakDelta into account - worst case is that all flushing, pending and blocked DWPT had maxMem and the last doc had the peakDelta
// 2 * ramBufferBytes -> before we stall we need to cross the 2xRAM Buffer border this is still a valid limit
// (numPending + numFlushingDWPT() + numBlockedFlushes()) * peakDelta) -> those are the total number of DWPT that are not active but not yet fully fluhsed
// all of them could theoretically be taken out of the loop once they crossed the RAM buffer and the last document was the peak delta
// (numDocsSinceStalled * peakDelta) -> at any given time there could be n threads in flight that crossed the stall control before we reached the limit and each of them could hold a peak document
long expected = (2 * (ramBufferBytes)) + ((numPending + NumFlushingDWPT + NumBlockedFlushes) * peakDelta) + (numDocsSinceStalled * peakDelta);
// the expected ram consumption is an upper bound at this point and not really the expected consumption
if (peakDelta < (ramBufferBytes >> 1))
{
/*
* if we are indexing with very low maxRamBuffer like 0.1MB memory can
* easily overflow if we check out some DWPT based on docCount and have
* several DWPT in flight indexing large documents (compared to the ram
* buffer). this means that those DWPT and their threads will not hit
* the stall control before asserting the memory which would in turn
* fail. To prevent this we only assert if the the largest document seen
* is smaller than the 1/2 of the maxRamBufferMB
*/
Debug.Assert(ram <= expected, "actual mem: " + ram + " byte, expected mem: " + expected + " byte, flush mem: " + flushBytes + ", active mem: " + activeBytes + ", pending DWPT: " + numPending + ", flushing DWPT: " + NumFlushingDWPT + ", blocked DWPT: " + NumBlockedFlushes + ", peakDelta mem: " + peakDelta + " byte");
}
}
return true;
}
private void CommitPerThreadBytes(ThreadState perThread)
{
long delta = perThread.dwpt.BytesUsed - perThread.bytesUsed;
perThread.bytesUsed += delta;
/*
* We need to differentiate here if we are pending since setFlushPending
* moves the perThread memory to the flushBytes and we could be set to
* pending during a delete
*/
if (perThread.flushPending)
{
flushBytes += delta;
}
else
{
activeBytes += delta;
}
Debug.Assert(UpdatePeaks(delta));
}
// only for asserts
private bool UpdatePeaks(long delta)
{
peakActiveBytes = Math.Max(peakActiveBytes, activeBytes);
peakFlushBytes = Math.Max(peakFlushBytes, flushBytes);
peakNetBytes = Math.Max(peakNetBytes, NetBytes);
peakDelta = Math.Max(peakDelta, delta);
return true;
}
internal DocumentsWriterPerThread DoAfterDocument(ThreadState perThread, bool isUpdate)
{
lock (this)
{
try
{
CommitPerThreadBytes(perThread);
if (!perThread.flushPending)
{
if (isUpdate)
{
flushPolicy.OnUpdate(this, perThread);
}
else
{
flushPolicy.OnInsert(this, perThread);
}
if (!perThread.flushPending && perThread.bytesUsed > hardMaxBytesPerDWPT)
{
// Safety check to prevent a single DWPT exceeding its RAM limit. this
// is super important since we can not address more than 2048 MB per DWPT
SetFlushPending(perThread);
}
}
DocumentsWriterPerThread flushingDWPT;
if (fullFlush)
{
if (perThread.flushPending)
{
CheckoutAndBlock(perThread);
flushingDWPT = NextPendingFlush();
}
else
{
flushingDWPT = null;
}
}
else
{
flushingDWPT = TryCheckoutForFlush(perThread);
}
return flushingDWPT;
}
finally
{
bool stalled = UpdateStallState();
Debug.Assert(AssertNumDocsSinceStalled(stalled) && AssertMemory());
}
}
}
private bool AssertNumDocsSinceStalled(bool stalled)
{
/*
* updates the number of documents "finished" while we are in a stalled state.
* this is important for asserting memory upper bounds since it corresponds
* to the number of threads that are in-flight and crossed the stall control
* check before we actually stalled.
* see #assertMemory()
*/
if (stalled)
{
numDocsSinceStalled++;
}
else
{
numDocsSinceStalled = 0;
}
return true;
}
internal void DoAfterFlush(DocumentsWriterPerThread dwpt)
{
lock (this)
{
Debug.Assert(flushingWriters.ContainsKey(dwpt));
try
{
long? bytes = flushingWriters[dwpt];
flushingWriters.Remove(dwpt);
flushBytes -= (long)bytes;
perThreadPool.Recycle(dwpt);
Debug.Assert(AssertMemory());
}
finally
{
try
{
UpdateStallState();
}
finally
{
Monitor.PulseAll(this);
}
}
}
}
private bool UpdateStallState()
{
//Debug.Assert(Thread.holdsLock(this));
long limit = StallLimitBytes;
/*
* we block indexing threads if net byte grows due to slow flushes
* yet, for small ram buffers and large documents we can easily
* reach the limit without any ongoing flushes. we need to ensure
* that we don't stall/block if an ongoing or pending flush can
* not free up enough memory to release the stall lock.
*/
bool stall = ((activeBytes + flushBytes) > limit) && (activeBytes < limit) && !closed;
stallControl.UpdateStalled(stall);
return stall;
}
public void WaitForFlush()
{
lock (this)
{
while (flushingWriters.Count != 0)
{
//#if !NETSTANDARD1_6
// try
// {
//#endif
Monitor.Wait(this);
//#if !NETSTANDARD1_6 // LUCENENET NOTE: Senseless to catch and rethrow the same exception type
// }
// catch (ThreadInterruptedException e)
// {
// throw new ThreadInterruptedException("Thread Interrupted Exception", e);
// }
//#endif
}
}
}
/// <summary>
/// Sets flush pending state on the given <see cref="ThreadState"/>. The
/// <see cref="ThreadState"/> must have indexed at least on <see cref="Documents.Document"/> and must not be
/// already pending.
/// </summary>
public void SetFlushPending(ThreadState perThread)
{
lock (this)
{
Debug.Assert(!perThread.flushPending);
if (perThread.dwpt.NumDocsInRAM > 0)
{
perThread.flushPending = true; // write access synced
long bytes = perThread.bytesUsed;
flushBytes += bytes;
activeBytes -= bytes;
numPending++; // write access synced
Debug.Assert(AssertMemory());
} // don't assert on numDocs since we could hit an abort excp. while selecting that dwpt for flushing
}
}
internal void DoOnAbort(ThreadState state)
{
lock (this)
{
try
{
if (state.flushPending)
{
flushBytes -= state.bytesUsed;
}
else
{
activeBytes -= state.bytesUsed;
}
Debug.Assert(AssertMemory());
// Take it out of the loop this DWPT is stale
perThreadPool.Reset(state, closed);
}
finally
{
UpdateStallState();
}
}
}
internal DocumentsWriterPerThread TryCheckoutForFlush(ThreadState perThread)
{
lock (this)
{
return perThread.flushPending ? InternalTryCheckOutForFlush(perThread) : null;
}
}
private void CheckoutAndBlock(ThreadState perThread)
{
perThread.@Lock();
try
{
Debug.Assert(perThread.flushPending, "can not block non-pending threadstate");
Debug.Assert(fullFlush, "can not block if fullFlush == false");
DocumentsWriterPerThread dwpt;
long bytes = perThread.bytesUsed;
dwpt = perThreadPool.Reset(perThread, closed);
numPending--;
blockedFlushes.AddLast(new BlockedFlush(dwpt, bytes));
}
finally
{
perThread.Unlock();
}
}
private DocumentsWriterPerThread InternalTryCheckOutForFlush(ThreadState perThread)
{
//Debug.Assert(Thread.HoldsLock(this));
Debug.Assert(perThread.flushPending);
try
{
// We are pending so all memory is already moved to flushBytes
if (perThread.TryLock())
{
try
{
if (perThread.IsInitialized)
{
//Debug.Assert(perThread.HeldByCurrentThread);
DocumentsWriterPerThread dwpt;
long bytes = perThread.bytesUsed; // do that before
// replace!
dwpt = perThreadPool.Reset(perThread, closed);
Debug.Assert(!flushingWriters.ContainsKey(dwpt), "DWPT is already flushing");
// Record the flushing DWPT to reduce flushBytes in doAfterFlush
flushingWriters[dwpt] = Convert.ToInt64(bytes);
numPending--; // write access synced
return dwpt;
}
}
finally
{
perThread.Unlock();
}
}
return null;
}
finally
{
UpdateStallState();
}
}
public override string ToString()
{
return "DocumentsWriterFlushControl [activeBytes=" + activeBytes + ", flushBytes=" + flushBytes + "]";
}
internal DocumentsWriterPerThread NextPendingFlush()
{
int numPending;
bool fullFlush;
lock (this)
{
DocumentsWriterPerThread poll;
if (flushQueue.Count > 0 && (poll = flushQueue.Dequeue()) != null)
{
UpdateStallState();
return poll;
}
fullFlush = this.fullFlush;
numPending = this.numPending;
}
if (numPending > 0 && !fullFlush) // don't check if we are doing a full flush
{
int limit = perThreadPool.NumThreadStatesActive;
for (int i = 0; i < limit && numPending > 0; i++)
{
ThreadState next = perThreadPool.GetThreadState(i);
if (next.flushPending)
{
DocumentsWriterPerThread dwpt = TryCheckoutForFlush(next);
if (dwpt != null)
{
return dwpt;
}
}
}
}
return null;
}
internal void SetClosed()
{
lock (this)
{
// set by DW to signal that we should not release new DWPT after close
if (!closed)
{
this.closed = true;
perThreadPool.DeactivateUnreleasedStates();
}
}
}
/// <summary>
/// Returns an iterator that provides access to all currently active <see cref="ThreadState"/>s
/// </summary>
public IEnumerator<ThreadState> AllActiveThreadStates()
{
return GetPerThreadsIterator(perThreadPool.NumThreadStatesActive);
}
private IEnumerator<ThreadState> GetPerThreadsIterator(int upto)
{
return new IteratorAnonymousInnerClassHelper(this, upto);
}
private class IteratorAnonymousInnerClassHelper : IEnumerator<ThreadState>
{
private readonly DocumentsWriterFlushControl outerInstance;
private ThreadState current;
private int upto;
private int i;
public IteratorAnonymousInnerClassHelper(DocumentsWriterFlushControl outerInstance, int upto)
{
this.outerInstance = outerInstance;
this.upto = upto;
i = 0;
}
public ThreadState Current
{
get { return current; }
}
public void Dispose()
{
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (i < upto)
{
current = outerInstance.perThreadPool.GetThreadState(i++);
return true;
}
return false;
}
public void Reset()
{
throw new NotSupportedException();
}
}
internal void DoOnDelete()
{
lock (this)
{
// pass null this is a global delete no update
flushPolicy.OnDelete(this, null);
}
}
/// <summary>
/// Returns the number of delete terms in the global pool
/// </summary>
public int NumGlobalTermDeletes
{
get
{
return documentsWriter.deleteQueue.NumGlobalTermDeletes + bufferedUpdatesStream.NumTerms;
}
}
public long DeleteBytesUsed
{
get
{
return documentsWriter.deleteQueue.BytesUsed + bufferedUpdatesStream.BytesUsed;
}
}
internal int NumFlushingDWPT
{
get
{
lock (this)
{
return flushingWriters.Count;
}
}
}
public bool GetAndResetApplyAllDeletes()
{
return flushDeletes.GetAndSet(false);
}
public void SetApplyAllDeletes()
{
flushDeletes.Set(true);
}
internal int NumActiveDWPT
{
get { return this.perThreadPool.NumThreadStatesActive; }
}
internal ThreadState ObtainAndLock()
{
ThreadState perThread = perThreadPool.GetAndLock(Thread.CurrentThread, documentsWriter);
bool success = false;
try
{
if (perThread.IsInitialized && perThread.dwpt.deleteQueue != documentsWriter.deleteQueue)
{
// There is a flush-all in process and this DWPT is
// now stale -- enroll it for flush and try for
// another DWPT:
AddFlushableState(perThread);
}
success = true;
// simply return the ThreadState even in a flush all case sine we already hold the lock
return perThread;
}
finally
{
if (!success) // make sure we unlock if this fails
{
perThread.Unlock();
}
}
}
internal void MarkForFullFlush()
{
DocumentsWriterDeleteQueue flushingQueue;
lock (this)
{
Debug.Assert(!fullFlush, "called DWFC#markForFullFlush() while full flush is still running");
Debug.Assert(fullFlushBuffer.Count == 0, "full flush buffer should be empty: " + fullFlushBuffer);
fullFlush = true;
flushingQueue = documentsWriter.deleteQueue;
// Set a new delete queue - all subsequent DWPT will use this queue until
// we do another full flush
DocumentsWriterDeleteQueue newQueue = new DocumentsWriterDeleteQueue(flushingQueue.generation + 1);
documentsWriter.deleteQueue = newQueue;
}
int limit = perThreadPool.NumThreadStatesActive;
for (int i = 0; i < limit; i++)
{
ThreadState next = perThreadPool.GetThreadState(i);
next.@Lock();
try
{
if (!next.IsInitialized)
{
if (closed && next.IsActive)
{
perThreadPool.DeactivateThreadState(next);
}
continue;
}
Debug.Assert(next.dwpt.deleteQueue == flushingQueue || next.dwpt.deleteQueue == documentsWriter.deleteQueue, " flushingQueue: " + flushingQueue + " currentqueue: " + documentsWriter.deleteQueue + " perThread queue: " + next.dwpt.deleteQueue + " numDocsInRam: " + next.dwpt.NumDocsInRAM);
if (next.dwpt.deleteQueue != flushingQueue)
{
// this one is already a new DWPT
continue;
}
AddFlushableState(next);
}
finally
{
next.Unlock();
}
}
lock (this)
{
/* make sure we move all DWPT that are where concurrently marked as
* pending and moved to blocked are moved over to the flushQueue. There is
* a chance that this happens since we marking DWPT for full flush without
* blocking indexing.*/
PruneBlockedQueue(flushingQueue);
Debug.Assert(AssertBlockedFlushes(documentsWriter.deleteQueue));
//FlushQueue.AddAll(FullFlushBuffer);
foreach (var dwpt in fullFlushBuffer)
{
flushQueue.Enqueue(dwpt);
}
fullFlushBuffer.Clear();
UpdateStallState();
}
Debug.Assert(AssertActiveDeleteQueue(documentsWriter.deleteQueue));
}
private bool AssertActiveDeleteQueue(DocumentsWriterDeleteQueue queue)
{
int limit = perThreadPool.NumThreadStatesActive;
for (int i = 0; i < limit; i++)
{
ThreadState next = perThreadPool.GetThreadState(i);
next.@Lock();
try
{
Debug.Assert(!next.IsInitialized || next.dwpt.deleteQueue == queue, "isInitialized: " + next.IsInitialized + " numDocs: " + (next.IsInitialized ? next.dwpt.NumDocsInRAM : 0));
}
finally
{
next.Unlock();
}
}
return true;
}
private readonly IList<DocumentsWriterPerThread> fullFlushBuffer = new List<DocumentsWriterPerThread>();
internal void AddFlushableState(ThreadState perThread)
{
if (infoStream.IsEnabled("DWFC"))
{
infoStream.Message("DWFC", "addFlushableState " + perThread.dwpt);
}
DocumentsWriterPerThread dwpt = perThread.dwpt;
//Debug.Assert(perThread.HeldByCurrentThread);
Debug.Assert(perThread.IsInitialized);
Debug.Assert(fullFlush);
Debug.Assert(dwpt.deleteQueue != documentsWriter.deleteQueue);
if (dwpt.NumDocsInRAM > 0)
{
lock (this)
{
if (!perThread.flushPending)
{
SetFlushPending(perThread);
}
DocumentsWriterPerThread flushingDWPT = InternalTryCheckOutForFlush(perThread);
Debug.Assert(flushingDWPT != null, "DWPT must never be null here since we hold the lock and it holds documents");
Debug.Assert(dwpt == flushingDWPT, "flushControl returned different DWPT");
fullFlushBuffer.Add(flushingDWPT);
}
}
else
{
perThreadPool.Reset(perThread, closed); // make this state inactive
}
}
/// <summary>
/// Prunes the blockedQueue by removing all DWPT that are associated with the given flush queue.
/// </summary>
private void PruneBlockedQueue(DocumentsWriterDeleteQueue flushingQueue)
{
var node = blockedFlushes.First;
while (node != null)
{
var nextNode = node.Next;
BlockedFlush blockedFlush = node.Value;
if (blockedFlush.Dwpt.deleteQueue == flushingQueue)
{
blockedFlushes.Remove(node);
Debug.Assert(!flushingWriters.ContainsKey(blockedFlush.Dwpt), "DWPT is already flushing");
// Record the flushing DWPT to reduce flushBytes in doAfterFlush
flushingWriters[blockedFlush.Dwpt] = Convert.ToInt64(blockedFlush.Bytes);
// don't decr pending here - its already done when DWPT is blocked
flushQueue.Enqueue(blockedFlush.Dwpt);
}
node = nextNode;
}
}
internal void FinishFullFlush()
{
lock (this)
{
Debug.Assert(fullFlush);
Debug.Assert(flushQueue.Count == 0);
Debug.Assert(flushingWriters.Count == 0);
try
{
if (blockedFlushes.Count > 0)
{
Debug.Assert(AssertBlockedFlushes(documentsWriter.deleteQueue));
PruneBlockedQueue(documentsWriter.deleteQueue);
Debug.Assert(blockedFlushes.Count == 0);
}
}
finally
{
fullFlush = false;
UpdateStallState();
}
}
}
internal bool AssertBlockedFlushes(DocumentsWriterDeleteQueue flushingQueue)
{
foreach (BlockedFlush blockedFlush in blockedFlushes)
{
Debug.Assert(blockedFlush.Dwpt.deleteQueue == flushingQueue);
}
return true;
}
internal void AbortFullFlushes(ISet<string> newFiles)
{
lock (this)
{
try
{
AbortPendingFlushes(newFiles);
}
finally
{
fullFlush = false;
}
}
}
internal void AbortPendingFlushes(ISet<string> newFiles)
{
lock (this)
{
try
{
foreach (DocumentsWriterPerThread dwpt in flushQueue)
{
try
{
documentsWriter.SubtractFlushedNumDocs(dwpt.NumDocsInRAM);
dwpt.Abort(newFiles);
}
catch (Exception)
{
// ignore - keep on aborting the flush queue
}
finally
{
DoAfterFlush(dwpt);
}
}
foreach (BlockedFlush blockedFlush in blockedFlushes)
{
try
{
flushingWriters[blockedFlush.Dwpt] = Convert.ToInt64(blockedFlush.Bytes);
documentsWriter.SubtractFlushedNumDocs(blockedFlush.Dwpt.NumDocsInRAM);
blockedFlush.Dwpt.Abort(newFiles);
}
catch (Exception)
{
// ignore - keep on aborting the blocked queue
}
finally
{
DoAfterFlush(blockedFlush.Dwpt);
}
}
}
finally
{
flushQueue.Clear();
blockedFlushes.Clear();
UpdateStallState();
}
}
}
/// <summary>
/// Returns <c>true</c> if a full flush is currently running
/// </summary>
internal bool IsFullFlush
{
get
{
lock (this)
{
return fullFlush;
}
}
}
/// <summary>
/// Returns the number of flushes that are already checked out but not yet
/// actively flushing
/// </summary>
internal int NumQueuedFlushes
{
get
{
lock (this)
{
return flushQueue.Count;
}
}
}
/// <summary>
/// Returns the number of flushes that are checked out but not yet available
/// for flushing. This only applies during a full flush if a DWPT needs
/// flushing but must not be flushed until the full flush has finished.
/// </summary>
internal int NumBlockedFlushes
{
get
{
lock (this)
{
return blockedFlushes.Count;
}
}
}
private class BlockedFlush
{
internal DocumentsWriterPerThread Dwpt { get; private set; }
internal long Bytes { get; private set; }
internal BlockedFlush(DocumentsWriterPerThread dwpt, long bytes)
: base()
{
this.Dwpt = dwpt;
this.Bytes = bytes;
}
}
/// <summary>
/// This method will block if too many DWPT are currently flushing and no
/// checked out DWPT are available
/// </summary>
internal void WaitIfStalled()
{
if (infoStream.IsEnabled("DWFC"))
{
infoStream.Message("DWFC", "waitIfStalled: numFlushesPending: " + flushQueue.Count + " netBytes: " + NetBytes + " flushBytes: " + FlushBytes + " fullFlush: " + fullFlush);
}
stallControl.WaitIfStalled();
}
/// <summary>
/// Returns <c>true</c> iff stalled
/// </summary>
internal bool AnyStalledThreads()
{
return stallControl.AnyStalledThreads();
}
/// <summary>
/// Returns the <see cref="IndexWriter"/> <see cref="Util.InfoStream"/>
/// </summary>
public InfoStream InfoStream
{
get
{
return infoStream;
}
}
}
}
| |
namespace SagiriBot.Objects.Nsfw
{
using System;
using System.Reflection;
/// <summary>
/// Gelbooru Image Object
/// </summary>
public class GelbooruImage : INsfwImage
{
/// <summary>
/// Gets or sets the height.
/// </summary>
/// <value>The height.</value>
public int Height { get; set; }
/// <summary>
/// Gets or sets the score.
/// </summary>
/// <value>The score.</value>
public int Score { get; set; }
/// <summary>
/// Gets or sets the file URL.
/// </summary>
/// <value>The file URL.</value>
public string File_url { get; set; }
/// <summary>
/// Gets or sets the parent identifier.
/// </summary>
/// <value>The parent identifier.</value>
public long Parent_id { get; set; }
/// <summary>
/// Gets or sets the sample URL.
/// </summary>
/// <value>The sample URL.</value>
public string Sample_url { get; set; }
/// <summary>
/// Gets or sets the width of the sample.
/// </summary>
/// <value>The width of the sample.</value>
public int Sample_width { get; set; }
/// <summary>
/// Gets or sets the height of the sample.
/// </summary>
/// <value>The height of the sample.</value>
public int Sample_height { get; set; }
/// <summary>
/// Gets or sets the preview URL.
/// </summary>
/// <value>The preview URL.</value>
public string Preview_url { get; set; }
/// <summary>
/// Gets or sets the rating.
/// </summary>
/// <value>The rating.</value>
public string Rating { get; set; }
/// <summary>
/// Gets or sets the tags.
/// </summary>
/// <value>The tags.</value>
public string Tags { get; set; }
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
public long Id { get; set; }
/// <summary>
/// Gets or sets the width.
/// </summary>
/// <value>The width.</value>
public int Width { get; set; }
/// <summary>
/// Gets or sets the change.
/// </summary>
/// <value>The change.</value>
public long Change { get; set; }
/// <summary>
/// Gets or sets the md5.
/// </summary>
/// <value>The md5.</value>
public string Md5 { get; set; }
/// <summary>
/// Gets or sets the creator identifier.
/// </summary>
/// <value>The creator identifier.</value>
public long Creator_id { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:StultBot.Objects.GelbooruImage"/> has children.
/// </summary>
/// <value><c>true</c> if has children; otherwise, <c>false</c>.</value>
public bool Has_children { get; set; }
/// <summary>
/// Gets or sets the created at.
/// </summary>
/// <value>The created at.</value>
public DateTime Created_at { get; set; }
/// <summary>
/// Gets or sets the status.
/// </summary>
/// <value>The status.</value>
public string Status { get; set; }
/// <summary>
/// Gets or sets the source.
/// </summary>
/// <value>The source.</value>
public Uri Source { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:StultBot.Objects.GelbooruImage"/> has notes.
/// </summary>
/// <value><c>true</c> if has notes; otherwise, <c>false</c>.</value>
public bool Has_notes { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:StultBot.Objects.GelbooruImage"/> has comments.
/// </summary>
/// <value><c>true</c> if has comments; otherwise, <c>false</c>.</value>
public bool Has_comments { get; set; }
/// <summary>
/// Gets or sets the width of the preview.
/// </summary>
/// <value>The width of the preview.</value>
public int Preview_width { get; set; }
/// <summary>
/// Gets or sets the height of the preview.
/// </summary>
/// <value>The height of the preview.</value>
public int Preview_height { get; set; }
string INsfwImage.Rating => this.Rating;
string INsfwImage.FileUrl => "https:" + this.File_url;
string INsfwImage.Type => "Gelbooru";
/// <summary>
/// Gets or sets the <see cref="T:StultBot.Objects.GelbooruImage"/> with the specified propertyName.
/// </summary>
/// <param name="propertyName">Property name.</param>
/// <returns>a new object</returns>
public object this[string propertyName]
{
get
{
Type gelbooruImageType = typeof(GelbooruImage);
PropertyInfo propInfo = gelbooruImageType.GetProperty(propertyName[0].ToString().ToUpper() + propertyName.Substring(1));
return propInfo.GetValue(this, null);
}
set
{
Type gelbooruImageType = typeof(GelbooruImage);
PropertyInfo propInfo = gelbooruImageType.GetProperty(propertyName[0].ToString().ToUpper() + propertyName.Substring(1));
if (propInfo.PropertyType == typeof(int))
{
try
{
int val = int.Parse(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
if (propInfo.PropertyType == typeof(bool))
{
try
{
var val = bool.Parse(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
if (propInfo.PropertyType == typeof(DateTime))
{
try
{
var val = DateTime.Parse(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
if (propInfo.PropertyType == typeof(Uri))
{
try
{
var val = new Uri(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
if (propInfo.PropertyType == typeof(long))
{
try
{
var val = long.Parse(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
propInfo.SetValue(this, value, null);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Windows.Forms;
using System.ComponentModel;
namespace Probe.Utility
{
/// <summary>
/// This class allows you to tap keyboard and mouse and / or to detect their activity even when an
/// application runes in background or does not have any user interface at all. This class raises
/// common .NET events with KeyEventArgs and MouseEventArgs so you can easily retrive any information you need.
/// </summary>
public class UserActivityHook
{
#region Windows structure definitions
/// <summary>
/// The POINT structure defines the x- and y- coordinates of a point.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/rectangl_0tiq.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class POINT
{
/// <summary>
/// Specifies the x-coordinate of the point.
/// </summary>
public int x;
/// <summary>
/// Specifies the y-coordinate of the point.
/// </summary>
public int y;
}
/// <summary>
/// The MOUSEHOOKSTRUCT structure contains information about a mouse event passed to a WH_MOUSE hook procedure, MouseProc.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class MouseHookStruct
{
/// <summary>
/// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.
/// </summary>
public POINT pt;
/// <summary>
/// Handle to the window that will receive the mouse message corresponding to the mouse event.
/// </summary>
public int hwnd;
/// <summary>
/// Specifies the hit-test value. For a list of hit-test values, see the description of the WM_NCHITTEST message.
/// </summary>
public int wHitTestCode;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}
/// <summary>
/// The MSLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private class MouseLLHookStruct
{
/// <summary>
/// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.
/// </summary>
public POINT pt;
/// <summary>
/// If the message is WM_MOUSEWHEEL, the high-order word of this member is the wheel delta.
/// The low-order word is reserved. A positive value indicates that the wheel was rotated forward,
/// away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
/// One wheel click is defined as WHEEL_DELTA, which is 120.
///If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
/// or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
/// and the low-order word is reserved. This value can be one or more of the following values. Otherwise, mouseData is not used.
///XBUTTON1
///The first X button was pressed or released.
///XBUTTON2
///The second X button was pressed or released.
/// </summary>
public int mouseData;
/// <summary>
/// Specifies the event-injected flag. An application can use the following value to test the mouse flags. Value Purpose
///LLMHF_INJECTED Test the event-injected flag.
///0
///Specifies whether the event was injected. The value is 1 if the event was injected; otherwise, it is 0.
///1-15
///Reserved.
/// </summary>
public int flags;
/// <summary>
/// Specifies the time stamp for this message.
/// </summary>
public int time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}
/// <summary>
/// The KBDLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class KeyboardHookStruct
{
/// <summary>
/// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int vkCode;
/// <summary>
/// Specifies a hardware scan code for the key.
/// </summary>
public int scanCode;
/// <summary>
/// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
/// </summary>
public int flags;
/// <summary>
/// Specifies the time stamp for this message.
/// </summary>
public int time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}
#endregion
#region Windows function imports
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events
/// are associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">
/// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values.
/// </param>
/// <param name="lpfn">
/// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a
/// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link
/// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
/// </param>
/// <param name="hMod">
/// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
/// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
/// the current process and if the hook procedure is within the code associated with the current process.
/// </param>
/// <param name="dwThreadId">
/// [in] Specifies the identifier of the thread with which the hook procedure is to be associated.
/// If this parameter is zero, the hook procedure is associated with all existing threads running in the
/// same desktop as the calling thread.
/// </param>
/// <returns>
/// If the function succeeds, the return value is the handle to the hook procedure.
/// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="idHook">
/// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int UnhookWindowsHookEx(int idHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="idHook">Ignored.</param>
/// <param name="nCode">
/// [in] Specifies the hook code passed to the current hook procedure.
/// The next hook procedure uses this code to determine how to process the hook information.
/// </param>
/// <param name="wParam">
/// [in] Specifies the wParam value passed to the current hook procedure.
/// The meaning of this parameter depends on the type of hook associated with the current hook chain.
/// </param>
/// <param name="lParam">
/// [in] Specifies the lParam value passed to the current hook procedure.
/// The meaning of this parameter depends on the type of hook associated with the current hook chain.
/// </param>
/// <returns>
/// This value is returned by the next hook procedure in the chain.
/// The current hook procedure must also return this value. The meaning of the return value depends on the hook type.
/// For more information, see the descriptions of the individual hook procedures.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(
int idHook,
int nCode,
int wParam,
IntPtr lParam);
/// <summary>
/// The CallWndProc hook procedure is an application-defined or library-defined callback
/// function used with the SetWindowsHookEx function. The HOOKPROC type defines a pointer
/// to this callback function. CallWndProc is a placeholder for the application-defined
/// or library-defined function name.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp
/// </remarks>
private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
/// <summary>
/// The ToAscii function translates the specified virtual-key code and keyboard
/// state to the corresponding character or characters. The function translates the code
/// using the input language and physical keyboard layout identified by the keyboard layout handle.
/// </summary>
/// <param name="uVirtKey">
/// [in] Specifies the virtual-key code to be translated.
/// </param>
/// <param name="uScanCode">
/// [in] Specifies the hardware scan code of the key to be translated.
/// The high-order bit of this value is set if the key is up (not pressed).
/// </param>
/// <param name="lpbKeyState">
/// [in] Pointer to a 256-byte array that contains the current keyboard state.
/// Each element (byte) in the array contains the state of one key.
/// If the high-order bit of a byte is set, the key is down (pressed).
/// The low bit, if set, indicates that the key is toggled on. In this function,
/// only the toggle bit of the CAPS LOCK key is relevant. The toggle state
/// of the NUM LOCK and SCROLL LOCK keys is ignored.
/// </param>
/// <param name="lpwTransKey">
/// [out] Pointer to the buffer that receives the translated character or characters.
/// </param>
/// <param name="fuState">
/// [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
/// </param>
/// <returns>
/// If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values.
/// Value Meaning
/// 0 The specified virtual key has no translation for the current state of the keyboard.
/// 1 One character was copied to the buffer.
/// 2 Two characters were copied to the buffer. This usually happens when a dead-key character
/// (accent or diacritic) stored in the keyboard layout cannot be composed with the specified
/// virtual key to form a single character.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
/// </remarks>
[DllImport("user32")]
private static extern int ToAscii(
int uVirtKey,
int uScanCode,
byte[] lpbKeyState,
byte[] lpwTransKey,
int fuState);
/// <summary>
/// The GetKeyboardState function copies the status of the 256 virtual keys to the
/// specified buffer.
/// </summary>
/// <param name="pbKeyState">
/// [in] Pointer to a 256-byte array that contains keyboard key states.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
/// </remarks>
[DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern short GetKeyState(int vKey);
#endregion
#region Windows constants
//values from Winuser.h in Microsoft SDK.
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events.
/// </summary>
private const int WH_MOUSE_LL = 14;
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events.
/// </summary>
private const int WH_KEYBOARD_LL = 13;
/// <summary>
/// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
/// </summary>
private const int WH_MOUSE = 7;
/// <summary>
/// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
/// </summary>
private const int WH_KEYBOARD = 2;
/// <summary>
/// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
/// </summary>
private const int WM_MOUSEMOVE = 0x200;
/// <summary>
/// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
/// </summary>
private const int WM_LBUTTONDOWN = 0x201;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_RBUTTONDOWN = 0x204;
/// <summary>
/// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
/// </summary>
private const int WM_MBUTTONDOWN = 0x207;
/// <summary>
/// The WM_LBUTTONUP message is posted when the user releases the left mouse button
/// </summary>
private const int WM_LBUTTONUP = 0x202;
/// <summary>
/// The WM_RBUTTONUP message is posted when the user releases the right mouse button
/// </summary>
private const int WM_RBUTTONUP = 0x205;
/// <summary>
/// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
/// </summary>
private const int WM_MBUTTONUP = 0x208;
/// <summary>
/// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
/// </summary>
private const int WM_LBUTTONDBLCLK = 0x203;
/// <summary>
/// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
/// </summary>
private const int WM_RBUTTONDBLCLK = 0x206;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_MBUTTONDBLCLK = 0x209;
/// <summary>
/// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
/// </summary>
private const int WM_MOUSEWHEEL = 0x020A;
/// <summary>
/// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem
/// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.
/// </summary>
private const int WM_KEYDOWN = 0x100;
/// <summary>
/// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem
/// key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed,
/// or a keyboard key that is pressed when a window has the keyboard focus.
/// </summary>
private const int WM_KEYUP = 0x101;
/// <summary>
/// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
/// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
/// presses another key. It also occurs when no window currently has the keyboard focus;
/// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
/// receives the message can distinguish between these two contexts by checking the context
/// code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYDOWN = 0x104;
/// <summary>
/// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
/// releases a key that was pressed while the ALT key was held down. It also occurs when no
/// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
/// to the active window. The window that receives the message can distinguish between
/// these two contexts by checking the context code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYUP = 0x105;
private const byte VK_SHIFT = 0x10;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;
#endregion
/// <summary>
/// Creates an instance of UserActivityHook object and sets mouse and keyboard hooks.
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public UserActivityHook()
{
Start();
}
/// <summary>
/// Creates an instance of UserActivityHook object and installs both or one of mouse and/or keyboard hooks and starts rasing events
/// </summary>
/// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
/// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
/// <remarks>
/// To create an instance without installing hooks call new UserActivityHook(false, false)
/// </remarks>
public UserActivityHook(bool InstallMouseHook, bool InstallKeyboardHook)
{
Start(InstallMouseHook, InstallKeyboardHook);
}
/// <summary>
/// Destruction.
/// </summary>
~UserActivityHook()
{
//uninstall hooks and do not throw exceptions
Stop(true, true, false);
}
/// <summary>
/// Occurs when the user moves the mouse, presses any mouse button or scrolls the wheel
/// </summary>
public event MouseEventHandler OnMouseActivity;
/// <summary>
/// Occurs when the user presses a key
/// </summary>
public event KeyEventHandler KeyDown;
/// <summary>
/// Occurs when the user presses and releases
/// </summary>
public event KeyPressEventHandler KeyPress;
/// <summary>
/// Occurs when the user releases a key
/// </summary>
public event KeyEventHandler KeyUp;
/// <summary>
/// Stores the handle to the mouse hook procedure.
/// </summary>
private int hMouseHook = 0;
/// <summary>
/// Stores the handle to the keyboard hook procedure.
/// </summary>
private int hKeyboardHook = 0;
/// <summary>
/// Declare MouseHookProcedure as HookProc type.
/// </summary>
private static HookProc MouseHookProcedure;
/// <summary>
/// Declare KeyboardHookProcedure as HookProc type.
/// </summary>
private static HookProc KeyboardHookProcedure;
/// <summary>
/// Installs both mouse and keyboard hooks and starts rasing events
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Start()
{
this.Start(true, true);
}
/// <summary>
/// Installs both or one of mouse and/or keyboard hooks and starts rasing events
/// </summary>
/// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
/// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
{
// install Mouse hook only if it is not installed and must be installed
if (hMouseHook == 0 && InstallMouseHook)
{
// Create an instance of HookProc.
MouseHookProcedure = new HookProc(MouseHookProc);
//install hook
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL,
MouseHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
//If SetWindowsHookEx fails.
if (hMouseHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(true, false, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
// install Keyboard hook only if it is not installed and must be installed
if (hKeyboardHook == 0 && InstallKeyboardHook)
{
// Create an instance of HookProc.
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//install hook
hKeyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
KeyboardHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
//If SetWindowsHookEx fails.
if (hKeyboardHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(false, true, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
/// <summary>
/// Stops monitoring both mouse and keyboard events and rasing events.
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Stop()
{
this.Stop(true, true, true);
}
/// <summary>
/// Stops monitoring both or one of mouse and/or keyboard events and rasing events.
/// </summary>
/// <param name="UninstallMouseHook"><b>true</b> if mouse hook must be uninstalled</param>
/// <param name="UninstallKeyboardHook"><b>true</b> if keyboard hook must be uninstalled</param>
/// <param name="ThrowExceptions"><b>true</b> if exceptions which occured during uninstalling must be thrown</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions)
{
//if mouse hook set and must be uninstalled
if (hMouseHook != 0 && UninstallMouseHook)
{
//uninstall hook
int retMouse = UnhookWindowsHookEx(hMouseHook);
//reset invalid handle
hMouseHook = 0;
//if failed and exception must be thrown
if (retMouse == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
//if keyboard hook set and must be uninstalled
if (hKeyboardHook != 0 && UninstallKeyboardHook)
{
//uninstall hook
int retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
//reset invalid handle
hKeyboardHook = 0;
//if failed and exception must be thrown
if (retKeyboard == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
/// <summary>
/// A callback function which will be called every time a mouse activity detected.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
{
// if ok and someone listens to our events
if ((nCode >= 0) && (OnMouseActivity != null))
{
//Marshall the data from callback.
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
//detect button clicked
MouseButtons button = MouseButtons.None;
short mouseDelta = 0;
switch (wParam)
{
case WM_LBUTTONDOWN:
//case WM_LBUTTONUP:
//case WM_LBUTTONDBLCLK:
button = MouseButtons.Left;
break;
case WM_RBUTTONDOWN:
//case WM_RBUTTONUP:
//case WM_RBUTTONDBLCLK:
button = MouseButtons.Right;
break;
case WM_MOUSEWHEEL:
//If the message is WM_MOUSEWHEEL, the high-order word of mouseData member is the wheel delta.
//One wheel click is defined as WHEEL_DELTA, which is 120.
//(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value
mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff);
//If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
//or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
//and the low-order word is reserved. This value can be one or more of the following values.
//Otherwise, mouseData is not used.
break;
}
//double clicks
int clickCount = 0;
if (button != MouseButtons.None)
if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2;
else clickCount = 1;
//generate event
MouseEventArgs e = new MouseEventArgs(
button,
clickCount,
mouseHookStruct.pt.x,
mouseHookStruct.pt.y,
mouseDelta);
//raise it
OnMouseActivity(this, e);
}
//call next hook
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
/// <summary>
/// A callback function which will be called every time a keyboard activity detected.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
//indicates if any of underlaing events set e.Handled flag
bool handled = false;
//it was ok and someone listens to events
if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
//raise KeyDown
if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
KeyDown(this, e);
handled = handled || e.Handled;
}
// raise KeyPress
if (KeyPress != null && wParam == WM_KEYDOWN)
{
bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false);
bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false);
byte[] keyState = new byte[256];
GetKeyboardState(keyState);
byte[] inBuffer = new byte[2];
if (ToAscii(MyKeyboardHookStruct.vkCode,
MyKeyboardHookStruct.scanCode,
keyState,
inBuffer,
MyKeyboardHookStruct.flags) == 1)
{
char key = (char)inBuffer[0];
if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key);
KeyPressEventArgs e = new KeyPressEventArgs(key);
KeyPress(this, e);
handled = handled || e.Handled;
}
}
// raise KeyUp
if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
KeyUp(this, e);
handled = handled || e.Handled;
}
}
//if event handled in application do not handoff to other listeners
if (handled)
return 1;
else
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
}
}
| |
namespace antlr.debug
{
using System;
using System.Reflection;
using Hashtable = System.Collections.Hashtable;
using ArrayList = System.Collections.ArrayList;
using antlr.collections.impl;
/// <summary>A class to assist in firing parser events
/// NOTE: I intentionally _did_not_ synchronize the event firing and
/// add/remove listener methods. This is because the add/remove should
/// _only_ be called by the parser at its start/end, and the _same_thread_
/// should be performing the parsing. This should help performance a tad...
/// </summary>
public class ScannerEventSupport
{
private object source;
private Hashtable listeners;
private MatchEventArgs matchEvent;
private MessageEventArgs messageEvent;
private TokenEventArgs tokenEvent;
private SemanticPredicateEventArgs semPredEvent;
private SyntacticPredicateEventArgs synPredEvent;
private TraceEventArgs traceEvent;
private NewLineEventArgs newLineEvent;
//private ParserController controller;
private int ruleDepth = 0;
public ScannerEventSupport(object source)
{
matchEvent = new MatchEventArgs();
messageEvent = new MessageEventArgs();
tokenEvent = new TokenEventArgs();
traceEvent = new TraceEventArgs();
semPredEvent = new SemanticPredicateEventArgs();
synPredEvent = new SyntacticPredicateEventArgs();
newLineEvent = new NewLineEventArgs();
listeners = new Hashtable();
this.source = source;
}
public virtual void checkController()
{
//if (controller != null)
// controller.checkBreak();
}
public virtual void addDoneListener(Listener l)
{
((CharScanner)source).Done += new TraceEventHandler(l.doneParsing);
listeners[l] = l;
}
public virtual void addMessageListener(MessageListener l)
{
((CharScanner)source).ErrorReported += new MessageEventHandler(l.reportError);
((CharScanner)source).WarningReported += new MessageEventHandler(l.reportWarning);
addDoneListener(l);
}
public virtual void addNewLineListener(NewLineListener l)
{
((CharScanner)source).HitNewLine += new NewLineEventHandler(l.hitNewLine);
addDoneListener(l);
}
public virtual void addParserListener(ParserListener l)
{
if (l is ParserController)
{
//((ParserController) l).ParserEventSupport = this;
//controller = (ParserController) l;
}
addParserMatchListener(l);
addParserTokenListener(l);
addMessageListener(l);
addTraceListener(l);
addSemanticPredicateListener(l);
addSyntacticPredicateListener(l);
}
public virtual void addParserMatchListener(ParserMatchListener l)
{
((CharScanner)source).MatchedChar += new MatchEventHandler(l.parserMatch);
((CharScanner)source).MatchedNotChar += new MatchEventHandler(l.parserMatchNot);
((CharScanner)source).MisMatchedChar += new MatchEventHandler(l.parserMismatch);
((CharScanner)source).MisMatchedNotChar += new MatchEventHandler(l.parserMismatchNot);
addDoneListener(l);
}
public virtual void addParserTokenListener(ParserTokenListener l)
{
((CharScanner)source).ConsumedChar += new TokenEventHandler(l.parserConsume);
((CharScanner)source).CharLA += new TokenEventHandler(l.parserLA);
addDoneListener(l);
}
public virtual void addSemanticPredicateListener(SemanticPredicateListener l)
{
((CharScanner)source).SemPredEvaluated += new SemanticPredicateEventHandler(l.semanticPredicateEvaluated);
addDoneListener(l);
}
public virtual void addSyntacticPredicateListener(SyntacticPredicateListener l)
{
((CharScanner)source).SynPredStarted += new SyntacticPredicateEventHandler(l.syntacticPredicateStarted);
((CharScanner)source).SynPredFailed += new SyntacticPredicateEventHandler(l.syntacticPredicateFailed);
((CharScanner)source).SynPredSucceeded += new SyntacticPredicateEventHandler(l.syntacticPredicateSucceeded);
addDoneListener(l);
}
public virtual void addTraceListener(TraceListener l)
{
((CharScanner)source).EnterRule += new TraceEventHandler(l.enterRule);
((CharScanner)source).ExitRule += new TraceEventHandler(l.exitRule);
addDoneListener(l);
}
public virtual void fireConsume(int c)
{
TokenEventHandler eventDelegate = (TokenEventHandler)((CharScanner)source).Events[Parser.LAEventKey];
if (eventDelegate != null)
{
tokenEvent.setValues(TokenEventArgs.CONSUME, 1, c);
eventDelegate(source, tokenEvent);
}
checkController();
}
public virtual void fireDoneParsing()
{
TraceEventHandler eventDelegate = (TraceEventHandler)((CharScanner)source).Events[Parser.DoneEventKey];
if (eventDelegate != null)
{
traceEvent.setValues(TraceEventArgs.DONE_PARSING, 0, 0, 0);
eventDelegate(source, traceEvent);
}
checkController();
}
public virtual void fireEnterRule(int ruleNum, int guessing, int data)
{
ruleDepth++;
TraceEventHandler eventDelegate = (TraceEventHandler)((CharScanner)source).Events[Parser.EnterRuleEventKey];
if (eventDelegate != null)
{
traceEvent.setValues(TraceEventArgs.ENTER, ruleNum, guessing, data);
eventDelegate(source, traceEvent);
}
checkController();
}
public virtual void fireExitRule(int ruleNum, int guessing, int data)
{
TraceEventHandler eventDelegate = (TraceEventHandler)((CharScanner)source).Events[Parser.ExitRuleEventKey];
if (eventDelegate != null)
{
traceEvent.setValues(TraceEventArgs.EXIT, ruleNum, guessing, data);
eventDelegate(source, traceEvent);
}
checkController();
ruleDepth--;
if (ruleDepth == 0)
fireDoneParsing();
}
public virtual void fireLA(int k, int la)
{
TokenEventHandler eventDelegate = (TokenEventHandler)((CharScanner)source).Events[Parser.LAEventKey];
if (eventDelegate != null)
{
tokenEvent.setValues(TokenEventArgs.LA, k, la);
eventDelegate(source, tokenEvent);
}
checkController();
}
public virtual void fireMatch(char c, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR, c, c, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(char c, BitSet b, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR_BITSET, c, b, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(char c, string target, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR_RANGE, c, target, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(int c, BitSet b, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.BITSET, c, b, text, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(int n, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.TOKEN, n, n, text, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatch(string s, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.STRING, 0, s, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatchNot(char c, char n, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MatchNotEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR, c, n, null, guessing, true, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMatchNot(int c, int n, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MatchNotEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.TOKEN, c, n, text, guessing, true, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(char c, char n, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR, c, n, null, guessing, false, false);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(char c, BitSet b, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR_BITSET, c, b, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(char c, string target, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR_RANGE, c, target, null, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(int i, int n, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.TOKEN, i, n, text, guessing, false, false);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(int i, BitSet b, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.BITSET, i, b, text, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatch(string s, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MisMatchEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.STRING, 0, text, s, guessing, false, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatchNot(char v, char c, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MisMatchNotEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.CHAR, v, c, null, guessing, true, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireMismatchNot(int i, int n, string text, int guessing)
{
MatchEventHandler eventDelegate = (MatchEventHandler)((CharScanner)source).Events[Parser.MisMatchNotEventKey];
if (eventDelegate != null)
{
matchEvent.setValues(MatchEventArgs.TOKEN, i, n, text, guessing, true, true);
eventDelegate(source, matchEvent);
}
checkController();
}
public virtual void fireNewLine(int line)
{
NewLineEventHandler eventDelegate = (NewLineEventHandler)((CharScanner)source).Events[Parser.NewLineEventKey];
if (eventDelegate != null)
{
newLineEvent.Line = line;
eventDelegate(source, newLineEvent);
}
checkController();
}
public virtual void fireReportError(System.Exception e)
{
MessageEventHandler eventDelegate = (MessageEventHandler)((CharScanner)source).Events[Parser.ReportErrorEventKey];
if (eventDelegate != null)
{
messageEvent.setValues(MessageEventArgs.ERROR, e.ToString());
eventDelegate(source, messageEvent);
}
checkController();
}
public virtual void fireReportError(string s)
{
MessageEventHandler eventDelegate = (MessageEventHandler)((CharScanner)source).Events[Parser.ReportErrorEventKey];
if (eventDelegate != null)
{
messageEvent.setValues(MessageEventArgs.ERROR, s);
eventDelegate(source, messageEvent);
}
checkController();
}
public virtual void fireReportWarning(string s)
{
MessageEventHandler eventDelegate = (MessageEventHandler)((CharScanner)source).Events[Parser.ReportWarningEventKey];
if (eventDelegate != null)
{
messageEvent.setValues(MessageEventArgs.WARNING, s);
eventDelegate(source, messageEvent);
}
checkController();
}
public virtual bool fireSemanticPredicateEvaluated(int type, int condition, bool result, int guessing)
{
SemanticPredicateEventHandler eventDelegate = (SemanticPredicateEventHandler)((CharScanner)source).Events[Parser.SemPredEvaluatedEventKey];
if (eventDelegate != null)
{
semPredEvent.setValues(type, condition, result, guessing);
eventDelegate(source, semPredEvent);
}
checkController();
return result;
}
public virtual void fireSyntacticPredicateFailed(int guessing)
{
SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((CharScanner)source).Events[Parser.SynPredFailedEventKey];
if (eventDelegate != null)
{
synPredEvent.setValues(0, guessing);
eventDelegate(source, synPredEvent);
}
checkController();
}
public virtual void fireSyntacticPredicateStarted(int guessing)
{
SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((CharScanner)source).Events[Parser.SynPredStartedEventKey];
if (eventDelegate != null)
{
synPredEvent.setValues(0, guessing);
eventDelegate(source, synPredEvent);
}
checkController();
}
public virtual void fireSyntacticPredicateSucceeded(int guessing)
{
SyntacticPredicateEventHandler eventDelegate = (SyntacticPredicateEventHandler)((CharScanner)source).Events[Parser.SynPredSucceededEventKey];
if (eventDelegate != null)
{
synPredEvent.setValues(0, guessing);
eventDelegate(source, synPredEvent);
}
checkController();
}
public virtual void refreshListeners()
{
Hashtable clonedTable;
lock(listeners.SyncRoot)
{
clonedTable = (Hashtable)listeners.Clone();
}
foreach (Listener l in clonedTable)
{
l.refresh();
}
}
public virtual void removeDoneListener(Listener l)
{
((CharScanner)source).Done -= new TraceEventHandler(l.doneParsing);
listeners.Remove(l);
}
public virtual void removeMessageListener(MessageListener l)
{
((CharScanner)source).ErrorReported -= new MessageEventHandler(l.reportError);
((CharScanner)source).WarningReported -= new MessageEventHandler(l.reportWarning);
removeDoneListener(l);
}
public virtual void removeNewLineListener(NewLineListener l)
{
((CharScanner)source).HitNewLine -= new NewLineEventHandler(l.hitNewLine);
removeDoneListener(l);
}
public virtual void removeParserListener(ParserListener l)
{
removeParserMatchListener(l);
removeMessageListener(l);
removeParserTokenListener(l);
removeTraceListener(l);
removeSemanticPredicateListener(l);
removeSyntacticPredicateListener(l);
}
public virtual void removeParserMatchListener(ParserMatchListener l)
{
((CharScanner)source).MatchedChar -= new MatchEventHandler(l.parserMatch);
((CharScanner)source).MatchedNotChar -= new MatchEventHandler(l.parserMatchNot);
((CharScanner)source).MisMatchedChar -= new MatchEventHandler(l.parserMismatch);
((CharScanner)source).MisMatchedNotChar -= new MatchEventHandler(l.parserMismatchNot);
removeDoneListener(l);
}
public virtual void removeParserTokenListener(ParserTokenListener l)
{
((CharScanner)source).ConsumedChar -= new TokenEventHandler(l.parserConsume);
((CharScanner)source).CharLA -= new TokenEventHandler(l.parserLA);
removeDoneListener(l);
}
public virtual void removeSemanticPredicateListener(SemanticPredicateListener l)
{
((CharScanner)source).SemPredEvaluated -= new SemanticPredicateEventHandler(l.semanticPredicateEvaluated);
removeDoneListener(l);
}
public virtual void removeSyntacticPredicateListener(SyntacticPredicateListener l)
{
((CharScanner)source).SynPredStarted -= new SyntacticPredicateEventHandler(l.syntacticPredicateStarted);
((CharScanner)source).SynPredFailed -= new SyntacticPredicateEventHandler(l.syntacticPredicateFailed);
((CharScanner)source).SynPredSucceeded -= new SyntacticPredicateEventHandler(l.syntacticPredicateSucceeded);
removeDoneListener(l);
}
public virtual void removeTraceListener(TraceListener l)
{
((CharScanner)source).EnterRule -= new TraceEventHandler(l.enterRule);
((CharScanner)source).ExitRule -= new TraceEventHandler(l.exitRule);
removeDoneListener(l);
}
}
}
| |
using System;
using System.CodeDom;
using System.IO;
using System.Text;
using System.Web.Services.Configuration;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
namespace Microsoft.Hs
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
public class HsSoapExtensionAttribute : SoapExtensionAttribute
{
public HsSoapExtensionAttribute()
{
}
public HsSoapExtensionAttribute(bool enabled)
{
m_enabled = enabled;
}
public override int Priority
{
get
{
return m_priority;
}
set
{
m_priority = value;
}
}
public bool Enabled
{
get
{
return m_enabled;
}
set
{
m_enabled = value;
}
}
public override Type ExtensionType
{
get
{
return typeof(HsSoapExtension);
}
}
private int m_priority = 0;
private bool m_enabled = true;
}
/// <summary>
/// The Hs SoapExtension class responsible for intercepting and modifying the request and response soap
/// messages.
/// </summary>
public class HsSoapExtension : SoapExtension
{
public HsSoapExtension()
{
}
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
HsSoapExtensionAttribute attr = attribute as HsSoapExtensionAttribute;
if(attr != null)
{
return attr.Enabled;
}
return true;
}
public override object GetInitializer(Type serviceType)
{
return true;
}
public override void Initialize(object initializer)
{
if(initializer is Boolean)
{
m_enabled = (bool)initializer;
}
}
public override Stream ChainStream(Stream stream)
{
if(!m_enabled)
{
return base.ChainStream(stream);
}
m_oldStream = stream;
m_newStream = new MemoryStream();
return m_newStream;
}
/// <summary>
/// This method is called at all stages of serialization / deserialization and provides
/// the opportunity to modify the inbound / outbound message.
/// </summary>
public override void ProcessMessage(SoapMessage message)
{
if(!m_enabled)
{
return;
}
switch(message.Stage)
{
case SoapMessageStage.BeforeSerialize:
{
break;
}
case SoapMessageStage.AfterSerialize:
{
ProcessHsRequest(message);
break;
}
case SoapMessageStage.BeforeDeserialize:
{
ProcessHsResponse(message);
break;
}
case SoapMessageStage.AfterDeserialize:
{
break;
}
}
}
/// <summary>
/// Used to intercept the HsRequest SOAP and modify it as needed.
/// </summary>
/// <remarks>
/// We need to determine if there is a more efficient way to parse this than
/// with a StringBuilder buffer.
/// </remarks>
private void ProcessHsRequest(SoapMessage message)
{
//
// set the new stream postion to the beginning
//
m_newStream.Position = 0;
//
// read the stream into a StringBuilder
//
TextReader reader = new StreamReader(m_newStream);
TextWriter writer = new StreamWriter(m_oldStream);
StringBuilder request = new StringBuilder();
request.Append(reader.ReadToEnd());
string requestString = request.ToString();
//
// find the location of the <request element
//
int requestPos = requestString.IndexOf(s_requestStartTag);
//
// determine the service name
//
int servicePos = requestString.IndexOf(s_serviceAttribute, requestPos) + s_serviceAttribute.Length;
int servicePosEnd = requestString.IndexOf("\"", servicePos);
string serviceName = requestString.Substring(servicePos, servicePosEnd - servicePos);
//
// get the 'action' being passed and store it in the m_action private member
//
int pathPos = requestString.IndexOf(s_pathStartTag);
int actionPos = requestString.IndexOf(s_actionStartTag, pathPos);
int actionPosEnd = requestString.IndexOf(s_actionCloseTag, actionPos) + s_actionCloseTag.Length;
m_action = requestString.Substring(actionPos, actionPosEnd - actionPos);
//
// get the 'to' value being passed and store it in the m_to private member
//
int toPos = requestString.IndexOf(s_toStartTag, pathPos);
int toPosEnd = requestString.IndexOf(s_toCloseTag, toPos) + s_toCloseTag.Length;
m_to = requestString.Substring(toPos, toPosEnd - toPos);
//
// get the 'fwd' value being passed and store it in the m_forward private member
//
int fwdPos = requestString.IndexOf(s_fwdStartTag, pathPos);
int fwdPosEnd = requestString.IndexOf(s_fwdCloseTag, fwdPos) + s_fwdCloseTag.Length;
m_forward = requestString.Substring(fwdPos, fwdPosEnd - fwdPos);
//
// get the 'rev' value being passed and store it in the m_reverse private member
//
int revPos = requestString.IndexOf(s_revStartTag, pathPos);
int revPosEnd = requestString.IndexOf(s_revCloseTag, revPos) + s_revCloseTag.Length;
m_reverse = requestString.Substring(revPos, revPosEnd - revPos);
//
// get the postion of the request/@method attribute
//
int methodAttPos = requestString.IndexOf(s_methodAttribute, servicePosEnd);
int methodAttPosEnd = requestString.IndexOf("\"", methodAttPos);
string methodAttribute = requestString.Substring(methodAttPos, s_methodAttribute.Length + (methodAttPosEnd - methodAttPos));
//
// determine the method being requestd
//
int bodyPos = requestString.IndexOf(s_soapBodyStartTag) + s_soapBodyStartTag.Length;
int methodPos = requestString.IndexOf("<", bodyPos) + 1;
int methodPosEnd = requestString.IndexOf("Request", methodPos);
string methodName = requestString.Substring(methodPos, methodPosEnd - methodPos);
//
// see if a logfile was specified
//
int licensesPos = requestString.IndexOf(s_licensesStartTag);
int logfileTagPos = requestString.IndexOf(s_logfileStartTag, licensesPos);
if (logfileTagPos != -1)
{
int logfilePos = logfileTagPos + s_logfileStartTag.Length;
int logfileEndPos = requestString.IndexOf(s_logfileEndTag, logfilePos);
m_logfile = requestString.Substring(logfilePos, logfileEndPos - logfilePos);
//
// check to see if we're logging original messages
//
int flagPos = m_logfile.IndexOf(":logOriginalMessages");
if(flagPos != -1)
{
m_logOriginalMessages = true;
m_logfile = m_logfile.Substring(0, flagPos);
}
m_logfileTag = requestString.Substring(logfileTagPos, (logfileEndPos + s_logfileEndTag.Length) - logfileTagPos);
}
//
// write the original request to the log file (this will only work if the logfile was initialized)
//
if(m_logOriginalMessages)
{
WriteToLogFile(request, "Original Request");
}
//
// replace the method name with the one really being called (incase someone forgot to set this)
// but start at the request tag and only replace up to the s:Body tag (for efficiency)
//
request.Replace(methodAttribute, "method=\"" + methodName + "\" ", requestPos, bodyPos - requestPos);
//
// insert a namespace declaration for the service
//
request.Replace(s_soapEnvelopeStartTag, "<soap:Envelope xmlns:m=\"http://schemas.microsoft.com/hs/2001/10/" + serviceName + "\"", 0, pathPos);
//
// remove the logfile tag if it was found
//
if(m_logfileTag != null)
{
request.Replace(m_logfileTag, "");
}
//
// write the modified request to the log file
//
WriteToLogFile(request, "Modified Request");
writer.Write(request.ToString());
writer.Flush();
}
/// <summary>
/// Used to intercept HsResponse SOAP and modify it as needed
/// </summary>
/// <remarks>
/// We need to determine if there is a more efficient way to parse this than
/// with a StringBuilder buffer.
/// </remarks>
private void ProcessHsResponse(SoapMessage message)
{
//
// Write the response to the new stream
//
TextReader reader = new StreamReader(m_oldStream);
TextWriter writer = new StreamWriter(m_newStream);
StringBuilder response = new StringBuilder();
response.Append(reader.ReadToEnd());
//
// write the original response to the log file
//
if(m_logOriginalMessages)
{
WriteToLogFile(response, "Original Response");
}
string responseString = response.ToString();
//
// find the location of the <path element
//
int pathPos = responseString.IndexOf(s_pathStartTag);
//
// get the action element
//
int actionPos = responseString.IndexOf(s_actionStartTag, pathPos);
int actionPosEnd = responseString.IndexOf(s_actionCloseTag, actionPos) + s_actionCloseTag.Length;
string action = responseString.Substring(actionPos, actionPosEnd - actionPos);
//
// get the rev element
//
int revPos = responseString.IndexOf(s_revStartTag, pathPos);
int revPosEnd = responseString.IndexOf(s_revCloseTag, revPos) + s_revCloseTag.Length;
string rev = responseString.Substring(revPos, revPosEnd - revPos);
//
// replace rev with the original one (so the client doesn't have to set this again.
//
response.Replace(rev, m_forward + m_reverse);
//
// replace the action (with the original one) and add the <to> header back
//
response.Replace(action, m_action + m_to);
//
// replace the logfile tag (if it was removed)
//
if(m_logfileTag != null)
{
response.Replace(s_licensesEndTag, m_logfileTag + s_licensesEndTag);
}
//
// write the modified response to the log file
//
WriteToLogFile(response, "Modified Response");
writer.Write(response.ToString());
writer.Flush();
m_newStream.Position = 0;
}
/// <summary>
/// Writes the contents of a StringBuilder instance to a log file
/// </summary>
private void WriteToLogFile(StringBuilder sb, string title)
{
if(m_logfile != null)
{
FileStream fs = new FileStream(m_logfile, FileMode.Append, FileAccess.Write);
StreamWriter w = new StreamWriter(fs);
w.WriteLine("---------------------------------- " + title + " at " + DateTime.Now);
w.Write(sb.ToString());
w.WriteLine(" ");
w.WriteLine(" ");
w.Flush();
fs.Close();
}
}
//
// private member variables
//
private bool m_enabled = true;
private Stream m_oldStream;
private Stream m_newStream;
private string m_forward = "";
private string m_reverse = "";
private string m_action = "";
private string m_to = "";
//
// this temporary variable demonstrates how we'll pass the security context to the soap extension
//
private string m_logfile = null;
private string m_logfileTag = null;
private bool m_logOriginalMessages = false;
//
// common search targets. we declare them here statically to save on the GC
//
private static string s_actionStartTag = "<action";
private static string s_actionCloseTag = "</action>";
private static string s_toStartTag = "<to>";
private static string s_toCloseTag = "</to>";
private static string s_fwdStartTag = "<fwd>";
private static string s_fwdCloseTag = "</fwd>";
private static string s_revStartTag = "<rev>";
private static string s_revCloseTag = "</rev>";
private static string s_requestStartTag = "<request";
private static string s_pathStartTag = "<path";
private static string s_licensesStartTag = "<licenses";
private static string s_licensesEndTag = "</licenses>";
private static string s_soapBodyStartTag = "<soap:Body>";
private static string s_soapEnvelopeStartTag = "<soap:Envelope";
private static string s_serviceAttribute = "service=\"";
private static string s_methodAttribute = "method=\"";
//
// these temporary variables demonstrate how we'll pass the security context to the soap extension
//
private static string s_logfileStartTag = "<temp:logfile xmlns:temp=\"http://temp\">";
private static string s_logfileEndTag = "</temp:logfile>";
}
/// <summary>
/// This class is called during proxy class generation when <hs:operation> is encountered in the service wsdl
/// </summary>
public class HsSoapExtensionImporter : SoapExtensionImporter
{
public override void ImportMethod(CodeAttributeDeclarationCollection metadata)
{
SoapProtocolImporter importer = ImportContext;
HsSoapExtensionOperationBinding hcOperation = (HsSoapExtensionOperationBinding)importer.OperationBinding.Extensions.Find(typeof(HsSoapExtensionOperationBinding));
if(hcOperation == null)
{
//no hc:operation element was found.
return;
}
CodeAttributeDeclaration attr = new CodeAttributeDeclaration(typeof(HsSoapExtensionAttribute).FullName);
attr.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(true)));
metadata.Add(attr);
}
}
/// <summary>
/// This class is invoked when the XmlSerializer is serializing the proxy class and it encounters
/// the [Microsoft.Hs.HsSoapExtensionAttribute()] attribute on the method being called. This is
/// how HsSoapExtension is invoked
/// </summary>
public class HsSoapExtensionReflector : SoapExtensionReflector
{
public override void ReflectMethod()
{
ProtocolReflector reflector = ReflectionContext;
HsSoapExtensionAttribute attr = (HsSoapExtensionAttribute)reflector.Method.GetCustomAttribute(typeof(HsSoapExtensionAttribute));
if (attr != null)
{
HsSoapExtensionOperationBinding hssec = new HsSoapExtensionOperationBinding();
reflector.OperationBinding.Extensions.Add(hssec);
}
}
}
/// <summary>
/// This class associates the <hs:operation> tag in the my*.wsdl with this soap extension
/// </summary>
[XmlFormatExtension("operation", HsSoapExtensionOperationBinding.Namespace, typeof(OperationBinding))]
[XmlFormatExtensionPrefix("hc", HsSoapExtensionOperationBinding.Namespace)]
public class HsSoapExtensionOperationBinding : ServiceDescriptionFormatExtension
{
public const string Namespace = "http://schemas.microsoft.com/hs/2001/10/core";
}
}
| |
// 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 BitFieldExtractUInt64()
{
var test = new ScalarBinaryOpTest__BitFieldExtractUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ScalarBinaryOpTest__BitFieldExtractUInt64
{
private struct TestStruct
{
public UInt64 _fld1;
public UInt16 _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld1 = 0x1E00000000000000;
testStruct._fld2 = 0x0439;
return testStruct;
}
public void RunStructFldScenario(ScalarBinaryOpTest__BitFieldExtractUInt64 testClass)
{
var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static UInt64 _data1;
private static UInt16 _data2;
private static UInt64 _clsVar1;
private static UInt16 _clsVar2;
private UInt64 _fld1;
private UInt16 _fld2;
static ScalarBinaryOpTest__BitFieldExtractUInt64()
{
_clsVar1 = 0x1E00000000000000;
_clsVar2 = 0x0439;
}
public ScalarBinaryOpTest__BitFieldExtractUInt64()
{
Succeeded = true;
_fld1 = 0x1E00000000000000;
_fld2 = 0x0439;
_data1 = 0x1E00000000000000;
_data2 = 0x0439;
}
public bool IsSupported => Bmi1.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Bmi1.X64.BitFieldExtract(
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2))
);
ValidateResult(_data1, _data2, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.BitFieldExtract), new Type[] { typeof(UInt64), typeof(UInt16) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2))
});
ValidateResult(_data1, _data2, (UInt64)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Bmi1.X64.BitFieldExtract(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data1 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1));
var data2 = Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2));
var result = Bmi1.X64.BitFieldExtract(data1, data2);
ValidateResult(data1, data2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarBinaryOpTest__BitFieldExtractUInt64();
var result = Bmi1.X64.BitFieldExtract(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Bmi1.X64.BitFieldExtract(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(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(UInt64 left, UInt16 right, UInt64 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
ulong expectedResult = 15; isUnexpectedResult = (expectedResult != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.BitFieldExtract)}<UInt64>(UInt64, UInt16): BitFieldExtract failed:");
TestLibrary.TestFramework.LogInformation($" left: {left}");
TestLibrary.TestFramework.LogInformation($" right: {right}");
TestLibrary.TestFramework.LogInformation($" result: {result}");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/**
* Copyright 2015 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using biz.dfch.CS.Web.Utilities.OData;
using Microsoft.Data.OData;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
using System.Web.Http.OData;
using System.Web.Http.OData.Extensions;
using System.Web.Http.OData.Routing;
using System.Web.Http;
using System.Net.Http;
using System.Net;
namespace biz.dfch.CS.Web.Utilities.Tests.OData
{
[TestClass]
public class ODataControllerHelperTest
{
private static ODataController controller;
private static HttpRequestMessage httpRequestMessage;
private const string ODATA_LINK = "http://localhost/api/Utilities.svc/BaseEntities(1)";
[TestInitialize]
public void TestInitialize()
{
httpRequestMessage =
new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/Utilities.svc/BaseEntities");
httpRequestMessage.SetConfiguration(new HttpConfiguration());
Mock.SetupStatic(typeof(System.Web.Http.OData.Extensions.HttpRequestMessageExtensions));
}
[TestMethod]
[ExpectedException(typeof(ODataErrorException))]
public void DoResponseCreatedForControllerNotContainingControllerValueInRouteDataThrowsODataErrorException()
{
controller = Mock.Create<ODataController>();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values["controller"])
.Returns("test")
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values.ContainsKey("controller"))
.Returns(false)
.MustBeCalled();
Mock.Assert(controller);
ODataControllerHelper.ResponseCreated(controller, new BaseEntity(1));
}
[TestMethod]
public void DoResponseCreatedReturnsHttpResponseMessageWithStatusCreated()
{
controller = Mock.Create<ODataController>();
Mock.Arrange(() => controller.Request).Returns(httpRequestMessage).MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values.ContainsKey("controller"))
.Returns(true)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values["controller"])
.Returns("test")
.MustBeCalled();
Mock.Arrange(() => controller.Url.CreateODataLink(Arg.IsAny<string>(), Arg.IsAny<IODataPathHandler>(), Arg.IsAny<IList<ODataPathSegment>>()))
.Returns(ODATA_LINK).MustBeCalled();
var response = ODataControllerHelper.ResponseCreated(controller, new BaseEntity(1));
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
Mock.Assert(controller);
}
[TestMethod]
public void DoResponseCreatedReturnsHttpResponseMessageWithLocationSetInHeaders()
{
controller = Mock.Create<ODataController>();
Mock.Arrange(() => controller.Request)
.Returns(httpRequestMessage)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values.ContainsKey("controller"))
.Returns(true)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values["controller"])
.Returns("test")
.MustBeCalled();
Mock.Arrange(() => controller.Url.CreateODataLink(Arg.IsAny<string>(), Arg.IsAny<IODataPathHandler>(), Arg.IsAny<IList<ODataPathSegment>>()))
.Returns(ODATA_LINK)
.MustBeCalled();
var response = ODataControllerHelper.ResponseCreated(controller, new BaseEntity(1));
Assert.IsNotNull(response.Headers.Location);
Assert.AreEqual(ODATA_LINK, response.Headers.Location.ToString());
Mock.Assert(controller);
}
[TestMethod]
public void DoResponseCreatedReturnsHttpResponseMessageWithETagSetInHeaders()
{
controller = Mock.Create<ODataController>();
Mock.Arrange(() => controller.Request).Returns(httpRequestMessage).MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values.ContainsKey("controller"))
.Returns(true)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values["controller"])
.Returns("test")
.MustBeCalled();
Mock.Arrange(() => controller.Url.CreateODataLink(Arg.IsAny<string>(), Arg.IsAny<IODataPathHandler>(), Arg.IsAny<IList<ODataPathSegment>>()))
.Returns(ODATA_LINK)
.MustBeCalled();
var response = ODataControllerHelper.ResponseCreated(controller, new BaseEntity(1));
Assert.IsNotNull(response.Headers.ETag);
Mock.Assert(controller);
}
[TestMethod]
[ExpectedException(typeof(ODataErrorException))]
public void DoResponseAcceptedForControllerNotContainingControllerValueInRouteDataThrowsODataErrorException()
{
controller = Mock.Create<ODataController>();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values.ContainsKey("controller"))
.Returns(false)
.MustBeCalled();
Mock.Assert(controller);
ODataControllerHelper.ResponseAccepted(controller, new BaseEntity(1));
}
[TestMethod]
public void DoResponseAcceptedReturnsHttpResponseMessageWithStatusCreated()
{
controller = Mock.Create<ODataController>();
Mock.Arrange(() => controller.Request).Returns(httpRequestMessage).MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values.ContainsKey("controller"))
.Returns(true)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values["controller"])
.Returns("test")
.MustBeCalled();
Mock.Arrange(() => controller.Url.CreateODataLink(Arg.IsAny<string>(), Arg.IsAny<IODataPathHandler>(), Arg.IsAny<IList<ODataPathSegment>>()))
.Returns(ODATA_LINK)
.MustBeCalled();
var response = ODataControllerHelper.ResponseAccepted(controller, new BaseEntity(1));
Assert.AreEqual(HttpStatusCode.Accepted, response.StatusCode);
Mock.Assert(controller);
}
[TestMethod]
public void DoResponseAcceptedReturnsHttpResponseMessageWithLocationSetInHeaders()
{
controller = Mock.Create<ODataController>();
Mock.Arrange(() => controller.Request)
.Returns(httpRequestMessage)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values.ContainsKey("controller"))
.Returns(true)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values["controller"])
.Returns("test")
.MustBeCalled();
Mock.Arrange(() => controller.Url.CreateODataLink(Arg.IsAny<string>(), Arg.IsAny<IODataPathHandler>(), Arg.IsAny<IList<ODataPathSegment>>()))
.Returns(ODATA_LINK)
.MustBeCalled();
var response = ODataControllerHelper.ResponseAccepted(controller, new BaseEntity(1));
Assert.IsNotNull(response.Headers.Location);
Assert.AreEqual(ODATA_LINK, response.Headers.Location.ToString());
Mock.Assert(controller);
}
[TestMethod]
public void DoResponseAcceptedReturnsHttpResponseMessageWithETagSetInHeaders()
{
controller = Mock.Create<ODataController>();
Mock.Arrange(() => controller.Request)
.Returns(httpRequestMessage)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values.ContainsKey("controller"))
.Returns(true)
.MustBeCalled();
Mock.Arrange(() => controller.ControllerContext.RouteData.Values["controller"])
.Returns("test")
.MustBeCalled();
Mock.Arrange(() => controller.Url.CreateODataLink(Arg.IsAny<string>(), Arg.IsAny<IODataPathHandler>(), Arg.IsAny<IList<ODataPathSegment>>()))
.Returns(ODATA_LINK)
.MustBeCalled();
var response = ODataControllerHelper.ResponseAccepted(controller, new BaseEntity(1));
Assert.IsNotNull(response.Headers.ETag);
Mock.Assert(controller);
}
}
public class BaseEntity
{
public BaseEntity(long id)
{
Id = id;
}
public long Id { 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;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class NormalPriorityProcessor : GlobalOperationAwareIdleProcessor
{
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers;
private readonly ConcurrentDictionary<DocumentId, bool> _higherPriorityDocumentsNotProcessed;
private readonly HashSet<ProjectId> _currentSnapshotVersionTrackingSet;
private ProjectId _currentProjectProcessing;
private Solution _processingSolution;
private IDisposable _projectCache;
// whether this processor is running or not
private Task _running;
public NormalPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
IGlobalOperationNotificationService globalOperationNotificationService,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, processor, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken)
{
_lazyAnalyzers = lazyAnalyzers;
_running = SpecializedTasks.EmptyTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter);
_higherPriorityDocumentsNotProcessed = new ConcurrentDictionary<DocumentId, bool>(concurrencyLevel: 2, capacity: 20);
_currentProjectProcessing = default(ProjectId);
_processingSolution = null;
_currentSnapshotVersionTrackingSet = new HashSet<ProjectId>();
Start();
}
internal ImmutableArray<IIncrementalAnalyzer> Analyzers
{
get
{
return _lazyAnalyzers.Value;
}
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
this.UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_DocumentWorker_Enqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
CheckHigherPriorityDocument(item);
SolutionCrawlerLogger.LogWorkItemEnqueue(
this.Processor._logAggregator, item.Language, item.DocumentId, item.InvocationReasons, item.IsLowPriority, item.ActiveMember, added);
}
private void CheckHigherPriorityDocument(WorkItem item)
{
if (item.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened) ||
item.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed))
{
AddHigherPriorityDocument(item.DocumentId);
}
}
private void AddHigherPriorityDocument(DocumentId id)
{
_higherPriorityDocumentsNotProcessed[id] = true;
SolutionCrawlerLogger.LogHigherPriority(this.Processor._logAggregator, id.Id);
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
if (!_workItemQueue.HasAnyWork)
{
if (_projectCache != null)
{
_projectCache.Dispose();
_projectCache = null;
}
}
return _workItemQueue.WaitAsync(cancellationToken);
}
public Task Running
{
get
{
return _running;
}
}
public bool HasAnyWork
{
get
{
return _workItemQueue.HasAnyWork;
}
}
protected override async Task ExecuteAsync()
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object>();
try
{
// mark it as running
_running = source.Task;
await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false);
// okay, there must be at least one item in the map
await ResetStatesAsync().ConfigureAwait(false);
if (await TryProcessOneHigherPriorityDocumentAsync().ConfigureAwait(false))
{
// successfully processed a high priority document.
return;
}
// process one of documents remaining
var documentCancellation = default(CancellationTokenSource);
WorkItem workItem;
if (!_workItemQueue.TryTakeAnyWork(_currentProjectProcessing, this.Processor.DependencyGraph, out workItem, out documentCancellation))
{
return;
}
// check whether we have been shutdown
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
// check whether we have moved to new project
SetProjectProcessing(workItem.ProjectId);
// process the new document
await ProcessDocumentAsync(this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
protected override Task HigherQueueOperationTask
{
get
{
return this.Processor._highPriorityProcessor.Running;
}
}
protected override bool HigherQueueHasWorkItem
{
get
{
return this.Processor._highPriorityProcessor.HasAnyWork;
}
}
protected override void PauseOnGlobalOperation()
{
_workItemQueue.RequestCancellationOnRunningTasks();
}
private void SetProjectProcessing(ProjectId currentProject)
{
if (currentProject != _currentProjectProcessing)
{
if (_projectCache != null)
{
_projectCache.Dispose();
_projectCache = null;
}
var projectCacheService = _processingSolution.Workspace.Services.GetService<IProjectCacheService>();
if (projectCacheService != null)
{
_projectCache = projectCacheService.EnableCaching(currentProject);
}
}
_currentProjectProcessing = currentProject;
}
private IEnumerable<DocumentId> GetPrioritizedPendingDocuments()
{
if (this.Processor._documentTracker != null)
{
// First the active document
var activeDocumentId = this.Processor._documentTracker.GetActiveDocument();
if (activeDocumentId != null && _higherPriorityDocumentsNotProcessed.ContainsKey(activeDocumentId))
{
yield return activeDocumentId;
}
// Now any visible documents
foreach (var visibleDocumentId in this.Processor._documentTracker.GetVisibleDocuments())
{
if (_higherPriorityDocumentsNotProcessed.ContainsKey(visibleDocumentId))
{
yield return visibleDocumentId;
}
}
}
// Any other opened documents
foreach (var documentId in _higherPriorityDocumentsNotProcessed.Keys)
{
yield return documentId;
}
}
private async Task<bool> TryProcessOneHigherPriorityDocumentAsync()
{
try
{
// this is an best effort algorithm with some shortcommings.
//
// the most obvious issue is if there is a new work item (without a solution change - but very unlikely)
// for a opened document we already processed, the work item will be treated as a regular one rather than higher priority one
// (opened document)
CancellationTokenSource documentCancellation;
foreach (var documentId in this.GetPrioritizedPendingDocuments())
{
if (this.CancellationToken.IsCancellationRequested)
{
return true;
}
// see whether we have work item for the document
WorkItem workItem;
if (!_workItemQueue.TryTake(documentId, out workItem, out documentCancellation))
{
continue;
}
// okay now we have work to do
await ProcessDocumentAsync(this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
// remove opened document processed
bool dummy;
_higherPriorityDocumentsNotProcessed.TryRemove(documentId, out dummy);
return true;
}
return false;
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task ProcessDocumentAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
{
var cancellationToken = source.Token;
var document = _processingSolution.GetDocument(documentId);
if (document != null)
{
await TrackSemanticVersionsAsync(document, workItem, cancellationToken).ConfigureAwait(false);
// if we are called because a document is opened, we invalidate the document so that
// it can be re-analyzed. otherwise, since newly opened document has same version as before
// analyzer will simply return same data back
if (workItem.MustRefresh && !workItem.IsRetry)
{
var isOpen = document.IsOpen();
await ProcessOpenDocumentIfNeeded(analyzers, workItem, document, isOpen, cancellationToken).ConfigureAwait(false);
await ProcessCloseDocumentIfNeeded(analyzers, workItem, document, isOpen, cancellationToken).ConfigureAwait(false);
}
// check whether we are having special reanalyze request
await ProcessReanalyzeDocumentAsync(workItem, document, cancellationToken).ConfigureAwait(false);
await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
else
{
SolutionCrawlerLogger.LogProcessDocumentNotExist(this.Processor._logAggregator);
RemoveDocument(documentId);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessDocument(this.Processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(workItem.DocumentId);
}
}
private async Task TrackSemanticVersionsAsync(Document document, WorkItem workItem, CancellationToken cancellationToken)
{
if (workItem.IsRetry ||
workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentAdded) ||
!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
return;
}
var service = document.Project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (service == null)
{
return;
}
// we already reported about this project for same snapshot, don't need to do it again
if (_currentSnapshotVersionTrackingSet.Contains(document.Project.Id))
{
return;
}
await service.RecordSemanticVersionsAsync(document.Project, cancellationToken).ConfigureAwait(false);
// mark this project as already processed.
_currentSnapshotVersionTrackingSet.Add(document.Project.Id);
}
private async Task ProcessOpenDocumentIfNeeded(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, bool isOpen, CancellationToken cancellationToken)
{
if (!isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened))
{
return;
}
SolutionCrawlerLogger.LogProcessOpenDocument(this.Processor._logAggregator, document.Id.Id);
await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.DocumentOpenAsync(d, c), cancellationToken).ConfigureAwait(false);
}
private async Task ProcessCloseDocumentIfNeeded(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, bool isOpen, CancellationToken cancellationToken)
{
if (isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed))
{
return;
}
SolutionCrawlerLogger.LogProcessCloseDocument(this.Processor._logAggregator, document.Id.Id);
await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.DocumentCloseAsync(d, c), cancellationToken).ConfigureAwait(false);
}
private async Task ProcessReanalyzeDocumentAsync(WorkItem workItem, Document document, CancellationToken cancellationToken)
{
try
{
#if DEBUG
Contract.Requires(!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze) || workItem.Analyzers.Count > 0);
#endif
// no-reanalyze request or we already have a request to re-analyze every thing
if (workItem.MustRefresh || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze))
{
return;
}
// First reset the document state in analyzers.
var reanalyzers = workItem.Analyzers.ToImmutableArray();
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.DocumentResetAsync(d, c), cancellationToken).ConfigureAwait(false);
// no request to re-run syntax change analysis. run it here
if (!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.AnalyzeSyntaxAsync(d, c), cancellationToken).ConfigureAwait(false);
}
// no request to re-run semantic change analysis. run it here
if (!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void RemoveDocument(DocumentId documentId)
{
RemoveDocument(this.Analyzers, documentId);
}
private static void RemoveDocument(IEnumerable<IIncrementalAnalyzer> analyzers, DocumentId documentId)
{
foreach (var analyzer in analyzers)
{
analyzer.RemoveDocument(documentId);
}
}
private void ResetLogAggregatorIfNeeded(Solution currentSolution)
{
if (currentSolution == null || _processingSolution == null ||
currentSolution.Id == _processingSolution.Id)
{
return;
}
SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(
this.Processor._registration.CorrelationId, _processingSolution, this.Processor._logAggregator, this.Analyzers);
this.Processor.ResetLogAggregator();
}
private async Task ResetStatesAsync()
{
try
{
var currentSolution = this.Processor.CurrentSolution;
if (currentSolution != _processingSolution)
{
ResetLogAggregatorIfNeeded(currentSolution);
// clear version tracking set we already reported.
_currentSnapshotVersionTrackingSet.Clear();
_processingSolution = currentSolution;
await RunAnalyzersAsync(this.Analyzers, currentSolution, (a, s, c) => a.NewSolutionSnapshotAsync(s, c), this.CancellationToken).ConfigureAwait(false);
foreach (var id in this.Processor.GetOpenDocumentIds())
{
AddHigherPriorityDocument(id);
}
SolutionCrawlerLogger.LogResetStates(this.Processor._logAggregator);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override void Shutdown()
{
base.Shutdown();
SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(this.Processor._registration.CorrelationId, _processingSolution, this.Processor._logAggregator, this.Analyzers);
_workItemQueue.Dispose();
if (_projectCache != null)
{
_projectCache.Dispose();
_projectCache = null;
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items)
{
CancellationTokenSource source = new CancellationTokenSource();
_processingSolution = this.Processor.CurrentSolution;
foreach (var item in items)
{
ProcessDocumentAsync(analyzers, item, source).Wait();
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
// this shouldn't happen. would like to get some diagnostic
while (_workItemQueue.HasAnyWork)
{
Environment.FailFast("How?");
}
}
}
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using wkt = Google.Protobuf.WellKnownTypes;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Monitoring.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAlertPolicyServiceClientTest
{
[xunit::FactAttribute]
public void GetAlertPolicyRequestObject()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.GetAlertPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAlertPolicyRequestObjectAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.GetAlertPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.GetAlertPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAlertPolicy()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.GetAlertPolicy(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAlertPolicyAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.GetAlertPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.GetAlertPolicyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAlertPolicyResourceNames1()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.GetAlertPolicy(request.AlertPolicyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAlertPolicyResourceNames1Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.GetAlertPolicyAsync(request.AlertPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.GetAlertPolicyAsync(request.AlertPolicyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAlertPolicyResourceNames2()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.GetAlertPolicy(request.ResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAlertPolicyResourceNames2Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.GetAlertPolicyAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.GetAlertPolicyAsync(request.ResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyRequestObject()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyRequestObjectAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicy()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.Name, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.Name, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.Name, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyResourceNames1()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.ProjectName, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyResourceNames1Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.ProjectName, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.ProjectName, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyResourceNames2()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.OrganizationName, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyResourceNames2Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.OrganizationName, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.OrganizationName, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyResourceNames3()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.FolderName, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyResourceNames3Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.FolderName, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.FolderName, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyResourceNames4()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.ResourceName, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyResourceNames4Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.ResourceName, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.ResourceName, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAlertPolicyRequestObject()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAlertPolicy(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAlertPolicyRequestObjectAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAlertPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAlertPolicyAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAlertPolicy()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAlertPolicy(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAlertPolicyAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAlertPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAlertPolicyAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAlertPolicyResourceNames1()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAlertPolicy(request.AlertPolicyName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAlertPolicyResourceNames1Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAlertPolicyAsync(request.AlertPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAlertPolicyAsync(request.AlertPolicyName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAlertPolicyResourceNames2()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAlertPolicy(request.ResourceName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAlertPolicyResourceNames2Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAlertPolicyAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAlertPolicyAsync(request.ResourceName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateAlertPolicyRequestObject()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new wkt::FieldMask(),
AlertPolicy = new AlertPolicy(),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.UpdateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.UpdateAlertPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateAlertPolicyRequestObjectAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new wkt::FieldMask(),
AlertPolicy = new AlertPolicy(),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.UpdateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.UpdateAlertPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.UpdateAlertPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateAlertPolicy()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new wkt::FieldMask(),
AlertPolicy = new AlertPolicy(),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.UpdateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.UpdateAlertPolicy(request.UpdateMask, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateAlertPolicyAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new wkt::FieldMask(),
AlertPolicy = new AlertPolicy(),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.UpdateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.UpdateAlertPolicyAsync(request.UpdateMask, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.UpdateAlertPolicyAsync(request.UpdateMask, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using ToolKit.DirectoryServices.ActiveDirectory;
using Xunit;
namespace UnitTests.DirectoryServices.ActiveDirectory
{
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "Test Suites do not need XML Documentation.")]
public class ComputerTests
{
[Fact]
public void AccountExpires_Should_ReturnExpectedResult()
{
// Arrange
var expected = new DateTime(2015, 12, 2, 5, 0, 0, DateTimeKind.Utc);
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.AccountExpires;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void AccountExpires_Should_ReturnsMaxDateTime_When_EmptyString()
{
// Arrange
var expected = DateTime.MaxValue;
var computer = new Computer(ComputerAccountExpireEmpty());
// Act
var actual = computer.AccountExpires;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void BadPasswordCount_Should_ReturnExpectedResult()
{
// Arrange
const int expected = 2;
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.BadPasswordCount;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void BadPasswordTime_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-05T11:00:51.0451845", null, DateTimeStyles.AdjustToUniversal);
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.BadPasswordTime;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Category_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "CN=Computer,CN=Schema,CN=Configuration,DC=company,DC=local";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Category;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Changed_Should_ReturnExpectedResult()
{
// Arrange
var expected = new DateTime(2015, 10, 28, 15, 39, 34, DateTimeKind.Utc);
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Changed;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void CommonName_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "COMPUTER01";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.CommonName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void ComputerAccountControl_Should_ReturnExpectedResult()
{
// Arrange
const int expected = 4096;
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.ComputerAccountControl;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void CountryCode_Should_ReturnExpectedResult()
{
// Arrange
const int expected = 42;
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.CountryCode;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Created_Should_ReturnExpectedResult()
{
// Arrange
var expected = new DateTime(2015, 10, 5, 11, 0, 50);
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Created;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Ctor_Should_ReturnExpectedResult()
{
// Arrange
var obj = InitializeProperties();
// Act
var computer = new Computer(obj);
// Assert
Assert.NotNull(computer);
}
[Fact]
public void Ctor_Should_ThrowException_When_NonComputerObject()
{
// Arrange
var obj = NotAComputer();
// Act/Assert
Assert.Throws<ArgumentException>(() => _ = new Computer(obj));
}
[Fact]
public void Description_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "Computer For Stuff";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Description;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Disabled_Should_ReturnExpectedResult()
{
// Arrange
const bool expected = false;
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Disabled;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void DistinguishedName_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "CN=COMPUTER01,CN=Computers,DC=company,DC=local";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.DistinguishedName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void DnsHostName_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "computer01.company.local";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.DnsHostName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Groups_Should_ReturnExpectedResult()
{
// Arrange
var expected = new List<string>()
{
"CN=group1,CN=Users,DC=company,DC=local"
};
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Groups;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Guid_Should_ReturnExpectedResult()
{
// Arrange
var expected = Guid.Parse("cd29418b-45d7-4d55-952e-e4da717172af");
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Guid;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void IsDomainController_Should_ReturnFalse_When_NotDomainController()
{
// Arrange
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.IsDomainController();
// Assert
Assert.False(actual);
}
[Fact]
public void IsDomainController_Should_ReturnTrue_When_DomainController()
{
// Arrange
var computer = new Computer(DomainController());
// Act
var actual = computer.IsDomainController();
// Assert
Assert.True(actual);
}
[Fact]
public void IsServer_Should_ReturnTrue_When_DomainContoller()
{
// Arrange
var computer = new Computer(DomainController());
// Act
var actual = computer.IsServer();
// Assert
Assert.True(actual);
}
[Fact]
public void IsServer_Should_ReturnTrue_When_ServerOs()
{
// Arrange
var computer = new Computer(ComputerServer());
// Act
var actual = computer.IsServer();
// Assert
Assert.True(actual);
}
[Fact]
public void IsWorkstation_Should_ReturnExpectedResult()
{
// Arrange
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.IsWorkstation();
// Assert
Assert.True(actual);
}
[Fact]
public void LastLogoff_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-29T00:24:10.5124008", null, DateTimeStyles.AdjustToUniversal);
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.LastLogoff;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void LastLogon_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-27T00:24:04.3524715", null, DateTimeStyles.AdjustToUniversal);
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.LastLogon;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Location_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "Ashburn";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Location;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void LogonCount_Should_ReturnExpectedResult()
{
// Arrange
const int expected = 60;
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.LogonCount;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void ManagedBy_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "CN=user1,CN=Users,DC=company,DC=local";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.ManagedBy;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Modified_Should_ReturnExpectedResult()
{
// Arrange
var expected = new DateTime(2015, 10, 28, 15, 39, 34);
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Modified;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Name_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "COMPUTER01";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Name;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void OperatingSystem_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "Windows 10 Pro";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.OperatingSystem;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void OperatingSystemServicePack_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "1";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.OperatingSystemServicePack;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void OperatingSystemVersion_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "10.0 (10240)";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.OperatingSystemVersion;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void PasswordLastSet_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-05T11:00:51.0459354", null, DateTimeStyles.AdjustToUniversal);
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.PasswordLastSet;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void PrimaryGroupId_Should_ReturnExpectedResult()
{
// Arrange
const int expected = 515;
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.PrimaryGroupId;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void SamAccountName_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "COMPUTER01$";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.SamAccountName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void ServicePrincipalNames_Should_ReturnExpectedResult()
{
// Arrange
var expected = new List<string>()
{
"WSMAN/COMPUTER01",
"WSMAN/COMPUTER01.company.local",
"TERMSRV/COMPUTER01",
"TERMSRV/COMPUTER01.company.local",
"HOST/COMPUTER01",
"HOST/COMPUTER01.company.local"
};
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.ServicePrincipalNames;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Sid_Should_ReturnExpectedResult()
{
// Arrange
const string expected = "S-1-5-21-1501611499-78517565-1004253924-2105";
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.Sid;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UpdateSequenceNumberCreated_Should_ReturnExpectedResult()
{
// Arrange
const int expected = 43640;
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.UpdateSequenceNumberCreated;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UpdateSequenceNumberCurrent_Should_ReturnExpectedResult()
{
// Arrange
const int expected = 129204;
var computer = new Computer(InitializeProperties());
// Act
var actual = computer.UpdateSequenceNumberCurrent;
// Assert
Assert.Equal(expected, actual);
}
private Dictionary<string, object> ComputerAccountExpireEmpty()
{
var properties = InitializeProperties();
properties["accountexpires"] = string.Empty;
return properties;
}
private Dictionary<string, object> ComputerServer()
{
var properties = InitializeProperties();
properties["operatingsystem"] = "Windows Server 2012 R2 Standard";
properties["operatingsystemversion"] = "6.3 (9600)";
return properties;
}
private Dictionary<string, object> DomainController()
{
var properties = InitializeProperties();
properties["useraccountcontrol"] = 532480;
properties["operatingsystem"] = "Some Computer OS";
return properties;
}
private Dictionary<string, object> InitializeProperties()
{
return new Dictionary<string, object>()
{
{ "accountexpires", 130935060000000000 },
{ "badpwdcount", 2 },
{ "badpasswordtime", 130885164510451845 },
{ "objectcategory", "CN=Computer,CN=Schema,CN=Configuration,DC=company,DC=local" },
{ "cn", "COMPUTER01" },
{ "useraccountcontrol", 4096 },
{ "countrycode", 42 },
{ "whencreated", DateTime.Parse("10/5/2015 11:00:50", null, DateTimeStyles.AdjustToUniversal) },
{ "description", "Computer For Stuff" },
{ "distinguishedname", "CN=COMPUTER01,CN=Computers,DC=company,DC=local" },
{ "dnshostname", "computer01.company.local" },
{ "memberof", "CN=group1,CN=Users,DC=company,DC=local" },
{ "objectguid", new byte[]
{
0x8B, 0x41, 0x29, 0xCD, 0xD7, 0x45, 0x55, 0x4D,
0x95, 0x2E, 0xE4, 0xDA, 0x71, 0x71, 0x72, 0xAF
}
},
{ "lastlogoff", 130905518505124008 },
{ "lastlogontimestamp", 130903790443524715 },
{ "location", "Ashburn" },
{ "logoncount", 60 },
{ "managedby", "CN=user1,CN=Users,DC=company,DC=local" },
{ "whenchanged", DateTime.Parse("10/28/2015 15:39:34", null, DateTimeStyles.AdjustToUniversal) },
{ "name", "COMPUTER01" },
{ "operatingsystem", "Windows 10 Pro" },
{ "operatingsystemservicepack", "1" },
{ "operatingsystemversion", "10.0 (10240)" },
{ "pwdlastset", 130885164510459354 },
{ "primarygroupid", 515 },
{ "samaccountname", "COMPUTER01$" },
{ "serviceprincipalname", new[]
{
"WSMAN/COMPUTER01",
"WSMAN/COMPUTER01.company.local",
"TERMSRV/COMPUTER01",
"TERMSRV/COMPUTER01.company.local",
"HOST/COMPUTER01",
"HOST/COMPUTER01.company.local"
}
},
{ "objectsid", new byte[]
{
0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
0x15, 0x00, 0x00, 0x00, 0xEB, 0xC5, 0x80, 0x59,
0x3D, 0x15, 0xAE, 0x04, 0xE4, 0xB2, 0xDB, 0x3B,
0x39, 0x08, 0x00, 0x00
}
},
{ "usncreated", (long)43640 },
{ "usnchanged", (long)129204 },
{ "objectclass", new[] { "top", "person", "user", "computer" } }
};
}
private Dictionary<string, object> NotAComputer()
{
var properties = InitializeProperties();
properties["objectclass"] = new[] { "top", "person", "user" };
return properties;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Timers;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Statistics;
using Timer=System.Timers.Timer;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Servers
{
/// <summary>
/// Common base for the main OpenSimServers (user, grid, inventory, region, etc)
/// </summary>
public abstract class BaseOpenSimServer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// This will control a periodic log printout of the current 'show stats' (if they are active) for this
/// server.
/// </summary>
private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000);
protected CommandConsole m_console;
protected OpenSimAppender m_consoleAppender;
protected IAppender m_logFileAppender = null;
/// <summary>
/// Time at which this server was started
/// </summary>
protected DateTime m_startuptime;
/// <summary>
/// Record the initial startup directory for info purposes
/// </summary>
protected string m_startupDirectory = Environment.CurrentDirectory;
/// <summary>
/// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
/// </summary>
protected string m_version;
protected string m_pidFile = String.Empty;
/// <summary>
/// Random uuid for private data
/// </summary>
protected string m_osSecret = String.Empty;
protected BaseHttpServer m_httpServer;
public BaseHttpServer HttpServer
{
get { return m_httpServer; }
}
/// <summary>
/// Holds the non-viewer statistics collection object for this service/server
/// </summary>
protected IStatsCollector m_stats;
public BaseOpenSimServer()
{
m_startuptime = DateTime.Now;
m_version = VersionInfo.Version;
// Random uuid for private data
m_osSecret = UUID.Random().ToString();
m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
m_periodicDiagnosticsTimer.Enabled = true;
// This thread will go on to become the console listening thread
Thread.CurrentThread.Name = "ConsoleThread";
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
foreach (IAppender appender in appenders)
{
if (appender.Name == "LogFileAppender")
{
m_logFileAppender = appender;
}
}
}
/// <summary>
/// Must be overriden by child classes for their own server specific startup behaviour.
/// </summary>
protected virtual void StartupSpecific()
{
if (m_console != null)
{
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
m_consoleAppender = (OpenSimAppender)appender;
break;
}
}
if (null == m_consoleAppender)
{
Notice("No appender named Console found (see the log4net config file for this executable)!");
}
else
{
m_consoleAppender.Console = m_console;
// If there is no threshold set then the threshold is effectively everything.
if (null == m_consoleAppender.Threshold)
m_consoleAppender.Threshold = Level.All;
Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
}
m_console.Commands.AddCommand("base", false, "quit",
"quit",
"Quit the application", HandleQuit);
m_console.Commands.AddCommand("base", false, "shutdown",
"shutdown",
"Quit the application", HandleQuit);
m_console.Commands.AddCommand("base", false, "set log level",
"set log level <level>",
"Set the console logging level", HandleLogLevel);
m_console.Commands.AddCommand("base", false, "show info",
"show info",
"Show general information", HandleShow);
m_console.Commands.AddCommand("base", false, "show stats",
"show stats",
"Show statistics", HandleShow);
m_console.Commands.AddCommand("base", false, "show threads",
"show threads",
"Show thread status", HandleShow);
m_console.Commands.AddCommand("base", false, "show uptime",
"show uptime",
"Show server uptime", HandleShow);
m_console.Commands.AddCommand("base", false, "show version",
"show version",
"Show server version", HandleShow);
}
}
/// <summary>
/// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
/// </summary>
public virtual void ShutdownSpecific() {}
/// <summary>
/// Provides a list of help topics that are available. Overriding classes should append their topics to the
/// information returned when the base method is called.
/// </summary>
///
/// <returns>
/// A list of strings that represent different help topics on which more information is available
/// </returns>
protected virtual List<string> GetHelpTopics() { return new List<string>(); }
/// <summary>
/// Print statistics to the logfile, if they are active
/// </summary>
protected void LogDiagnostics(object source, ElapsedEventArgs e)
{
StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n");
sb.Append(GetUptimeReport());
if (m_stats != null)
{
sb.Append(m_stats.Report());
}
sb.Append(Environment.NewLine);
sb.Append(GetThreadsReport());
m_log.Debug(sb);
}
/// <summary>
/// Get a report about the registered threads in this server.
/// </summary>
protected string GetThreadsReport()
{
StringBuilder sb = new StringBuilder();
ProcessThreadCollection threads = ThreadTracker.GetThreads();
if (threads == null)
{
sb.Append("OpenSim thread tracking is only enabled in DEBUG mode.");
}
else
{
sb.Append(threads.Count + " threads are being tracked:" + Environment.NewLine);
foreach (ProcessThread t in threads)
{
sb.Append("ID: " + t.Id + ", TotalProcessorTime: " + t.TotalProcessorTime + ", TimeRunning: " +
(DateTime.Now - t.StartTime) + ", Pri: " + t.CurrentPriority + ", State: " + t.ThreadState);
if (t.ThreadState == System.Diagnostics.ThreadState.Wait)
sb.Append(", Reason: " + t.WaitReason + Environment.NewLine);
else
sb.Append(Environment.NewLine);
}
}
int workers = 0, ports = 0, maxWorkers = 0, maxPorts = 0;
ThreadPool.GetAvailableThreads(out workers, out ports);
ThreadPool.GetMaxThreads(out maxWorkers, out maxPorts);
sb.Append(Environment.NewLine + "*** ThreadPool threads ***" + Environment.NewLine);
sb.Append("workers: " + (maxWorkers - workers) + " (" + maxWorkers + "); ports: " + (maxPorts - ports) + " (" + maxPorts + ")" + Environment.NewLine);
return sb.ToString();
}
/// <summary>
/// Return a report about the uptime of this server
/// </summary>
/// <returns></returns>
protected string GetUptimeReport()
{
StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
return sb.ToString();
}
/// <summary>
/// Performs initialisation of the scene, such as loading configuration from disk.
/// </summary>
public virtual void Startup()
{
m_log.Info("[STARTUP]: Beginning startup processing");
EnhanceVersionInformation();
m_log.Info("[STARTUP]: Version: " + m_version + "\n");
StartupSpecific();
TimeSpan timeTaken = DateTime.Now - m_startuptime;
m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds);
}
/// <summary>
/// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
/// </summary>
public virtual void Shutdown()
{
ShutdownSpecific();
m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
RemovePIDFile();
Environment.Exit(0);
}
private void HandleQuit(string module, string[] args)
{
Shutdown();
}
private void HandleLogLevel(string module, string[] cmd)
{
if (null == m_consoleAppender)
{
Notice("No appender named Console found (see the log4net config file for this executable)!");
return;
}
string rawLevel = cmd[3];
ILoggerRepository repository = LogManager.GetRepository();
Level consoleLevel = repository.LevelMap[rawLevel];
if (consoleLevel != null)
m_consoleAppender.Threshold = consoleLevel;
else
Notice(
String.Format(
"{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
rawLevel));
Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
}
/// <summary>
/// Show help information
/// </summary>
/// <param name="helpArgs"></param>
protected virtual void ShowHelp(string[] helpArgs)
{
Notice("");
if (helpArgs.Length == 0)
{
Notice("set log level [level] - change the console logging level only. For example, off or debug.");
Notice("show info - show server information (e.g. startup path).");
if (m_stats != null)
Notice("show stats - show statistical information for this server");
Notice("show threads - list tracked threads");
Notice("show uptime - show server startup time and uptime.");
Notice("show version - show server version.");
Notice("");
return;
}
}
public virtual void HandleShow(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] showParams = args.ToArray();
switch (showParams[0])
{
case "info":
Notice("Version: " + m_version);
Notice("Startup directory: " + m_startupDirectory);
break;
case "stats":
if (m_stats != null)
Notice(m_stats.Report());
break;
case "threads":
Notice(GetThreadsReport());
break;
case "uptime":
Notice(GetUptimeReport());
break;
case "version":
Notice(
String.Format(
"Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion));
break;
}
}
/// <summary>
/// Console output is only possible if a console has been established.
/// That is something that cannot be determined within this class. So
/// all attempts to use the console MUST be verified.
/// </summary>
protected void Notice(string msg)
{
if (m_console != null)
{
m_console.Output(msg);
}
}
/// <summary>
/// Enhance the version string with extra information if it's available.
/// </summary>
protected void EnhanceVersionInformation()
{
string buildVersion = string.Empty;
// Add commit hash and date information if available
// The commit hash and date are stored in a file bin/.version
// This file can automatically created by a post
// commit script in the opensim git master repository or
// by issuing the follwoing command from the top level
// directory of the opensim repository
// git log -n 1 --pretty="format:%h: %ci" >bin/.version
// For the full git commit hash use %H instead of %h
//
// The subversion information is deprecated and will be removed at a later date
// Add subversion revision information if available
// Try file "svn_revision" in the current directory first, then the .svn info.
// This allows to make the revision available in simulators not running from the source tree.
// FIXME: Making an assumption about the directory we're currently in - we do this all over the place
// elsewhere as well
string svnRevisionFileName = "svn_revision";
string svnFileName = ".svn/entries";
string gitCommitFileName = ".version";
string inputLine;
int strcmp;
if (File.Exists(gitCommitFileName))
{
StreamReader CommitFile = File.OpenText(gitCommitFileName);
buildVersion = CommitFile.ReadLine();
CommitFile.Close();
m_version += buildVersion ?? "";
}
// Remove the else logic when subversion mirror is no longer used
else
{
if (File.Exists(svnRevisionFileName))
{
StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
buildVersion = RevisionFile.ReadLine();
buildVersion.Trim();
RevisionFile.Close();
}
if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
{
StreamReader EntriesFile = File.OpenText(svnFileName);
inputLine = EntriesFile.ReadLine();
while (inputLine != null)
{
// using the dir svn revision at the top of entries file
strcmp = String.Compare(inputLine, "dir");
if (strcmp == 0)
{
buildVersion = EntriesFile.ReadLine();
break;
}
else
{
inputLine = EntriesFile.ReadLine();
}
}
EntriesFile.Close();
}
m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
}
}
protected void CreatePIDFile(string path)
{
try
{
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
FileStream fs = File.Create(path);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
fs.Close();
m_pidFile = path;
}
catch (Exception)
{
}
}
public string osSecret {
// Secret uuid for the simulator
get { return m_osSecret; }
}
public string StatReport(OSHttpRequest httpRequest)
{
// If we catch a request for "callback", wrap the response in the value for jsonp
if (httpRequest.Query.ContainsKey("callback"))
{
return httpRequest.Query["callback"].ToString() + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
}
else
{
return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
}
}
protected void RemovePIDFile()
{
if (m_pidFile != String.Empty)
{
try
{
File.Delete(m_pidFile);
m_pidFile = String.Empty;
}
catch (Exception)
{
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// VMware Azure specific enable protection input.
/// </summary>
[Newtonsoft.Json.JsonObject("InMageAzureV2")]
public partial class InMageAzureV2EnableProtectionInput : EnableProtectionProviderSpecificInput
{
/// <summary>
/// Initializes a new instance of the
/// InMageAzureV2EnableProtectionInput class.
/// </summary>
public InMageAzureV2EnableProtectionInput()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// InMageAzureV2EnableProtectionInput class.
/// </summary>
/// <param name="storageAccountId">The storage account name.</param>
/// <param name="masterTargetId">The Master target Id.</param>
/// <param name="processServerId">The Process Server Id.</param>
/// <param name="runAsAccountId">The CS account Id.</param>
/// <param name="multiVmGroupId">The multi vm group Id.</param>
/// <param name="multiVmGroupName">The multi vm group name.</param>
/// <param name="disksToInclude">The disks to include list.</param>
/// <param name="targetAzureNetworkId">The selected target Azure
/// network Id.</param>
/// <param name="targetAzureSubnetId">The selected target Azure subnet
/// Id.</param>
/// <param name="enableRDPOnTargetOption">The selected option to enable
/// RDP\SSH on target vm after failover.
/// String value of {SrsDataContract.EnableRDPOnTargetOption}
/// enum.</param>
/// <param name="targetAzureVmName">The target azure Vm Name.</param>
/// <param name="logStorageAccountId">The storage account to be used
/// for logging
/// during replication.</param>
/// <param name="targetAzureV1ResourceGroupId">The Id of the target
/// resource group (for classic deployment) in which the
/// failover VM is to be created.</param>
/// <param name="targetAzureV2ResourceGroupId">The Id of the target
/// resource group (for resource manager deployment) in
/// which the failover VM is to be created.</param>
/// <param name="useManagedDisks">A value indicating whether managed
/// disks should be used during failover.</param>
public InMageAzureV2EnableProtectionInput(string storageAccountId, string masterTargetId = default(string), string processServerId = default(string), string runAsAccountId = default(string), string multiVmGroupId = default(string), string multiVmGroupName = default(string), IList<string> disksToInclude = default(IList<string>), string targetAzureNetworkId = default(string), string targetAzureSubnetId = default(string), string enableRDPOnTargetOption = default(string), string targetAzureVmName = default(string), string logStorageAccountId = default(string), string targetAzureV1ResourceGroupId = default(string), string targetAzureV2ResourceGroupId = default(string), string useManagedDisks = default(string))
{
MasterTargetId = masterTargetId;
ProcessServerId = processServerId;
StorageAccountId = storageAccountId;
RunAsAccountId = runAsAccountId;
MultiVmGroupId = multiVmGroupId;
MultiVmGroupName = multiVmGroupName;
DisksToInclude = disksToInclude;
TargetAzureNetworkId = targetAzureNetworkId;
TargetAzureSubnetId = targetAzureSubnetId;
EnableRDPOnTargetOption = enableRDPOnTargetOption;
TargetAzureVmName = targetAzureVmName;
LogStorageAccountId = logStorageAccountId;
TargetAzureV1ResourceGroupId = targetAzureV1ResourceGroupId;
TargetAzureV2ResourceGroupId = targetAzureV2ResourceGroupId;
UseManagedDisks = useManagedDisks;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the Master target Id.
/// </summary>
[JsonProperty(PropertyName = "masterTargetId")]
public string MasterTargetId { get; set; }
/// <summary>
/// Gets or sets the Process Server Id.
/// </summary>
[JsonProperty(PropertyName = "processServerId")]
public string ProcessServerId { get; set; }
/// <summary>
/// Gets or sets the storage account name.
/// </summary>
[JsonProperty(PropertyName = "storageAccountId")]
public string StorageAccountId { get; set; }
/// <summary>
/// Gets or sets the CS account Id.
/// </summary>
[JsonProperty(PropertyName = "runAsAccountId")]
public string RunAsAccountId { get; set; }
/// <summary>
/// Gets or sets the multi vm group Id.
/// </summary>
[JsonProperty(PropertyName = "multiVmGroupId")]
public string MultiVmGroupId { get; set; }
/// <summary>
/// Gets or sets the multi vm group name.
/// </summary>
[JsonProperty(PropertyName = "multiVmGroupName")]
public string MultiVmGroupName { get; set; }
/// <summary>
/// Gets or sets the disks to include list.
/// </summary>
[JsonProperty(PropertyName = "disksToInclude")]
public IList<string> DisksToInclude { get; set; }
/// <summary>
/// Gets or sets the selected target Azure network Id.
/// </summary>
[JsonProperty(PropertyName = "targetAzureNetworkId")]
public string TargetAzureNetworkId { get; set; }
/// <summary>
/// Gets or sets the selected target Azure subnet Id.
/// </summary>
[JsonProperty(PropertyName = "targetAzureSubnetId")]
public string TargetAzureSubnetId { get; set; }
/// <summary>
/// Gets or sets the selected option to enable RDP\SSH on target vm
/// after failover.
/// String value of {SrsDataContract.EnableRDPOnTargetOption} enum.
/// </summary>
[JsonProperty(PropertyName = "enableRDPOnTargetOption")]
public string EnableRDPOnTargetOption { get; set; }
/// <summary>
/// Gets or sets the target azure Vm Name.
/// </summary>
[JsonProperty(PropertyName = "targetAzureVmName")]
public string TargetAzureVmName { get; set; }
/// <summary>
/// Gets or sets the storage account to be used for logging
/// during replication.
/// </summary>
[JsonProperty(PropertyName = "logStorageAccountId")]
public string LogStorageAccountId { get; set; }
/// <summary>
/// Gets or sets the Id of the target resource group (for classic
/// deployment) in which the
/// failover VM is to be created.
/// </summary>
[JsonProperty(PropertyName = "targetAzureV1ResourceGroupId")]
public string TargetAzureV1ResourceGroupId { get; set; }
/// <summary>
/// Gets or sets the Id of the target resource group (for resource
/// manager deployment) in
/// which the failover VM is to be created.
/// </summary>
[JsonProperty(PropertyName = "targetAzureV2ResourceGroupId")]
public string TargetAzureV2ResourceGroupId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether managed disks should be
/// used during failover.
/// </summary>
[JsonProperty(PropertyName = "useManagedDisks")]
public string UseManagedDisks { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (StorageAccountId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "StorageAccountId");
}
}
}
}
| |
// 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.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class DeflateStreamTests
{
static string gzTestFile(string fileName) => Path.Combine("GZTestData", fileName);
[Fact]
public void BaseStream1()
{
var writeStream = new MemoryStream();
var zip = new DeflateStream(writeStream, CompressionMode.Compress);
Assert.Same(zip.BaseStream, writeStream);
writeStream.Dispose();
}
[Fact]
public void BaseStream2()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Decompress);
Assert.Same(zip.BaseStream, ms);
ms.Dispose();
}
[Fact]
public async Task ModifyBaseStream()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var newMs = StripHeaderAndFooter.Strip(ms);
var zip = new DeflateStream(newMs, CompressionMode.Decompress);
int size = 1024;
byte[] bytes = new byte[size];
zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected
zip.BaseStream.Position = 0;
await zip.BaseStream.ReadAsync(bytes, 0, size);
}
[Fact]
public void DecompressCanRead()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Decompress);
Assert.True(zip.CanRead);
zip.Dispose();
Assert.False(zip.CanRead);
}
[Fact]
public void CompressCanWrite()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Compress);
Assert.True(zip.CanWrite);
zip.Dispose();
Assert.False(zip.CanWrite);
}
[Fact]
public void CanDisposeBaseStream()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Compress);
ms.Dispose(); // This would throw if this was invalid
}
[Fact]
public void CanDisposeDeflateStream()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Compress);
zip.Dispose();
// Base Stream should be null after dispose
Assert.Null(zip.BaseStream);
zip.Dispose(); // Should be a no-op
}
[Fact]
public async Task CanReadBaseStreamAfterDispose()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var newMs = StripHeaderAndFooter.Strip(ms);
var zip = new DeflateStream(newMs, CompressionMode.Decompress, leaveOpen: true);
var baseStream = zip.BaseStream;
zip.Dispose();
int size = 1024;
byte[] bytes = new byte[size];
baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected
baseStream.Position = 0;
await baseStream.ReadAsync(bytes, 0, size);
}
[Fact]
public async Task DecompressFailsWithRealGzStream()
{
string[] files = { gzTestFile("GZTestDocument.doc.gz"), gzTestFile("GZTestDocument.txt.gz") };
foreach (string fileName in files)
{
var baseStream = await LocalMemoryStream.readAppFileAsync(fileName);
var zip = new DeflateStream(baseStream, CompressionMode.Decompress);
int _bufferSize = 2048;
var bytes = new byte[_bufferSize];
Assert.Throws<InvalidDataException>(() => { zip.Read(bytes, 0, _bufferSize); });
zip.Dispose();
}
}
[Fact]
public void DisposedBaseStreamThrows()
{
var ms = new MemoryStream();
ms.Dispose();
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var deflate = new DeflateStream(ms, CompressionMode.Decompress);
});
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var deflate = new DeflateStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void ReadOnlyStreamThrowsOnCompress()
{
var ms = new LocalMemoryStream();
ms.SetCanWrite(false);
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var gzip = new DeflateStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void WriteOnlyStreamThrowsOnDecompress()
{
var ms = new LocalMemoryStream();
ms.SetCanRead(false);
AssertExtensions.Throws<ArgumentException>("stream", () =>
{
var gzip = new DeflateStream(ms, CompressionMode.Decompress);
});
}
[Fact]
public void TestCtors()
{
CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression };
foreach (CompressionLevel level in legalValues)
{
bool[] boolValues = new bool[] { true, false };
foreach (bool remainsOpen in boolValues)
{
TestCtor(level, remainsOpen);
}
}
}
[Fact]
public void TestLevelOptimial()
{
TestCtor(CompressionLevel.Optimal);
}
[Fact]
public void TestLevelNoCompression()
{
TestCtor(CompressionLevel.NoCompression);
}
[Fact]
public void TestLevelFastest()
{
TestCtor(CompressionLevel.Fastest);
}
private static void TestCtor(CompressionLevel level, bool? leaveOpen = null)
{
//Create the DeflateStream
int _bufferSize = 1024;
var bytes = new byte[_bufferSize];
var baseStream = new MemoryStream(bytes, writable: true);
DeflateStream ds;
if (leaveOpen == null)
{
ds = new DeflateStream(baseStream, level);
}
else
{
ds = new DeflateStream(baseStream, level, leaveOpen ?? false);
}
//Write some data and Close the stream
string strData = "Test Data";
var encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(strData);
ds.Write(data, 0, data.Length);
ds.Flush();
ds.Dispose();
if (leaveOpen != true)
{
//Check that Close has really closed the underlying stream
Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); });
}
//Read the data
byte[] data2 = new byte[_bufferSize];
baseStream = new MemoryStream(bytes, writable: false);
ds = new DeflateStream(baseStream, CompressionMode.Decompress);
int size = ds.Read(data2, 0, _bufferSize - 5);
//Verify the data roundtripped
for (int i = 0; i < size + 5; i++)
{
if (i < data.Length)
{
Assert.Equal(data[i], data2[i]);
}
else
{
Assert.Equal(data2[i], (byte)0);
}
}
}
[Fact]
public void CtorArgumentValidation()
{
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionLevel.Fastest));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Decompress));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Compress));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionLevel.Fastest, true));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Decompress, false));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Compress, true));
AssertExtensions.Throws<ArgumentException>("mode", () => new DeflateStream(new MemoryStream(), (CompressionMode)42));
AssertExtensions.Throws<ArgumentException>("mode", () => new DeflateStream(new MemoryStream(), (CompressionMode)43, true));
AssertExtensions.Throws<ArgumentException>("stream", () => new DeflateStream(new MemoryStream(new byte[1], writable: false), CompressionLevel.Optimal));
}
[Fact]
public async Task Flush()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Flush();
await ds.FlushAsync();
}
[Fact]
public void DoubleFlush()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Flush();
ds.Flush();
}
[Fact]
public void DoubleDispose()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Dispose();
ds.Dispose();
}
[Fact]
public void FlushThenDispose()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Flush();
ds.Dispose();
}
[Fact]
public void FlushFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Dispose();
Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); });
}
[Fact]
public async Task FlushAsyncFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(async () =>
{
await ds.FlushAsync();
});
}
[Fact]
public void TestSeekMethodsDecompress()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Decompress);
Assert.False(zip.CanSeek, "CanSeek should be false");
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
}
[Fact]
public void TestSeekMethodsCompress()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Compress);
Assert.False(zip.CanSeek, "CanSeek should be false");
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
}
[Fact]
public void ReadWriteArgumentValidation()
{
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<ArgumentNullException>(() => ds.Write(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], 0, -1));
AssertExtensions.Throws<ArgumentException>(null, () => ds.Write(new byte[1], 0, 2));
AssertExtensions.Throws<ArgumentException>(null, () => ds.Write(new byte[1], 1, 1));
Assert.Throws<InvalidOperationException>(() => ds.Read(new byte[1], 0, 1));
ds.Write(new byte[1], 0, 0);
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<ArgumentNullException>(() => { ds.WriteAsync(null, 0, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], -1, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], 0, -1); });
AssertExtensions.Throws<ArgumentException>(null, () => { ds.WriteAsync(new byte[1], 0, 2); });
AssertExtensions.Throws<ArgumentException>(null, () => { ds.WriteAsync(new byte[1], 1, 1); });
Assert.Throws<InvalidOperationException>(() => { ds.Read(new byte[1], 0, 1); });
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress))
{
Assert.Throws<ArgumentNullException>(() => ds.Read(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], 0, -1));
AssertExtensions.Throws<ArgumentException>(null, () => ds.Read(new byte[1], 0, 2));
AssertExtensions.Throws<ArgumentException>(null, () => ds.Read(new byte[1], 1, 1));
Assert.Throws<InvalidOperationException>(() => ds.Write(new byte[1], 0, 1));
var data = new byte[1] { 42 };
Assert.Equal(0, ds.Read(data, 0, 0));
Assert.Equal(42, data[0]);
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress))
{
Assert.Throws<ArgumentNullException>(() => { ds.ReadAsync(null, 0, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], -1, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], 0, -1); });
AssertExtensions.Throws<ArgumentException>(null, () => { ds.ReadAsync(new byte[1], 0, 2); });
AssertExtensions.Throws<ArgumentException>(null, () => { ds.ReadAsync(new byte[1], 1, 1); });
Assert.Throws<InvalidOperationException>(() => { ds.Write(new byte[1], 0, 1); });
}
}
[Fact]
public void CopyToAsyncArgumentValidation()
{
using (DeflateStream ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress))
{
AssertExtensions.Throws<ArgumentNullException>("destination", () => { ds.CopyToAsync(null); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { ds.CopyToAsync(new MemoryStream(), 0); });
Assert.Throws<NotSupportedException>(() => { ds.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
ds.Dispose();
Assert.Throws<ObjectDisposedException>(() => { ds.CopyToAsync(new MemoryStream()); });
}
using (DeflateStream ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<NotSupportedException>(() => { ds.CopyToAsync(new MemoryStream()); });
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public void Precancellation()
{
var ms = new MemoryStream();
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress, leaveOpen: true))
{
Assert.True(ds.WriteAsync(new byte[1], 0, 1, new CancellationToken(true)).IsCanceled);
Assert.True(ds.FlushAsync(new CancellationToken(true)).IsCanceled);
}
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
{
Assert.True(ds.ReadAsync(new byte[1], 0, 1, new CancellationToken(true)).IsCanceled);
}
}
[Fact]
public async Task RoundtripCompressDecompress()
{
await RoundtripCompressDecompress(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest);
await RoundtripCompressDecompress(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public async Task RoundTripWithFlush()
{
await RoundTripWithFlush(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest);
await RoundTripWithFlush(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public async Task WriteAfterFlushing()
{
await WriteAfterFlushing(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest);
await WriteAfterFlushing(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public async Task FlushBeforeFirstWrites()
{
await FlushBeforeFirstWrites(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest);
await FlushBeforeFirstWrites(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal);
}
public static IEnumerable<object[]> RoundtripCompressDecompressOuterData
{
get
{
foreach (bool useAsync in new[] { true, false }) // whether to use Read/Write or ReadAsync/WriteAsync
{
foreach (bool useGzip in new[] { true, false }) // whether to add on gzip headers/footers
{
foreach (var level in new[] { CompressionLevel.Fastest, CompressionLevel.Optimal, CompressionLevel.NoCompression }) // compression level
{
yield return new object[] { useAsync, useGzip, 1, 5, level }; // smallest possible writes
yield return new object[] { useAsync, useGzip, 1023, 1023 * 10, level }; // overflowing internal buffer
yield return new object[] { useAsync, useGzip, 1024 * 1024, 1024 * 1024, level }; // large single write
}
}
}
}
}
[OuterLoop]
[Theory]
[MemberData(nameof(RoundtripCompressDecompressOuterData))]
public async Task RoundtripCompressDecompress(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level)
{
byte[] data = new byte[totalSize];
new Random(42).NextBytes(data);
var compressed = new MemoryStream();
using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true))
{
for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test
{
switch (useAsync)
{
case true: await compressor.WriteAsync(data, i, chunkSize); break;
case false: compressor.Write(data, i, chunkSize); break;
}
}
}
compressed.Position = 0;
await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data);
compressed.Dispose();
}
[OuterLoop]
[Theory]
[MemberData(nameof(RoundtripCompressDecompressOuterData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public async Task RoundTripWithFlush(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level)
{
byte[] data = new byte[totalSize];
new Random(42).NextBytes(data);
using (var compressed = new MemoryStream())
using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true))
{
for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test
{
switch (useAsync)
{
case true: await compressor.WriteAsync(data, i, chunkSize); break;
case false: compressor.Write(data, i, chunkSize); break;
}
}
switch (useAsync)
{
case true: await compressor.FlushAsync(); break;
case false: compressor.Flush(); break;
}
compressed.Position = 0;
await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data);
}
}
[OuterLoop]
[Theory]
[MemberData(nameof(RoundtripCompressDecompressOuterData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public async Task WriteAfterFlushing(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level)
{
byte[] data = new byte[totalSize];
List<byte> expected = new List<byte>();
new Random(42).NextBytes(data);
using (var compressed = new MemoryStream())
using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true))
{
for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test
{
switch (useAsync)
{
case true: await compressor.WriteAsync(data, i, chunkSize); break;
case false: compressor.Write(data, i, chunkSize); break;
}
for (int j = i; j < i + chunkSize; j++)
expected.Insert(j, data[j]);
switch (useAsync)
{
case true: await compressor.FlushAsync(); break;
case false: compressor.Flush(); break;
}
MemoryStream partiallyCompressed = new MemoryStream(compressed.ToArray());
partiallyCompressed.Position = 0;
await ValidateCompressedData(useAsync, useGzip, chunkSize, partiallyCompressed, expected.ToArray());
}
}
}
[OuterLoop]
[Theory]
[MemberData(nameof(RoundtripCompressDecompressOuterData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public async Task FlushBeforeFirstWrites(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level)
{
byte[] data = new byte[totalSize];
new Random(42).NextBytes(data);
using (var compressed = new MemoryStream())
using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true))
{
switch (useAsync)
{
case true: await compressor.FlushAsync(); break;
case false: compressor.Flush(); break;
}
for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test
{
switch (useAsync)
{
case true: await compressor.WriteAsync(data, i, chunkSize); break;
case false: compressor.Write(data, i, chunkSize); break;
}
}
switch (useAsync)
{
case true: await compressor.FlushAsync(); break;
case false: compressor.Flush(); break;
}
compressed.Position = 0;
await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data);
}
}
/// <summary>
/// Given a MemoryStream of compressed data and a byte array of desired output, decompresses
/// the stream and validates that it is equal to the expected array.
/// </summary>
private async Task ValidateCompressedData(bool useAsync, bool useGzip, int chunkSize, MemoryStream compressed, byte[] expected)
{
using (MemoryStream decompressed = new MemoryStream())
using (Stream decompressor = useGzip ? (Stream)new GZipStream(compressed, CompressionMode.Decompress, true) : new DeflateStream(compressed, CompressionMode.Decompress, true))
{
if (useAsync)
decompressor.CopyTo(decompressed, chunkSize);
else
await decompressor.CopyToAsync(decompressed, chunkSize, CancellationToken.None);
Assert.Equal<byte>(expected, decompressed.ToArray());
}
}
[Fact]
public void SequentialReadsOnMemoryStream_Return_SameBytes()
{
byte[] data = new byte[1024 * 10];
new Random(42).NextBytes(data);
var compressed = new MemoryStream();
using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true))
{
for (int i = 0; i < data.Length; i += 1024)
{
compressor.Write(data, i, 1024);
}
}
compressed.Position = 0;
using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true))
{
int i, j;
byte[] array = new byte[100];
byte[] array2 = new byte[100];
// only read in the first 100 bytes
decompressor.Read(array, 0, array.Length);
for (i = 0; i < array.Length; i++)
Assert.Equal(data[i], array[i]);
// read in the next 100 bytes and make sure nothing is missing
decompressor.Read(array2, 0, array2.Length);
for (j = 0; j < array2.Length; j++)
Assert.Equal(data[j], array[j]);
}
}
[Fact]
public void Roundtrip_Write_ReadByte()
{
byte[] data = new byte[1024 * 10];
new Random(42).NextBytes(data);
var compressed = new MemoryStream();
using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true))
{
compressor.Write(data, 0, data.Length);
}
compressed.Position = 0;
using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true))
{
for (int i = 0; i < data.Length; i++)
Assert.Equal(data[i], decompressor.ReadByte());
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public async Task WrapNullReturningTasksStream()
{
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnNullTasks), CompressionMode.Decompress))
await Assert.ThrowsAsync<InvalidOperationException>(() => ds.ReadAsync(new byte[1024], 0, 1024));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework Flush is a no-op.")]
public async Task WrapStreamReturningBadReadValues()
{
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress))
Assert.Throws<InvalidDataException>(() => ds.Read(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress))
await Assert.ThrowsAsync<InvalidDataException>(() => ds.ReadAsync(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
Assert.Equal(0, ds.Read(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
Assert.Equal(0, await ds.ReadAsync(new byte[1024], 0, 1024));
}
public static IEnumerable<object[]> CopyToAsync_Roundtrip_OutputMatchesInput_MemberData()
{
var rand = new Random();
foreach (int dataSize in new[] { 1, 1024, 4095, 1024 * 1024 })
{
var data = new byte[dataSize];
rand.NextBytes(data);
var compressed = new MemoryStream();
using (var ds = new DeflateStream(compressed, CompressionMode.Compress, leaveOpen: true))
{
ds.Write(data, 0, data.Length);
}
byte[] compressedData = compressed.ToArray();
foreach (int copyBufferSize in new[] { 1, 4096, 80 * 1024 })
{
// Memory source
var m = new MemoryStream(compressedData, writable: false);
yield return new object[] { data, copyBufferSize, m };
// File sources, sync and async
foreach (bool useAsync in new[] { true, false })
{
string path = Path.GetTempFileName();
File.WriteAllBytes(path, compressedData);
FileOptions options = FileOptions.DeleteOnClose;
if (useAsync) options |= FileOptions.Asynchronous;
yield return new object[] { data, copyBufferSize, new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, options) };
}
}
}
}
[Theory]
[MemberData(nameof(CopyToAsync_Roundtrip_OutputMatchesInput_MemberData))]
public async Task CopyToAsync_Roundtrip_OutputMatchesInput(byte[] expectedDecrypted, int copyBufferSize, Stream source)
{
var m = new MemoryStream();
using (DeflateStream ds = new DeflateStream(source, CompressionMode.Decompress))
{
await ds.CopyToAsync(m);
}
Assert.Equal(expectedDecrypted, m.ToArray());
}
private sealed class BadWrappedStream : Stream
{
public enum Mode
{
Default,
ReturnNullTasks,
ReturnTooSmallCounts,
ReturnTooLargeCounts,
}
private readonly Mode _mode;
public BadWrappedStream(Mode mode) { _mode = mode; }
public override int Read(byte[] buffer, int offset, int count)
{
switch (_mode)
{
case Mode.ReturnTooSmallCounts: return -1;
case Mode.ReturnTooLargeCounts: return buffer.Length + 1;
default: return 0;
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _mode == Mode.ReturnNullTasks ?
null :
base.ReadAsync(buffer, offset, count, cancellationToken);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _mode == Mode.ReturnNullTasks ?
null :
base.WriteAsync(buffer, offset, count, cancellationToken);
}
public override void Write(byte[] buffer, int offset, int count) { }
public override void Flush() { }
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } }
public override long Length { get { throw new NotSupportedException(); } }
public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
}
}
public class ManualSyncMemoryStream : MemoryStream
{
private bool isSync;
public ManualResetEventSlim manualResetEvent = new ManualResetEventSlim(initialState: false);
public bool ReadHit = false; // For validation of the async methods we want to ensure they correctly delegate the async
public bool WriteHit = false; // methods of the underlying stream. This bool acts as a toggle to check that they're being used.
public static async Task<ManualSyncMemoryStream> GetStreamFromFileAsync(string testFile, bool sync = false, bool strip = false)
{
var baseStream = await StreamHelpers.CreateTempCopyStream(testFile);
if (strip)
{
baseStream = StripHeaderAndFooter.Strip(baseStream);
}
var ms = new ManualSyncMemoryStream(sync);
await baseStream.CopyToAsync(ms);
ms.Position = 0;
return ms;
}
public ManualSyncMemoryStream(bool sync = false) : base()
{
isSync = sync;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count), callback, state);
public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult);
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsync(buffer, offset, count), callback, state);
public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult);
public override async Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
ReadHit = true;
if (isSync)
{
manualResetEvent.Wait(cancellationToken);
}
else
{
await Task.Run(() => manualResetEvent.Wait(cancellationToken));
}
return await base.ReadAsync(array, offset, count, cancellationToken);
}
public override async Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
WriteHit = true;
if (isSync)
{
manualResetEvent.Wait(cancellationToken);
}
else
{
await Task.Run(() => manualResetEvent.Wait(cancellationToken));
}
await base.WriteAsync(array, offset, count, cancellationToken);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FtpConnectionData.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
// <author>Mark Junker</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Net.Sockets;
using System.Security.Claims;
using System.Text;
using FubarDev.FtpServer.AccountManagement;
using FubarDev.FtpServer.AccountManagement.Compatibility;
using FubarDev.FtpServer.Features;
using FubarDev.FtpServer.Features.Impl;
using FubarDev.FtpServer.FileSystem;
using FubarDev.FtpServer.Localization;
using Microsoft.AspNetCore.Http.Features;
using NGettext;
namespace FubarDev.FtpServer
{
/// <summary>
/// Common data for a <see cref="IFtpConnection"/>.
/// </summary>
public sealed class FtpConnectionData : ILocalizationFeature, IFileSystemFeature, IAuthorizationInformationFeature,
ITransferConfigurationFeature, IMlstFactsFeature, IDisposable
{
private readonly IFeatureCollection _featureCollection;
/// <summary>
/// Initializes a new instance of the <see cref="FtpConnectionData"/> class.
/// </summary>
/// <param name="defaultEncoding">The default encoding.</param>
/// <param name="featureCollection">The feature collection where all features get stored.</param>
/// <param name="catalogLoader">The catalog loader for the FTP server.</param>
public FtpConnectionData(
Encoding defaultEncoding,
IFeatureCollection featureCollection,
IFtpCatalogLoader catalogLoader)
{
_featureCollection = featureCollection;
featureCollection.Set<ILocalizationFeature>(new LocalizationFeature(catalogLoader));
featureCollection.Set<IFileSystemFeature>(new FileSystemFeature());
featureCollection.Set<IAuthorizationInformationFeature>(new AuthorizationInformationFeature());
featureCollection.Set<IEncodingFeature>(new EncodingFeature(defaultEncoding));
featureCollection.Set<ITransferConfigurationFeature>(new TransferConfigurationFeature());
}
/// <inheritdoc />
[Obsolete("Use the IAuthorizationInformationFeature services to get the current status.")]
public IFtpUser? User
{
get => _featureCollection.Get<IAuthorizationInformationFeature>().User;
set
{
var feature = _featureCollection.Get<IAuthorizationInformationFeature>();
feature.User = value;
feature.FtpUser = value?.CreateClaimsPrincipal();
}
}
/// <inheritdoc />
[Obsolete("Use the IAuthorizationInformationFeature services to get the current status.")]
public ClaimsPrincipal? FtpUser
{
get => _featureCollection.Get<IAuthorizationInformationFeature>().FtpUser;
set
{
var feature = _featureCollection.Get<IAuthorizationInformationFeature>();
feature.FtpUser = value;
feature.User = value?.CreateUser();
}
}
/// <inheritdoc />
[Obsolete("Use the IAuthorizationInformationFeature services to get the current status.")]
public IMembershipProvider? MembershipProvider
{
get => _featureCollection.Get<IAuthorizationInformationFeature>().MembershipProvider;
set
{
var feature = _featureCollection.Get<IAuthorizationInformationFeature>();
feature.MembershipProvider = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the user with the <see cref="User"/>.
/// is logged in.
/// </summary>
[Obsolete("Use the IFtpLoginStateMachine services to get the current status.")]
public bool IsLoggedIn { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the current user is anonymous.
/// </summary>
[Obsolete("An anonymous user object now implements IAnonymousFtpUser.")]
public bool IsAnonymous { get; set; }
/// <summary>
/// Gets or sets the <see cref="Encoding"/> for the <c>NLST</c> command.
/// </summary>
[Obsolete("Query the information using the IEncodingFeature instead.")]
public Encoding NlstEncoding
{
get => _featureCollection.Get<IEncodingFeature>().NlstEncoding;
set => _featureCollection.Get<IEncodingFeature>().NlstEncoding = value;
}
/// <inheritdoc />
[Obsolete("Query the information using the IFileSystemFeature instead.")]
public IUnixFileSystem FileSystem
{
get => _featureCollection.Get<IFileSystemFeature>().FileSystem;
set => _featureCollection.Get<IFileSystemFeature>().FileSystem = value;
}
/// <inheritdoc />
[Obsolete("Query the information using the IFileSystemFeature instead.")]
public Stack<IUnixDirectoryEntry> Path
{
get => _featureCollection.Get<IFileSystemFeature>().Path;
set => _featureCollection.Get<IFileSystemFeature>().Path = value;
}
/// <inheritdoc />
[Obsolete("Query the information using the IFileSystemFeature instead.")]
public IUnixDirectoryEntry CurrentDirectory => _featureCollection.Get<IFileSystemFeature>().CurrentDirectory;
/// <inheritdoc />
[Obsolete("Query the information using the ILocalizationFeature instead.")]
public CultureInfo Language
{
get => _featureCollection.Get<ILocalizationFeature>().Language;
set => _featureCollection.Get<ILocalizationFeature>().Language = value;
}
/// <inheritdoc />
[Obsolete("Query the information using the ILocalizationFeature instead.")]
public ICatalog Catalog
{
get => _featureCollection.Get<ILocalizationFeature>().Catalog;
set => _featureCollection.Get<ILocalizationFeature>().Catalog = value;
}
/// <inheritdoc />
[Obsolete("Query the information using the ITransferConfigurationFeature instead.")]
public FtpTransferMode TransferMode
{
get => _featureCollection.Get<ITransferConfigurationFeature>().TransferMode;
set => _featureCollection.Get<ITransferConfigurationFeature>().TransferMode = value;
}
/// <summary>
/// Gets or sets the address to use for an active data connection.
/// </summary>
[Obsolete("This property is not used any more. Use IFtpDataConnectionFeature instead.")]
public Address? PortAddress { get; set; }
/// <summary>
/// Gets or sets the data connection for a passive data transfer.
/// </summary>
[Obsolete("This property is not used any more. Use IFtpDataConnectionFeature instead.")]
public TcpClient? PassiveSocketClient { get; set; }
/// <summary>
/// Gets the <see cref="IBackgroundCommandHandler"/> that's required for the <c>ABOR</c> command.
/// </summary>
[Obsolete("Query IBackgroundTaskLifetimeFeature to get information about an active background task (if non-null).")]
public IBackgroundCommandHandler? BackgroundCommandHandler => null;
/// <summary>
/// Gets or sets the last used transfer type command.
/// </summary>
/// <remarks>
/// It's not allowed to use PASV when PORT was used previously - and vice versa.
/// </remarks>
[Obsolete("The restriction was lifted.")]
public string? TransferTypeCommandUsed { get; set; }
/// <summary>
/// Gets or sets the restart position for appending data to a file.
/// </summary>
[Obsolete("Query the information using the IRestCommandFeature instead.")]
public long? RestartPosition
{
get => _featureCollection.Get<IRestCommandFeature?>()?.RestartPosition;
set
{
var feature = _featureCollection.Get<IRestCommandFeature?>();
if (value != null)
{
if (feature == null)
{
feature = new RestCommandFeature();
_featureCollection.Set(feature);
}
feature.RestartPosition = value.Value;
}
else
{
if (feature != null)
{
_featureCollection.Set<IRestCommandFeature?>(null);
}
}
}
}
/// <summary>
/// Gets or sets the <see cref="IUnixFileEntry"/> to use for a <c>RNTO</c> operation.
/// </summary>
[Obsolete("Query the information using the IRenameCommandFeature instead.")]
public SearchResult<IUnixFileSystemEntry>? RenameFrom
{
get => _featureCollection.Get<IRenameCommandFeature?>()?.RenameFrom;
set
{
var feature = _featureCollection.Get<IRenameCommandFeature?>();
if (value != null)
{
if (feature == null)
{
feature = new RenameCommandFeature(value);
_featureCollection.Set(feature);
}
feature.RenameFrom = value;
}
else
{
if (feature != null)
{
_featureCollection.Set<IRenameCommandFeature?>(null);
}
}
}
}
/// <inheritdoc />
[Obsolete("Query the information using the IMlstFactsFeature instead.")]
public ISet<string> ActiveMlstFacts => _featureCollection.Get<IMlstFactsFeature>().ActiveMlstFacts;
/// <summary>
/// Gets or sets a delegate that allows the creation of an encrypted stream.
/// </summary>
[Obsolete("Query the information using the ISecureConnectionFeature instead.")]
public CreateEncryptedStreamDelegate? CreateEncryptedStream
{
get => _featureCollection.Get<ISecureConnectionFeature>().CreateEncryptedStream;
set => _featureCollection.Get<ISecureConnectionFeature>().CreateEncryptedStream = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Gets or sets user data as <c>dynamic</c> object.
/// </summary>
[Obsolete("Use IFtpConnection.Features to store custom information.")]
public dynamic UserData { get; set; } = new ExpandoObject();
/// <inheritdoc/>
public void Dispose()
{
}
/// <summary>
/// Container that implements <see cref="IRestCommandFeature"/>.
/// </summary>
private class RestCommandFeature : IRestCommandFeature
{
/// <inheritdoc />
public long RestartPosition { get; set; }
}
/// <summary>
/// Container that implements <see cref="IRenameCommandFeature"/>.
/// </summary>
private class RenameCommandFeature : IRenameCommandFeature
{
public RenameCommandFeature(SearchResult<IUnixFileSystemEntry> renameFrom)
{
RenameFrom = renameFrom;
}
/// <inheritdoc />
public SearchResult<IUnixFileSystemEntry> RenameFrom { get; set; }
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2015 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using Google.Protobuf.Reflection;
namespace Google.Protobuf
{
/// <summary>
/// Used to keep track of fields which were seen when parsing a protocol message
/// but whose field numbers or types are unrecognized. This most frequently
/// occurs when new fields are added to a message type and then messages containing
/// those fields are read by old software that was built before the new types were
/// added.
///
/// Most users will never need to use this class directly.
/// </summary>
public sealed partial class UnknownFieldSet
{
private readonly IDictionary<int, UnknownField> fields;
/// <summary>
/// Creates a new UnknownFieldSet.
/// </summary>
internal UnknownFieldSet()
{
this.fields = new Dictionary<int, UnknownField>();
}
/// <summary>
/// Checks whether or not the given field number is present in the set.
/// </summary>
internal bool HasField(int field)
{
return fields.ContainsKey(field);
}
/// <summary>
/// Serializes the set and writes it to <paramref name="output"/>.
/// </summary>
public void WriteTo(CodedOutputStream output)
{
WriteContext.Initialize(output, out WriteContext ctx);
try
{
WriteTo(ref ctx);
}
finally
{
ctx.CopyStateTo(output);
}
}
/// <summary>
/// Serializes the set and writes it to <paramref name="ctx"/>.
/// </summary>
[SecuritySafeCritical]
public void WriteTo(ref WriteContext ctx)
{
foreach (KeyValuePair<int, UnknownField> entry in fields)
{
entry.Value.WriteTo(entry.Key, ref ctx);
}
}
/// <summary>
/// Gets the number of bytes required to encode this set.
/// </summary>
public int CalculateSize()
{
int result = 0;
foreach (KeyValuePair<int, UnknownField> entry in fields)
{
result += entry.Value.GetSerializedSize(entry.Key);
}
return result;
}
/// <summary>
/// Checks if two unknown field sets are equal.
/// </summary>
public override bool Equals(object other)
{
if (ReferenceEquals(this, other))
{
return true;
}
UnknownFieldSet otherSet = other as UnknownFieldSet;
IDictionary<int, UnknownField> otherFields = otherSet.fields;
if (fields.Count != otherFields.Count)
{
return false;
}
foreach (KeyValuePair<int, UnknownField> leftEntry in fields)
{
UnknownField rightValue;
if (!otherFields.TryGetValue(leftEntry.Key, out rightValue))
{
return false;
}
if (!leftEntry.Value.Equals(rightValue))
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the unknown field set's hash code.
/// </summary>
public override int GetHashCode()
{
int ret = 1;
foreach (KeyValuePair<int, UnknownField> field in fields)
{
// Use ^ here to make the field order irrelevant.
int hash = field.Key.GetHashCode() ^ field.Value.GetHashCode();
ret ^= hash;
}
return ret;
}
// Optimization: We keep around the last field that was
// modified so that we can efficiently add to it multiple times in a
// row (important when parsing an unknown repeated field).
private int lastFieldNumber;
private UnknownField lastField;
private UnknownField GetOrAddField(int number)
{
if (lastField != null && number == lastFieldNumber)
{
return lastField;
}
if (number == 0)
{
return null;
}
UnknownField existing;
if (fields.TryGetValue(number, out existing))
{
return existing;
}
lastField = new UnknownField();
AddOrReplaceField(number, lastField);
lastFieldNumber = number;
return lastField;
}
/// <summary>
/// Adds a field to the set. If a field with the same number already exists, it
/// is replaced.
/// </summary>
internal UnknownFieldSet AddOrReplaceField(int number, UnknownField field)
{
if (number == 0)
{
throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number.");
}
fields[number] = field;
return this;
}
/// <summary>
/// Parse a single field from <paramref name="ctx"/> and merge it
/// into this set.
/// </summary>
/// <param name="ctx">The parse context from which to read the field</param>
/// <returns>false if the tag is an "end group" tag, true otherwise</returns>
private bool MergeFieldFrom(ref ParseContext ctx)
{
uint tag = ctx.LastTag;
int number = WireFormat.GetTagFieldNumber(tag);
switch (WireFormat.GetTagWireType(tag))
{
case WireFormat.WireType.Varint:
{
ulong uint64 = ctx.ReadUInt64();
GetOrAddField(number).AddVarint(uint64);
return true;
}
case WireFormat.WireType.Fixed32:
{
uint uint32 = ctx.ReadFixed32();
GetOrAddField(number).AddFixed32(uint32);
return true;
}
case WireFormat.WireType.Fixed64:
{
ulong uint64 = ctx.ReadFixed64();
GetOrAddField(number).AddFixed64(uint64);
return true;
}
case WireFormat.WireType.LengthDelimited:
{
ByteString bytes = ctx.ReadBytes();
GetOrAddField(number).AddLengthDelimited(bytes);
return true;
}
case WireFormat.WireType.StartGroup:
{
UnknownFieldSet set = new UnknownFieldSet();
ParsingPrimitivesMessages.ReadGroup(ref ctx, number, set);
GetOrAddField(number).AddGroup(set);
return true;
}
case WireFormat.WireType.EndGroup:
{
return false;
}
default:
throw InvalidProtocolBufferException.InvalidWireType();
}
}
internal void MergeGroupFrom(ref ParseContext ctx)
{
while (true)
{
uint tag = ctx.ReadTag();
if (tag == 0)
{
break;
}
if (!MergeFieldFrom(ref ctx))
{
break;
}
}
}
/// <summary>
/// Create a new UnknownFieldSet if unknownFields is null.
/// Parse a single field from <paramref name="input"/> and merge it
/// into unknownFields. If <paramref name="input"/> is configured to discard unknown fields,
/// <paramref name="unknownFields"/> will be returned as-is and the field will be skipped.
/// </summary>
/// <param name="unknownFields">The UnknownFieldSet which need to be merged</param>
/// <param name="input">The coded input stream containing the field</param>
/// <returns>The merged UnknownFieldSet</returns>
public static UnknownFieldSet MergeFieldFrom(UnknownFieldSet unknownFields,
CodedInputStream input)
{
ParseContext.Initialize(input, out ParseContext ctx);
try
{
return MergeFieldFrom(unknownFields, ref ctx);
}
finally
{
ctx.CopyStateTo(input);
}
}
/// <summary>
/// Create a new UnknownFieldSet if unknownFields is null.
/// Parse a single field from <paramref name="ctx"/> and merge it
/// into unknownFields. If <paramref name="ctx"/> is configured to discard unknown fields,
/// <paramref name="unknownFields"/> will be returned as-is and the field will be skipped.
/// </summary>
/// <param name="unknownFields">The UnknownFieldSet which need to be merged</param>
/// <param name="ctx">The parse context from which to read the field</param>
/// <returns>The merged UnknownFieldSet</returns>
[SecuritySafeCritical]
public static UnknownFieldSet MergeFieldFrom(UnknownFieldSet unknownFields,
ref ParseContext ctx)
{
if (ctx.DiscardUnknownFields)
{
ParsingPrimitivesMessages.SkipLastField(ref ctx.buffer, ref ctx.state);
return unknownFields;
}
if (unknownFields == null)
{
unknownFields = new UnknownFieldSet();
}
if (!unknownFields.MergeFieldFrom(ref ctx))
{
throw new InvalidProtocolBufferException("Merge an unknown field of end-group tag, indicating that the corresponding start-group was missing."); // match the old code-gen
}
return unknownFields;
}
/// <summary>
/// Merges the fields from <paramref name="other"/> into this set.
/// If a field number exists in both sets, the values in <paramref name="other"/>
/// will be appended to the values in this set.
/// </summary>
private UnknownFieldSet MergeFrom(UnknownFieldSet other)
{
if (other != null)
{
foreach (KeyValuePair<int, UnknownField> entry in other.fields)
{
MergeField(entry.Key, entry.Value);
}
}
return this;
}
/// <summary>
/// Created a new UnknownFieldSet to <paramref name="unknownFields"/> if
/// needed and merges the fields from <paramref name="other"/> into the first set.
/// If a field number exists in both sets, the values in <paramref name="other"/>
/// will be appended to the values in this set.
/// </summary>
public static UnknownFieldSet MergeFrom(UnknownFieldSet unknownFields,
UnknownFieldSet other)
{
if (other == null)
{
return unknownFields;
}
if (unknownFields == null)
{
unknownFields = new UnknownFieldSet();
}
unknownFields.MergeFrom(other);
return unknownFields;
}
/// <summary>
/// Adds a field to the unknown field set. If a field with the same
/// number already exists, the two are merged.
/// </summary>
private UnknownFieldSet MergeField(int number, UnknownField field)
{
if (number == 0)
{
throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number.");
}
if (HasField(number))
{
GetOrAddField(number).MergeFrom(field);
}
else
{
AddOrReplaceField(number, field);
}
return this;
}
/// <summary>
/// Clone an unknown field set from <paramref name="other"/>.
/// </summary>
public static UnknownFieldSet Clone(UnknownFieldSet other)
{
if (other == null)
{
return null;
}
UnknownFieldSet unknownFields = new UnknownFieldSet();
unknownFields.MergeFrom(other);
return unknownFields;
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// User
/// </summary>
[DataContract]
public partial class User : IEquatable<User>, IValidatableObject
{
public User()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="User" /> class.
/// </summary>
/// <param name="CellPhoneNumber">CellPhoneNumber.</param>
/// <param name="CountryCode">CountryCode.</param>
/// <param name="Credentials">Credentials.</param>
/// <param name="DisplayName">DisplayName.</param>
/// <param name="Email">Email.</param>
/// <param name="ExternalClaims">ExternalClaims.</param>
public User(string CellPhoneNumber = default(string), string CountryCode = default(string), List<Credential> Credentials = default(List<Credential>), string DisplayName = default(string), string Email = default(string), List<ExternalClaim> ExternalClaims = default(List<ExternalClaim>))
{
this.CellPhoneNumber = CellPhoneNumber;
this.CountryCode = CountryCode;
this.Credentials = Credentials;
this.DisplayName = DisplayName;
this.Email = Email;
this.ExternalClaims = ExternalClaims;
}
/// <summary>
/// Gets or Sets CellPhoneNumber
/// </summary>
[DataMember(Name="cellPhoneNumber", EmitDefaultValue=false)]
public string CellPhoneNumber { get; set; }
/// <summary>
/// Gets or Sets CountryCode
/// </summary>
[DataMember(Name="countryCode", EmitDefaultValue=false)]
public string CountryCode { get; set; }
/// <summary>
/// Gets or Sets Credentials
/// </summary>
[DataMember(Name="credentials", EmitDefaultValue=false)]
public List<Credential> Credentials { get; set; }
/// <summary>
/// Gets or Sets DisplayName
/// </summary>
[DataMember(Name="displayName", EmitDefaultValue=false)]
public string DisplayName { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
/// Gets or Sets ExternalClaims
/// </summary>
[DataMember(Name="externalClaims", EmitDefaultValue=false)]
public List<ExternalClaim> ExternalClaims { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class User {\n");
sb.Append(" CellPhoneNumber: ").Append(CellPhoneNumber).Append("\n");
sb.Append(" CountryCode: ").Append(CountryCode).Append("\n");
sb.Append(" Credentials: ").Append(Credentials).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" ExternalClaims: ").Append(ExternalClaims).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as User);
}
/// <summary>
/// Returns true if User instances are equal
/// </summary>
/// <param name="other">Instance of User to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(User other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CellPhoneNumber == other.CellPhoneNumber ||
this.CellPhoneNumber != null &&
this.CellPhoneNumber.Equals(other.CellPhoneNumber)
) &&
(
this.CountryCode == other.CountryCode ||
this.CountryCode != null &&
this.CountryCode.Equals(other.CountryCode)
) &&
(
this.Credentials == other.Credentials ||
this.Credentials != null &&
this.Credentials.SequenceEqual(other.Credentials)
) &&
(
this.DisplayName == other.DisplayName ||
this.DisplayName != null &&
this.DisplayName.Equals(other.DisplayName)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.ExternalClaims == other.ExternalClaims ||
this.ExternalClaims != null &&
this.ExternalClaims.SequenceEqual(other.ExternalClaims)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CellPhoneNumber != null)
hash = hash * 59 + this.CellPhoneNumber.GetHashCode();
if (this.CountryCode != null)
hash = hash * 59 + this.CountryCode.GetHashCode();
if (this.Credentials != null)
hash = hash * 59 + this.Credentials.GetHashCode();
if (this.DisplayName != null)
hash = hash * 59 + this.DisplayName.GetHashCode();
if (this.Email != null)
hash = hash * 59 + this.Email.GetHashCode();
if (this.ExternalClaims != null)
hash = hash * 59 + this.ExternalClaims.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
namespace Utilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using MagnitudeConcavityPeakFinder;
using Utilities.Models;
/// <summary>
/// The peak finder class, gives additional information over what the magnitude peak finder provides.
/// </summary>
public static class PeakFinder
{
#region Public Methods and Operators
/// <summary>
/// Find the peaks in the data set passed and returns a list of peak information.
/// </summary>
/// <param name="dataList">
/// The data List.
/// </param>
/// <param name="numberOfTopPeaks">
/// The number of peaks to return, starting with the highest intensity, if less than one it will return all peaks.
/// </param>
/// <returns>
/// The <see cref="System.Collections.Generic.List{T}"/> of peaks.
/// </returns>
public static PeakSet FindPeaks(IEnumerable<KeyValuePair<double, double>> data, int numberOfTopPeaks = 0)
{
var dataList = data.ToList();
const int Precision = 100000;
var peakDetector = new PeakDetector();
var finderOptions = PeakDetector.GetDefaultSICPeakFinderOptions();
List<double> smoothedY;
// Create a new dictionary so we don't modify the original one
var tempFrameList = new List<KeyValuePair<int, double>>(dataList.Count);
// We have to give it integers for the double, but we need this to handle doubles, so we will multiply the key by the precision
// and later get the correct value back by dividing it out again
// resultant linq quesry is less readable than this.
// ReSharper disable once LoopCanBeConvertedToQuery
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < dataList.Count; i++)
{
tempFrameList.Add(new KeyValuePair<int, double>((int)(dataList[i].Key * Precision), dataList[i].Value));
}
// I am not sure what the library does with this but in the example exe file that came with the library
// they used half of the length of the list in their previous examples and this seems to work.
// To be extra clear to future programmers, changing this number causes memory out of bounds from the peak detector
var originalpeakLocation = tempFrameList.Count / 2;
var allPeaks = peakDetector.FindPeaks(
finderOptions,
tempFrameList.OrderBy(x => x.Key).ToList(),
originalpeakLocation,
out smoothedY);
IEnumerable<clsPeak> peakSet;
// if a few peaks are wanted, it is better that we trim them up front, before we calculate the extra information
if (numberOfTopPeaks > 0)
{
var topPeaks = allPeaks.OrderByDescending(peak => smoothedY[peak.LocationIndex]).Take(numberOfTopPeaks);
peakSet = topPeaks;
}
else
{
peakSet = allPeaks;
}
var calculatedPeakSet =
peakSet.Select(peak => CalculatePeakInformation(peak, tempFrameList, smoothedY, Precision))
.Where(p => p.ResolvingPower > 0 && !double.IsInfinity(p.ResolvingPower));
return new PeakSet(calculatedPeakSet);
////var tempList =
//// datapointList.Where(x => !double.IsInfinity(x.ResolvingPower)).OrderByDescending(x => x.Intensity).Take(10);
}
/// <summary>
/// Calculates peak information.
/// </summary>
/// <param name="peak">
/// The peak to calculate.
/// </param>
/// <param name="originalList">
/// The original list given to the peak finder.
/// </param>
/// <param name="smoothedIntensityValues">
/// The smoothed intensity values from the peak finder.
/// </param>
/// <param name="precisionUsed">
/// The precision used when passing data to the peak finder so it can handle numbers with doubles.
/// </param>
/// <returns>
/// The <see cref="PeakInformation"/>.
/// </returns>
private static PeakInformation CalculatePeakInformation(
clsPeak peak,
List<KeyValuePair<int, double>> originalList,
IReadOnlyList<double> smoothedIntensityValues,
int precisionUsed)
{
const double Tolerance = 0.01;
var centerPoint = originalList.ElementAt(peak.LocationIndex);
var offsetCenter = centerPoint.Key; // + firstpoint.Key;
var intensity = centerPoint.Value;
var smoothedPeakIntensity = smoothedIntensityValues[peak.LocationIndex];
var realCenter = (double)offsetCenter / precisionUsed;
var halfmax = smoothedPeakIntensity / 2.0;
var currPoint = new KeyValuePair<int, double>(0, 0);
var currPointIndex = 0;
List<KeyValuePair<int, double>> leftSidePoints;
List<KeyValuePair<int, double>> rightSidePoints;
var allPoints = ExtractPointInformation(
peak,
originalList,
smoothedIntensityValues,
precisionUsed,
out leftSidePoints,
out rightSidePoints);
// find the left side half max
var leftMidpoint = FindMidPoint(
originalList,
smoothedIntensityValues,
leftSidePoints,
ref currPoint,
halfmax,
Tolerance,
ref currPointIndex,
Side.LeftSide);
// find the right side of the half max
var rightMidPoint = FindMidPoint(
originalList,
smoothedIntensityValues,
rightSidePoints,
ref currPoint,
halfmax,
Tolerance,
ref currPointIndex,
Side.RightSide);
var correctedRightMidPoint = rightMidPoint / precisionUsed;
var correctedLeftMidPoint = leftMidpoint / precisionUsed;
var fullWidthHalfMax = correctedRightMidPoint - correctedLeftMidPoint;
var resolution = realCenter / fullWidthHalfMax;
var temp = new PeakInformation
{
AreaUnderThePeak = peak.Area,
FullWidthHalfMax = fullWidthHalfMax,
Intensity = intensity,
LeftMidpoint = correctedLeftMidPoint,
PeakCenter = realCenter,
RightMidpoint = correctedRightMidPoint,
ResolvingPower = resolution,
SmoothedIntensity = smoothedPeakIntensity,
TotalDataPointSet = allPoints
};
return temp;
}
/// <summary>
/// Finds the left or right half max point.
/// </summary>
/// <param name="originalList">
/// The original list.
/// </param>
/// <param name="smoothedIntensityValues">
/// The smoothed intensity values.
/// </param>
/// <param name="sidePoints">
/// The points making up the side you want to search for the mid point.
/// </param>
/// <param name="currPoint">
/// The current point (designed to chain together.
/// </param>
/// <param name="halfmax">
/// The half max of the peak.
/// </param>
/// <param name="tolerance">
/// The tolerance for calculation.
/// </param>
/// <param name="currPointIndex">
/// The index of the original list for the <see cref="currPoint"/>.
/// </param>
/// <param name="sideToFind">
/// The side to find.
/// </param>
/// <returns>
/// The <see cref="double"/>.
/// </returns>
private static double FindMidPoint(
List<KeyValuePair<int, double>> originalList,
IReadOnlyList<double> smoothedIntensityValues,
IEnumerable<KeyValuePair<int, double>> sidePoints,
ref KeyValuePair<int, double> currPoint,
double halfmax,
double tolerance,
ref int currPointIndex,
Side sideToFind)
{
double midpoint = 0;
foreach (var sidePoint in sidePoints)
{
var prevPoint = currPoint;
currPoint = sidePoint;
var prevPointIndex = currPointIndex;
currPointIndex = originalList.BinarySearch(
currPoint,
Comparer<KeyValuePair<int, double>>.Create((left, right) => left.Key - right.Key));
switch (sideToFind)
{
case Side.LeftSide:
// value is too small to be the half-max point
if (smoothedIntensityValues[currPointIndex] < halfmax)
{
continue;
}
// we got lucky and have a point at the exact half way point
if (Math.Abs(smoothedIntensityValues[currPointIndex] - halfmax) < tolerance)
{
midpoint = currPoint.Key;
continue;
}
break;
case Side.RightSide:
if (smoothedIntensityValues[currPointIndex] > halfmax
|| smoothedIntensityValues[currPointIndex] < 0)
{
continue;
}
if (Math.Abs(smoothedIntensityValues[currPointIndex] - halfmax) < tolerance)
{
midpoint = currPoint.Key;
continue;
}
break;
}
// We didn't get luky and the two points we have are above and below where the half max would be, so we need to calculate it.
// Having the redundant argument names improves readability for the formula (which is broken out for future test cases
// ReSharper disable RedundantArgumentName
midpoint = GetX(
yValue: halfmax,
x1: prevPoint.Key,
y1: smoothedIntensityValues[prevPointIndex],
x2: currPoint.Key,
y2: smoothedIntensityValues[currPointIndex]);
// ReSharper restore RedundantArgumentName
break;
}
return midpoint;
}
/// <summary>
/// Gets an x value given a y value and two x,y points.
/// </summary>
/// <param name="yValue">
/// The y value for the point we want to calculate an x for.
/// </param>
/// <param name="x1">
/// The x value of the first point in the slope.
/// </param>
/// <param name="y1">
/// The y value of the first point in the slope.
/// </param>
/// <param name="x2">
/// The x value of the second point in the slope.
/// </param>
/// <param name="y2">
/// The y value of the second point in the slope.
/// </param>
/// <returns>
/// The the calculated c value, represented as a <see cref="double"/>.
/// </returns>
private static double GetX(double yValue, double x1, double y1, double x2, double y2)
{
/* Point/Slope solved for X:
* ( (yValue - y1) )
* x1 + ( (x2 - x1) * ---------------)
* ( (y2 - y1) )
*/
return x1 + ((x2 - x1) * ((yValue - y1) / (y2 - y1)));
}
/// <summary>
/// Gets information for points, required for calculations.
/// </summary>
/// <param name="peak">
/// The peak found.
/// </param>
/// <param name="originalList">
/// The original list given to the peak finder.
/// </param>
/// <param name="smoothedIntensityValues">
/// The smoothed intensity values output by the peak finder.
/// </param>
/// <param name="precisionUsed">
/// The precision used.
/// </param>
/// <param name="leftSidePoints">
/// The list to store the left side points.
/// </param>
/// <param name="rightSidePoints">
/// The list to store the right side points.
/// </param>
/// <returns>
/// The <see>
/// <cref>List</cref>
/// </see>
/// .
/// </returns>
private static List<PointInformation> ExtractPointInformation(
clsPeak peak,
IReadOnlyList<KeyValuePair<int, double>> originalList,
IReadOnlyList<double> smoothedIntensityValues,
int precisionUsed,
out List<KeyValuePair<int, double>> leftSidePoints,
out List<KeyValuePair<int, double>> rightSidePoints)
{
var allPoints = new List<PointInformation>();
// build left side
leftSidePoints = new List<KeyValuePair<int, double>>();
for (var l = peak.LeftEdge; l < peak.LocationIndex && l < originalList.Count; l++)
{
leftSidePoints.Add(originalList[l]);
allPoints.Add(
new PointInformation
{
Location = (double)originalList[l].Key / precisionUsed,
Intensity = originalList[l].Value,
SmoothedIntensity = smoothedIntensityValues[l]
});
}
// build right side
rightSidePoints = new List<KeyValuePair<int, double>>();
for (var r = peak.LocationIndex; r < peak.RightEdge && r < originalList.Count; r++)
{
rightSidePoints.Add(originalList[r]);
allPoints.Add(
new PointInformation
{
Location = (double)originalList[r].Key / precisionUsed,
Intensity = originalList[r].Value,
SmoothedIntensity = smoothedIntensityValues[r]
});
}
return allPoints;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
namespace System.Data.Odbc
{
internal sealed class OdbcConnectionHandle : OdbcHandle
{
private HandleState _handleState;
private enum HandleState
{
Allocated = 0,
Connected = 1,
Transacted = 2,
TransactionInProgress = 3,
}
internal OdbcConnectionHandle(OdbcConnection connection, OdbcConnectionString constr, OdbcEnvironmentHandle environmentHandle) : base(ODBC32.SQL_HANDLE.DBC, environmentHandle)
{
if (null == connection)
{
throw ADP.ArgumentNull("connection");
}
if (null == constr)
{
throw ADP.ArgumentNull("constr");
}
ODBC32.RetCode retcode;
//Set connection timeout (only before open).
//Note: We use login timeout since its odbc 1.0 option, instead of using
//connectiontimeout (which affects other things besides just login) and its
//a odbc 3.0 feature. The ConnectionTimeout on the managed providers represents
//the login timeout, nothing more.
int connectionTimeout = connection.ConnectionTimeout;
retcode = SetConnectionAttribute2(ODBC32.SQL_ATTR.LOGIN_TIMEOUT, (IntPtr)connectionTimeout, (Int32)ODBC32.SQL_IS.UINTEGER);
string connectionString = constr.UsersConnectionString(false);
// Connect to the driver. (Using the connection string supplied)
//Note: The driver doesn't filter out the password in the returned connection string
//so their is no need for us to obtain the returned connection string
// Prepare to handle a ThreadAbort Exception between SQLDriverConnectW and update of the state variables
retcode = Connect(connectionString);
connection.HandleError(this, retcode);
}
private ODBC32.RetCode AutoCommitOff()
{
ODBC32.RetCode retcode;
Debug.Assert(HandleState.Connected <= _handleState, "AutoCommitOff while in wrong state?");
// Avoid runtime injected errors in the following block.
// must call SQLSetConnectAttrW and set _handleState
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
retcode = UnsafeNativeMethods.SQLSetConnectAttrW(this, ODBC32.SQL_ATTR.AUTOCOMMIT, ODBC32.SQL_AUTOCOMMIT_OFF, (Int32)ODBC32.SQL_IS.UINTEGER);
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_handleState = HandleState.Transacted;
break;
}
}
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
internal ODBC32.RetCode BeginTransaction(ref IsolationLevel isolevel)
{
ODBC32.RetCode retcode = ODBC32.RetCode.SUCCESS;
ODBC32.SQL_ATTR isolationAttribute;
if (IsolationLevel.Unspecified != isolevel)
{
ODBC32.SQL_TRANSACTION sql_iso;
switch (isolevel)
{
case IsolationLevel.ReadUncommitted:
sql_iso = ODBC32.SQL_TRANSACTION.READ_UNCOMMITTED;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.ReadCommitted:
sql_iso = ODBC32.SQL_TRANSACTION.READ_COMMITTED;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.RepeatableRead:
sql_iso = ODBC32.SQL_TRANSACTION.REPEATABLE_READ;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.Serializable:
sql_iso = ODBC32.SQL_TRANSACTION.SERIALIZABLE;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.Snapshot:
sql_iso = ODBC32.SQL_TRANSACTION.SNAPSHOT;
// VSDD 414121: Snapshot isolation level must be set through SQL_COPT_SS_TXN_ISOLATION (http://msdn.microsoft.com/en-us/library/ms131709.aspx)
isolationAttribute = ODBC32.SQL_ATTR.SQL_COPT_SS_TXN_ISOLATION;
break;
case IsolationLevel.Chaos:
throw ODBC.NotSupportedIsolationLevel(isolevel);
default:
throw ADP.InvalidIsolationLevel(isolevel);
}
//Set the isolation level (unless its unspecified)
retcode = SetConnectionAttribute2(isolationAttribute, (IntPtr)sql_iso, (Int32)ODBC32.SQL_IS.INTEGER);
//Note: The Driver can return success_with_info to indicate it "rolled" the
//isolevel to the next higher value. If this is the case, we need to requery
//the value if th euser asks for it...
//We also still propagate the info, since it could be other info as well...
if (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode)
{
isolevel = IsolationLevel.Unspecified;
}
}
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
//Turn off auto-commit (which basically starts the transaction)
retcode = AutoCommitOff();
_handleState = HandleState.TransactionInProgress;
break;
}
return retcode;
}
internal ODBC32.RetCode CompleteTransaction(short transactionOperation)
{
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustRelease);
ODBC32.RetCode retcode = CompleteTransaction(transactionOperation, base.handle);
return retcode;
}
finally
{
if (mustRelease)
{
DangerousRelease();
}
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private ODBC32.RetCode CompleteTransaction(short transactionOperation, IntPtr handle)
{
// must only call this code from ReleaseHandle or DangerousAddRef region
ODBC32.RetCode retcode = ODBC32.RetCode.SUCCESS;
// using ConstrainedRegions to make the native ODBC call and change the _handleState
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
if (HandleState.TransactionInProgress == _handleState)
{
retcode = UnsafeNativeMethods.SQLEndTran(HandleType, handle, transactionOperation);
if ((ODBC32.RetCode.SUCCESS == retcode) || (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode))
{
_handleState = HandleState.Transacted;
}
Bid.TraceSqlReturn("<odbc.SQLEndTran|API|ODBC|RET> %08X{SQLRETURN}\n", retcode);
}
if (HandleState.Transacted == _handleState)
{ // AutoCommitOn
retcode = UnsafeNativeMethods.SQLSetConnectAttrW(handle, ODBC32.SQL_ATTR.AUTOCOMMIT, ODBC32.SQL_AUTOCOMMIT_ON, (Int32)ODBC32.SQL_IS.UINTEGER);
_handleState = HandleState.Connected;
Bid.TraceSqlReturn("<odbc.SQLSetConnectAttr|API|ODBC|RET> %08X{SQLRETURN}\n", retcode);
}
}
//Overactive assert which fires if handle was allocated - but failed to connect to the server
//it can more legitmately fire if transaction failed to rollback - but there isn't much we can do in that situation
//Debug.Assert((HandleState.Connected == _handleState) || (HandleState.TransactionInProgress == _handleState), "not expected HandleState.Connected");
return retcode;
}
private ODBC32.RetCode Connect(string connectionString)
{
Debug.Assert(HandleState.Allocated == _handleState, "SQLDriverConnect while in wrong state?");
ODBC32.RetCode retcode;
// Avoid runtime injected errors in the following block.
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
short cbActualSize;
retcode = UnsafeNativeMethods.SQLDriverConnectW(this, ADP.PtrZero, connectionString, ODBC32.SQL_NTS, ADP.PtrZero, 0, out cbActualSize, (short)ODBC32.SQL_DRIVER.NOPROMPT);
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_handleState = HandleState.Connected;
break;
}
}
ODBC.TraceODBC(3, "SQLDriverConnectW", retcode);
return retcode;
}
override protected bool ReleaseHandle()
{
// NOTE: The SafeHandle class guarantees this will be called exactly once and is non-interrutible.
ODBC32.RetCode retcode;
// must call complete the transaction rollback, change handle state, and disconnect the connection
retcode = CompleteTransaction(ODBC32.SQL_ROLLBACK, handle);
if ((HandleState.Connected == _handleState) || (HandleState.TransactionInProgress == _handleState))
{
retcode = UnsafeNativeMethods.SQLDisconnect(handle);
_handleState = HandleState.Allocated;
Bid.TraceSqlReturn("<odbc.SQLDisconnect|API|ODBC|RET> %08X{SQLRETURN}\n", retcode);
}
Debug.Assert(HandleState.Allocated == _handleState, "not expected HandleState.Allocated");
return base.ReleaseHandle();
}
internal ODBC32.RetCode GetConnectionAttribute(ODBC32.SQL_ATTR attribute, byte[] buffer, out int cbActual)
{
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetConnectAttrW(this, attribute, buffer, buffer.Length, out cbActual);
Bid.Trace("<odbc.SQLGetConnectAttr|ODBC> SQLRETURN=%d, Attribute=%d, BufferLength=%d, StringLength=%d\n", (int)retcode, (int)attribute, buffer.Length, (int)cbActual);
return retcode;
}
internal ODBC32.RetCode GetFunctions(ODBC32.SQL_API fFunction, out Int16 fExists)
{
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetFunctions(this, fFunction, out fExists);
ODBC.TraceODBC(3, "SQLGetFunctions", retcode);
return retcode;
}
internal ODBC32.RetCode GetInfo2(ODBC32.SQL_INFO info, byte[] buffer, out short cbActual)
{
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetInfoW(this, info, buffer, checked((short)buffer.Length), out cbActual);
Bid.Trace("<odbc.SQLGetInfo|ODBC> SQLRETURN=%d, InfoType=%d, BufferLength=%d, StringLength=%d\n", (int)retcode, (int)info, buffer.Length, (int)cbActual);
return retcode;
}
internal ODBC32.RetCode GetInfo1(ODBC32.SQL_INFO info, byte[] buffer)
{
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetInfoW(this, info, buffer, checked((short)buffer.Length), ADP.PtrZero);
Bid.Trace("<odbc.SQLGetInfo|ODBC> SQLRETURN=%d, InfoType=%d, BufferLength=%d\n", (int)retcode, (int)info, buffer.Length);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute2(ODBC32.SQL_ATTR attribute, IntPtr value, Int32 length)
{
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetConnectAttrW(this, attribute, value, length);
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute3(ODBC32.SQL_ATTR attribute, string buffer, Int32 length)
{
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetConnectAttrW(this, attribute, buffer, length);
Bid.Trace("<odbc.SQLSetConnectAttr|ODBC> SQLRETURN=%d, Attribute=%d, BufferLength=%d\n", (int)retcode, (int)attribute, buffer.Length);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute4(ODBC32.SQL_ATTR attribute, System.Transactions.IDtcTransaction transaction, Int32 length)
{
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetConnectAttrW(this, attribute, transaction, length);
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using System.Linq;
using WPFLight.Helpers;
using System.Windows.Controls;
namespace System.Windows.Markup {
public sealed class XamlReader {
XamlReader () { }
#region Eigenschaften
public XDocument Document { get; private set; }
#endregion
/// <summary>
/// loads a Xaml-Stream and converts it to an object
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static object Load (Stream stream) {
using (var reader = new StreamReader(stream)) {
return Parse(reader.ReadToEnd());
}
}
/// <summary>
/// Parses an object from XAML
/// </summary>
/// <param name="xaml">Xaml.</param>
public static object Parse (string xaml) {
var xdoc = XDocument.Parse (xaml);
var reader = new XamlReader ();
reader.Document = xdoc;
reader.ReadNamespaces ();
return reader.ReadElement (xdoc.Root, null, null, null,null);
}
/// <summary>
/// creates a new object by its typename
/// </summary>
/// <returns>The object.</returns>
/// <param name="element">Element.</param>
object CreateObject (XElement element) {
if (element == null)
throw new ArgumentNullException ();
return Activator.CreateInstance (
Type.GetType (this.GetTypeName (element), true));
}
/// <summary>
/// gets the full typename
/// </summary>
/// <returns>The type name.</returns>
/// <param name="element">Element.</param>
string GetTypeName (XElement element) {
if (element == null)
throw new ArgumentNullException ();
return this.GetTypeName (element.Name.LocalName);
}
/// <summary>
/// gets the full typename
/// </summary>
/// <returns>The type name.</returns>
/// <param name="value">Value.</param>
string GetTypeName ( string value ) {
if (value == null)
throw new ArgumentNullException ();
// resolve namespace
var tmp = value.IndexOf (":");
if (tmp > -1) {
var name = value.Substring (0, tmp);
return value.Replace(
name + ":", namespaces[name].Replace("clr-namespace:", String.Empty).Trim() + ".");
} else {
// xmlns - Microsoft Xaml-Presentation Schema
if (this.HasDefaultNamespace ()) {
foreach (var type in Assembly.GetCallingAssembly ( ).GetTypes ( )) {
if (type.Name == value) {
value = type.FullName;
break;
}
}
}
return value;
}
}
/// <summary>
/// gets the DependencyProperty of a type by its property-name
/// </summary>
/// <param name="propertyName"></param>
/// <param name="targetType"></param>
/// <returns></returns>
DependencyProperty GetDependencyProperty ( string propertyName, Type targetType ) {
if (String.IsNullOrEmpty (propertyName))
throw new ArgumentException ();
var value = default ( DependencyProperty );
if (targetType != null ) {
// gets the static DependencyProperty-field,
// like "static readonly DependencyProperty BackgroundProperty"
var field = targetType.GetField (
propertyName + "Property",
BindingFlags.FlattenHierarchy
| BindingFlags.Public
| BindingFlags.Static);
value = ( DependencyProperty ) field.GetValue (null);
}
return value;
}
object CreateObject (XElement element, object parent) {
if (element == null || parent == null )
throw new ArgumentNullException();
if (parent == null || parent is ICollection || parent.GetType() == typeof(Object) ) {
return Activator.CreateInstance(
Type.GetType(this.GetTypeName(element), true));
}else {
var type = parent.GetType();
var propInfo = type.GetProperty(element.Name.LocalName);
var propType = propInfo.PropertyType;
return Activator.CreateInstance(propType);
}
}
Type GetTypeByClassAttribute ( XElement element ) {
var classAttr = element.Attributes ()
.Where (a => a.Name.LocalName == "Class")
.FirstOrDefault ();
var type = default ( Type );
if (classAttr != null) {
#if WINDOWS_PHONE
type = Assembly.GetExecutingAssembly ()
.GetType(classAttr.Value, true);
#else
type = Assembly.GetEntryAssembly()
.GetType(classAttr.Value, true);
#endif
}
return type;
}
/// <summary>
/// // assign a field in codebehind-class to a named Xaml-Element, like <Button x:Name="button1" />
/// </summary>
/// <param name="elementName">Element name.</param>
/// <param name="codeBehind">Code behind.</param>
/// <param name="element">Element.</param>
void SetElementField ( string elementName, object codeBehind, object element ) {
if (codeBehind == null || element == null || String.IsNullOrWhiteSpace ( elementName ) )
throw new ArgumentException ();
var elementField = codeBehind.GetType ().GetField (elementName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
if (elementField != null)
elementField.SetValue (codeBehind, element);
}
/// <summary>
/// reads a xml-element and also its children to return it as object
/// </summary>
/// <returns>The element.</returns>
/// <param name="element">Element.</param>
object ReadElement (
XElement element,
Type targetType,
Type targetStyleType,
object parent,
object codeBehind ) {
var classType = GetTypeByClassAttribute (element);
if (classType != null) {
targetType = classType;
}
var isPropertyElement = element.Name.LocalName.Contains ( "." )
&& element.Parent != null
&& element.Name.LocalName.StartsWith (
element.Parent.Name.LocalName + ".");
var parentContentPropertyInfo = default ( PropertyInfo );
if (parent != null) {
var parentType = parent.GetType ();
#if WINDOWS_PHONE
var parentContentPropertyAttr = (ContentPropertyAttribute)(parentType.GetCustomAttributes(
typeof(ContentPropertyAttribute), true)).FirstOrDefault ( );
#else
var parentContentPropertyAttr = (ContentPropertyAttribute)parentType.GetCustomAttribute (
typeof(ContentPropertyAttribute), true);
#endif
if (parentContentPropertyAttr != null)
parentContentPropertyInfo = parentType.GetProperty (parentContentPropertyAttr.Name);
}
var item = default ( Object );
if (targetType == null) {
if (parentContentPropertyInfo != null) {
item = CreateObject (element);
} else {
if (parent != null && !(parent is ResourceDictionary))
item = CreateObject (element, parent);
else
item = CreateObject (element);
}
} else {
item = Activator.CreateInstance (targetType);
if (classType != null)
codeBehind = item;
}
if (item != null) {
var itemType = item.GetType ();
var contentPropertyInfo = default ( PropertyInfo );
// check target-item for ContentProperty-Attrbitue,
// which describes the property which is set by default
// like <Style><Setter ... /></Style> -- Parent of Setter is the Style.Setters-Property
var contentPropertyAttribute = ( ContentPropertyAttribute )
Attribute.GetCustomAttribute(
itemType,
typeof ( ContentPropertyAttribute ) );
if ( contentPropertyAttribute != null
&& !String.IsNullOrEmpty ( contentPropertyAttribute.Name ) ) {
contentPropertyInfo = itemType.GetProperty (
contentPropertyAttribute.Name );
}
if (element.HasAttributes) {
// iterate attributes
foreach (var attribute in element.Attributes ( )) {
if ( !attribute.IsNamespaceDeclaration ) {
if (this.IsKeyAttribute (attribute)) {
// save resource by key
ResourceHelper.SetResourceKey (
ReadValue (attribute.Value, null), item);
} else if (this.IsNameAttribute (attribute)) {
if (String.IsNullOrWhiteSpace (attribute.Value))
throw new InvalidOperationException ( "Name-Attribute can't be empty" );
if (codeBehind != null) {
this.SetElementField (attribute.Value, codeBehind, item );
var frameworkElement = codeBehind as FrameworkElement;
if (frameworkElement != null) {
// TODO Implement RegisterName
//frameworkElement.RegisterName (attribute.Value, item);
}
}
} else if ( this.IsClassAttribute ( attribute ) ) {
// do nothing, it will be checked at the beginning
} else {
var name = attribute.Name.LocalName;
var value = attribute.Value;
// check if a property exists
var propInfo = itemType.GetProperty(name);
if (propInfo != null) {
if (propInfo.PropertyType == typeof(DependencyProperty)
&& targetStyleType != null) {
// sets the DependecyProperty-Value
propInfo.SetValue (
item,
this.GetDependencyProperty (
value, targetStyleType),
null);
} else {
if (propInfo.PropertyType != typeof(System.Object)
&& (propInfo.PropertyType != typeof(Type))) {
propInfo.SetValue (
item,
Convert (
this.ReadValue (
attribute.Value, propInfo.PropertyType),
propInfo.PropertyType),
null);
} else {
// sets the converted value
propInfo.SetValue (
item,
//Convert (
this.ReadValue (
attribute.Value,
propInfo.PropertyType),
//propInfo.PropertyType ),
null);
}
}
} else {
// check if an event exists
var eventInfo = itemType.GetEvent (name);
if (eventInfo != null) {
// gets the handler-method
var method = codeBehind.GetType ()
.GetMethod (attribute.Value,
BindingFlags.NonPublic
| BindingFlags.Public
| BindingFlags.Instance);
if (method != null) {
// create delegate
var del = Delegate.CreateDelegate (
eventInfo.EventHandlerType, codeBehind, attribute.Value, false, true );
// add eventhandler-delegate
eventInfo.AddEventHandler (item, del);
} else {
// handler-method doesn't exsists
throw new Exception ("Declared EventHandler-Method not found.");
}
} else {
// there is a xaml-attribute defined,
// which doesn't exists as property or event in the final object
}
}
}
}
}
}
var style = item as Style;
if (style != null && style.TargetType != null)
targetStyleType = style.TargetType;
/* <Style targetType="{x:Type Button}"> <!-- targetType, Property of the Style-Object !>
* <Style.Setters> <!-- Child-Element, Property of its parent-element !>
* ...
* </Style.Setters>
* </Style>
* */
// iterate child-elements
foreach (var childElement in element.Elements()) {
// check whether its a property of the parent
if (childElement.Name.LocalName.StartsWith(element.Name.LocalName + ".")) {
var name = childElement.Name.LocalName.Replace(
element.Name.LocalName + ".", String.Empty);
var propInfo = itemType.GetProperty(name);
if (propInfo != null) {
propInfo.SetValue(
item,
this.ReadValue(
this.ReadElement(
childElement,
propInfo.PropertyType,
targetStyleType,
item,
codeBehind ),
propInfo.PropertyType),
null);
}
} else {
// child of a collection
var childItem = this.ReadElement (
childElement, null, targetStyleType, item, codeBehind);
if (item is ResourceDictionary) {
((ResourceDictionary)item).Add (
ResourceHelper.GetResourceKey (childItem), childItem);
} else if (item is Panel) {
if ( childItem is UIElement )
((Panel)item).Children.Add ((UIElement)childItem);
} else if (item is ContentControl) {
((ContentControl)item).Content = childItem;
} else {
if (item is IList) {
var parentCollection = item as IList;
if (parentCollection != null) {
parentCollection.Add(childItem);
} else {
// check for contentproperty-Attribute
if (contentPropertyInfo != null) {
var v = contentPropertyInfo.GetValue(item, null);
var collection = v as IList;
if (collection != null) {
if (collection.GetType() == childItem.GetType()) {
foreach (var c in ((IList)childItem)) {
collection.Add(c);
}
} else
collection.Add(childItem);
} else {
var newItem = Activator.CreateInstance(contentPropertyInfo.PropertyType);
contentPropertyInfo.SetValue(item, newItem, null);
var list = newItem as IList;
if (list != null)
list.Add(childItem);
else {
// SOMETHING WRONG
}
}
} else {
// Maybe, something is wrong
Console.WriteLine("");
}
}
} else {
if (isPropertyElement) {
return childItem;
/*
var name = element.Name.LocalName.Replace(
element.Parent.Name.LocalName + ".", String.Empty);
var parentType = parent.GetType ();
var parentProp = parentType.GetProperty (name);
parentProp.SetValue (parent, childItem, null);
Console.WriteLine("");
*/
}
// Set Content
//Console.WriteLine("");
}
}
// converts the value of setters and triggers to its DependencyProperty-Type
ConvertPropertyValues (childItem);
}
}
if (!String.IsNullOrWhiteSpace (element.Value)) {
if (contentPropertyInfo != null) {
contentPropertyInfo.SetValue (
item,
Convert(
this.ReadValue(
element.Value.Trim(), contentPropertyInfo.PropertyType),
contentPropertyInfo.PropertyType),
null);
} else {
// there is content, but this is not allowed without a ContentPropertyAttribute
}
}
}
return item;
}
bool IsKeyAttribute (XAttribute attr) {
return attr.Name.LocalName == "Key";
}
bool IsNameAttribute (XAttribute attr) {
return attr.Name.LocalName == "Name";
}
bool IsClassAttribute (XAttribute attr) {
return attr.Name.LocalName == "Class";
}
void ConvertPropertyValues ( object value ) {
if ( value != null ){
var setter = value as Setter;
if (setter != null) {
if (setter.Value != null) {
var valueType = setter.Value.GetType ();
var dp = setter.Property;
if (!dp.PropertyType.IsAssignableFrom (valueType)) {
setter.Value = Convert (setter.Value, dp.PropertyType);
return;
}
}
}
var trigger = value as Trigger;
if (trigger != null) {
var dp = trigger.Property;
var valueType = trigger.Value.GetType ();
if (!dp.PropertyType.IsAssignableFrom ( valueType )) {
trigger.Value = Convert(trigger.Value,dp.PropertyType);
return;
}
}
}
}
/// <summary>
/// Converts a value to a specific type and uses its default converter
/// or its attributed custom TypeConverter like [TypeConverter(typeof(BrushConverter))]...
/// </summary>
/// <param name="propertyType"></param>
/// <param name="value"></param>
/// <returns></returns>
object Convert (object value, Type propertyType) {
// TODO check ValueType and throw exception if value is null
if (propertyType == typeof(Object))
return value;
if (value == null)
return null;
var underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
propertyType = underlyingType;
var conv = TypeDescriptor.GetConverter(propertyType);
if (conv != null)
return conv.ConvertFrom(value);
if (propertyType.IsEnum)
value = Enum.Parse(propertyType, (string) value, true);
return System.Convert.ChangeType(
value, propertyType, System.Globalization.CultureInfo.InvariantCulture);
}
object ReadValue (object value, Type targetType) {
var prefix = GetXamlPrefix ();
var stringValue = value as String;
if (stringValue != null) {
// check for Null-Value
if (stringValue == "{" + prefix + ":Null}")
return null;
// check for Type-Value
if (stringValue.StartsWith ("{" + prefix + ":Type")) {
var typeName = stringValue
.Replace ("{" + prefix + ":Type ", String.Empty)
.Replace ("}", String.Empty);
// create type by its name
return Type.GetType (
this.GetTypeName (typeName),
true );
}
}
return value;
}
/// <summary>
/// reads the namespaces which are declared in the root-element (xmlns:c="...")
/// </summary>
void ReadNamespaces () {
var dic = new Dictionary<string,string> ();
foreach (var attribute in Document.Root.Attributes ( )) {
if (attribute.IsNamespaceDeclaration) {
dic [attribute.Name.LocalName] = attribute.Value;
}
}
this.namespaces = dic;
}
/// <summary>
/// gets the prefix which was defined in xaml
/// </summary>
/// <returns></returns>
string GetXamlPrefix () {
foreach (var ns in namespaces) {
if (ns.Value == SCHEMA_XAML) {
return ns.Key;
}
}
return null;
}
bool HasDefaultNamespace () {
return namespaces.ContainsValue (SCHEMA_PRESENTATION);
}
private Dictionary<string, string> namespaces;
const string SCHEMA_XAML = "http://schemas.microsoft.com/winfx/2006/xaml";
const string SCHEMA_PRESENTATION = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
}
}
| |
// 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.Reflection
{
using System;
using System.Diagnostics.SymbolStore;
using System.Runtime.Remoting;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum PortableExecutableKinds
{
NotAPortableExecutableImage = 0x0,
ILOnly = 0x1,
Required32Bit = 0x2,
PE32Plus = 0x4,
Unmanaged32Bit = 0x8,
[ComVisible(false)]
Preferred32Bit = 0x10,
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum ImageFileMachine
{
I386 = 0x014c,
IA64 = 0x0200,
AMD64 = 0x8664,
ARM = 0x01c4,
}
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Module))]
[System.Runtime.InteropServices.ComVisible(true)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
#pragma warning restore 618
public abstract class Module : _Module, ISerializable, ICustomAttributeProvider
{
#region Static Constructor
static Module()
{
__Filters _fltObj;
_fltObj = new __Filters();
FilterTypeName = new TypeFilter(_fltObj.FilterTypeName);
FilterTypeNameIgnoreCase = new TypeFilter(_fltObj.FilterTypeNameIgnoreCase);
}
#endregion
#region Constructor
protected Module()
{
}
#endregion
#region Public Statics
public static readonly TypeFilter FilterTypeName;
public static readonly TypeFilter FilterTypeNameIgnoreCase;
public static bool operator ==(Module left, Module right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeModule || right is RuntimeModule)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(Module left, Module right)
{
return !(left == right);
}
public override bool Equals(object o)
{
return base.Equals(o);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
#region Literals
private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
#endregion
#region object overrides
public override String ToString()
{
return ScopeName;
}
#endregion
public virtual IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
return GetCustomAttributesData();
}
}
#region ICustomAttributeProvider Members
public virtual Object[] GetCustomAttributes(bool inherit)
{
throw new NotImplementedException();
}
public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public virtual bool IsDefined(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public virtual IList<CustomAttributeData> GetCustomAttributesData()
{
throw new NotImplementedException();
}
#endregion
#region public instances members
public MethodBase ResolveMethod(int metadataToken)
{
return ResolveMethod(metadataToken, null, null);
}
public virtual MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
throw new NotImplementedException();
}
public FieldInfo ResolveField(int metadataToken)
{
return ResolveField(metadataToken, null, null);
}
public virtual FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
throw new NotImplementedException();
}
public Type ResolveType(int metadataToken)
{
return ResolveType(metadataToken, null, null);
}
public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
throw new NotImplementedException();
}
public MemberInfo ResolveMember(int metadataToken)
{
return ResolveMember(metadataToken, null, null);
}
public virtual MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments);
throw new NotImplementedException();
}
public virtual byte[] ResolveSignature(int metadataToken)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveSignature(metadataToken);
throw new NotImplementedException();
}
public virtual string ResolveString(int metadataToken)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveString(metadataToken);
throw new NotImplementedException();
}
public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
rtModule.GetPEKind(out peKind, out machine);
throw new NotImplementedException();
}
public virtual int MDStreamVersion
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.MDStreamVersion;
throw new NotImplementedException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
[System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className, bool ignoreCase)
{
return GetType(className, false, ignoreCase);
}
[System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className) {
return GetType(className, false, false);
}
[System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className, bool throwOnError, bool ignoreCase)
{
throw new NotImplementedException();
}
public virtual String FullyQualifiedName
{
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
get
{
throw new NotImplementedException();
}
}
public virtual Type[] FindTypes(TypeFilter filter,Object filterCriteria)
{
Type[] c = GetTypes();
int cnt = 0;
for (int i = 0;i<c.Length;i++) {
if (filter!=null && !filter(c[i],filterCriteria))
c[i] = null;
else
cnt++;
}
if (cnt == c.Length)
return c;
Type[] ret = new Type[cnt];
cnt=0;
for (int i=0;i<c.Length;i++) {
if (c[i] != null)
ret[cnt++] = c[i];
}
return ret;
}
public virtual Type[] GetTypes()
{
throw new NotImplementedException();
}
public virtual Guid ModuleVersionId
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ModuleVersionId;
throw new NotImplementedException();
}
}
public virtual int MetadataToken
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.MetadataToken;
throw new NotImplementedException();
}
}
public virtual bool IsResource()
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.IsResource();
throw new NotImplementedException();
}
public FieldInfo[] GetFields()
{
return GetFields(Module.DefaultLookup);
}
public virtual FieldInfo[] GetFields(BindingFlags bindingFlags)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.GetFields(bindingFlags);
throw new NotImplementedException();
}
public FieldInfo GetField(String name)
{
return GetField(name,Module.DefaultLookup);
}
public virtual FieldInfo GetField(String name, BindingFlags bindingAttr)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.GetField(name, bindingAttr);
throw new NotImplementedException();
}
public MethodInfo[] GetMethods()
{
return GetMethods(Module.DefaultLookup);
}
public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.GetMethods(bindingFlags);
throw new NotImplementedException();
}
public MethodInfo GetMethod(
String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (types == null)
throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
}
public MethodInfo GetMethod(String name, Type[] types)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (types == null)
throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, types, null);
}
public MethodInfo GetMethod(String name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any,
null, null);
}
protected virtual MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
public virtual String ScopeName
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ScopeName;
throw new NotImplementedException();
}
}
public virtual String Name
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.Name;
throw new NotImplementedException();
}
}
public virtual Assembly Assembly
{
[Pure]
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.Assembly;
throw new NotImplementedException();
}
}
// This API never fails, it will return an empty handle for non-runtime handles and
// a valid handle for reflection only modules.
public ModuleHandle ModuleHandle
{
get
{
return GetModuleHandle();
}
}
// Used to provide implementation and overriding point for ModuleHandle.
// To get a module handle inside mscorlib, use GetNativeHandle instead.
internal virtual ModuleHandle GetModuleHandle()
{
return ModuleHandle.EmptyHandle;
}
#if FEATURE_X509 && FEATURE_CAS_POLICY
public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
{
throw new NotImplementedException();
}
#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
#if !FEATURE_CORECLR
void _Module.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
[Serializable]
internal class RuntimeModule : Module
{
internal RuntimeModule() { throw new NotSupportedException(); }
#region FCalls
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive);
[System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
private static extern bool nIsTransientInternal(RuntimeModule module);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static RuntimeType[] GetTypes(RuntimeModule module);
[System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeType[] GetDefinedTypes()
{
return GetTypes(GetNativeHandle());
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool IsResource(RuntimeModule module);
#if FEATURE_X509 && FEATURE_CAS_POLICY
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData);
#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
#region Module overrides
private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments)
{
if (genericArguments == null)
return null;
int size = genericArguments.Length;
RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size];
for (int i = 0; i < size; i++)
{
Type typeArg = genericArguments[i];
if (typeArg == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
typeArg = typeArg.UnderlyingSystemType;
if (typeArg == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
if (!(typeArg is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
typeHandleArgs[i] = typeArg.GetTypeHandleInternal();
}
return typeHandleArgs;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override byte[] ResolveSignature(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this),
nameof(metadataToken));
ConstArray signature;
if (tk.IsMemberRef)
signature = MetadataImport.GetMemberRefProps(metadataToken);
else
signature = MetadataImport.GetSignatureFromToken(metadataToken);
byte[] sig = new byte[signature.Length];
for (int i = 0; i < signature.Length; i++)
sig[i] = signature[i];
return sig;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
if (!tk.IsMethodDef && !tk.IsMethodSpec)
{
if (!tk.IsMemberRef)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
nameof(metadataToken));
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
nameof(metadataToken));
}
}
IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle);
if (declaringType.IsGenericType || declaringType.IsArray)
{
MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk));
if (tk.IsMethodSpec)
tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType));
declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
}
return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle);
}
catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
}
}
[System.Security.SecurityCritical] // auto-generated
private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef)
throw new ArgumentOutOfRangeException(nameof(metadataToken),
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
int tkDeclaringType;
string fieldName;
fieldName = MetadataImport.GetName(tk).ToString();
tkDeclaringType = MetadataImport.GetParentToken(tk);
Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
declaringType.GetFields();
try
{
return declaringType.GetField(fieldName,
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.DeclaredOnly);
}
catch
{
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), nameof(metadataToken));
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
IRuntimeFieldInfo fieldHandle = null;
if (!tk.IsFieldDef)
{
if (!tk.IsMemberRef)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
nameof(metadataToken));
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
nameof(metadataToken));
}
fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
}
fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs);
RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value);
if (declaringType.IsGenericType || declaringType.IsArray)
{
int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken);
declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
}
return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle);
}
catch(MissingFieldException)
{
return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
}
catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (tk.IsGlobalTypeDefToken)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), nameof(metadataToken));
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken));
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType();
if (t == null)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken));
return t;
}
catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (tk.IsProperty)
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable"));
if (tk.IsEvent)
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable"));
if (tk.IsMethodSpec || tk.IsMethodDef)
return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsFieldDef)
return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsMemberRef)
{
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
Environment.GetResourceString("Argument_InvalidToken", tk, this));
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
unsafe
{
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
{
return ResolveField(tk, genericTypeArguments, genericMethodArguments);
}
else
{
return ResolveMethod(tk, genericTypeArguments, genericMethodArguments);
}
}
}
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMember", tk, this),
nameof(metadataToken));
}
[System.Security.SecuritySafeCritical] // auto-generated
public override string ResolveString(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!tk.IsString)
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
string str = MetadataImport.GetUserString(metadataToken);
if (str == null)
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
return str;
}
public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine);
}
public override int MDStreamVersion
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return ModuleHandle.GetMDStreamVersion(GetNativeHandle());
}
}
#endregion
#region Data Members
#pragma warning disable 169
// If you add any data members, you need to update the native declaration ReflectModuleBaseObject.
private RuntimeType m_runtimeType;
private RuntimeAssembly m_runtimeAssembly;
private IntPtr m_pRefClass;
private IntPtr m_pData;
private IntPtr m_pGlobals;
private IntPtr m_pFields;
#pragma warning restore 169
#endregion
#region Protected Virtuals
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
}
internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (RuntimeType == null)
return null;
if (types == null)
{
return RuntimeType.GetMethod(name, bindingAttr);
}
else
{
return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
}
}
#endregion
#region Internal Members
internal RuntimeType RuntimeType
{
get
{
if (m_runtimeType == null)
m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle());
return m_runtimeType;
}
}
[System.Security.SecuritySafeCritical]
internal bool IsTransientInternal()
{
return RuntimeModule.nIsTransientInternal(this.GetNativeHandle());
}
internal MetadataImport MetadataImport
{
[System.Security.SecurityCritical] // auto-generated
get
{
unsafe
{
return ModuleHandle.GetMetadataImport(GetNativeHandle());
}
}
}
#endregion
#region ICustomAttributeProvider Members
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region Public Virtuals
[System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public override Type GetType(String className, bool throwOnError, bool ignoreCase)
{
// throw on null strings regardless of the value of "throwOnError"
if (className == null)
throw new ArgumentNullException(nameof(className));
RuntimeType retType = null;
Object keepAlive = null;
GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return retType;
}
[System.Security.SecurityCritical] // auto-generated
internal string GetFullyQualifiedName()
{
String fullyQualifiedName = null;
GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName));
return fullyQualifiedName;
}
public override String FullyQualifiedName
{
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
get
{
String fullyQualifiedName = GetFullyQualifiedName();
if (fullyQualifiedName != null) {
bool checkPermission = true;
try {
Path.GetFullPathInternal(fullyQualifiedName);
}
catch(ArgumentException) {
checkPermission = false;
}
if (checkPermission) {
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand();
}
}
return fullyQualifiedName;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetTypes()
{
return GetTypes(GetNativeHandle());
}
#endregion
#region Public Members
public override Guid ModuleVersionId
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
unsafe
{
Guid mvid;
MetadataImport.GetScopeProps(out mvid);
return mvid;
}
}
}
public override int MetadataToken
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return ModuleHandle.GetToken(GetNativeHandle());
}
}
public override bool IsResource()
{
return IsResource(GetNativeHandle());
}
public override FieldInfo[] GetFields(BindingFlags bindingFlags)
{
if (RuntimeType == null)
return new FieldInfo[0];
return RuntimeType.GetFields(bindingFlags);
}
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (RuntimeType == null)
return null;
return RuntimeType.GetField(name, bindingAttr);
}
public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
{
if (RuntimeType == null)
return new MethodInfo[0];
return RuntimeType.GetMethods(bindingFlags);
}
public override String ScopeName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
string scopeName = null;
GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName));
return scopeName;
}
}
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
String s = GetFullyQualifiedName();
#if !FEATURE_PAL
int i = s.LastIndexOf('\\');
#else
int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
#endif
if (i == -1)
return s;
return s.Substring(i + 1);
}
}
public override Assembly Assembly
{
[Pure]
get
{
return GetRuntimeAssembly();
}
}
internal RuntimeAssembly GetRuntimeAssembly()
{
return m_runtimeAssembly;
}
internal override ModuleHandle GetModuleHandle()
{
return new ModuleHandle(this);
}
internal RuntimeModule GetNativeHandle()
{
return this;
}
#if FEATURE_X509 && FEATURE_CAS_POLICY
[System.Security.SecuritySafeCritical] // auto-generated
public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
{
byte[] data = null;
GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data));
return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null;
}
#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// Provides functionality to use static sprites (images) to your scenes.
/// </summary>
public class OTSprite : OTObject
{
//-----------------------------------------------------------------------------
// Editor settings
//-----------------------------------------------------------------------------
public bool _flipHorizontal = false;
public bool _flipVertical = false;
public bool _transparent = true;
public bool _additive = false;
public string _materialReference = "transparent";
public Color _tintColor = Color.white;
public float _alpha = 1.0f;
public Texture _image = null;
public int _frameIndex = 0;
public string _frameName = "";
public OTContainer _spriteContainer;
//-----------------------------------------------------------------------------
// public attributes (get/set)
//-----------------------------------------------------------------------------
/// <summary>
/// Flips sprite image horizontally
/// </summary>
public bool flipHorizontal
{
get
{
return _flipHorizontal;
}
set
{
_flipHorizontal = value;
meshDirty = true;
_flipHorizontal_ = _flipHorizontal;
Update();
}
}
/// <summary>
/// Flips sprite image verically
/// </summary>
public bool flipVertical
{
get
{
return _flipVertical;
}
set
{
_flipVertical = value;
meshDirty = true;
_flipVertical_ = _flipVertical;
Update();
}
}
/// <summary>
/// Sprite needs transparency support
/// </summary>
public bool transparent
{
get
{
return _transparent;
}
set
{
_transparent = value;
Clean();
}
}
/// <summary>
/// Sprite needs additive transparency support
/// </summary>
public bool additive
{
get
{
return _additive;
}
set
{
_additive = value;
Clean();
}
}
/// <summary>
/// Current texture of the sprite (image or spriteContainer)
/// </summary>
public Texture texture
{
get
{
if (spriteContainer != null)
return spriteContainer.GetTexture();
else
return image;
}
}
/// <summary>
/// Default image texture for this sprite.
/// </summary>
public Texture image
{
get
{
return _image;
}
set
{
_image = value;
CheckSettings();
Clean();
}
}
/// <summary>
/// Sprite Container that will provide image information for this sprite
/// </summary>
public OTContainer spriteContainer
{
get
{
return _spriteContainer;
}
set
{
_spriteContainer = value;
_containerName = "";
Clean();
}
}
/// <summary>
/// Index of the frame that is used to get image information from the Sprite Container
/// </summary>
public int frameIndex
{
get
{
return _frameIndex;
}
set
{
_frameIndex = value;
Clean();
}
}
/// <summary>
/// name of the frame that is used to get image information from the Sprite Container
/// </summary>
public string frameName
{
get
{
return _frameName;
}
set
{
_frameName = value;
Clean();
}
}
public Material material
{
get
{
if (Application.isPlaying)
return renderer.material;
else
return renderer.sharedMaterial;
}
set
{
assignedMaterial = true;
if (Application.isPlaying)
renderer.material = value;
else
renderer.sharedMaterial = value;
}
}
/// <summary>
/// Reference name of material for this sprite
/// </summary>
public string materialReference
{
get
{
return _materialReference;
}
set
{
_materialReference = value;
Clean();
}
}
/// <summary>
/// Tinting color of this sprite.
/// </summary>
/// <remarks>
/// This setting will only work if this sprite's materialReference can work with color tinting.
/// </remarks>
public Color tintColor
{
get
{
return _tintColor;
}
set
{
_tintColor = value;
Clean();
}
}
/// <summary>
/// Alpha channel for this sprite.
/// </summary>
/// <remarks>
/// This setting will only work if this sprite's materialReference can work with alpha channels/color.
/// </remarks>
public float alpha
{
get
{
return _alpha;
}
set
{
_alpha = value;
Clean();
}
}
[HideInInspector]
public string _containerName = "";
[HideInInspector]
public bool _newSprite = true;
//-----------------------------------------------------------------------------
// protected and private fields
//-----------------------------------------------------------------------------
protected OTContainer _spriteContainer_ = null;
int _frameIndex_ = 0;
string _frameName_ = "";
bool _flipHorizontal_ = false;
bool _flipVertical_ = false;
protected Texture _image_ = null;
bool _transparent_ = true;
Color _tintColor_ = Color.white;
float _alpha_ = 1;
bool _additive_ = false;
string _materialReference_ = "transparent";
string lastMatName = "";
Material lastMat = null;
OTMatRef mr;
bool assignedMaterial = false;
bool spriteInvalid = false;
//-----------------------------------------------------------------------------
// public methods
//-----------------------------------------------------------------------------
/// <summary>
/// Retrieve frame data of the sprite's current frame. This data will include the
/// texture scale, texture offset and uv coordinates that are needed to get the
/// current frame's image.
/// </summary>
/// <returns>frame data of sprite's current frame</returns>
public OTContainer.Frame CurrentFrame()
{
if (spriteContainer != null && spriteContainer.isReady)
return spriteContainer.GetFrame(frameIndex);
else
{
if (spriteContainer == null)
throw new System.Exception("No Sprite Container available [" + name + "]");
else
throw new System.Exception("Sprite Container not ready [" + name + "]");
}
}
public override void StartUp()
{
isDirty = true;
lastMatName = GetMatName();
Material mat = OT.LookupMaterial(lastMatName);
lastMat = mat;
if (mat != null)
{
renderer.material = mat;
HandleUV();
}
base.StartUp();
}
public override void Assign(OTObject protoType)
{
base.Assign(protoType);
OTSprite pSprite = protoType as OTSprite;
tintColor = pSprite.tintColor;
alpha = pSprite.alpha;
image = pSprite.image;
spriteContainer = pSprite.spriteContainer;
frameIndex = pSprite.frameIndex;
materialReference = pSprite.materialReference;
}
protected float mLeft = 0,mRight = 0,mTop = 0, mBottom = 0;
protected Vector2 _meshsize_ = Vector2.one;
protected Mesh InitMesh()
{
Mesh mesh = new Mesh();
_meshsize_ = Vector2.one;
_meshsize_ = Vector2.one;
_pivotPoint = pivotPoint;
float dx = (_meshsize_.x/2);
float dy = (_meshsize_.y/2);
float px = _pivotPoint.x;
float py = _pivotPoint.y;
mTop = dy - py;
mLeft = -dx - px;
mBottom = -dy - py;
mRight = dx - px;
return mesh;
}
//-----------------------------------------------------------------------------
// overridden subclass methods
//-----------------------------------------------------------------------------
protected override Mesh GetMesh()
{
Mesh mesh = InitMesh();
mesh.vertices = new Vector3[] {
new Vector3(mLeft, mTop, 0), // topleft
new Vector3(mRight, mTop, 0), // topright
new Vector3(mRight, mBottom, 0), // botright
new Vector3(mLeft, mBottom, 0) // botleft
};
mesh.triangles = new int[] {
0,1,2,2,3,0
};
Vector2[] meshUV = new Vector2[] {
new Vector2(0,1), new Vector2(1,1),
new Vector2(1,0), new Vector2(0,0) };
if (flipHorizontal)
{
Vector2 v;
v = meshUV[0];
meshUV[0] = meshUV[1]; meshUV[1] = v;
v = meshUV[2];
meshUV[2] = meshUV[3]; meshUV[3] = v;
}
if (flipVertical)
{
Vector2 v;
v = meshUV[0];
meshUV[0] = meshUV[3]; meshUV[3] = v;
v = meshUV[1];
meshUV[1] = meshUV[2]; meshUV[2] = v;
}
mesh.uv = meshUV;
return mesh;
}
protected override string GetTypeName()
{
return "Sprite";
}
protected override void AfterMesh()
{
base.AfterMesh();
// reset size because mesh has been created with a size (x/y) of 1/1
size = _size;
_frameIndex_ = -1;
_frameName_ = "";
isDirty = true;
}
public virtual string GetMatName()
{
string matName = "";
if (spriteContainer != null)
matName += "spc:" + spriteContainer.name + ":" + materialReference;
else
if (image != null)
matName += "img:" + _image.GetInstanceID() + " : " +
materialReference;
if (matName == "") matName = materialReference;
if (mr != null)
{
if (mr.fieldColorTint != "")
matName += " : " + tintColor.ToString();
if (mr.fieldAlphaChannel != "" || mr.fieldAlphaColor != "")
matName += " : " + alpha;
}
return matName;
}
private void SetMatReference()
{
if (transparent)
_materialReference = "transparent";
else
if (additive)
_materialReference = "additive";
else
if (_materialReference == "additive" || _materialReference == "transparent" || _materialReference == "")
_materialReference = "solid";
}
override protected void CheckDirty()
{
base.CheckDirty();
if (spriteContainer != null)
{
if (spriteContainer.isReady)
{
if (_spriteContainer_ != spriteContainer || _frameIndex_ != frameIndex || _frameName_ != frameName)
isDirty = true;
}
}
else
if (_spriteContainer_ != null || image != _image_)
isDirty = true;
if (flipHorizontal != _flipHorizontal_ || flipVertical != _flipVertical_)
{
_flipHorizontal_ = flipHorizontal;
_flipVertical_ = flipVertical;
meshDirty = true;
}
if (!Application.isPlaying)
{
if (!isDirty && spriteContainer != null && material.mainTexture != spriteContainer.GetTexture())
isDirty = true;
}
if (transparent != _transparent_ && transparent)
{
_additive = false;
_additive_ = additive;
_transparent_ = transparent;
SetMatReference();
}
else
if (additive != _additive_ && additive)
{
_transparent = false;
_additive_ = additive;
_transparent_ = transparent;
SetMatReference();
}
else
if (!_additive && !_transparent)
{
_additive_ = additive;
_transparent_ = transparent;
if (_materialReference == "transparent" || _materialReference == "additive")
_materialReference = "solid";
}
if (materialReference != _materialReference_)
{
mr = OT.GetMatRef(materialReference);
if (_materialReference == "transparent")
{
_transparent = true;
_additive = false;
}
else
if (_materialReference == "additive")
{
_transparent = false;
_additive = true;
}
else
{
_transparent = false;
_additive = false;
}
isDirty = true;
}
if (mr != null)
{
if (_tintColor_ != tintColor)
{
if (mr.fieldColorTint != "")
isDirty = true;
else
{
_tintColor = Color.white;
_tintColor_ = _tintColor;
Debug.LogWarning("Orthello : TintColor can not be set on this materialReference!");
}
}
if (_alpha_ != alpha)
{
if (mr.fieldAlphaColor != "" || mr.fieldAlphaChannel != "")
isDirty = true;
else
{
_alpha = 1;
_alpha_ = 1;
Debug.LogWarning("Orthello : Alpha value can not be set on this materialReference!");
}
}
}
}
protected Vector2[] SpliceUV(Vector2[] uv, float[] pos, bool horizontal)
{
if (pos.Length<=2)
return uv;
Vector2 tl = uv[0];
Vector2 tr = uv[1];
Vector2 bl = uv[3];
Vector2[] _uv = new Vector2[pos.Length * 2];
for (int vr=0; vr<pos.Length; vr++)
{
float vi = pos[vr];
if (vr==0) vi=0;
if (vr == pos.Length-1) vi=100;
if (horizontal)
{
float dd = ((tr.x-tl.x)/100f) * vi;
int vp = vr;
if (flipHorizontal)
vp = (pos.Length-1-vr);
Vector2 p1 = new Vector2(tl.x+dd,tl.y);
Vector2 p2 = new Vector2(bl.x+dd,bl.y);
if (flipVertical)
{
Vector2 ps = p1;
p1 = p2;
p2 = ps;
}
_uv[vp * 2] = p1;
_uv[vp * 2+1] = p2;
}
else
{
float dd = ((tl.y-bl.y)/100f) * vi;
int vp = vr;
if (flipVertical)
vp = (pos.Length-1-vr);
Vector2 p1 = new Vector2(tl.x,tl.y-dd);
Vector2 p2 = new Vector2(tr.x,tr.y-dd);
if (flipHorizontal)
{
Vector2 ps = p1;
p1 = p2;
p2 = ps;
}
_uv[vp * 2] = p1;
_uv[vp * 2+1] = p2;
}
}
return _uv;
}
protected virtual void HandleUV()
{
if (spriteContainer != null && spriteContainer.isReady)
{
OTContainer.Frame frame = spriteContainer.GetFrame(frameIndex);
// adjust this sprites UV coords
if (frame.uv != null && mesh != null)
{
Vector2[] meshUV = frame.uv.Clone() as Vector2[];
if (meshUV.Length == mesh.vertexCount)
{
if (flipHorizontal)
{
Vector2 v;
v = meshUV[0];
meshUV[0] = meshUV[1]; meshUV[1] = v;
v = meshUV[2];
meshUV[2] = meshUV[3]; meshUV[3] = v;
}
if (flipVertical)
{
Vector2 v;
v = meshUV[0];
meshUV[0] = meshUV[3]; meshUV[3] = v;
v = meshUV[1];
meshUV[1] = meshUV[2]; meshUV[2] = v;
}
mesh.uv = meshUV;
}
}
}
}
protected virtual Material InitMaterial()
{
OTDebug.Message("@-->InitMaterial-In()","ot-mat");
if (spriteContainer != null && !spriteContainer.isReady)
{
// if we have a non-ready sprite container
// lets use the current assigned and scene saved material
lastMat = material;
assignedMaterial = false;
isDirty = true;
return lastMat;
}
// correct _frameIndex
if (spriteContainer!=null && _frameIndex>spriteContainer.frameCount-1)
_frameIndex = spriteContainer.frameCount-1;
// Get the new material base instance
Material spMat = OT.GetMaterial(_materialReference, tintColor, alpha);
// If we couldn't generate the material lets take our 'default' transparent
if (spMat == null) spMat = OT.materialTransparent;
if (spMat == null) return null;
// lets create a unique material instance belonging to this
// material name. This will be cached so other sprites that use
// the same material name will use the same and will get batched
// automaticly
Material mat = new Material(spMat);
if (spriteContainer != null && spriteContainer.isReady)
{
// setup the sprite material hooked to the sprite container
Texture tex = spriteContainer.GetTexture();
if (mat.mainTexture != tex)
mat.mainTexture = tex;
mat.mainTextureScale = Vector2.one;
mat.mainTextureOffset = Vector2.zero;
HandleUV();
}
else
if (image != null)
{
// setup the sprite material hooked to the image texture
if (mat != null)
{
mat.mainTexture = image;
mat.mainTextureScale = Vector2.one;
mat.mainTextureOffset = Vector3.zero;
}
}
if (mat != null)
{
// if we had a previous created material assigned we have to decrease
// the material cache count
if (lastMatName != "" && lastMat != null)
OT.MatDec(lastMat, lastMatName);
// because we are recreating the material the first time
// we will have to destroy the current material or it
// will start floating
if (lastMat == null && !assignedMaterial && !isCopy)
{
if (renderer!=null)
{
if (!Application.isPlaying)
DestroyImmediate(renderer.sharedMaterial, true);
else
Destroy(renderer.material);
}
}
// assign the new material to the renderer
if (Application.isPlaying)
renderer.material = mat;
else
renderer.sharedMaterial = mat;
// store this material as the last material
lastMat = mat;
lastMatName = GetMatName();
// we created/cached this material so it was not assigned
assignedMaterial = false;
}
OTDebug.Message("@<--InitMaterial()","ot-mat");
return mat;
}
protected bool adjustFrameSize = true;
protected override void Clean()
{
if (!OT.isValid || mesh == null) return;
base.Clean();
if (_spriteContainer_ != spriteContainer ||
_frameIndex_ != frameIndex ||
_frameName_ != frameName ||
_image_ != image ||
_tintColor_ != tintColor ||
_alpha_ != alpha ||
_materialReference_ != _materialReference ||
isCopy)
{
if (spriteContainer != null && spriteContainer.isReady)
{
if (_frameName_ != frameName)
_frameIndex = spriteContainer.GetFrameIndex(frameName);
if (frameIndex < 0) _frameIndex = 0;
if (frameIndex > spriteContainer.frameCount - 1) _frameIndex = spriteContainer.frameCount - 1;
// set frame name
OTContainer.Frame fr = CurrentFrame();
if (fr.name!="" && (frameName == "" || fr.name.IndexOf(frameName)!=0))
_frameName = fr.name;
if (spriteContainer is OTSpriteAtlas)
{
if (adjustFrameSize)
{
if ((spriteContainer as OTSpriteAtlas).offsetSizing)
{
if (Vector2.Equals(oSize, Vector2.zero))
{
oSize = fr.size * OT.view.sizeFactor;
Vector2 nOffset = fr.offset * OT.view.sizeFactor;
if (_baseOffset.x != nOffset.x || _baseOffset.y != nOffset.y)
{
offset = nOffset;
position = _position;
imageSize = fr.imageSize * OT.view.sizeFactor;
}
}
if (_frameIndex_ != frameIndex || _spriteContainer_ != spriteContainer)
{
float _sx = (size.x / oSize.x);
float _sy = (size.y / oSize.y);
Vector2 sc = new Vector2(_sx * fr.size.x * OT.view.sizeFactor, _sy * fr.size.y * OT.view.sizeFactor);
Vector3 sc3 = new Vector3(sc.x, sc.y, 1);
_size = sc;
if (!Vector3.Equals(transform.localScale, sc3))
transform.localScale = sc3;
oSize = fr.size * OT.view.sizeFactor;
imageSize = new Vector2(_sx * fr.imageSize.x * OT.view.sizeFactor, _sy * fr.imageSize.y * OT.view.sizeFactor);
Vector2 nOffset = new Vector2(_sx * fr.offset.x * OT.view.sizeFactor, _sy * fr.offset.y * OT.view.sizeFactor);
offset = nOffset;
position = _position;
}
}
else
{
Vector3[] verts = fr.vertices.Clone() as Vector3[];
verts[0] -= new Vector3(pivotPoint.x, pivotPoint.y, 0);
verts[1] -= new Vector3(pivotPoint.x, pivotPoint.y, 0);
verts[2] -= new Vector3(pivotPoint.x, pivotPoint.y, 0);
verts[3] -= new Vector3(pivotPoint.x, pivotPoint.y, 0);
mesh.vertices = verts;
_size = fr.size;
Vector3 sc3 = new Vector3(_size.x, _size.y, 1);
if (!Vector3.Equals(transform.localScale, sc3))
transform.localScale = sc3;
}
}
}
}
// keep old and get new material name
string cMatName = GetMatName();
if (lastMatName!=cMatName)
{
// material name has changed to look it up
Material mat = OT.LookupMaterial(cMatName);
// if we could not find the material let create a new one
if (mat == null)
mat = InitMaterial();
else
{
// if we had a previous generated material lets
// decrease its use
if (lastMat!=null && lastMatName!="")
OT.MatDec(lastMat,lastMatName);
renderer.material = mat;
HandleUV();
lastMat = mat;
lastMatName = cMatName;
}
// increase the current material's use
OT.MatInc(mat, cMatName);
}
else
{
if (_frameIndex_ != frameIndex)
HandleUV();
}
_spriteContainer_ = spriteContainer;
_materialReference_ = materialReference;
_frameIndex_ = frameIndex;
_frameName_ = frameName;
_image_ = image;
_tintColor_ = tintColor;
_alpha_ = alpha;
}
isDirty = false;
if (spriteContainer != null && !spriteContainer.isReady)
isDirty = true;
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this);
#endif
}
new protected void OnDestroy()
{
if (lastMatName != "" && lastMat != null)
OT.MatDec(lastMat, lastMatName);
else
DestroyImmediate(material);
base.OnDestroy();
}
protected Vector2 baseSize = Vector2.zero;
bool frameReloaded = false;
override protected void CheckSettings()
{
base.CheckSettings();
if (Application.isEditor || OT.dirtyChecks || dirtyChecks)
{
if (spriteContainer != null && spriteContainer.isReady)
{
if (baseSize.Equals(Vector2.zero) || _newSprite)
baseSize = _size;
_newSprite = false;
if (spriteContainer is OTSpriteAtlasImport && (spriteContainer as OTSpriteAtlasImport).reloadFrame && !frameReloaded)
{
_frameIndex_ = -1;
frameReloaded = true;
}
if (frameIndex < 0) _frameIndex = 0;
if (frameIndex > spriteContainer.frameCount - 1) _frameIndex = spriteContainer.frameCount - 1;
OTContainer.Frame fr = CurrentFrame();
if (_spriteContainer_ == null && _containerName != "")
{
// set basesize to current frame size if we just had a lookup from a prefab
baseSize = fr.size;
}
_containerName = spriteContainer.name;
if (_spriteContainer_ != spriteContainer && adjustFrameSize)
ResizeFrame();
baseSize = fr.size;
}
else
{
if (_spriteContainer_ != null && _spriteContainer == null)
{
_containerName = "";
}
if (_image_ != image)
{
if (!baseSize.Equals(Vector2.zero))
size = new Vector2 (size.x * (image.width / baseSize.x) , size.y * (image.height / baseSize.y) ) * OT.view.sizeFactor;
else
size = new Vector2(image.width, image.height) * OT.view.sizeFactor;
baseSize = new Vector2(image.width, image.height);
}
}
if (alpha < 0) _alpha = 0;
else
if (alpha > 1) _alpha = 1;
}
}
//-----------------------------------------------------------------------------
// class methods
//-----------------------------------------------------------------------------
// Use this for initialization
protected override void Awake()
{
if (_frameIndex<0)
_frameIndex = 0;
_spriteContainer_ = spriteContainer;
_frameIndex_ = frameIndex;
_frameName_ = frameName;
_image_ = image;
_materialReference_ = materialReference;
_transparent_ = transparent;
_flipHorizontal_ = flipHorizontal;
_flipVertical_ = flipVertical;
_tintColor_ = _tintColor;
_alpha_ = _alpha;
isDirty = true;
if (image!=null)
baseSize = new Vector2(image.width, image.height);
if (_spriteContainer != null || image!=null)
_newSprite = false;
base.Awake();
}
public Material GetMat()
{
Material mat = OT.LookupMaterial(lastMatName);
if (mat != null)
{
OTDebug.Message("GetMat -> Found","ot-mat");
renderer.material = mat;
HandleUV();
}
else
{
OTDebug.Message("GetMat -> Not Found","ot-mat");
mat = InitMaterial();
}
OTDebug.Message("@OT.MatInc - GetMat()","ot-mat");
OT.MatInc(mat, lastMatName);
lastMat = mat;
return mat;
}
protected override void Start()
{
mr = OT.GetMatRef(materialReference);
lastMatName = GetMatName();
base.Start();
if (!Application.isPlaying || (Application.isPlaying && !assignedMaterial))
material = GetMat();
if (Application.isPlaying)
_frameIndex_ = -1;
}
void ResizeFrame()
{
OTContainer.Frame fr = CurrentFrame();
oSize = fr.size;
if (!baseSize.Equals(Vector2.zero))
size = new Vector2(size.x * (fr.size.x / baseSize.x) , size.y * (fr.size.y / baseSize.y) ) * OT.view.sizeFactor;
else
size = fr.size * OT.view.sizeFactor;
baseSize = fr.size;
}
int _frameStartIndex = -1;
public void InvalidateSprite()
{
spriteInvalid = true;
otRenderer.enabled = false;
if (spriteContainer!=null)
_frameStartIndex = _frameIndex;
if (otTransform.childCount > 0)
{
hiddenRenderers.Clear();
Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();
for (int r = 0; r < renderers.Length; r++)
{
if (renderers[r].enabled)
hiddenRenderers.Add(renderers[r]);
renderers[r].enabled = false;
}
}
}
public bool isInvalid
{
get
{
return spriteInvalid;
}
}
public void IsValid()
{
spriteInvalid = false;
}
bool SpriteValid()
{
if (!spriteInvalid)
return true;
if (spriteInvalid)
{
if (!Application.isPlaying || _image != null || (spriteContainer!=null && spriteContainer.isReady))
{
spriteInvalid = false;
if ((spriteContainer!=null && spriteContainer.isReady) && adjustFrameSize && _frameStartIndex>=0)
{
baseSize = spriteContainer.GetFrame(_frameStartIndex).size;
ResizeFrame();
}
if (!otRenderer.enabled)
{
otRenderer.enabled = true;
if (transform.childCount > 0)
{
Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();
for (int r = 0; r < renderers.Length; r++)
renderers[r].enabled = true;
}
}
return true;
}
return false;
}
return true;
}
// Update is called once per frame
protected override void Update()
{
if (!OT.isValid) return;
if (spriteInvalid)
SpriteValid();
if (image == null && _spriteContainer_ == null)
{
if (_containerName!="")
{
OTContainer c = OT.ContainerByName(_containerName);
if (c!=null && c.isReady)
spriteContainer = c;
}
}
// check if no material has been assigned yet
if (!Application.isPlaying)
{
Material mat = material;
if (mat == null)
{
mat = new Material(OT.materialTransparent);
material = mat;
mat.mainTexture = texture;
}
}
base.Update();
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonViewInspector.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
// Custom inspector for the PhotonView component.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
#if UNITY_5 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2
#define UNITY_MIN_5_3
#endif
using System;
using Rotorz.ReorderableList.Internal;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof (PhotonView))]
public class PhotonViewInspector : Editor
{
private PhotonView m_Target;
public override void OnInspectorGUI()
{
this.m_Target = (PhotonView)target;
bool isProjectPrefab = EditorUtility.IsPersistent(this.m_Target.gameObject);
if (this.m_Target.ObservedComponents == null)
{
this.m_Target.ObservedComponents = new System.Collections.Generic.List<Component>();
}
if (this.m_Target.ObservedComponents.Count == 0)
{
this.m_Target.ObservedComponents.Add(null);
}
EditorGUILayout.BeginHorizontal();
// Owner
if (isProjectPrefab)
{
EditorGUILayout.LabelField("Owner:", "Set at runtime");
}
else if (!this.m_Target.isOwnerActive)
{
EditorGUILayout.LabelField("Owner", "Scene");
}
else
{
PhotonPlayer owner = this.m_Target.owner;
string ownerInfo = (owner != null) ? owner.name : "<no PhotonPlayer found>";
if (string.IsNullOrEmpty(ownerInfo))
{
ownerInfo = "<no playername set>";
}
EditorGUILayout.LabelField("Owner", "[" + this.m_Target.ownerId + "] " + ownerInfo);
}
// ownership requests
EditorGUI.BeginDisabledGroup(Application.isPlaying);
OwnershipOption own = (OwnershipOption)EditorGUILayout.EnumPopup(this.m_Target.ownershipTransfer, GUILayout.Width(100));
if (own != this.m_Target.ownershipTransfer)
{
// jf: fixed 5 and up prefab not accepting changes if you quit Unity straight after change.
// not touching the define nor the rest of the code to avoid bringing more problem than solving.
EditorUtility.SetDirty(this.m_Target);
Undo.RecordObject(this.m_Target, "Change PhotonView Ownership Transfer");
this.m_Target.ownershipTransfer = own;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
// View ID
if (isProjectPrefab)
{
EditorGUILayout.LabelField("View ID", "Set at runtime");
}
else if (EditorApplication.isPlaying)
{
EditorGUILayout.LabelField("View ID", this.m_Target.viewID.ToString());
}
else
{
int idValue = EditorGUILayout.IntField("View ID [1.." + (PhotonNetwork.MAX_VIEW_IDS - 1) + "]", this.m_Target.viewID);
if (this.m_Target.viewID != idValue)
{
Undo.RecordObject(this.m_Target, "Change PhotonView viewID");
this.m_Target.viewID = idValue;
}
}
// Locally Controlled
if (EditorApplication.isPlaying)
{
string masterClientHint = PhotonNetwork.isMasterClient ? "(master)" : "";
EditorGUILayout.Toggle("Controlled locally: " + masterClientHint, this.m_Target.isMine);
}
//DrawOldObservedItem();
ConvertOldObservedItemToObservedList();
// ViewSynchronization (reliability)
if (this.m_Target.synchronization == ViewSynchronization.Off)
{
GUI.color = Color.grey;
}
EditorGUILayout.PropertyField(serializedObject.FindProperty("synchronization"), new GUIContent("Observe option:"));
if (this.m_Target.synchronization != ViewSynchronization.Off && this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0)
{
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Warning", EditorStyles.boldLabel);
GUILayout.Label("Setting the synchronization option only makes sense if you observe something.");
GUILayout.EndVertical();
}
/*ViewSynchronization vsValue = (ViewSynchronization)EditorGUILayout.EnumPopup("Observe option:", m_Target.synchronization);
if (vsValue != m_Target.synchronization)
{
m_Target.synchronization = vsValue;
if (m_Target.synchronization != ViewSynchronization.Off && m_Target.observed == null)
{
EditorUtility.DisplayDialog("Warning", "Setting the synchronization option only makes sense if you observe something.", "OK, I will fix it.");
}
}*/
DrawSpecificTypeSerializationOptions();
GUI.color = Color.white;
DrawObservedComponentsList();
// Cleanup: save and fix look
if (GUI.changed)
{
#if !UNITY_MIN_5_3
EditorUtility.SetDirty(this.m_Target);
#endif
PhotonViewHandler.HierarchyChange(); // TODO: check if needed
}
GUI.color = Color.white;
#if !UNITY_MIN_5_3
EditorGUIUtility.LookLikeControls();
#endif
}
private void DrawSpecificTypeSerializationOptions()
{
if (this.m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof (Transform)).Count > 0 ||
(this.m_Target.observed != null && this.m_Target.observed.GetType() == typeof (Transform)))
{
this.m_Target.onSerializeTransformOption = (OnSerializeTransform)EditorGUILayout.EnumPopup("Transform Serialization:", this.m_Target.onSerializeTransformOption);
}
else if (this.m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof (Rigidbody)).Count > 0 ||
(this.m_Target.observed != null && this.m_Target.observed.GetType() == typeof (Rigidbody)) ||
this.m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof (Rigidbody2D)).Count > 0 ||
(this.m_Target.observed != null && this.m_Target.observed.GetType() == typeof (Rigidbody2D)))
{
this.m_Target.onSerializeRigidBodyOption = (OnSerializeRigidBody)EditorGUILayout.EnumPopup("Rigidbody Serialization:", this.m_Target.onSerializeRigidBodyOption);
}
}
private void DrawSpecificTypeOptions()
{
if (this.m_Target.observed != null)
{
Type type = this.m_Target.observed.GetType();
if (type == typeof (Transform))
{
this.m_Target.onSerializeTransformOption = (OnSerializeTransform)EditorGUILayout.EnumPopup("Serialization:", this.m_Target.onSerializeTransformOption);
}
else if (type == typeof (Rigidbody))
{
this.m_Target.onSerializeRigidBodyOption = (OnSerializeRigidBody)EditorGUILayout.EnumPopup("Serialization:", this.m_Target.onSerializeRigidBodyOption);
}
}
}
private void ConvertOldObservedItemToObservedList()
{
if (Application.isPlaying)
{
return;
}
if (this.m_Target.observed != null)
{
Undo.RecordObject(this.m_Target, null);
if (this.m_Target.ObservedComponents.Contains(this.m_Target.observed) == false)
{
bool wasAdded = false;
for (int i = 0; i < this.m_Target.ObservedComponents.Count; ++i)
{
if (this.m_Target.ObservedComponents[i] == null)
{
this.m_Target.ObservedComponents[i] = this.m_Target.observed;
wasAdded = true;
}
}
if (wasAdded == false)
{
this.m_Target.ObservedComponents.Add(this.m_Target.observed);
}
}
this.m_Target.observed = null;
#if !UNITY_MIN_5_3
EditorUtility.SetDirty(this.m_Target);
#endif
}
}
private void DrawOldObservedItem()
{
EditorGUILayout.BeginHorizontal();
// Using a lower version then 3.4? Remove the TRUE in the next line to fix an compile error
string typeOfObserved = string.Empty;
if (this.m_Target.observed != null)
{
int firstBracketPos = this.m_Target.observed.ToString().LastIndexOf('(');
if (firstBracketPos > 0)
{
typeOfObserved = this.m_Target.observed.ToString().Substring(firstBracketPos);
}
}
Component componenValue = (Component)EditorGUILayout.ObjectField("Observe: " + typeOfObserved, this.m_Target.observed, typeof (Component), true);
if (this.m_Target.observed != componenValue)
{
if (this.m_Target.observed == null)
{
this.m_Target.synchronization = ViewSynchronization.UnreliableOnChange; // if we didn't observe anything yet. use unreliable on change as default
}
if (componenValue == null)
{
this.m_Target.synchronization = ViewSynchronization.Off;
}
this.m_Target.observed = componenValue;
}
EditorGUILayout.EndHorizontal();
}
private int GetObservedComponentsCount()
{
int count = 0;
for (int i = 0; i < this.m_Target.ObservedComponents.Count; ++i)
{
if (this.m_Target.ObservedComponents[i] != null)
{
count++;
}
}
return count;
}
private void DrawObservedComponentsList()
{
GUILayout.Space(5);
SerializedProperty listProperty = serializedObject.FindProperty("ObservedComponents");
if (listProperty == null)
{
return;
}
float containerElementHeight = 22;
float containerHeight = listProperty.arraySize*containerElementHeight;
bool isOpen = PhotonGUI.ContainerHeaderFoldout("Observed Components (" + GetObservedComponentsCount() + ")", serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue);
serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue = isOpen;
if (isOpen == false)
{
containerHeight = 0;
}
//Texture2D statsIcon = AssetDatabase.LoadAssetAtPath( "Assets/Photon Unity Networking/Editor/PhotonNetwork/PhotonViewStats.png", typeof( Texture2D ) ) as Texture2D;
Rect containerRect = PhotonGUI.ContainerBody(containerHeight);
bool wasObservedComponentsEmpty = this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0;
if (isOpen == true)
{
for (int i = 0; i < listProperty.arraySize; ++i)
{
Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + containerElementHeight*i, containerRect.width, containerElementHeight);
{
Rect texturePosition = new Rect(elementRect.xMin + 6, elementRect.yMin + elementRect.height/2f - 1, 9, 5);
ReorderableListResources.DrawTexture(texturePosition, ReorderableListResources.texGrabHandle);
Rect propertyPosition = new Rect(elementRect.xMin + 20, elementRect.yMin + 3, elementRect.width - 45, 16);
EditorGUI.PropertyField(propertyPosition, listProperty.GetArrayElementAtIndex(i), new GUIContent());
//Debug.Log( listProperty.GetArrayElementAtIndex( i ).objectReferenceValue.GetType() );
//Rect statsPosition = new Rect( propertyPosition.xMax + 7, propertyPosition.yMin, statsIcon.width, statsIcon.height );
//ReorderableListResources.DrawTexture( statsPosition, statsIcon );
Rect removeButtonRect = new Rect(elementRect.xMax - PhotonGUI.DefaultRemoveButtonStyle.fixedWidth,
elementRect.yMin + 2,
PhotonGUI.DefaultRemoveButtonStyle.fixedWidth,
PhotonGUI.DefaultRemoveButtonStyle.fixedHeight);
GUI.enabled = listProperty.arraySize > 1;
if (GUI.Button(removeButtonRect, new GUIContent(ReorderableListResources.texRemoveButton), PhotonGUI.DefaultRemoveButtonStyle))
{
listProperty.DeleteArrayElementAtIndex(i);
}
GUI.enabled = true;
if (i < listProperty.arraySize - 1)
{
texturePosition = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1);
PhotonGUI.DrawSplitter(texturePosition);
}
}
}
}
if (PhotonGUI.AddButton())
{
listProperty.InsertArrayElementAtIndex(Mathf.Max(0, listProperty.arraySize - 1));
}
serializedObject.ApplyModifiedProperties();
bool isObservedComponentsEmpty = this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0;
if (wasObservedComponentsEmpty == true && isObservedComponentsEmpty == false && this.m_Target.synchronization == ViewSynchronization.Off)
{
Undo.RecordObject(this.m_Target, "Change PhotonView");
this.m_Target.synchronization = ViewSynchronization.UnreliableOnChange;
#if !UNITY_MIN_5_3
EditorUtility.SetDirty(this.m_Target);
#endif
serializedObject.Update();
}
if (wasObservedComponentsEmpty == false && isObservedComponentsEmpty == true)
{
Undo.RecordObject(this.m_Target, "Change PhotonView");
this.m_Target.synchronization = ViewSynchronization.Off;
#if !UNITY_MIN_5_3
EditorUtility.SetDirty(this.m_Target);
#endif
serializedObject.Update();
}
}
private static GameObject GetPrefabParent(GameObject mp)
{
#if UNITY_2_6_1 || UNITY_2_6 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4
// Unity 3.4 and older use EditorUtility
return (EditorUtility.GetPrefabParent(mp) as GameObject);
#else
// Unity 3.5 uses PrefabUtility
return PrefabUtility.GetPrefabParent(mp) as GameObject;
#endif
}
}
| |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Windows.Media;
namespace Colors
{
public class ColorItem : INotifyPropertyChanged
{
public enum Sources
{
UserDefined,
BuiltIn
};
private byte _alpha;
private byte _blue;
private byte _green;
private double _hue;
private string _name;
private byte _red;
private double _saturation;
private double _value;
public ColorItem(string name, SolidColorBrush brush)
{
Source = Sources.BuiltIn;
_name = name;
Brush = brush;
var color = brush.Color;
_alpha = color.A;
_red = color.R;
_green = color.G;
_blue = color.B;
HsvFromRgb();
}
public ColorItem(ColorItem item)
{
Source = Sources.UserDefined;
_name = "New Color";
_red = item._red;
_green = item._green;
_blue = item._blue;
_hue = item._hue;
_saturation = item._saturation;
_value = item._value;
_alpha = item._alpha;
Luminance = item.Luminance;
Brush = new SolidColorBrush(item.Brush.Color);
}
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public Sources Source { get; } = Sources.UserDefined;
public double Luminance { get; set; }
public SolidColorBrush Brush { get; private set; }
public byte Alpha
{
get { return _alpha; }
set
{
_alpha = value;
OnPropertyChanged("Alpha");
UpdateBrush();
}
}
public byte Red
{
get { return _red; }
set
{
_red = value;
OnPropertyChanged("Red");
HsvFromRgb();
}
}
public byte Green
{
get { return _green; }
set
{
_green = value;
OnPropertyChanged("Green");
HsvFromRgb();
}
}
public byte Blue
{
get { return _blue; }
set
{
_blue = value;
OnPropertyChanged("Blue");
HsvFromRgb();
}
}
public double Hue
{
get { return _hue; }
set
{
if (value > 360.0) value = 360.0;
if (value < 0.0) value = 0.0;
_hue = value;
OnPropertyChanged("Hue");
RgbFromHsv();
}
}
public double Saturation
{
get { return _saturation; }
set
{
if (value > 1.0) value = 1.0;
if (value < 0.0) value = 0.0;
_saturation = value;
OnPropertyChanged("Saturation");
RgbFromHsv();
}
}
public double Value
{
get { return _value; }
set
{
if (value > 1.0) value = 1.0;
if (value < 0.0) value = 0.0;
_value = value;
OnPropertyChanged("Value");
RgbFromHsv();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private void HsvFromRgb()
{
int imax = _red, imin = _red;
if (_green > imax) imax = _green;
else if (_green < imin) imin = _green;
if (_blue > imax) imax = _blue;
else if (_blue < imin) imin = _blue;
double max = imax/255.0, min = imin/255.0;
var value = max;
var saturation = (max > 0) ? (max - min)/max : 0.0;
var hue = _hue;
if (imax > imin)
{
var f = 1.0/((max - min)*255.0);
hue = (imax == _red)
? 0.0 + f*(_green - _blue)
: (imax == _green)
? 2.0 + f*(_blue - _red)
: 4.0 + f*(_red - _green);
hue = hue*60.0;
if (hue < 0.0)
hue += 360.0;
}
// now update the real values as necessary
if (hue != _hue)
{
_hue = hue;
OnPropertyChanged("Hue");
}
if (saturation != _saturation)
{
_saturation = saturation;
OnPropertyChanged("Saturation");
}
if (value != _value)
{
_value = value;
OnPropertyChanged("Value");
}
UpdateBrush();
}
private void RgbFromHsv()
{
double red = 0.0, green = 0.0, blue = 0.0;
if (_saturation == 0.0)
{
red = green = blue = _value;
}
else
{
var h = _hue;
while (h >= 360.0)
h -= 360.0;
h = h/60.0;
var i = (int) h;
var f = h - i;
var r = _value*(1.0 - _saturation);
var s = _value*(1.0 - _saturation*f);
var t = _value*(1.0 - _saturation*(1.0 - f));
switch (i)
{
case 0:
red = _value;
green = t;
blue = r;
break;
case 1:
red = s;
green = _value;
blue = r;
break;
case 2:
red = r;
green = _value;
blue = t;
break;
case 3:
red = r;
green = s;
blue = _value;
break;
case 4:
red = t;
green = r;
blue = _value;
break;
case 5:
red = _value;
green = r;
blue = s;
break;
}
}
byte iRed = (byte) (red*255.0), iGreen = (byte) (green*255.0), iBlue = (byte) (blue*255.0);
if (iRed != _red)
{
_red = iRed;
OnPropertyChanged("Red");
}
if (iGreen != _green)
{
_green = iGreen;
OnPropertyChanged("Green");
}
if (iBlue != _blue)
{
_blue = iBlue;
OnPropertyChanged("Blue");
}
UpdateBrush();
}
private void UpdateBrush()
{
var color = Brush.Color;
if (_alpha != color.A || _red != color.R || _green != color.G || _blue != color.B)
{
color = Color.FromArgb(_alpha, _red, _green, _blue);
Brush = new SolidColorBrush(color);
OnPropertyChanged("Brush");
}
var luminance = (0.30*_red + 0.59*_green + 0.11*_blue)/255.0;
if (Luminance != luminance)
{
Luminance = luminance;
OnPropertyChanged("Luminance");
}
}
}
}
| |
// 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.
/*=============================================================================
**
** Class: CollectionBase
**
** Purpose: Provides the abstract base class for a strongly typed collection.
**
=============================================================================*/
namespace System.Collections
{
// Useful base class for typed read/write collections where items derive from object
public abstract class CollectionBase : IList
{
private ArrayList _list;
protected CollectionBase()
{
_list = new ArrayList();
}
protected CollectionBase(int capacity)
{
_list = new ArrayList(capacity);
}
protected ArrayList InnerList
{
get
{
return _list;
}
}
protected IList List
{
get { return (IList)this; }
}
public int Capacity
{
get
{
return InnerList.Capacity;
}
set
{
InnerList.Capacity = value;
}
}
public int Count
{
get
{
return _list.Count;
}
}
public void Clear()
{
OnClear();
InnerList.Clear();
OnClearComplete();
}
public void RemoveAt(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
object temp = InnerList[index];
OnValidate(temp);
OnRemove(index, temp);
InnerList.RemoveAt(index);
try
{
OnRemoveComplete(index, temp);
}
catch
{
InnerList.Insert(index, temp);
throw;
}
}
bool IList.IsReadOnly
{
get { return InnerList.IsReadOnly; }
}
bool IList.IsFixedSize
{
get { return InnerList.IsFixedSize; }
}
bool ICollection.IsSynchronized
{
get { return InnerList.IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return InnerList.SyncRoot; }
}
void ICollection.CopyTo(Array array, int index)
{
InnerList.CopyTo(array, index);
}
object IList.this[int index]
{
get
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
return InnerList[index];
}
set
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
OnValidate(value);
object temp = InnerList[index];
OnSet(index, temp, value);
InnerList[index] = value;
try
{
OnSetComplete(index, temp, value);
}
catch
{
InnerList[index] = temp;
throw;
}
}
}
bool IList.Contains(object value)
{
return InnerList.Contains(value);
}
int IList.Add(object value)
{
OnValidate(value);
OnInsert(InnerList.Count, value);
int index = InnerList.Add(value);
try
{
OnInsertComplete(index, value);
}
catch
{
InnerList.RemoveAt(index);
throw;
}
return index;
}
void IList.Remove(object value)
{
OnValidate(value);
int index = InnerList.IndexOf(value);
if (index < 0) throw new ArgumentException(SR.Arg_RemoveArgNotFound);
OnRemove(index, value);
InnerList.RemoveAt(index);
try
{
OnRemoveComplete(index, value);
}
catch
{
InnerList.Insert(index, value);
throw;
}
}
int IList.IndexOf(object value)
{
return InnerList.IndexOf(value);
}
void IList.Insert(int index, object value)
{
if (index < 0 || index > Count)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
OnValidate(value);
OnInsert(index, value);
InnerList.Insert(index, value);
try
{
OnInsertComplete(index, value);
}
catch
{
InnerList.RemoveAt(index);
throw;
}
}
public IEnumerator GetEnumerator()
{
return InnerList.GetEnumerator();
}
protected virtual void OnSet(int index, object oldValue, object newValue)
{
}
protected virtual void OnInsert(int index, object value)
{
}
protected virtual void OnClear()
{
}
protected virtual void OnRemove(int index, object value)
{
}
protected virtual void OnValidate(object value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
}
protected virtual void OnSetComplete(int index, object oldValue, object newValue)
{
}
protected virtual void OnInsertComplete(int index, object value)
{
}
protected virtual void OnClearComplete()
{
}
protected virtual void OnRemoveComplete(int index, object value)
{
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class PdbHelpers
{
/// <remarks>
/// Test helper.
/// </remarks>
internal static void GetAllScopes(this ISymUnmanagedMethod method, ArrayBuilder<ISymUnmanagedScope> builder)
{
var unused = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
GetAllScopes(method, builder, unused, offset: -1, isScopeEndInclusive: false);
unused.Free();
}
internal static void GetAllScopes(
this ISymUnmanagedMethod method,
ArrayBuilder<ISymUnmanagedScope> allScopes,
ArrayBuilder<ISymUnmanagedScope> containingScopes,
int offset,
bool isScopeEndInclusive)
{
GetAllScopes(method.GetRootScope(), allScopes, containingScopes, offset, isScopeEndInclusive);
}
private static void GetAllScopes(
ISymUnmanagedScope root,
ArrayBuilder<ISymUnmanagedScope> allScopes,
ArrayBuilder<ISymUnmanagedScope> containingScopes,
int offset,
bool isScopeEndInclusive)
{
var stack = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
stack.Push(root);
while (stack.Any())
{
var scope = stack.Pop();
allScopes.Add(scope);
if (offset >= 0 && scope.IsInScope(offset, isScopeEndInclusive))
{
containingScopes.Add(scope);
}
foreach (var nested in scope.GetScopes())
{
stack.Push(nested);
}
}
stack.Free();
}
/// <summary>
/// Translates the value of a constant returned by <see cref="ISymUnmanagedConstant.GetValue(out object)"/> to a <see cref="ConstantValue"/>.
/// </summary>
public static ConstantValue GetSymConstantValue(ITypeSymbol type, object symValue)
{
if (type.TypeKind == TypeKind.Enum)
{
type = ((INamedTypeSymbol)type).EnumUnderlyingType;
}
short shortValue;
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
if (!(symValue is short))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((short)symValue != 0);
case SpecialType.System_Byte:
if (!(symValue is short))
{
return ConstantValue.Bad;
}
shortValue = (short)symValue;
if (unchecked((byte)shortValue) != shortValue)
{
return ConstantValue.Bad;
}
return ConstantValue.Create((byte)shortValue);
case SpecialType.System_SByte:
if (!(symValue is short))
{
return ConstantValue.Bad;
}
shortValue = (short)symValue;
if (unchecked((sbyte)shortValue) != shortValue)
{
return ConstantValue.Bad;
}
return ConstantValue.Create((sbyte)shortValue);
case SpecialType.System_Int16:
if (!(symValue is short))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((short)symValue);
case SpecialType.System_Char:
if (!(symValue is ushort))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((char)(ushort)symValue);
case SpecialType.System_UInt16:
if (!(symValue is ushort))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((ushort)symValue);
case SpecialType.System_Int32:
if (!(symValue is int))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((int)symValue);
case SpecialType.System_UInt32:
if (!(symValue is uint))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((uint)symValue);
case SpecialType.System_Int64:
if (!(symValue is long))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((long)symValue);
case SpecialType.System_UInt64:
if (!(symValue is ulong))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((ulong)symValue);
case SpecialType.System_Single:
if (!(symValue is float))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((float)symValue);
case SpecialType.System_Double:
if (!(symValue is double))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((double)symValue);
case SpecialType.System_String:
if (symValue is int && (int)symValue == 0)
{
return ConstantValue.Null;
}
if (symValue == null)
{
return ConstantValue.Create(string.Empty);
}
var str = symValue as string;
if (str == null)
{
return ConstantValue.Bad;
}
return ConstantValue.Create(str);
case SpecialType.System_Object:
if (symValue is int && (int)symValue == 0)
{
return ConstantValue.Null;
}
return ConstantValue.Bad;
case SpecialType.System_Decimal:
if (!(symValue is decimal))
{
return ConstantValue.Bad;
}
return ConstantValue.Create((decimal)symValue);
case SpecialType.System_DateTime:
if (!(symValue is double))
{
return ConstantValue.Bad;
}
return ConstantValue.Create(DateTimeUtilities.ToDateTime((double)symValue));
case SpecialType.None:
if (type.IsReferenceType)
{
if (symValue is int && (int)symValue == 0)
{
return ConstantValue.Null;
}
return ConstantValue.Bad;
}
return ConstantValue.Bad;
default:
return ConstantValue.Bad;
}
}
}
}
| |
// Copyright (c) 2015 ZZZ Projects. All rights reserved
// Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
// Website: http://www.zzzprojects.com/
// Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
// All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public static partial class Extensions
{
/// <summary>
/// Returns an enumerable collection of directory names in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// .
/// </returns>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static IEnumerable<DirectoryInfo> EnumerateDirectories(this DirectoryInfo @this)
{
return Directory.EnumerateDirectories(@this.FullName).Select(x => new DirectoryInfo(x));
}
/// <summary>
/// Returns an enumerable collection of directory names that match a search pattern in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using System.Linq;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_EnumerateDirectories
/// {
/// [TestMethod]
/// public void EnumerateDirectories()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("Directory1");
/// root.CreateSubdirectory("Directory2");
///
/// // Exemples
/// List<DirectoryInfo> result = root.EnumerateDirectories().ToList();
///
/// // Unit Test
/// Assert.AreEqual(2, result.Count);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using System.Linq;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_EnumerateDirectories
/// {
/// [TestMethod]
/// public void EnumerateDirectories()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("Directory1");
/// root.CreateSubdirectory("Directory2");
///
/// // Exemples
/// List<DirectoryInfo> result = root.EnumerateDirectories().ToList();
///
/// // Unit Test
/// Assert.AreEqual(2, result.Count);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static IEnumerable<DirectoryInfo> EnumerateDirectories(this DirectoryInfo @this, String searchPattern)
{
return Directory.EnumerateDirectories(@this.FullName, searchPattern).Select(x => new DirectoryInfo(x));
}
/// <summary>
/// Returns an enumerable collection of directory names that match a search pattern in a specified @this, and
/// optionally searches subdirectories.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <param name="searchOption">
/// One of the enumeration values that specifies whether the search operation should
/// include only the current directory or should include all subdirectories.The default value is
/// <see
/// cref="F:System.IO.SearchOption.TopDirectoryOnly" />
/// .
/// </param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern and option.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using System.Linq;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_EnumerateDirectories
/// {
/// [TestMethod]
/// public void EnumerateDirectories()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("Directory1");
/// root.CreateSubdirectory("Directory2");
///
/// // Exemples
/// List<DirectoryInfo> result = root.EnumerateDirectories().ToList();
///
/// // Unit Test
/// Assert.AreEqual(2, result.Count);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using System.Linq;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_EnumerateDirectories
/// {
/// [TestMethod]
/// public void EnumerateDirectories()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("Directory1");
/// root.CreateSubdirectory("Directory2");
///
/// // Exemples
/// List<DirectoryInfo> result = root.EnumerateDirectories().ToList();
///
/// // Unit Test
/// Assert.AreEqual(2, result.Count);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="searchOption" /> is not a valid
/// <see cref="T:System.IO.SearchOption" /> value.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static IEnumerable<DirectoryInfo> EnumerateDirectories(this DirectoryInfo @this, String searchPattern, SearchOption searchOption)
{
return Directory.EnumerateDirectories(@this.FullName, searchPattern, searchOption).Select(x => new DirectoryInfo(x));
}
/// <summary>
/// Returns an enumerable collection of directory names that match a search pattern in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPatterns">The search string to match against the names of directories in.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using System.Linq;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_EnumerateDirectories
/// {
/// [TestMethod]
/// public void EnumerateDirectories()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("Directory1");
/// root.CreateSubdirectory("Directory2");
///
/// // Exemples
/// List<DirectoryInfo> result = root.EnumerateDirectories().ToList();
///
/// // Unit Test
/// Assert.AreEqual(2, result.Count);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using System.Linq;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_EnumerateDirectories
/// {
/// [TestMethod]
/// public void EnumerateDirectories()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("Directory1");
/// root.CreateSubdirectory("Directory2");
///
/// // Exemples
/// List<DirectoryInfo> result = root.EnumerateDirectories().ToList();
///
/// // Unit Test
/// Assert.AreEqual(2, result.Count);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static IEnumerable<DirectoryInfo> EnumerateDirectories(this DirectoryInfo @this, String[] searchPatterns)
{
return searchPatterns.SelectMany(x => @this.GetDirectories(x)).Distinct();
}
/// <summary>
/// Returns an enumerable collection of directory names that match a search pattern in a specified @this, and
/// optionally searches subdirectories.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPatterns">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <param name="searchOption">
/// One of the enumeration values that specifies whether the search operation should
/// include only the current directory or should include all subdirectories.The default value is
/// <see
/// cref="F:System.IO.SearchOption.TopDirectoryOnly" />
/// .
/// </param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the directories in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern and option.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using System.Linq;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_EnumerateDirectories
/// {
/// [TestMethod]
/// public void EnumerateDirectories()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("Directory1");
/// root.CreateSubdirectory("Directory2");
///
/// // Exemples
/// List<DirectoryInfo> result = root.EnumerateDirectories().ToList();
///
/// // Unit Test
/// Assert.AreEqual(2, result.Count);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using System.IO;
/// using System.Linq;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_EnumerateDirectories
/// {
/// [TestMethod]
/// public void EnumerateDirectories()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories"));
/// Directory.CreateDirectory(root.FullName);
/// root.CreateSubdirectory("Directory1");
/// root.CreateSubdirectory("Directory2");
///
/// // Exemples
/// List<DirectoryInfo> result = root.EnumerateDirectories().ToList();
///
/// // Unit Test
/// Assert.AreEqual(2, result.Count);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="searchOption" /> is not a valid
/// <see cref="T:System.IO.SearchOption" /> value.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static IEnumerable<DirectoryInfo> EnumerateDirectories(this DirectoryInfo @this, String[] searchPatterns, SearchOption searchOption)
{
return searchPatterns.SelectMany(x => @this.GetDirectories(x, searchOption)).Distinct();
}
}
| |
namespace DeOps.Services.Transfer
{
partial class TransferView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader1 = new DeOps.Interface.TLVex.ToggleColumnHeader();
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader2 = new DeOps.Interface.TLVex.ToggleColumnHeader();
this.FastTimer = new System.Windows.Forms.Timer(this.components);
this.TransferList = new DeOps.Interface.TLVex.TreeListViewEx();
this.ShowDownloads = new System.Windows.Forms.CheckBox();
this.ShowUploads = new System.Windows.Forms.CheckBox();
this.ShowPending = new System.Windows.Forms.CheckBox();
this.ShowPartials = new System.Windows.Forms.CheckBox();
this.ExpandLink = new System.Windows.Forms.LinkLabel();
this.CollapseLink = new System.Windows.Forms.LinkLabel();
this.SuspendLayout();
//
// FastTimer
//
this.FastTimer.Enabled = true;
this.FastTimer.Interval = 250;
this.FastTimer.Tick += new System.EventHandler(this.FastTimer_Tick);
//
// TransferList
//
this.TransferList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.TransferList.BackColor = System.Drawing.SystemColors.Window;
toggleColumnHeader1.Hovered = false;
toggleColumnHeader1.Image = null;
toggleColumnHeader1.Index = 0;
toggleColumnHeader1.Pressed = false;
toggleColumnHeader1.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Spring;
toggleColumnHeader1.Selected = false;
toggleColumnHeader1.Text = "Details";
toggleColumnHeader1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader1.Visible = true;
toggleColumnHeader1.Width = 414;
toggleColumnHeader2.Hovered = false;
toggleColumnHeader2.Image = null;
toggleColumnHeader2.Index = 0;
toggleColumnHeader2.Pressed = false;
toggleColumnHeader2.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Slide;
toggleColumnHeader2.Selected = false;
toggleColumnHeader2.Text = "Bitfield";
toggleColumnHeader2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader2.Visible = true;
toggleColumnHeader2.Width = 200;
this.TransferList.Columns.AddRange(new DeOps.Interface.TLVex.ToggleColumnHeader[] {
toggleColumnHeader1,
toggleColumnHeader2});
this.TransferList.ColumnSortColor = System.Drawing.Color.Gainsboro;
this.TransferList.ColumnTrackColor = System.Drawing.Color.WhiteSmoke;
this.TransferList.GridLineColor = System.Drawing.Color.WhiteSmoke;
this.TransferList.HeaderMenu = null;
this.TransferList.ItemHeight = 20;
this.TransferList.ItemMenu = null;
this.TransferList.LabelEdit = false;
this.TransferList.Location = new System.Drawing.Point(12, 38);
this.TransferList.Name = "TransferList";
this.TransferList.RowSelectColor = System.Drawing.SystemColors.Highlight;
this.TransferList.RowTrackColor = System.Drawing.Color.WhiteSmoke;
this.TransferList.Size = new System.Drawing.Size(618, 230);
this.TransferList.SmallImageList = null;
this.TransferList.StateImageList = null;
this.TransferList.TabIndex = 1;
this.TransferList.Text = "treeListViewEx2";
this.TransferList.MouseClick += new System.Windows.Forms.MouseEventHandler(this.TransferList_MouseClick);
//
// ShowDownloads
//
this.ShowDownloads.AutoSize = true;
this.ShowDownloads.Checked = true;
this.ShowDownloads.CheckState = System.Windows.Forms.CheckState.Checked;
this.ShowDownloads.Location = new System.Drawing.Point(12, 12);
this.ShowDownloads.Name = "ShowDownloads";
this.ShowDownloads.Size = new System.Drawing.Size(79, 17);
this.ShowDownloads.TabIndex = 2;
this.ShowDownloads.Text = "Downloads";
this.ShowDownloads.UseVisualStyleBackColor = true;
this.ShowDownloads.CheckedChanged += new System.EventHandler(this.DownloadsCheck_CheckedChanged);
//
// ShowUploads
//
this.ShowUploads.AutoSize = true;
this.ShowUploads.Checked = true;
this.ShowUploads.CheckState = System.Windows.Forms.CheckState.Checked;
this.ShowUploads.Location = new System.Drawing.Point(97, 12);
this.ShowUploads.Name = "ShowUploads";
this.ShowUploads.Size = new System.Drawing.Size(65, 17);
this.ShowUploads.TabIndex = 3;
this.ShowUploads.Text = "Uploads";
this.ShowUploads.UseVisualStyleBackColor = true;
this.ShowUploads.CheckedChanged += new System.EventHandler(this.UploadsCheck_CheckedChanged);
//
// ShowPending
//
this.ShowPending.AutoSize = true;
this.ShowPending.Location = new System.Drawing.Point(168, 12);
this.ShowPending.Name = "ShowPending";
this.ShowPending.Size = new System.Drawing.Size(65, 17);
this.ShowPending.TabIndex = 4;
this.ShowPending.Text = "Pending";
this.ShowPending.UseVisualStyleBackColor = true;
this.ShowPending.CheckedChanged += new System.EventHandler(this.PendingCheck_CheckedChanged);
//
// ShowPartials
//
this.ShowPartials.AutoSize = true;
this.ShowPartials.Location = new System.Drawing.Point(239, 12);
this.ShowPartials.Name = "ShowPartials";
this.ShowPartials.Size = new System.Drawing.Size(60, 17);
this.ShowPartials.TabIndex = 5;
this.ShowPartials.Text = "Partials";
this.ShowPartials.UseVisualStyleBackColor = true;
this.ShowPartials.CheckedChanged += new System.EventHandler(this.PartialsCheck_CheckedChanged);
//
// ExpandLink
//
this.ExpandLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ExpandLink.AutoSize = true;
this.ExpandLink.Location = new System.Drawing.Point(506, 16);
this.ExpandLink.Name = "ExpandLink";
this.ExpandLink.Size = new System.Drawing.Size(57, 13);
this.ExpandLink.TabIndex = 6;
this.ExpandLink.TabStop = true;
this.ExpandLink.Text = "Expand All";
this.ExpandLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.ExpandLink_LinkClicked);
//
// CollapseLink
//
this.CollapseLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.CollapseLink.AutoSize = true;
this.CollapseLink.Location = new System.Drawing.Point(569, 16);
this.CollapseLink.Name = "CollapseLink";
this.CollapseLink.Size = new System.Drawing.Size(61, 13);
this.CollapseLink.TabIndex = 7;
this.CollapseLink.TabStop = true;
this.CollapseLink.Text = "Collapse All";
this.CollapseLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.CollapseLink_LinkClicked);
//
// TransferView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(642, 280);
this.Controls.Add(this.CollapseLink);
this.Controls.Add(this.ExpandLink);
this.Controls.Add(this.ShowPartials);
this.Controls.Add(this.ShowPending);
this.Controls.Add(this.ShowUploads);
this.Controls.Add(this.ShowDownloads);
this.Controls.Add(this.TransferList);
this.Name = "TransferView";
this.Text = "Transfers";
this.Load += new System.EventHandler(this.TransferView_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.TransferView_FormClosing);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Timer FastTimer;
private DeOps.Interface.TLVex.TreeListViewEx TransferList;
private System.Windows.Forms.CheckBox ShowDownloads;
private System.Windows.Forms.CheckBox ShowUploads;
private System.Windows.Forms.CheckBox ShowPending;
private System.Windows.Forms.CheckBox ShowPartials;
private System.Windows.Forms.LinkLabel ExpandLink;
private System.Windows.Forms.LinkLabel CollapseLink;
}
}
| |
// ============================================================
// Name: UMABonePoseBuildWindow
// Author: Eli Curtz
// Copyright: (c) 2013 Eli Curtz
// ============================================================
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace UMA.PoseTools
{
public class UMABonePoseBuildWindow : EditorWindow
{
public Transform sourceSkeleton;
public UnityEngine.Object poseFolder;
private Transform poseSkeleton;
private string skelPoseID;
private bool skelOpen;
private AnimationClip poseAnimation;
public class AnimationPose
{
[XmlAttribute("ID")]
public string ID = "";
public int frame = 0;
}
private List<AnimationPose> poses;
private bool animOpen;
private Vector2 scrollPosition;
public void SavePoseSet()
{
string folderPath = "";
if (poseFolder != null)
{
folderPath = AssetDatabase.GetAssetPath(poseFolder);
}
else if (poseAnimation != null)
{
folderPath = AssetDatabase.GetAssetPath(poseAnimation);
folderPath = folderPath.Substring(0, folderPath.LastIndexOf('/'));
}
string filePath = EditorUtility.SaveFilePanel("Save pose set", folderPath, poseAnimation.name + "_Poses.xml", "xml");
if (filePath.Length != 0)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AnimationPose>));
using (var stream = new FileStream(filePath, FileMode.Create))
{
serializer.Serialize(stream, poses);
}
}
}
public void LoadPoseSet()
{
string folderPath = "";
if (poseFolder != null)
{
folderPath = AssetDatabase.GetAssetPath(poseFolder);
}
else if (poseAnimation != null)
{
folderPath = AssetDatabase.GetAssetPath(poseAnimation);
folderPath = folderPath.Substring(0, folderPath.LastIndexOf('/'));
}
string filePath = EditorUtility.OpenFilePanel("Load pose set", folderPath, "xml");
if (filePath.Length != 0)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AnimationPose>));
using (var stream = new FileStream(filePath, FileMode.Open))
{
poses = serializer.Deserialize(stream) as List<AnimationPose>;
}
}
}
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = AssetDatabase.GetAssetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = AssetDatabase.LoadMainAssetAtPath(destpath);
}
}
}
void OnGUI()
{
sourceSkeleton = EditorGUILayout.ObjectField("Rig Prefab", sourceSkeleton, typeof(Transform), true) as Transform;
poseFolder = EditorGUILayout.ObjectField("Pose Folder", poseFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
EnforceFolder(ref poseFolder);
EditorGUILayout.Space();
// Single pose from skeleton
if (skelOpen = EditorGUILayout.Foldout(skelOpen, "Rig Source"))
{
EditorGUI.indentLevel++;
poseSkeleton = EditorGUILayout.ObjectField("Pose Rig", poseSkeleton, typeof(Transform), false) as Transform;
skelPoseID = EditorGUILayout.TextField("ID", skelPoseID);
if ((sourceSkeleton == null) || (poseSkeleton == null) || (skelPoseID == null) || (skelPoseID.Length < 1))
{
GUI.enabled = false;
}
if (GUILayout.Button("Build Pose"))
{
string folderPath;
if (poseFolder != null)
{
folderPath = AssetDatabase.GetAssetPath(poseFolder);
}
else
{
folderPath = AssetDatabase.GetAssetPath(poseAnimation);
folderPath = folderPath.Substring(0, folderPath.LastIndexOf('/'));
}
UMABonePose bonePose = CreatePoseAsset(folderPath, skelPoseID);
Transform[] sourceBones = UMABonePose.GetTransformsInPrefab(sourceSkeleton);
Transform[] poseBones = UMABonePose.GetTransformsInPrefab(poseSkeleton);
List<UMABonePose.PoseBone> poseList = new List<UMABonePose.PoseBone>();
foreach (Transform bone in poseBones)
{
Transform source = System.Array.Find<Transform>(sourceBones, entry => entry.name == bone.name);
if (source)
{
if ((bone.localPosition != source.localPosition) ||
(bone.localRotation != source.localRotation) ||
(bone.localScale != source.localScale))
{
UMABonePose.PoseBone poseB = new UMABonePose.PoseBone();
poseB.bone = bone.name;
poseB.position = bone.localPosition - source.localPosition;
poseB.rotation = bone.localRotation * Quaternion.Inverse(source.localRotation);
poseB.scale = new Vector3(bone.localScale.x / source.localScale.x,
bone.localScale.y / source.localScale.y,
bone.localScale.z / source.localScale.z);
poseList.Add(poseB);
}
}
else
{
Debug.Log("Unmatched bone: " + bone.name);
}
}
bonePose.poses = poseList.ToArray();
EditorUtility.SetDirty(bonePose);
AssetDatabase.SaveAssets();
}
GUI.enabled = true;
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
// Multiple poses from animation frames
if (animOpen = EditorGUILayout.Foldout(animOpen, "Animation Source"))
{
EditorGUI.indentLevel++;
poseAnimation = EditorGUILayout.ObjectField("Pose Animation", poseAnimation, typeof(AnimationClip), false) as AnimationClip;
if (poses == null)
{
poses = new List<AnimationPose>();
poses.Add(new AnimationPose());
}
bool validPose = false;
AnimationPose deletedPose = null;
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
foreach (AnimationPose pose in poses)
{
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("ID", GUILayout.Width(50f));
pose.ID = EditorGUILayout.TextField(pose.ID);
EditorGUILayout.LabelField("Frame", GUILayout.Width(60f));
pose.frame = EditorGUILayout.IntField(pose.frame, GUILayout.Width(50f));
if ((pose.ID != null) && (pose.ID.Length > 0))
{
validPose = true;
}
if (GUILayout.Button("-", GUILayout.Width(20f)))
{
deletedPose = pose;
validPose = false;
break;
}
GUILayout.EndHorizontal();
}
if (deletedPose != null)
{
poses.Remove(deletedPose);
}
GUILayout.EndScrollView();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("+", GUILayout.Width(30f)))
{
poses.Add(new AnimationPose());
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Load Pose Set"))
{
LoadPoseSet();
}
if (!validPose)
{
GUI.enabled = false;
}
if (GUILayout.Button("Save Pose Set"))
{
SavePoseSet();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
if ((sourceSkeleton == null) || (poseAnimation == null) || (!validPose))
{
GUI.enabled = false;
}
if (GUILayout.Button("Build Poses"))
{
string folderPath;
if (poseFolder != null)
{
folderPath = AssetDatabase.GetAssetPath(poseFolder);
}
else
{
folderPath = AssetDatabase.GetAssetPath(poseAnimation);
folderPath = folderPath.Substring(0, folderPath.LastIndexOf('/'));
}
Transform[] sourceBones = UMABonePose.GetTransformsInPrefab(sourceSkeleton);
EditorCurveBinding[] bindings = AnimationUtility.GetCurveBindings(poseAnimation);
Dictionary<string, Vector3> positions = new Dictionary<string, Vector3>();
Dictionary<string, Quaternion> rotations = new Dictionary<string, Quaternion>();
Dictionary<string, Vector3> scales = new Dictionary<string, Vector3>();
foreach (AnimationPose pose in poses)
{
if ((pose.ID == null) || (pose.ID.Length < 1))
{
Debug.LogWarning("Bad pose identifier, not building for frame: " + pose.frame);
continue;
}
float time = (float)pose.frame / poseAnimation.frameRate;
if ((time < 0f) || (time > poseAnimation.length))
{
Debug.LogWarning("Bad frame number, not building for pose: " + pose.ID);
continue;
}
positions.Clear();
rotations.Clear();
scales.Clear();
foreach (EditorCurveBinding binding in bindings)
{
if (binding.type == typeof(Transform))
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(poseAnimation, binding);
float val = curve.Evaluate(time);
Vector3 position;
Quaternion rotation;
Vector3 scale;
switch (binding.propertyName)
{
case "m_LocalPosition.x":
if (positions.TryGetValue(binding.path, out position))
{
position.x = val;
positions[binding.path] = position;
}
else
{
position = new Vector3();
position.x = val;
positions.Add(binding.path, position);
}
break;
case "m_LocalPosition.y":
if (positions.TryGetValue(binding.path, out position))
{
position.y = val;
positions[binding.path] = position;
}
else
{
position = new Vector3();
position.y = val;
positions.Add(binding.path, position);
}
break;
case "m_LocalPosition.z":
if (positions.TryGetValue(binding.path, out position))
{
position.z = val;
positions[binding.path] = position;
}
else
{
position = new Vector3();
position.z = val;
positions.Add(binding.path, position);
}
break;
case "m_LocalRotation.w":
if (rotations.TryGetValue(binding.path, out rotation))
{
rotation.w = val;
rotations[binding.path] = rotation;
}
else
{
rotation = new Quaternion();
rotation.w = val;
rotations.Add(binding.path, rotation);
}
break;
case "m_LocalRotation.x":
if (rotations.TryGetValue(binding.path, out rotation))
{
rotation.x = val;
rotations[binding.path] = rotation;
}
else
{
rotation = new Quaternion();
rotation.x = val;
rotations.Add(binding.path, rotation);
}
break;
case "m_LocalRotation.y":
if (rotations.TryGetValue(binding.path, out rotation))
{
rotation.y = val;
rotations[binding.path] = rotation;
}
else
{
rotation = new Quaternion();
rotation.y = val;
rotations.Add(binding.path, rotation);
}
break;
case "m_LocalRotation.z":
if (rotations.TryGetValue(binding.path, out rotation))
{
rotation.z = val;
rotations[binding.path] = rotation;
}
else
{
rotation = new Quaternion();
rotation.z = val;
rotations.Add(binding.path, rotation);
}
break;
case "m_LocalScale.x":
if (scales.TryGetValue(binding.path, out scale))
{
scale.x = val;
scales[binding.path] = scale;
}
else
{
scale = new Vector3();
scale.x = val;
scales.Add(binding.path, scale);
}
break;
case "m_LocalScale.y":
if (scales.TryGetValue(binding.path, out scale))
{
scale.y = val;
scales[binding.path] = scale;
}
else
{
scale = new Vector3();
scale.y = val;
scales.Add(binding.path, scale);
}
break;
case "m_LocalScale.z":
if (scales.TryGetValue(binding.path, out scale))
{
scale.z = val;
scales[binding.path] = scale;
}
else
{
scale = new Vector3();
scale.z = val;
scales.Add(binding.path, scale);
}
break;
default:
Debug.LogError("Unexpected property:" + binding.propertyName);
break;
}
}
}
UMABonePose bonePose = CreatePoseAsset(folderPath, pose.ID);
foreach (Transform bone in sourceBones)
{
string path = AnimationUtility.CalculateTransformPath(bone, sourceSkeleton.parent);
Vector3 position;
Quaternion rotation;
Vector3 scale;
if (!positions.TryGetValue(path, out position))
{
position = bone.localPosition;
}
if (!rotations.TryGetValue(path, out rotation))
{
rotation = bone.localRotation;
}
if (!scales.TryGetValue(path, out scale))
{
scale = bone.localScale;
}
if ((bone.localPosition != position) ||
(bone.localRotation != rotation) ||
(bone.localScale != scale))
{
bonePose.AddBone(bone, position, rotation, scale);
}
}
EditorUtility.SetDirty(bonePose);
}
AssetDatabase.SaveAssets();
}
GUI.enabled = true;
EditorGUI.indentLevel--;
}
}
public static UMABonePose CreatePoseAsset(string assetFolder, string assetName)
{
if (!System.IO.Directory.Exists(assetFolder))
{
System.IO.Directory.CreateDirectory(assetFolder);
}
UMABonePose asset = ScriptableObject.CreateInstance<UMABonePose>();
AssetDatabase.CreateAsset(asset, assetFolder + "/" + assetName + ".asset");
AssetDatabase.SaveAssets();
return asset;
}
[MenuItem("UMA/Pose Tools/Bone Pose Builder", priority = 1)]
public static void OpenUMABonePoseBuildWindow()
{
EditorWindow win = EditorWindow.GetWindow(typeof(UMABonePoseBuildWindow));
win.titleContent.text = "Pose Builder";
}
}
}
#endif
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using Windows.UI.Core;
using Windows.Media.SpeechRecognition;
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml.Media;
namespace SpeechAndTTS
{
public sealed partial class ContinuousDictationScenario : Page
{
// Reference to the main sample page in order to post status messages.
private MainPage rootPage;
// Speech events may come in on a thread other than the UI thread, keep track of the UI thread's
// dispatcher, so we can update the UI in a thread-safe manner.
private CoreDispatcher dispatcher;
// The speech recognizer used throughout this sample.
private SpeechRecognizer speechRecognizer;
// Keep track of whether the continuous recognizer is currently running, so it can be cleaned up appropriately.
private bool isListening;
// Keep track of existing text that we've accepted in ContinuousRecognitionSession_ResultGenerated(), so
// that we can combine it and Hypothesized results to show in-progress dictation mid-sentence.
private StringBuilder dictatedTextBuilder;
/// <summary>
/// This HResult represents the scenario where a user is prompted to allow in-app speech, but
/// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
/// not per-app.
/// </summary>
private static uint HResultPrivacyStatementDeclined = 0x80045509;
public ContinuousDictationScenario()
{
this.InitializeComponent();
isListening = false;
dictatedTextBuilder = new StringBuilder();
}
/// <summary>
/// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
/// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to
/// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
/// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow
/// audio input.
/// </summary>
/// <param name="e">Unused navigation parameters</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
// Keep track of the UI thread dispatcher, as speech events will come in on a separate thread.
dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
// Prompt the user for permission to access the microphone. This request will only happen
// once, it will not re-prompt if the user rejects the permission.
bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
if (permissionGained)
{
btnContinuousRecognize.IsEnabled = true;
}
else
{
this.dictationTextBox.Text = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
}
this.speechRecognizer = new SpeechRecognizer();
// Provide feedback to the user about the state of the recognizer. This can be used to provide visual feedback in the form
// of an audio indicator to help the user understand whether they're being heard.
speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
// Apply the dictation topic constraint to optimize for dictated freeform speech.
var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "dictation");
speechRecognizer.Constraints.Add(dictationConstraint);
SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync();
if (result.Status != SpeechRecognitionResultStatus.Success)
{
rootPage.NotifyUser("Grammar Compilation Failed: " + result.Status.ToString(), NotifyType.ErrorMessage);
btnContinuousRecognize.IsEnabled = false;
}
// Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
// some recognized phrases occur, or the garbage rule is hit. HypothesisGenerated fires during recognition, and
// allows us to provide incremental feedback based on what the user's currently saying.
speechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed;
speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
speechRecognizer.HypothesisGenerated += SpeechRecognizer_HypothesisGenerated;
}
/// <summary>
/// Upon leaving, clean up the speech recognizer. Ensure we aren't still listening, and disable the event
/// handlers to prevent leaks.
/// </summary>
/// <param name="e">Unused navigation parameters.</param>
protected async override void OnNavigatedFrom(NavigationEventArgs e)
{
if (this.speechRecognizer != null)
{
if (isListening)
{
await this.speechRecognizer.ContinuousRecognitionSession.CancelAsync();
isListening = false;
DictationButtonText.Text = " Dictate";
}
dictationTextBox.Text = "";
speechRecognizer.ContinuousRecognitionSession.Completed -= ContinuousRecognitionSession_Completed;
speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated;
speechRecognizer.HypothesisGenerated -= SpeechRecognizer_HypothesisGenerated;
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
}
/// <summary>
/// Handle events fired when error conditions occur, such as the microphone becoming unavailable, or if
/// some transient issues occur.
/// </summary>
/// <param name="sender">The continuous recognition session</param>
/// <param name="args">The state of the recognizer</param>
private async void ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionCompletedEventArgs args)
{
if (args.Status != SpeechRecognitionResultStatus.Success)
{
// If TimeoutExceeded occurs, the user has been silent for too long. We can use this to
// cancel recognition if the user in dictation mode and walks away from their device, etc.
// In a global-command type scenario, this timeout won't apply automatically.
// With dictation (no grammar in place) modes, the default timeout is 20 seconds.
if (args.Status == SpeechRecognitionResultStatus.TimeoutExceeded)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Automatic Time Out of Dictation", NotifyType.StatusMessage);
DictationButtonText.Text = " Dictate";
dictationTextBox.Text = dictatedTextBuilder.ToString();
isListening = false;
});
}
else
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Continuous Recognition Completed: " + args.Status.ToString(), NotifyType.StatusMessage);
DictationButtonText.Text = " Dictate";
isListening = false;
});
}
}
}
/// <summary>
/// While the user is speaking, update the textbox with the partial sentence of what's being said for user feedback.
/// </summary>
/// <param name="sender">The recognizer that has generated the hypothesis</param>
/// <param name="args">The hypothesis formed</param>
private async void SpeechRecognizer_HypothesisGenerated(SpeechRecognizer sender, SpeechRecognitionHypothesisGeneratedEventArgs args)
{
string hypothesis = args.Hypothesis.Text;
// Update the textbox with the currently confirmed text, and the hypothesis combined.
string textboxContent = dictatedTextBuilder.ToString() + " " + hypothesis + " ...";
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
dictationTextBox.Text = textboxContent;
btnClearText.IsEnabled = true;
});
}
/// <summary>
/// Handle events fired when a result is generated. Check for high to medium confidence, and then append the
/// string to the end of the stringbuffer, and replace the content of the textbox with the string buffer, to
/// remove any hypothesis text that may be present.
/// </summary>
/// <param name="sender">The Recognition session that generated this result</param>
/// <param name="args">Details about the recognized speech</param>
private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args)
{
// We may choose to discard content that has low confidence, as that could indicate that we're picking up
// noise via the microphone, or someone could be talking out of earshot.
if (args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
args.Result.Confidence == SpeechRecognitionConfidence.High)
{
dictatedTextBuilder.Append(args.Result.Text + " ");
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
dictationTextBox.Text = dictatedTextBuilder.ToString();
btnClearText.IsEnabled = true;
});
}
else
{
// In some scenarios, a developer may choose to ignore giving the user feedback in this case, if speech
// is not the primary input mechanism for the application.
// Here, just remove any hypothesis text by resetting it to the last known good.
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
dictationTextBox.Text = dictatedTextBuilder.ToString();
});
}
}
/// <summary>
/// Provide feedback to the user based on whether the recognizer is receiving their voice input.
/// </summary>
/// <param name="sender">The recognizer that is currently running.</param>
/// <param name="args">The current state of the recognizer.</param>
private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
rootPage.NotifyUser(args.State.ToString(), NotifyType.StatusMessage);
});
}
/// <summary>
/// Begin recognition, or finish the recognition session.
/// </summary>
/// <param name="sender">The button that generated this event</param>
/// <param name="e">Unused event details</param>
public async void ContinuousRecognize_Click(object sender, RoutedEventArgs e)
{
if (isListening == false)
{
// The recognizer can only start listening in a continuous fashion if the recognizer is currently idle.
// This prevents an exception from occurring.
if (speechRecognizer.State == SpeechRecognizerState.Idle)
{
DictationButtonText.Text = " Stop Dictation";
try
{
isListening = true;
await speechRecognizer.ContinuousRecognitionSession.StartAsync();
}
catch (Exception ex)
{
if ((uint)ex.HResult == HResultPrivacyStatementDeclined)
{
dictationTextBox.Text = "The privacy statement was declined. Go to Settings -> Privacy -> Speech, inking and typing, and ensure you have viewed the privacy policy, and Cortana is set to 'Get To Know You'";
}
else
{
var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
await messageDialog.ShowAsync();
}
isListening = false;
DictationButtonText.Text = " Dictate";
}
}
}
else
{
isListening = false;
DictationButtonText.Text = " Dictate";
if (speechRecognizer.State != SpeechRecognizerState.Idle)
{
// Cancelling recognition prevents any currently recognized speech from
// generating a ResultGenerated event. StopAsync() will allow the final session to
// complete.
await speechRecognizer.ContinuousRecognitionSession.StopAsync();
// Ensure we don't leave any hypothesis text behind
dictationTextBox.Text = dictatedTextBuilder.ToString();
}
}
}
private void btnClearText_Click(object sender, RoutedEventArgs e)
{
btnClearText.IsEnabled = false;
dictatedTextBuilder.Clear();
dictationTextBox.Text = "";
// Avoid setting focus on the text box, since it's a non-editable control.
btnContinuousRecognize.Focus(FocusState.Programmatic);
}
/// <summary>
/// Automatically scroll the textbox down to the bottom whenever new dictated text arrives
/// </summary>
/// <param name="sender">The dictation textbox</param>
/// <param name="e">Unused text changed arguments</param>
private void dictationTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var grid = (Grid)VisualTreeHelper.GetChild(dictationTextBox, 0);
for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)
{
object obj = VisualTreeHelper.GetChild(grid, i);
if (!(obj is ScrollViewer))
{
continue;
}
((ScrollViewer)obj).ChangeView(0.0f, ((ScrollViewer)obj).ExtentHeight, 1.0f);
break;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.CommandLineUtils;
namespace Zyborg.CLI.Binder
{
/// <summary>
/// Base class for core CLI model binding behavior.
/// </summary>
public abstract class CommandLineBinding
{
#region -- Constants --
/// <summary>
/// Name of optional method on the model class that would get invoked
/// after binding is completed, but before executing CLI parsing.
/// </summary>
/// <summary>
/// The method name should match exactly and the method should take a single
/// parameter of type <see cref="CommandLineApplication"/>.
/// </summary>
public const string ModelOnInitMethodName = "Model_OnInit";
/// <summary>
/// Name of optional method on the model class that would get invoked
/// after executing CLI parsing.
/// </summary>
/// <summary>
/// The method name should match exactly and the method should take a single
/// parameter of type <see cref="CommandLineApplication"/>.
/// <para>
/// The difference between this handler and the <see cref="Model_OnExec"/>
/// handler is that in a model with nested child sub-commands, only the most
/// deeply nested child command that is resolved for the parsed CLI arguments
/// will have its <c>Command_OnExec</c> invoked, whereas the <c>Model_OnExec</c>
/// handler for the nested child command and its parent (and its parent, etc.)
/// will be invoked, in the order of most deeply out to the root.
/// </para>
/// </summary>
public const string CommandOnExecMethodName = "Command_OnExec";
/// <summary>
/// Name of optional method on the model class that would get invoked
/// after executing CLI parsing.
/// </summary>
/// <summary>
/// The method name should match exactly and the method should take a single
/// parameter of type <see cref="CommandLineApplication"/>.
/// </summary>
public const string ModelOnExecMethodName = "Model_OnExec";
/// <summary>
/// Suffix used to compute the name of optional methods on the model class that would
/// get invoked after configing bound members.
/// </summary>
/// <summary>
/// The method names are computed by appending this suffix to the name of the member
/// of the model class that is bing bound for CLI parameter parsing.
/// The names should match exactly and the methods should take a single
/// parameter of type equivalent to their CLI parameter type as follows:
/// <list>
/// <item>Option - <see cref="CommandOption"/></item>
/// <item>Argument - <see cref="CommandArgument"/></item>
/// <item>Command - <see cref="CommandLineApplication"/> (child CLA)</item>
/// <item>RemainingArguments - <see cref="CommandLineApplication"/></item>
/// </list>
/// </summary>
public const string MemberOnBindMethodSuffix = "_OnBind";
#endregion -- Constants --
#region -- Fields --
internal static readonly Type[] OnInitParams = new[] { typeof(CommandLineApplication) };
internal static readonly Type[] OnExecParams = OnInitParams;
internal static readonly Type[] OnBindOptionParams = new[] { typeof(CommandOption) };
internal static readonly Type[] OnBindArgumentParams = new[] { typeof(CommandArgument) };
internal static readonly Type[] OnBindRemainingArgumentsParams = OnInitParams;
internal static readonly Type[] OnBindCommandParams = OnInitParams;
internal static readonly object[] EmptyValues = new object[0];
internal Dictionary<Type, Action<CommandLineBinding, Attribute, MemberInfo>> _attributeParsers =
new Dictionary<Type, Action<CommandLineBinding, Attribute, MemberInfo>>
{
[typeof(HelpOptionAttribute)] = AddHelpOption,
[typeof(VersionOptionAttribute)] = AddVersionOption,
[typeof(ShortVersionGetterAttribute)] = AddVersionOption,
[typeof(LongVersionGetterAttribute)] = AddVersionOption,
[typeof(CommandAttribute)] = AddCommand,
[typeof(OptionAttribute)] = AddOption,
[typeof(ArgumentAttribute)] = AddArgument,
[typeof(RemainingArgumentsAttribute)] = AddRemainingArguments,
};
internal CommandLineBinding _parentBinding;
internal List<CommandLineBinding> _childBindings = new List<CommandLineBinding>();
internal CommandLineApplication _cla;
internal HelpOptionAttribute _helpOption;
internal VersionOptionAttribute _versionOption;
internal Func<string> _versionShortGetter;
internal Func<string> _versionLongGetter;
internal MemberInfo _remainingArgumentsMember;
internal bool _executed;
internal IList<Action> _bindingActions = new List<Action>();
internal IList<Action> _postExecActions = new List<Action>();
#endregion -- Fields --
#region -- Properties --
/// <summary>
/// Maps to the Out stream for the bound CommandLineApplication.
/// </summary>
public TextWriter Out
{
get { return _cla?.Out; }
set
{
if (_cla != null) _cla.Out = value;
foreach (var b in _childBindings)
b.Out = value;
}
}
/// <summary>
/// Maps to the Error stream for the bound CommandLineApplication.
/// </summary>
public TextWriter Error
{
get { return _cla?.Error; }
set
{
if (_cla != null) _cla.Error = value;
foreach (var b in _childBindings)
b.Error = value;
}
}
/// <summary>
/// Resolves the optional full name and version of the bound CommandLineApplication.
/// </summary>
public string GetFullNameAndVersion() => _cla?.GetFullNameAndVersion();
#endregion -- Properties --
#region -- Methods --
internal int PostExec(bool isParent)
{
_executed = true;
foreach (var action in _postExecActions)
action();
int? ret;
if (!isParent)
{
ret = InvokeExec(CommandOnExecMethodName);
if (ret != null)
return ret.Value;
}
ret = InvokeExec(ModelOnExecMethodName);
if (ret != null)
return ret.Value;
return 0;
}
internal int? InvokeExec(string methodName)
{
var onExecMeth = GetModel().GetType().GetTypeInfo().GetMethod(methodName, OnExecParams);
if (onExecMeth != null)
{
var ret = onExecMeth.Invoke(GetModel(), new[] { _cla });
if (ret != null && typeof(int).GetTypeInfo().IsInstanceOfType(ret))
return (int)ret;
}
return null;
}
internal static CommandLineBinding BindModel(Type modelType,
CommandLineApplication cla = null, object parentModel = null,
Action postExec = null)
{
object model;
if (parentModel != null && modelType.GetTypeInfo().GetConstructor(
new[] { parentModel.GetType() }) != null)
model = Activator.CreateInstance(modelType, parentModel);
else
model = Activator.CreateInstance(modelType);
var bindingType = typeof(CommandLineBinding<>).MakeGenericType(modelType);
var binding = (CommandLineBinding)Activator.CreateInstance(bindingType);
binding.SetModel(model);
binding.BindTo(cla, postExec);
return binding;
}
internal void BindTo(CommandLineApplication cla, Action postExec = null)
{
var binding = this;
var model = binding.GetModel();
if (model == null)
throw new InvalidOperationException("binding has no model instance");
var modelType = model.GetType();
binding._cla = cla;
if (postExec != null)
binding._postExecActions.Add(postExec);
SetCLA(binding, modelType.GetTypeInfo().GetCustomAttribute<CommandLineAttribute>());
foreach (var a in modelType.GetTypeInfo().GetCustomAttributes())
{
var at = a.GetType();
foreach (var ap in binding._attributeParsers)
{
if (at == ap.Key)
ap.Value(binding, a, null);
}
}
foreach (var m in modelType.GetTypeInfo().GetMembers(BindingFlags.Public | BindingFlags.Instance))
{
foreach (var a in m.GetCustomAttributes())
{
var at = a.GetType();
foreach (var ap in binding._attributeParsers)
{
if (at == ap.Key)
ap.Value(binding, a, m);
}
}
}
foreach (var action in binding._bindingActions)
action();
BindRemainingArguments(this);
binding._cla.OnExecute(() =>
{
return binding.PostExec(false);
});
var onInitMeth = modelType.GetTypeInfo().GetMethod(ModelOnInitMethodName, OnInitParams);
if (onInitMeth != null)
onInitMeth.Invoke(model, new[] { binding._cla });
}
static void SetCLA(CommandLineBinding binding, Attribute att)
{
var claAtt = (CommandLineAttribute)att;
if (claAtt == null)
claAtt = new CommandLineAttribute();
if (binding._cla == null)
binding._cla = new CommandLineApplication(claAtt.ThrowOnUnexpectedArg);
binding._cla.Name = claAtt.Name ?? string.Empty;
binding._cla.FullName = claAtt.FullName ?? string.Empty;
binding._cla.Description = claAtt.Description ?? string.Empty;
binding._cla.AllowArgumentSeparator = claAtt.AllowArgumentSeparator;
}
static void AddHelpOption(CommandLineBinding binding, Attribute att, MemberInfo m)
{
var a = (HelpOptionAttribute)att;
binding._helpOption = a;
binding._bindingActions.Add(() =>
{
binding._cla.HelpOption(binding._helpOption.Template);
});
}
static void AddVersionOption(CommandLineBinding binding, Attribute att, MemberInfo m)
{
if (att is VersionOptionAttribute)
{
binding._versionOption = (VersionOptionAttribute)att;
binding._bindingActions.Add(() =>
{
if (binding._versionOption == null)
return;
if (binding._versionShortGetter == null)
binding._versionShortGetter = binding._versionLongGetter;
if (binding._versionShortGetter != null)
binding._cla.VersionOption(binding._versionOption.Template,
binding._versionShortGetter, binding._versionLongGetter);
else
binding._cla.VersionOption(binding._versionOption.Template,
binding._versionOption.ShortVersion, binding._versionOption.LongVersion);
});
}
else if (att is ShortVersionGetterAttribute || att is LongVersionGetterAttribute)
{
var mi = m as MethodInfo;
var pi = m as PropertyInfo;
Func<string> getter = null;
if (mi != null && mi.ReturnParameter.ParameterType == typeof(string)
&& mi.GetParameters().Length == 0)
getter = () => (string)mi.Invoke(binding.GetModel(), EmptyValues);
else if (pi != null && pi.PropertyType == typeof(string))
getter = () => (string)pi.GetValue(binding.GetModel());
if (getter != null && att is ShortVersionGetterAttribute)
binding._versionShortGetter = getter;
if (getter != null && att is LongVersionGetterAttribute)
binding._versionLongGetter = getter;
}
}
static void AddCommand(CommandLineBinding binding, Attribute att, MemberInfo m)
{
var a = (CommandAttribute)att;
var cmdName = a.Name;
if (string.IsNullOrEmpty(cmdName))
cmdName = m.Name.ToLower();
Type cmdType;
if (m is MethodInfo)
{
var mi = (MethodInfo)m;
var miParams = mi.GetParameters();
if (miParams.Length == 1)
cmdType = miParams[0].ParameterType;
else if (miParams.Length == 0)
cmdType = null;
else
throw new NotSupportedException("method signature is not supported");
}
else if(m is PropertyInfo)
{
var pi = (PropertyInfo)m;
cmdType = pi.PropertyType;
}
else
{
return;
}
// See if there is an optional configuration method for this sub-command
var onConfigName = $"{m.Name}{MemberOnBindMethodSuffix}";
var onConfigMeth = binding.GetModel().GetType().GetTypeInfo().GetMethod(
onConfigName, OnBindCommandParams);
// Add the option based on whether there is a config method
Action<CommandLineApplication> configAction = cla => { };
if (onConfigMeth != null)
configAction = cla => onConfigMeth.Invoke(binding.GetModel(), new[] { cla });
var subCla = binding._cla.Command(cmdName, configAction, a.ThrowOnUnexpectedArg);
// When a sub-command is specified, its OnExecute handler is invoked instead of the
// parent's so we inject a post-exec action to invoke the parent's post-exec actions
Action parentPostExec = () => binding.PostExec(true);
var subBinding = CommandLineBinding.BindModel(cmdType, subCla,
binding.GetModel(), parentPostExec);
subBinding._parentBinding = binding;
binding._childBindings.Add(subBinding);
// This is already invoked by Apply which is invoke by Build
//subModelSetCLA.Invoke(null, new object[] { subModel, cmdType.GetTypeInfo()
// .GetCustomAttribute<CommandLineApplicationAttribute>() });
// We need to make sure the command name from the Command attr is preserved after
// processing of the optional CLA attr on the subclass which may have its own name
subCla.Name = cmdName;
binding._postExecActions.Add(() => HandleCommand(subCla, subBinding, m,
() => subBinding.GetModel()));
}
static void HandleCommand(CommandLineApplication cla, CommandLineBinding binding,
MemberInfo m, Func<object> modelGetter)
{
if (!binding._executed)
return;
if (m is MethodInfo)
{
var mi = (MethodInfo)m;
var miParams = mi.GetParameters();
if (miParams.Length == 1)
mi.Invoke(binding._parentBinding.GetModel(), new object[] { modelGetter() });
else if (miParams.Length == 0)
mi.Invoke(binding._parentBinding.GetModel(), EmptyValues);
}
else if (m is PropertyInfo)
{
var pi = (PropertyInfo)m;
pi.SetValue(binding._parentBinding.GetModel(), modelGetter());
}
}
static void AddOption(CommandLineBinding binding, Attribute att, MemberInfo m)
{
var a = (OptionAttribute)att;
// Resolve the option value type
Type valueType = null;
if (m is PropertyInfo)
{
var pi = (PropertyInfo)m;
valueType = pi.PropertyType;
}
else if (m is MethodInfo)
{
var mi = (MethodInfo)m;
var miParams = mi.GetParameters();
if (miParams.Length == 1 || (miParams.Length == 2
&& typeof(CommandLineBinding).GetTypeInfo().IsAssignableFrom(miParams[1].ParameterType)))
valueType = miParams[0].ParameterType;
else if (miParams.Length > 0)
throw new NotSupportedException("method signature is not supported");
}
// Figure out the option type based on value type if it wasn't explicitly specified
CommandOptionType optionType = CommandOptionType.NoValue;
if (a.OptionType == null && valueType != null)
{
// Try to resolve the option type based on the property type
if (valueType.GetTypeInfo().IsAssignableFrom(typeof(string)))
{
optionType = CommandOptionType.SingleValue;
}
else if (valueType.GetTypeInfo().IsAssignableFrom(typeof(string[])))
{
optionType = CommandOptionType.MultipleValue;
}
else if (valueType == typeof(bool?) || valueType == typeof(bool))
{
optionType = CommandOptionType.NoValue;
}
else
throw new NotSupportedException("option value type is not supported");
}
// Resolve the option template if it wasn't explicitly specified
var template = a.Template;
if (string.IsNullOrEmpty(template))
template = $"--{m.Name.ToLower()}";
// See if there is an optional configuration method for this option
var onConfigName = $"{m.Name}{MemberOnBindMethodSuffix}";
var onConfigMeth = binding.GetModel().GetType().GetTypeInfo().GetMethod(
onConfigName, OnBindOptionParams);
// Add the option based on whether there is a config method
CommandOption co;
if (onConfigMeth != null)
{
co = binding._cla.Option(template, a.Description,
optionType,
cmdOpt => onConfigMeth.Invoke(binding.GetModel(), new[] { cmdOpt }),
a.Inherited);
}
else
{
co = binding._cla.Option(template, a.Description,
optionType,
a.Inherited);
}
// Add a post-exec handler for this option
binding._postExecActions.Add(() => HandleOption(co, binding, m));
}
static void HandleOption(CommandOption co, CommandLineBinding binding, MemberInfo m)
{
if (!co.HasValue())
return;
object coValue;
if (co.OptionType == CommandOptionType.NoValue)
{
//coValue = bool.Parse(co.Value());
coValue = true;
}
else if (co.OptionType == CommandOptionType.SingleValue)
{
coValue = co.Value();
}
else
{
coValue = co.Values.ToArray();
}
if (m is MethodInfo)
{
var mi = (MethodInfo)m;
var miParams = mi.GetParameters();
if (miParams.Length == 2)
mi.Invoke(binding.GetModel(), new object[] { coValue, binding });
else if (miParams.Length == 1)
mi.Invoke(binding.GetModel(), new object[] { coValue });
else
mi.Invoke(binding.GetModel(), EmptyValues);
}
else if (m is PropertyInfo)
{
var pi = (PropertyInfo)m;
pi.SetValue(binding.GetModel(), coValue);
}
}
static void AddArgument(CommandLineBinding binding, Attribute att, MemberInfo m)
{
var a = (ArgumentAttribute)att;
// Resolve the option value type
Type valueType = null;
if (m is PropertyInfo)
{
var pi = (PropertyInfo)m;
valueType = pi.PropertyType;
}
else if (m is MethodInfo)
{
var mi = (MethodInfo)m;
var miParams = mi.GetParameters();
if (miParams.Length == 1 || (miParams.Length == 2
&& typeof(CommandLineBinding).GetTypeInfo().IsAssignableFrom(miParams[1].ParameterType)))
valueType = miParams[0].ParameterType;
else if (miParams.Length > 0)
throw new NotSupportedException("method signature is not supported");
}
// Figure out the argument arity based on value type if it wasn't explicitly specified
var multi = a.MultipleValues;
if (multi == null && valueType != null)
{
// Try to resolve the option type based on the property type
if (valueType.GetTypeInfo().IsAssignableFrom(typeof(string)))
{
multi = false;
}
else if (valueType.GetTypeInfo().IsAssignableFrom(typeof(string[])))
{
multi = true;
}
else
throw new NotSupportedException("option value type is not supported");
}
// Resolve the arg name if it wasn't explicitly specified
var argName = a.Name;
if (string.IsNullOrEmpty(argName))
argName = m.Name.ToLower();
// See if there is an optional configuration method for this option
var onConfigName = $"{m.Name}{MemberOnBindMethodSuffix}";
var onConfigMeth = binding.GetModel().GetType().GetTypeInfo().GetMethod(
onConfigName, OnBindArgumentParams);
CommandArgument ca;
if (onConfigMeth != null)
{
ca = binding._cla.Argument(argName, a.Description,
cmdArg => onConfigMeth.Invoke(binding.GetModel(), new[] { cmdArg }),
multi.GetValueOrDefault());
}
else
{
ca = binding._cla.Argument(argName, a.Description, multi.GetValueOrDefault());
}
binding._postExecActions.Add(() => { HandleArgument(ca, binding, m); });
}
static void HandleArgument(CommandArgument ca, CommandLineBinding binding, MemberInfo m)
{
if (ca.Values?.Count == 0)
return;
object caValue;
if (ca.MultipleValues)
caValue = ca.Values.ToArray();
else
caValue = ca.Value;
if (m is MethodInfo)
{
var mi = (MethodInfo)m;
var miParams = mi.GetParameters();
if (miParams.Length == 2)
mi.Invoke(binding.GetModel(), new object[] { caValue, binding });
else
mi.Invoke(binding.GetModel(), new object[] { caValue });
}
else if (m is PropertyInfo)
{
var pi = (PropertyInfo)m;
pi.SetValue(binding.GetModel(), caValue);
}
}
static void AddRemainingArguments(CommandLineBinding binding, Attribute att, MemberInfo m)
{
var a = (RemainingArgumentsAttribute)att;
binding._remainingArgumentsMember = m;
}
static void BindRemainingArguments(CommandLineBinding binding)
{
var m = binding._remainingArgumentsMember;
if (m == null)
return;
var a = (RemainingArgumentsAttribute)m.GetCustomAttribute(typeof(RemainingArgumentsAttribute));
var onConfigName = $"{m.Name}{MemberOnBindMethodSuffix}";
var onConfigMeth = binding.GetModel().GetType().GetTypeInfo().GetMethod(
onConfigName, OnBindRemainingArgumentsParams);
if (onConfigMeth != null)
{
onConfigMeth.Invoke(binding.GetModel(), new[] { binding._cla });
}
binding._postExecActions.Add(() => { HandleRemainingArguments(a, binding, m); });
}
static void HandleRemainingArguments(RemainingArgumentsAttribute att,
CommandLineBinding binding, MemberInfo m)
{
if (att.SkipIfNone && binding._cla.RemainingArguments?.Count == 0)
// No remaining args
return;
var args = binding._cla.RemainingArguments?.ToArray();
if (args == null)
args = new string[0];
if (m is MethodInfo)
{
var mi = (MethodInfo)m;
mi.Invoke(binding.GetModel(), args);
}
else if (m is PropertyInfo)
{
var pi = (PropertyInfo)m;
pi.SetValue(binding.GetModel(), args);
}
}
internal abstract object GetModel();
internal abstract void SetModel(object model);
#endregion -- Methods --
}
/// <summary>
/// Type-safe implementation of a model-bound Command Line Interface parameter parser.
/// </summary>
public class CommandLineBinding<T> : CommandLineBinding
{
public T Model
{ get; internal set; }
internal override object GetModel() => Model;
internal override void SetModel(object model) => Model = (T)model;
public static CommandLineBinding<T> Build()
{
return (CommandLineBinding<T>)BindModel(typeof(T));
}
public int Execute(params string[] args)
{
return _cla.Execute(args);
}
}
}
| |
// 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;
using System.Linq;
using System.Text;
namespace System.IO.IsolatedStorage
{
public sealed partial class IsolatedStorageFile : IsolatedStorage, IDisposable
{
internal const string s_files = "Files";
internal const string s_assemFiles = "AssemFiles";
internal const string s_appFiles = "AppFiles";
private string _rootDirectory;
private bool _disposed;
private bool _closed;
private readonly object _internalLock = new object();
// Data file notes
// ===============
// "identity.dat" is the serialized identity object, such as StrongName or Url. It is used to
// enumerate stores, which we currently do not support.
//
// private const string IDFile = "identity.dat";
// "info.dat" is used to track disk space usage (against quota). The accounting file for Silverlight
// stores is "appInfo.dat". CoreFX is always in full trust so we can safely ignore these.
//
// private const string InfoFile = "info.dat";
// private const string AppInfoFile = "appInfo.dat";
internal IsolatedStorageFile() { }
// Using this property to match NetFX for testing
private string RootDirectory
{
get { return _rootDirectory; }
}
internal bool Disposed
{
get
{
return _disposed;
}
}
internal bool IsDeleted
{
get
{
try
{
return !Directory.Exists(RootDirectory);
}
catch (IOException)
{
// It's better to assume the IsoStore is gone if we can't prove it is there.
return true;
}
catch (UnauthorizedAccessException)
{
// It's better to assume the IsoStore is gone if we can't prove it is there.
return true;
}
}
}
public void Close()
{
if (Helper.IsRoaming(Scope))
return;
lock (_internalLock)
{
if (!_closed)
{
_closed = true;
GC.SuppressFinalize(this);
}
}
}
public void DeleteFile(string file)
{
if (file == null)
throw new ArgumentNullException(nameof(file));
EnsureStoreIsValid();
try
{
string fullPath = GetFullPath(file);
File.Delete(fullPath);
}
catch (Exception e)
{
throw GetIsolatedStorageException(SR.IsolatedStorage_DeleteFile, e);
}
}
public bool FileExists(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
EnsureStoreIsValid();
return File.Exists(GetFullPath(path));
}
public bool DirectoryExists(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
EnsureStoreIsValid();
return Directory.Exists(GetFullPath(path));
}
public void CreateDirectory(string dir)
{
if (dir == null)
throw new ArgumentNullException(nameof(dir));
EnsureStoreIsValid();
string isPath = GetFullPath(dir); // Prepend IS root
// We can save a bunch of work if the directory we want to create already exists. This also
// saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the
// final path is accessible and the directory already exists. For example, consider trying
// to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo
// and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar
// and fail to due so, causing an exception to be thrown. This is not what we want.
if (Directory.Exists(isPath))
{
return;
}
try
{
Directory.CreateDirectory(isPath);
}
catch (Exception e)
{
// We have a slightly different behavior here in comparison to the traditional IsolatedStorage
// which tries to remove any partial directories created in case of failure.
// However providing that behavior required we could not reply on FileSystem APIs in general
// and had to keep tabs on what all directories needed to be created and at what point we failed
// and back-track from there. It is unclear how many apps would depend on this behavior and if required
// we could add the behavior as a bug-fix later.
throw GetIsolatedStorageException(SR.IsolatedStorage_CreateDirectory, e);
}
}
public void DeleteDirectory(string dir)
{
if (dir == null)
throw new ArgumentNullException(nameof(dir));
EnsureStoreIsValid();
try
{
string fullPath = GetFullPath(dir);
Directory.Delete(fullPath, false);
}
catch (Exception e)
{
throw GetIsolatedStorageException(SR.IsolatedStorage_DeleteDirectory, e);
}
}
public string[] GetFileNames()
{
return GetFileNames("*");
}
// foo\abc*.txt will give all abc*.txt files in foo directory
public string[] GetFileNames(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
EnsureStoreIsValid();
try
{
// FileSystem APIs return the complete path of the matching files however Iso store only provided the FileName
// and hid the IsoStore root. Hence we find all the matching files from the fileSystem and simply return the fileNames.
return Directory.EnumerateFiles(RootDirectory, searchPattern).Select(f => Path.GetFileName(f)).ToArray();
}
catch (UnauthorizedAccessException e)
{
throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e);
}
}
public string[] GetDirectoryNames()
{
return GetDirectoryNames("*");
}
// foo\data* will give all directory names in foo directory that starts with data
public string[] GetDirectoryNames(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
EnsureStoreIsValid();
try
{
// FileSystem APIs return the complete path of the matching directories however Iso store only provided the directory name
// and hid the IsoStore root. Hence we find all the matching directories from the fileSystem and simply return their names.
return Directory.EnumerateDirectories(RootDirectory, searchPattern).Select(m => m.Substring(Path.GetDirectoryName(m).Length + 1)).ToArray();
}
catch (UnauthorizedAccessException e)
{
throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e);
}
}
// When constructing an IsolatedStorageFileStream we pass the partial path- it will call back for the full path
public IsolatedStorageFileStream OpenFile(string path, FileMode mode)
{
EnsureStoreIsValid();
return new IsolatedStorageFileStream(path, mode, this);
}
public IsolatedStorageFileStream OpenFile(string path, FileMode mode, FileAccess access)
{
EnsureStoreIsValid();
return new IsolatedStorageFileStream(path, mode, access, this);
}
public IsolatedStorageFileStream OpenFile(string path, FileMode mode, FileAccess access, FileShare share)
{
EnsureStoreIsValid();
return new IsolatedStorageFileStream(path, mode, access, share, this);
}
public IsolatedStorageFileStream CreateFile(string path)
{
EnsureStoreIsValid();
return new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, this);
}
public DateTimeOffset GetCreationTime(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
}
EnsureStoreIsValid();
try
{
return new DateTimeOffset(File.GetCreationTime(GetFullPath(path)));
}
catch (UnauthorizedAccessException)
{
return new DateTimeOffset(1601, 1, 1, 0, 0, 0, TimeSpan.Zero).ToLocalTime();
}
}
public DateTimeOffset GetLastAccessTime(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
}
EnsureStoreIsValid();
try
{
return new DateTimeOffset(File.GetLastAccessTime(GetFullPath(path)));
}
catch (UnauthorizedAccessException)
{
return new DateTimeOffset(1601, 1, 1, 0, 0, 0, TimeSpan.Zero).ToLocalTime();
}
}
public DateTimeOffset GetLastWriteTime(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
}
EnsureStoreIsValid();
try
{
return new DateTimeOffset(File.GetLastWriteTime(GetFullPath(path)));
}
catch (UnauthorizedAccessException)
{
return new DateTimeOffset(1601, 1, 1, 0, 0, 0, TimeSpan.Zero).ToLocalTime();
}
}
public void CopyFile(string sourceFileName, string destinationFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName));
if (destinationFileName == null)
throw new ArgumentNullException(nameof(destinationFileName));
if (sourceFileName == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(sourceFileName));
}
if (destinationFileName == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(destinationFileName));
}
CopyFile(sourceFileName, destinationFileName, false);
}
public void CopyFile(string sourceFileName, string destinationFileName, bool overwrite)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName));
if (destinationFileName == null)
throw new ArgumentNullException(nameof(destinationFileName));
if (sourceFileName == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(sourceFileName));
}
if (destinationFileName == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(destinationFileName));
}
EnsureStoreIsValid();
string sourceFileNameFullPath = GetFullPath(sourceFileName);
string destinationFileNameFullPath = GetFullPath(destinationFileName);
try
{
File.Copy(sourceFileNameFullPath, destinationFileNameFullPath, overwrite);
}
catch (FileNotFoundException)
{
throw new FileNotFoundException(SR.Format(SR.PathNotFound_Path, sourceFileName));
}
catch (PathTooLongException)
{
throw;
}
catch (Exception e)
{
throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e);
}
}
public void MoveFile(string sourceFileName, string destinationFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName));
if (destinationFileName == null)
throw new ArgumentNullException(nameof(destinationFileName));
if (sourceFileName == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(sourceFileName));
}
if (destinationFileName == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(destinationFileName));
}
EnsureStoreIsValid();
string sourceFileNameFullPath = GetFullPath(sourceFileName);
string destinationFileNameFullPath = GetFullPath(destinationFileName);
try
{
File.Move(sourceFileNameFullPath, destinationFileNameFullPath);
}
catch (FileNotFoundException)
{
throw new FileNotFoundException(SR.Format(SR.PathNotFound_Path, sourceFileName));
}
catch (PathTooLongException)
{
throw;
}
catch (Exception e)
{
throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e);
}
}
public void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName)
{
if (sourceDirectoryName == null)
throw new ArgumentNullException(nameof(sourceDirectoryName));
if (destinationDirectoryName == null)
throw new ArgumentNullException(nameof(destinationDirectoryName));
if (sourceDirectoryName == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(sourceDirectoryName));
}
if (destinationDirectoryName == string.Empty)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(destinationDirectoryName));
}
EnsureStoreIsValid();
string sourceDirectoryNameFullPath = GetFullPath(sourceDirectoryName);
string destinationDirectoryNameFullPath = GetFullPath(destinationDirectoryName);
try
{
Directory.Move(sourceDirectoryNameFullPath, destinationDirectoryNameFullPath);
}
catch (DirectoryNotFoundException)
{
throw new DirectoryNotFoundException(SR.Format(SR.PathNotFound_Path, sourceDirectoryName));
}
catch (PathTooLongException)
{
throw;
}
catch (Exception e)
{
throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e);
}
}
public static IEnumerator GetEnumerator(IsolatedStorageScope scope)
{
// Not currently supported: https://github.com/dotnet/corefx/issues/10936
// Implementing this would require serializing/deserializing identity objects which is particularly
// complicated given the normal identity objects used by NetFX aren't available on CoreFX.
//
// Starting expectation is that a given store's location would be identical between implementations
// (say, for a particular StrongName). You could iterate any store opened at least once by NetFX on
// NetFX as it would create the needed identity file. You wouldn't be able to iterate if it was only
// ever opened by CoreFX, as the needed file isn't there yet.
return new IsolatedStorageFileEnumerator();
}
internal sealed class IsolatedStorageFileEnumerator : IEnumerator
{
public object Current
{
get
{
// Getting current throws on NetFX if there is no current item.
throw new InvalidOperationException();
}
}
public bool MoveNext()
{
// Nothing to return
return false;
}
public void Reset()
{
// Do nothing
}
}
public override long AvailableFreeSpace
{
get
{
return Quota - UsedSize;
}
}
[CLSCompliant(false)]
[Obsolete("IsolatedStorage.MaximumSize has been deprecated because it is not CLS Compliant. To get the maximum size use IsolatedStorage.Quota")]
public override ulong MaximumSize
{
get
{
return long.MaxValue;
}
}
public override long Quota
{
get
{
return long.MaxValue;
}
}
public override long UsedSize
{
get
{
return 0; // We do not have a mechanism for tracking usage.
}
}
[CLSCompliant(false)]
[Obsolete("IsolatedStorage.CurrentSize has been deprecated because it is not CLS Compliant. To get the current size use IsolatedStorage.UsedSize")]
public override ulong CurrentSize
{
get
{
return 0; // We do not have a mechanism for tracking usage.
}
}
public static IsolatedStorageFile GetUserStoreForApplication()
{
return GetStore(IsolatedStorageScope.Application | IsolatedStorageScope.User);
}
public static IsolatedStorageFile GetUserStoreForAssembly()
{
return GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User);
}
public static IsolatedStorageFile GetUserStoreForDomain()
{
return GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain | IsolatedStorageScope.User);
}
public static IsolatedStorageFile GetUserStoreForSite()
{
// NetFX and Mono both throw for this method
throw new NotSupportedException(SR.IsolatedStorage_NotValidOnDesktop);
}
public static IsolatedStorageFile GetMachineStoreForApplication()
{
return GetStore(IsolatedStorageScope.Application | IsolatedStorageScope.Machine);
}
public static IsolatedStorageFile GetMachineStoreForAssembly()
{
return GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.Machine);
}
public static IsolatedStorageFile GetMachineStoreForDomain()
{
return GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain | IsolatedStorageScope.Machine);
}
private static IsolatedStorageFile GetStore(IsolatedStorageScope scope)
{
IsolatedStorageFile isf = new IsolatedStorageFile();
isf.Initialize(scope);
return isf;
}
// Notes on the GetStore methods:
//
// The System.Security types that NetFX would be getting aren't available. We could potentially map the two
// we implicitly support (StrongName and Url) to AssemblyName and Uri. We could also consider accepting those two
// types.
//
// For the methods that take actual evidence objects we would have to do the same mapping and implement the
// hashing required if it wasn't the two types we know. The hash is a two part hash of {typehash}.{instancehash}.
// The hashing logic is basically this:
//
// - if not a "known type" the type hash is from a BinaryFormatter serialized object.GetType()
// - if the identity object is INomalizeForIsolatedStorage, use .Normalize() result for hashing identity, otherwise the object itself
// - again, use BinaryFormatter to serialize the selected identity object for getting the instance hash
//
// Hashing for the streams created is done in Helper.GetStrongHashSuitableForObjectName()
//
// "Known" types are Publisher, StrongName, Url, Site, and Zone.
public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Type applicationEvidenceType)
{
// Scope MUST be Application
return (applicationEvidenceType == null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/corefx/issues/10935
}
public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, object applicationIdentity)
{
// Scope MUST be Application
return (applicationIdentity == null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/corefx/issues/10935
}
public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
{
// Scope MUST NOT be Application (assembly is assumed otherwise)
return (domainEvidenceType == null && assemblyEvidenceType == null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/corefx/issues/10935
}
public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, object domainIdentity, object assemblyIdentity)
{
// Scope MUST NOT be Application (assembly is assumed otherwise)
return (domainIdentity == null && assemblyIdentity == null) ? GetStore(scope) : throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // https://github.com/dotnet/corefx/issues/10935
}
// https://github.com/dotnet/corefx/issues/10935
// Evidence isn't currently available
// public static IsolatedStorageFile GetStore(IsolatedStorageScope scope, Evidence domainEvidence, Type domainEvidenceType, Evidence assemblyEvidence, Type assemblyEvidenceType) { return default(IsolatedStorageFile); }
private void Initialize(IsolatedStorageScope scope)
{
// InitStore will set up the IdentityHash
InitStore(scope, null, null);
StringBuilder sb = new StringBuilder(Helper.GetRootDirectory(scope));
sb.Append(SeparatorExternal);
sb.Append(IdentityHash);
sb.Append(SeparatorExternal);
if (Helper.IsApplication(scope))
{
sb.Append(s_appFiles);
}
else if (Helper.IsDomain(scope))
{
sb.Append(s_files);
}
else
{
sb.Append(s_assemFiles);
}
sb.Append(SeparatorExternal);
_rootDirectory = sb.ToString();
Helper.CreateDirectory(_rootDirectory, scope);
}
internal string GetFullPath(string partialPath)
{
Debug.Assert(partialPath != null, "partialPath should be non null");
int i;
// Chop off directory separator characters at the start of the string because they counfuse Path.Combine.
for (i = 0; i < partialPath.Length; i++)
{
if (partialPath[i] != Path.DirectorySeparatorChar && partialPath[i] != Path.AltDirectorySeparatorChar)
{
break;
}
}
partialPath = partialPath.Substring(i);
return Path.Combine(RootDirectory, partialPath);
}
internal void EnsureStoreIsValid()
{
// This validation is something we only did in Silverlight previously.
if (Disposed)
throw new ObjectDisposedException(null, SR.IsolatedStorage_StoreNotOpen);
if (_closed || IsDeleted)
throw new InvalidOperationException(SR.IsolatedStorage_StoreNotOpen);
}
public void Dispose()
{
Close();
_disposed = true;
}
internal static Exception GetIsolatedStorageException(string exceptionMsg, Exception rootCause)
{
IsolatedStorageException e = new IsolatedStorageException(exceptionMsg, rootCause);
e._underlyingException = rootCause;
return e;
}
public override bool IncreaseQuotaTo(long newQuotaSize)
{
// We don't support quotas, just call it ok
return true;
}
public override void Remove()
{
// Deletes the current IsoFile's directory and the identity folder if possible.
// (e.g. @"C:\Users\jerem\AppData\Local\IsolatedStorage\10v31ho4.bo2\eeolfu22.f2w\Url.qgeirsoc3cznuklvq5xlalurh1m0unxl\AssemFiles\")
// This matches NetFX logic. We want to try and clean as well as possible without being more aggressive with the identity folders.
// (e.g. Url.qgeirsoc3cznuklvq5xlalurh1m0unxl, etc.) We don't want to inadvertently yank folders for a different scope under the same
// identity (at least no more so than NetFX).
try
{
Directory.Delete(RootDirectory, recursive: true);
}
catch
{
throw new IsolatedStorageException(SR.IsolatedStorage_DeleteDirectories);
}
Close();
string parentDirectory = Path.GetDirectoryName(RootDirectory.TrimEnd(Path.DirectorySeparatorChar));
if (ContainsUnknownFiles(parentDirectory))
return;
try
{
Directory.Delete(parentDirectory, recursive: true);
}
catch
{
return;
}
// Domain paths are doubly nested
// @"C:\Users\jerem\AppData\Local\IsolatedStorage\10v31ho4.bo2\eeolfu22.f2w\Url.qgeirsoc3cznuklvq5xlalurh1m0unxl\Url.qgeirsoc3cznuklvq5xlalurh1m0unxl\Files\"
if (Helper.IsDomain(Scope))
{
parentDirectory = Path.GetDirectoryName(parentDirectory);
if (ContainsUnknownFiles(parentDirectory))
return;
try
{
Directory.Delete(parentDirectory, recursive: true);
}
catch
{
return;
}
}
}
public static void Remove(IsolatedStorageScope scope)
{
// The static Remove() deletes ALL IsoStores for the given scope
VerifyGlobalScope(scope);
string root = Helper.GetRootDirectory(scope);
try
{
Directory.Delete(root, recursive: true);
Directory.CreateDirectory(root);
}
catch
{
throw new IsolatedStorageException(SR.IsolatedStorage_DeleteDirectories);
}
}
public static bool IsEnabled
{
// Isolated storage is always available
get { return true; }
}
private static void VerifyGlobalScope(IsolatedStorageScope scope)
{
if ((scope != IsolatedStorageScope.User) &&
(scope != (IsolatedStorageScope.User |
IsolatedStorageScope.Roaming)) &&
(scope != IsolatedStorageScope.Machine))
{
throw new ArgumentException(SR.IsolatedStorage_Scope_U_R_M);
}
}
private bool ContainsUnknownFiles(string directory)
{
string[] dirs, files;
try
{
files = Directory.GetFiles(directory);
dirs = Directory.GetDirectories(directory);
}
catch
{
throw new IsolatedStorageException(SR.IsolatedStorage_DeleteDirectories);
}
if (dirs.Length > 1 || (dirs.Length > 0 && !IsMatchingScopeDirectory(dirs[0])))
{
// Unknown folder present
return true;
}
if (files.Length == 0)
return false;
// Check if we have unknown files
// Note that we don't generate these files in CoreFX, but we want to match
// NetFX removal semantics as NetFX will generate these.
if (Helper.IsRoaming(Scope))
return ((files.Length > 1) || !IsIdFile(files[0]));
return (files.Length > 2 ||
(
(!IsIdFile(files[0]) && !IsInfoFile(files[0]))) ||
(files.Length == 2 && !IsIdFile(files[1]) && !IsInfoFile(files[1]))
);
}
private bool IsMatchingScopeDirectory(string directory)
{
string directoryName = Path.GetFileName(directory);
return
(Helper.IsApplication(Scope) && string.Equals(directoryName, s_appFiles, StringComparison.Ordinal))
|| (Helper.IsAssembly(Scope) && string.Equals(directoryName, s_assemFiles, StringComparison.Ordinal))
|| (Helper.IsDomain(Scope) && string.Equals(directoryName, s_files, StringComparison.Ordinal));
}
private static bool IsIdFile(string file) => string.Equals(Path.GetFileName(file), "identity.dat");
private static bool IsInfoFile(string file) => string.Equals(Path.GetFileName(file), "info.dat");
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using Generator.Enums;
using Generator.IO;
namespace Generator.Misc.Python {
[Generator(TargetLanguage.Python, double.MaxValue)]
sealed class PyiGen {
readonly GenTypes genTypes;
readonly ExportedPythonTypes exportedPythonTypes;
public PyiGen(GeneratorContext generatorContext) {
genTypes = generatorContext.Types;
exportedPythonTypes = genTypes.GetObject<ExportedPythonTypes>(TypeIds.ExportedPythonTypes);
}
public void Generate() {
var classes = new List<PyClass>();
foreach (var filename in Directory.GetFiles(genTypes.Dirs.GetPythonRustDir(), "*.rs")) {
var parser = new PyClassParser(filename);
classes.AddRange(parser.ParseFile());
}
if (classes.Count == 0)
throw new InvalidOperationException();
WritePyi(classes);
}
// Gets all required enum fields that must be part of the pyi file because they're
// default values in some methods.
Dictionary<EnumType, HashSet<EnumValue>> GetRequiredEnumFields(List<PyClass> classes) {
var reqEnumFields = new Dictionary<EnumType, HashSet<EnumValue>>();
var argToEnumType = new Dictionary<string, EnumType>(StringComparer.Ordinal);
foreach (var pyClass in classes) {
foreach (var method in pyClass.Methods) {
DocComments docComments;
if (method.Attributes.Any(AttributeKind.New))
docComments = pyClass.DocComments;
else
docComments = method.DocComments;
var docs = docComments.Sections.OfType<ArgsDocCommentSection>().FirstOrDefault();
if (docs is null)
continue;
int hasThis = method.Arguments.Count != 0 && method.Arguments[0].IsSelf ? 1 : 0;
if (docs.Args.Length != (method.Arguments.Count - hasThis))
throw new InvalidOperationException();
argToEnumType.Clear();
for (int i = 0; i < docs.Args.Length; i++) {
var docArg = docs.Args[i];
if (docArg.Name != method.Arguments[hasThis + i].Name)
throw new InvalidOperationException();
if (!ParseUtils.TryConvertSphinxTypeToTypeName(docArg.SphinxType, out var typeName))
continue;
if (!exportedPythonTypes.TryFindByName(typeName, out var enumType))
continue;
argToEnumType.Add(docArg.Name, enumType);
}
var argsAttr = method.Attributes.Attributes.FirstOrDefault(a => a.Kind == AttributeKind.Args);
if (argsAttr is null)
continue;
foreach (var (name, value) in ParseUtils.GetArgsNameValues(argsAttr.Text)) {
if (!argToEnumType.TryGetValue(name, out var enumType))
continue;
if (!uint.TryParse(value, out var rawValue))
throw new InvalidOperationException($"Couldn't parse {value} as an integer");
var enumValue = enumType.Values.FirstOrDefault(a => a.Value == rawValue);
if (enumValue is null)
throw new InvalidOperationException($"Couldn't find an enum value in {enumType.RawName} with a value equal to {value}");
if (!reqEnumFields.TryGetValue(enumType, out var hash))
reqEnumFields.Add(enumType, hash = new HashSet<EnumValue>());
hash.Add(enumValue);
}
}
}
return reqEnumFields;
}
void WritePyi(List<PyClass> classes) {
var reqEnumFields = GetRequiredEnumFields(classes);
var filename = genTypes.Dirs.GetPythonPyFilename("_iced_x86_py.pyi");
using (var writer = new FileWriter(TargetLanguage.Python, FileUtils.OpenWrite(filename))) {
writer.WriteFileHeader();
writer.WriteLine("from collections.abc import Iterator");
writer.WriteLine("from enum import IntEnum, IntFlag");
writer.WriteLine("from typing import Any, List, Optional, Union");
writer.WriteLine();
var idConverter = PythonIdentifierConverter.Create();
var allEnumTypes = exportedPythonTypes.Enums.Select(a => (enumType: a, pythonName: a.Name(idConverter)));
var toEnumType = allEnumTypes.ToDictionary(a => a.pythonName, a => a.enumType, StringComparer.Ordinal);
foreach (var (enumType, pythonName) in allEnumTypes.OrderBy(a => a.pythonName, StringComparer.Ordinal)) {
var baseClass = enumType.IsFlags ? "IntFlag" : "IntEnum";
if (reqEnumFields.TryGetValue(enumType, out var fields)) {
writer.WriteLine($"class {pythonName}({baseClass}):");
using (writer.Indent()) {
bool uppercaseRawName = PythonUtils.UppercaseEnum(enumType.TypeId.Id1);
foreach (var value in enumType.Values) {
if (fields.Contains(value)) {
fields.Remove(value);
var (valueName, numStr) = PythonUtils.GetEnumNameValue(idConverter, value, uppercaseRawName);
writer.WriteLine($"{valueName} = {numStr}");
}
if (fields.Count == 0)
break;
}
if (fields.Count != 0)
throw new InvalidOperationException();
writer.WriteLine("...");
}
}
else
writer.WriteLine($"class {pythonName}({baseClass}): ...");
}
var docGen = new PyiDocGen();
foreach (var pyClass in classes.OrderBy(a => a.Name, StringComparer.Ordinal)) {
writer.WriteLine();
writer.WriteLine($"class {idConverter.Type(pyClass.Name)}:");
using (writer.Indent()) {
WriteDocs(writer, docGen.Convert(pyClass.DocComments));
int defCount = 0;
foreach (var member in GetMembers(pyClass)) {
switch (member) {
case PyMethod method:
var docComments = method.Attributes.Any(AttributeKind.New) ?
pyClass.DocComments : method.DocComments;
Write(writer, docGen, idConverter, pyClass, method, docComments, toEnumType);
defCount++;
break;
case PyProperty property:
Write(writer, docGen, idConverter, pyClass, property.Getter, property.Getter.DocComments, toEnumType);
defCount++;
if (property.Setter is not null) {
Write(writer, docGen, idConverter, pyClass, property.Setter, property.Getter.DocComments, toEnumType);
defCount++;
}
break;
default:
throw new InvalidOperationException();
}
}
if (defCount == 0)
throw new InvalidOperationException($"class {pyClass.Name}: No class members");
}
}
}
}
static void WriteDocs(FileWriter writer, List<string> docs) {
if (docs.Count == 0)
throw new InvalidOperationException();
const string docQuotes = "\"\"\"";
if (docs.Count == 1)
writer.WriteLine($"{docQuotes}{docs[0]}{docQuotes}");
else {
writer.WriteLine(docQuotes);
foreach (var doc in docs) {
if (doc == string.Empty)
writer.WriteLineNoIndent(string.Empty);
else
writer.WriteLine(doc);
}
writer.WriteLine(docQuotes);
}
}
static void Write(FileWriter writer, PyiDocGen docGen, IdentifierConverter idConverter, PyClass pyClass, PyMethod method, DocComments docComments, Dictionary<string, EnumType> toEnumType) {
if (method.Attributes.Any(AttributeKind.ClassMethod))
writer.WriteLine("@classmethod");
if (method.Attributes.Any(AttributeKind.StaticMethod))
writer.WriteLine("@staticmethod");
bool isGetter = method.Attributes.Any(AttributeKind.Getter);
bool isSetter = method.Attributes.Any(AttributeKind.Setter);
if (isGetter)
writer.WriteLine("@property");
if (isSetter)
writer.WriteLine($"@{method.Name}.setter");
string sphinxReturnType = string.Empty;
if (isGetter || isSetter) {
if (docComments.Sections.FirstOrDefault() is not TextDocCommentSection textDocs || textDocs.Lines.Length == 0)
throw new InvalidOperationException();
if (!ParseUtils.TryParseTypeAndDocs(textDocs.Lines[0], out _, out var typeInfo))
throw new InvalidOperationException();
sphinxReturnType = typeInfo.SphinxType;
}
else {
var returns = docComments.Sections.OfType<ReturnsDocCommentSection>().FirstOrDefault();
if (returns is not null)
sphinxReturnType = returns.Returns.SphinxType;
}
bool isCtor = method.Attributes.Any(AttributeKind.New);
writer.Write("def ");
writer.Write(isCtor ? "__init__" : method.Name);
writer.Write("(");
int argCount = 0;
if (isCtor) {
writer.Write("self");
argCount++;
}
var argsDocs = docComments.Sections.OfType<ArgsDocCommentSection>().FirstOrDefault();
int hasThis = method.Arguments.Count != 0 && method.Arguments[0].IsSelf ? 1 : 0;
Dictionary<string, string> toDefaultValue;
var argsAttr = method.Attributes.Attributes.FirstOrDefault(a => a.Kind == AttributeKind.Args);
if (argsAttr is null)
toDefaultValue = new Dictionary<string, string>(StringComparer.Ordinal);
else
toDefaultValue = ParseUtils.GetArgsNameValues(argsAttr.Text).ToDictionary(a => a.name, a => a.value, StringComparer.Ordinal);
for (int i = 0; i < method.Arguments.Count; i++) {
if (argsDocs is not null && argsDocs.Args.Length != method.Arguments.Count - hasThis)
throw new InvalidOperationException();
var methodArg = method.Arguments[i];
if (argCount > 0)
writer.Write(", ");
argCount++;
if (methodArg.IsSelf)
writer.Write("self");
else {
writer.Write(methodArg.Name);
string docsSphinxType;
if (argsDocs is not null) {
var docsArg = argsDocs.Args[i - hasThis];
if (docsArg.Name != methodArg.Name)
throw new InvalidOperationException();
docsSphinxType = docsArg.SphinxType;
}
else
docsSphinxType = string.Empty;
if (i == 1 && isSetter)
docsSphinxType = sphinxReturnType;
writer.Write(": ");
var type = GetType(pyClass, method.Name, methodArg.RustType, docsSphinxType);
writer.Write(type);
if (toDefaultValue.TryGetValue(methodArg.Name, out var defaultValueStr)) {
writer.Write(" = ");
if (!TryGetValueStr(idConverter, type, defaultValueStr, toEnumType, out var valueStr))
throw new InvalidOperationException($"method {pyClass.Name}.{method.Name}(): Couldn't convert default value `{defaultValueStr}` to a Python value");
writer.Write(valueStr);
}
}
}
writer.Write(") -> ");
if (method.HasReturnType && !isCtor)
writer.Write(GetReturnType(pyClass, method.Name, method.RustReturnType, sphinxReturnType));
else
writer.Write("None");
if (method.DocComments.Sections.Count == 0)
writer.WriteLine(": ...");
else {
writer.WriteLine(":");
using (writer.Indent()) {
WriteDocs(writer, docGen.Convert(method.DocComments));
writer.WriteLine("...");
}
}
}
static bool TryGetValueStr(IdentifierConverter idConverter, string typeStr, string defaultValueStr, Dictionary<string, EnumType> toEnumType, [NotNullWhen(true)] out string? valueStr) {
valueStr = null;
if (toEnumType.TryGetValue(typeStr, out var enumType)) {
if (!uint.TryParse(defaultValueStr, out var rawValue))
return false;
var enumValue = enumType.Values.FirstOrDefault(a => a.Value == rawValue);
if (enumValue is null)
return false;
valueStr = enumValue.DeclaringType.Name(idConverter) + "." + enumValue.Name(idConverter);
return true;
}
if (typeStr == "int") {
if (ulong.TryParse(defaultValueStr, out _) || long.TryParse(defaultValueStr, out _)) {
valueStr = defaultValueStr;
return true;
}
}
switch (defaultValueStr) {
case "true":
valueStr = "True";
return true;
case "false":
valueStr = "False";
return true;
}
valueStr = null;
return false;
}
static string GetReturnType(PyClass pyClass, string methodName, string rustType, string sphinxType) {
var typeStr = GetType(pyClass, methodName, rustType, sphinxType);
if (methodName == "__iter__") {
string returnType = pyClass.Name switch {
"Decoder" => "Instruction",
_ => throw new InvalidOperationException($"Unexpected iterator class {pyClass.Name}"),
};
return $"Iterator[{returnType}]";
}
return typeStr;
}
static string GetType(PyClass pyClass, string methodName, string rustType, string sphinxType) {
// The type in the docs (sphinx type) is more accurate than the type in the source code
// since `u32` is used in the source code if it's an enum value.
if (sphinxType != string.Empty) {
var sphinxTypes = ParseUtils.SplitSphinxTypes(sphinxType).ToList();
var convertedTypes = new List<string>();
foreach (var stype in sphinxTypes) {
if (!ParseUtils.TryConvertSphinxTypeToTypeName(stype, out var typeName))
typeName = stype;
convertedTypes.Add(typeName);
}
int index = convertedTypes.Count == 1 ? -1 : convertedTypes.IndexOf("None");
if (index >= 0)
convertedTypes.RemoveAt(index);
string typeStr;
if (convertedTypes.Count > 1)
typeStr = "Union[" + string.Join(", ", convertedTypes.ToArray()) + "]";
else
typeStr = convertedTypes[0];
if (index >= 0)
return "Optional[" + typeStr + "]";
return typeStr;
}
if (ParseUtils.TryRemovePrefixSuffix(rustType, "PyResult<", ">", out var extractedType))
rustType = extractedType;
switch (rustType) {
case "i8" or "i16" or "i32" or "i64" or "isize" or
"u8" or "u16" or "u32" or "u64" or "usize":
return "int";
case "bool":
return "bool";
case "&str" or "String":
return "str";
case "PyRef<Self>" or "PyRefMut<Self>" or "Self":
return pyClass.Name;
case "&PyAny":
return "Any";
default:
if (ParseUtils.TryRemovePrefixSuffix(rustType, "IterNextOutput<", ", ()>", out extractedType))
return extractedType;
break;
}
throw new InvalidOperationException($"Method {pyClass.Name}.{methodName}(): Couldn't convert Rust/sphinx type to Python type: Rust=`{rustType}`, sphinx=`{sphinxType}`");
}
sealed class PyProperty {
public readonly PyMethod Getter;
public readonly PyMethod? Setter;
public PyProperty(PyMethod getter, PyMethod? setter) {
Getter = getter;
Setter = setter;
}
}
static IEnumerable<object> GetMembers(PyClass pyClass) {
var setters = pyClass.Methods.Where(a => a.Attributes.Any(AttributeKind.Setter)).ToDictionary(a => a.Name, a => a, StringComparer.Ordinal);
foreach (var method in pyClass.Methods) {
if (method.Attributes.Any(AttributeKind.Setter))
continue;
if (method.Attributes.Any(AttributeKind.Getter)) {
setters.TryGetValue(method.Name, out var setterMethod);
setters.Remove(method.Name);
yield return new PyProperty(method, setterMethod);
}
else
yield return method;
}
if (setters.Count != 0)
throw new InvalidOperationException($"{pyClass.Name}: Setter without a getter: {setters.First().Value.Name}");
}
}
}
| |
// 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.GkeHub.V1Beta1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedGkeHubMembershipServiceClientSnippets
{
/// <summary>Snippet for ListMemberships</summary>
public void ListMembershipsRequestObject()
{
// Snippet: ListMemberships(ListMembershipsRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
ListMembershipsRequest request = new ListMembershipsRequest
{
Parent = "",
Filter = "",
OrderBy = "",
};
// Make the request
PagedEnumerable<ListMembershipsResponse, Membership> response = gkeHubMembershipServiceClient.ListMemberships(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Membership 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 (ListMembershipsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Membership 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<Membership> 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 (Membership 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 ListMembershipsAsync</summary>
public async Task ListMembershipsRequestObjectAsync()
{
// Snippet: ListMembershipsAsync(ListMembershipsRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
ListMembershipsRequest request = new ListMembershipsRequest
{
Parent = "",
Filter = "",
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<ListMembershipsResponse, Membership> response = gkeHubMembershipServiceClient.ListMembershipsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Membership 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((ListMembershipsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Membership 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<Membership> 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 (Membership 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 ListMemberships</summary>
public void ListMemberships()
{
// Snippet: ListMemberships(string, string, int?, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedEnumerable<ListMembershipsResponse, Membership> response = gkeHubMembershipServiceClient.ListMemberships(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Membership 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 (ListMembershipsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Membership 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<Membership> 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 (Membership 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 ListMembershipsAsync</summary>
public async Task ListMembershipsAsync()
{
// Snippet: ListMembershipsAsync(string, string, int?, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedAsyncEnumerable<ListMembershipsResponse, Membership> response = gkeHubMembershipServiceClient.ListMembershipsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Membership 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((ListMembershipsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Membership 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<Membership> 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 (Membership 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 GetMembership</summary>
public void GetMembershipRequestObject()
{
// Snippet: GetMembership(GetMembershipRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
GetMembershipRequest request = new GetMembershipRequest { Name = "", };
// Make the request
Membership response = gkeHubMembershipServiceClient.GetMembership(request);
// End snippet
}
/// <summary>Snippet for GetMembershipAsync</summary>
public async Task GetMembershipRequestObjectAsync()
{
// Snippet: GetMembershipAsync(GetMembershipRequest, CallSettings)
// Additional: GetMembershipAsync(GetMembershipRequest, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
GetMembershipRequest request = new GetMembershipRequest { Name = "", };
// Make the request
Membership response = await gkeHubMembershipServiceClient.GetMembershipAsync(request);
// End snippet
}
/// <summary>Snippet for GetMembership</summary>
public void GetMembership()
{
// Snippet: GetMembership(string, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
Membership response = gkeHubMembershipServiceClient.GetMembership(name);
// End snippet
}
/// <summary>Snippet for GetMembershipAsync</summary>
public async Task GetMembershipAsync()
{
// Snippet: GetMembershipAsync(string, CallSettings)
// Additional: GetMembershipAsync(string, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
Membership response = await gkeHubMembershipServiceClient.GetMembershipAsync(name);
// End snippet
}
/// <summary>Snippet for CreateMembership</summary>
public void CreateMembershipRequestObject()
{
// Snippet: CreateMembership(CreateMembershipRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
CreateMembershipRequest request = new CreateMembershipRequest
{
Parent = "",
MembershipId = "",
Resource = new Membership(),
RequestId = "",
};
// Make the request
Operation<Membership, OperationMetadata> response = gkeHubMembershipServiceClient.CreateMembership(request);
// Poll until the returned long-running operation is complete
Operation<Membership, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Membership 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
Operation<Membership, OperationMetadata> retrievedResponse = gkeHubMembershipServiceClient.PollOnceCreateMembership(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Membership retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateMembershipAsync</summary>
public async Task CreateMembershipRequestObjectAsync()
{
// Snippet: CreateMembershipAsync(CreateMembershipRequest, CallSettings)
// Additional: CreateMembershipAsync(CreateMembershipRequest, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
CreateMembershipRequest request = new CreateMembershipRequest
{
Parent = "",
MembershipId = "",
Resource = new Membership(),
RequestId = "",
};
// Make the request
Operation<Membership, OperationMetadata> response = await gkeHubMembershipServiceClient.CreateMembershipAsync(request);
// Poll until the returned long-running operation is complete
Operation<Membership, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Membership 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
Operation<Membership, OperationMetadata> retrievedResponse = await gkeHubMembershipServiceClient.PollOnceCreateMembershipAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Membership retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateMembership</summary>
public void CreateMembership()
{
// Snippet: CreateMembership(string, Membership, string, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
string parent = "";
Membership resource = new Membership();
string membershipId = "";
// Make the request
Operation<Membership, OperationMetadata> response = gkeHubMembershipServiceClient.CreateMembership(parent, resource, membershipId);
// Poll until the returned long-running operation is complete
Operation<Membership, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Membership 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
Operation<Membership, OperationMetadata> retrievedResponse = gkeHubMembershipServiceClient.PollOnceCreateMembership(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Membership retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateMembershipAsync</summary>
public async Task CreateMembershipAsync()
{
// Snippet: CreateMembershipAsync(string, Membership, string, CallSettings)
// Additional: CreateMembershipAsync(string, Membership, string, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
Membership resource = new Membership();
string membershipId = "";
// Make the request
Operation<Membership, OperationMetadata> response = await gkeHubMembershipServiceClient.CreateMembershipAsync(parent, resource, membershipId);
// Poll until the returned long-running operation is complete
Operation<Membership, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Membership 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
Operation<Membership, OperationMetadata> retrievedResponse = await gkeHubMembershipServiceClient.PollOnceCreateMembershipAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Membership retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteMembership</summary>
public void DeleteMembershipRequestObject()
{
// Snippet: DeleteMembership(DeleteMembershipRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
DeleteMembershipRequest request = new DeleteMembershipRequest
{
Name = "",
RequestId = "",
};
// Make the request
Operation<Empty, OperationMetadata> response = gkeHubMembershipServiceClient.DeleteMembership(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty 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
Operation<Empty, OperationMetadata> retrievedResponse = gkeHubMembershipServiceClient.PollOnceDeleteMembership(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteMembershipAsync</summary>
public async Task DeleteMembershipRequestObjectAsync()
{
// Snippet: DeleteMembershipAsync(DeleteMembershipRequest, CallSettings)
// Additional: DeleteMembershipAsync(DeleteMembershipRequest, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteMembershipRequest request = new DeleteMembershipRequest
{
Name = "",
RequestId = "",
};
// Make the request
Operation<Empty, OperationMetadata> response = await gkeHubMembershipServiceClient.DeleteMembershipAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty 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
Operation<Empty, OperationMetadata> retrievedResponse = await gkeHubMembershipServiceClient.PollOnceDeleteMembershipAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteMembership</summary>
public void DeleteMembership()
{
// Snippet: DeleteMembership(string, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
Operation<Empty, OperationMetadata> response = gkeHubMembershipServiceClient.DeleteMembership(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty 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
Operation<Empty, OperationMetadata> retrievedResponse = gkeHubMembershipServiceClient.PollOnceDeleteMembership(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteMembershipAsync</summary>
public async Task DeleteMembershipAsync()
{
// Snippet: DeleteMembershipAsync(string, CallSettings)
// Additional: DeleteMembershipAsync(string, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
Operation<Empty, OperationMetadata> response = await gkeHubMembershipServiceClient.DeleteMembershipAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty 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
Operation<Empty, OperationMetadata> retrievedResponse = await gkeHubMembershipServiceClient.PollOnceDeleteMembershipAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateMembership</summary>
public void UpdateMembershipRequestObject()
{
// Snippet: UpdateMembership(UpdateMembershipRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
UpdateMembershipRequest request = new UpdateMembershipRequest
{
Name = "",
UpdateMask = new FieldMask(),
Resource = new Membership(),
RequestId = "",
};
// Make the request
Operation<Membership, OperationMetadata> response = gkeHubMembershipServiceClient.UpdateMembership(request);
// Poll until the returned long-running operation is complete
Operation<Membership, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Membership 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
Operation<Membership, OperationMetadata> retrievedResponse = gkeHubMembershipServiceClient.PollOnceUpdateMembership(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Membership retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateMembershipAsync</summary>
public async Task UpdateMembershipRequestObjectAsync()
{
// Snippet: UpdateMembershipAsync(UpdateMembershipRequest, CallSettings)
// Additional: UpdateMembershipAsync(UpdateMembershipRequest, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateMembershipRequest request = new UpdateMembershipRequest
{
Name = "",
UpdateMask = new FieldMask(),
Resource = new Membership(),
RequestId = "",
};
// Make the request
Operation<Membership, OperationMetadata> response = await gkeHubMembershipServiceClient.UpdateMembershipAsync(request);
// Poll until the returned long-running operation is complete
Operation<Membership, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Membership 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
Operation<Membership, OperationMetadata> retrievedResponse = await gkeHubMembershipServiceClient.PollOnceUpdateMembershipAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Membership retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateMembership</summary>
public void UpdateMembership()
{
// Snippet: UpdateMembership(string, Membership, FieldMask, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
string name = "";
Membership resource = new Membership();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<Membership, OperationMetadata> response = gkeHubMembershipServiceClient.UpdateMembership(name, resource, updateMask);
// Poll until the returned long-running operation is complete
Operation<Membership, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Membership 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
Operation<Membership, OperationMetadata> retrievedResponse = gkeHubMembershipServiceClient.PollOnceUpdateMembership(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Membership retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateMembershipAsync</summary>
public async Task UpdateMembershipAsync()
{
// Snippet: UpdateMembershipAsync(string, Membership, FieldMask, CallSettings)
// Additional: UpdateMembershipAsync(string, Membership, FieldMask, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "";
Membership resource = new Membership();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<Membership, OperationMetadata> response = await gkeHubMembershipServiceClient.UpdateMembershipAsync(name, resource, updateMask);
// Poll until the returned long-running operation is complete
Operation<Membership, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Membership 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
Operation<Membership, OperationMetadata> retrievedResponse = await gkeHubMembershipServiceClient.PollOnceUpdateMembershipAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Membership retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GenerateConnectManifest</summary>
public void GenerateConnectManifestRequestObject()
{
// Snippet: GenerateConnectManifest(GenerateConnectManifestRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
GenerateConnectManifestRequest request = new GenerateConnectManifestRequest
{
Name = "",
ConnectAgent = new ConnectAgent(),
Version = "",
IsUpgrade = false,
Registry = "",
ImagePullSecretContent = ByteString.Empty,
};
// Make the request
GenerateConnectManifestResponse response = gkeHubMembershipServiceClient.GenerateConnectManifest(request);
// End snippet
}
/// <summary>Snippet for GenerateConnectManifestAsync</summary>
public async Task GenerateConnectManifestRequestObjectAsync()
{
// Snippet: GenerateConnectManifestAsync(GenerateConnectManifestRequest, CallSettings)
// Additional: GenerateConnectManifestAsync(GenerateConnectManifestRequest, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
GenerateConnectManifestRequest request = new GenerateConnectManifestRequest
{
Name = "",
ConnectAgent = new ConnectAgent(),
Version = "",
IsUpgrade = false,
Registry = "",
ImagePullSecretContent = ByteString.Empty,
};
// Make the request
GenerateConnectManifestResponse response = await gkeHubMembershipServiceClient.GenerateConnectManifestAsync(request);
// End snippet
}
/// <summary>Snippet for ValidateExclusivity</summary>
public void ValidateExclusivityRequestObject()
{
// Snippet: ValidateExclusivity(ValidateExclusivityRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
ValidateExclusivityRequest request = new ValidateExclusivityRequest
{
Parent = "",
CrManifest = "",
IntendedMembership = "",
};
// Make the request
ValidateExclusivityResponse response = gkeHubMembershipServiceClient.ValidateExclusivity(request);
// End snippet
}
/// <summary>Snippet for ValidateExclusivityAsync</summary>
public async Task ValidateExclusivityRequestObjectAsync()
{
// Snippet: ValidateExclusivityAsync(ValidateExclusivityRequest, CallSettings)
// Additional: ValidateExclusivityAsync(ValidateExclusivityRequest, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
ValidateExclusivityRequest request = new ValidateExclusivityRequest
{
Parent = "",
CrManifest = "",
IntendedMembership = "",
};
// Make the request
ValidateExclusivityResponse response = await gkeHubMembershipServiceClient.ValidateExclusivityAsync(request);
// End snippet
}
/// <summary>Snippet for GenerateExclusivityManifest</summary>
public void GenerateExclusivityManifestRequestObject()
{
// Snippet: GenerateExclusivityManifest(GenerateExclusivityManifestRequest, CallSettings)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = GkeHubMembershipServiceClient.Create();
// Initialize request argument(s)
GenerateExclusivityManifestRequest request = new GenerateExclusivityManifestRequest
{
Name = "",
CrdManifest = "",
CrManifest = "",
};
// Make the request
GenerateExclusivityManifestResponse response = gkeHubMembershipServiceClient.GenerateExclusivityManifest(request);
// End snippet
}
/// <summary>Snippet for GenerateExclusivityManifestAsync</summary>
public async Task GenerateExclusivityManifestRequestObjectAsync()
{
// Snippet: GenerateExclusivityManifestAsync(GenerateExclusivityManifestRequest, CallSettings)
// Additional: GenerateExclusivityManifestAsync(GenerateExclusivityManifestRequest, CancellationToken)
// Create client
GkeHubMembershipServiceClient gkeHubMembershipServiceClient = await GkeHubMembershipServiceClient.CreateAsync();
// Initialize request argument(s)
GenerateExclusivityManifestRequest request = new GenerateExclusivityManifestRequest
{
Name = "",
CrdManifest = "",
CrManifest = "",
};
// Make the request
GenerateExclusivityManifestResponse response = await gkeHubMembershipServiceClient.GenerateExclusivityManifestAsync(request);
// End snippet
}
}
}
| |
// 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;
namespace System.Security.Cryptography
{
/// <summary>
/// Provides support for computing a hash or HMAC value incrementally across several segments.
/// </summary>
public sealed class IncrementalHash : IDisposable
{
private const int NTE_BAD_ALGID = unchecked((int)0x80090008);
private static readonly byte[] s_empty = new byte[0];
private readonly HashAlgorithmName _algorithmName;
private HashAlgorithm _hash;
private bool _disposed;
private bool _resetPending;
private IncrementalHash(HashAlgorithmName name, HashAlgorithm hash)
{
Debug.Assert(name != null);
Debug.Assert(!string.IsNullOrEmpty(name.Name));
Debug.Assert(hash != null);
_algorithmName = name;
_hash = hash;
}
/// <summary>
/// Get the name of the algorithm being performed.
/// </summary>
public HashAlgorithmName AlgorithmName
{
get { return _algorithmName; }
}
/// <summary>
/// Append the entire contents of <paramref name="data"/> to the data already processed in the hash or HMAC.
/// </summary>
/// <param name="data">The data to process.</param>
/// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public void AppendData(byte[] data)
{
if (data == null)
throw new ArgumentNullException("data");
AppendData(data, 0, data.Length);
}
/// <summary>
/// Append <paramref name="count"/> bytes of <paramref name="data"/>, starting at <paramref name="offset"/>,
/// to the data already processed in the hash or HMAC.
/// </summary>
/// <param name="data">The data to process.</param>
/// <param name="offset">The offset into the byte array from which to begin using data.</param>
/// <param name="count">The number of bytes in the array to use as data.</param>
/// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="offset"/> is out of range. This parameter requires a non-negative number.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="count"/> is out of range. This parameter requires a non-negative number less than
/// the <see cref="Array.Length"/> value of <paramref name="data"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="count"/> is greater than
/// <paramref name="data"/>.<see cref="Array.Length"/> - <paramref name="offset"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public void AppendData(byte[] data, int offset, int count)
{
if (data == null)
throw new ArgumentNullException("data");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0 || (count > data.Length))
throw new ArgumentOutOfRangeException("count");
if ((data.Length - count) < offset)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_disposed)
throw new ObjectDisposedException(typeof(IncrementalHash).Name);
Debug.Assert(_hash != null);
if (_resetPending)
{
_hash.Initialize();
_resetPending = false;
}
_hash.TransformBlock(data, offset, count, null, 0);
}
/// <summary>
/// Retrieve the hash or HMAC for the data accumulated from prior calls to
/// <see cref="AppendData(byte[])"/>, and return to the state the object
/// was in at construction.
/// </summary>
/// <returns>The computed hash or HMAC.</returns>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public byte[] GetHashAndReset()
{
if (_disposed)
throw new ObjectDisposedException(typeof(IncrementalHash).Name);
Debug.Assert(_hash != null);
if (_resetPending)
{
// No point in setting _resetPending to false, we're about to set it to true.
_hash.Initialize();
}
_hash.TransformFinalBlock(s_empty, 0, 0);
byte[] hashValue = _hash.Hash;
_resetPending = true;
return hashValue;
}
/// <summary>
/// Release all resources used by the current instance of the
/// <see cref="IncrementalHash"/> class.
/// </summary>
public void Dispose()
{
_disposed = true;
if (_hash != null)
{
_hash.Dispose();
_hash = null;
}
}
/// <summary>
/// Create an <see cref="IncrementalHash"/> for the algorithm specified by <paramref name="hashAlgorithm"/>.
/// </summary>
/// <param name="hashAlgorithm">The name of the hash algorithm to perform.</param>
/// <returns>
/// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified
/// by <paramref name="hashAlgorithm"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or
/// the empty string.
/// </exception>
/// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception>
public static IncrementalHash CreateHash(HashAlgorithmName hashAlgorithm)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
return new IncrementalHash(hashAlgorithm, GetHashAlgorithm(hashAlgorithm));
}
/// <summary>
/// Create an <see cref="IncrementalHash"/> for the Hash-based Message Authentication Code (HMAC)
/// algorithm utilizing the hash algorithm specified by <paramref name="hashAlgorithm"/>, and a
/// key specified by <paramref name="key"/>.
/// </summary>
/// <param name="hashAlgorithm">The name of the hash algorithm to perform within the HMAC.</param>
/// <param name="key">
/// The secret key for the HMAC. The key can be any length, but a key longer than the output size
/// of the hash algorithm specified by <paramref name="hashAlgorithm"/> will be hashed (using the
/// algorithm specified by <paramref name="hashAlgorithm"/>) to derive a correctly-sized key. Therefore,
/// the recommended size of the secret key is the output size of the hash specified by
/// <paramref name="hashAlgorithm"/>.
/// </param>
/// <returns>
/// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified
/// by <paramref name="hashAlgorithm"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or
/// the empty string.
/// </exception>
/// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception>
public static IncrementalHash CreateHMAC(HashAlgorithmName hashAlgorithm, byte[] key)
{
if (key == null)
throw new ArgumentNullException("key");
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
return new IncrementalHash(hashAlgorithm, GetHMAC(hashAlgorithm, key));
}
private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm)
{
if (hashAlgorithm == HashAlgorithmName.MD5)
return new MD5CryptoServiceProvider();
if (hashAlgorithm == HashAlgorithmName.SHA1)
return new SHA1CryptoServiceProvider();
if (hashAlgorithm == HashAlgorithmName.SHA256)
return new SHA256CryptoServiceProvider();
if (hashAlgorithm == HashAlgorithmName.SHA384)
return new SHA384CryptoServiceProvider();
if (hashAlgorithm == HashAlgorithmName.SHA512)
return new SHA512CryptoServiceProvider();
throw new CryptographicException(NTE_BAD_ALGID);
}
private static HashAlgorithm GetHMAC(HashAlgorithmName hashAlgorithm, byte[] key)
{
if (hashAlgorithm == HashAlgorithmName.MD5)
return new HMACMD5(key);
if (hashAlgorithm == HashAlgorithmName.SHA1)
return new HMACSHA1(key);
if (hashAlgorithm == HashAlgorithmName.SHA256)
return new HMACSHA256(key);
if (hashAlgorithm == HashAlgorithmName.SHA384)
return new HMACSHA384(key);
if (hashAlgorithm == HashAlgorithmName.SHA512)
return new HMACSHA512(key);
throw new CryptographicException(NTE_BAD_ALGID);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.