context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//
// Pop3Stream.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.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.IO;
using System.Threading;
using Buffer = System.Buffer;
#if NETFX_CORE
using Windows.Storage.Streams;
using Windows.Networking.Sockets;
using Socket = Windows.Networking.Sockets.StreamSocket;
#else
using System.Net.Security;
using System.Net.Sockets;
#endif
using MimeKit.IO;
namespace MailKit.Net.Pop3 {
/// <summary>
/// An enumeration of the possible POP3 streaming modes.
/// </summary>
/// <remarks>
/// Normal operation is done in the <see cref="Pop3StreamMode.Line"/> mode,
/// but when retrieving messages (via RETR) or headers (via TOP), the
/// <see cref="Pop3StreamMode.Data"/> mode should be used.
/// </remarks>
enum Pop3StreamMode {
/// <summary>
/// Reads 1 line at a time.
/// </summary>
Line,
/// <summary>
/// Reads data in chunks, ignoring line state.
/// </summary>
Data
}
/// <summary>
/// A stream for communicating with a POP3 server.
/// </summary>
/// <remarks>
/// A stream capable of reading data line-by-line (<see cref="Pop3StreamMode.Line"/>)
/// or by raw byte streams (<see cref="Pop3StreamMode.Data"/>).
/// </remarks>
class Pop3Stream : Stream, ICancellableStream
{
const int ReadAheadSize = 128;
const int BlockSize = 4096;
const int PadSize = 4;
// I/O buffering
readonly byte[] input = new byte[ReadAheadSize + BlockSize + PadSize];
const int inputStart = ReadAheadSize;
readonly byte[] output = new byte[BlockSize];
int outputIndex;
readonly IProtocolLogger logger;
int inputIndex = ReadAheadSize;
int inputEnd = ReadAheadSize;
Pop3StreamMode mode;
bool disposed;
bool midline;
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Net.Pop3.Pop3Stream"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="Pop3Stream"/>.
/// </remarks>
/// <param name="source">The underlying network stream.</param>
/// <param name="socket">The underlying network socket.</param>
/// <param name="protocolLogger">The protocol logger.</param>
public Pop3Stream (Stream source, Socket socket, IProtocolLogger protocolLogger)
{
logger = protocolLogger;
IsConnected = true;
Stream = source;
Socket = socket;
}
/// <summary>
/// Get or sets the underlying network stream.
/// </summary>
/// <remarks>
/// Gets or sets the underlying network stream.
/// </remarks>
/// <value>The underlying network stream.</value>
public Stream Stream {
get; internal set;
}
/// <summary>
/// Get the underlying network socket.
/// </summary>
/// <remarks>
/// Gets the underlying network socket.
/// </remarks>
/// <value>The underlying network socket.</value>
public Socket Socket {
get; private set;
}
/// <summary>
/// Gets or sets the mode used for reading.
/// </summary>
/// <value>The mode.</value>
public Pop3StreamMode Mode {
get { return mode; }
set {
IsEndOfData = false;
mode = value;
}
}
/// <summary>
/// Get whether or not the stream is connected.
/// </summary>
/// <remarks>
/// Gets whether or not the stream is connected.
/// </remarks>
/// <value><c>true</c> if the stream is connected; otherwise, <c>false</c>.</value>
public bool IsConnected {
get; private set;
}
/// <summary>
/// Get whether or not the end of the raw data has been reached in <see cref="Pop3StreamMode.Data"/> mode.
/// </summary>
/// <remarks>
/// When reading the resonse to a command such as RETR, the end of the data is marked by line matching ".\r\n".
/// </remarks>
/// <value><c>true</c> if the end of the data has been reached; otherwise, <c>false</c>.</value>
public bool IsEndOfData {
get; private set;
}
/// <summary>
/// Get whether the stream supports reading.
/// </summary>
/// <remarks>
/// Gets whether the stream supports reading.
/// </remarks>
/// <value><c>true</c> if the stream supports reading; otherwise, <c>false</c>.</value>
public override bool CanRead {
get { return Stream.CanRead; }
}
/// <summary>
/// Get whether the stream supports writing.
/// </summary>
/// <remarks>
/// Gets whether the stream supports writing.
/// </remarks>
/// <value><c>true</c> if the stream supports writing; otherwise, <c>false</c>.</value>
public override bool CanWrite {
get { return Stream.CanWrite; }
}
/// <summary>
/// Get whether the stream supports seeking.
/// </summary>
/// <remarks>
/// Gets whether the stream supports seeking.
/// </remarks>
/// <value><c>true</c> if the stream supports seeking; otherwise, <c>false</c>.</value>
public override bool CanSeek {
get { return false; }
}
/// <summary>
/// Get whether the stream supports I/O timeouts.
/// </summary>
/// <remarks>
/// Gets whether the stream supports I/O timeouts.
/// </remarks>
/// <value><c>true</c> if the stream supports I/O timeouts; otherwise, <c>false</c>.</value>
public override bool CanTimeout {
get { return Stream.CanTimeout; }
}
/// <summary>
/// Get or set a value, in milliseconds, that determines how long the stream will attempt to read before timing out.
/// </summary>
/// <remarks>
/// Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.
/// </remarks>
/// <returns>A value, in milliseconds, that determines how long the stream will attempt to read before timing out.</returns>
/// <value>The read timeout.</value>
public override int ReadTimeout {
get { return Stream.ReadTimeout; }
set { Stream.ReadTimeout = value; }
}
/// <summary>
/// Get or set a value, in milliseconds, that determines how long the stream will attempt to write before timing out.
/// </summary>
/// <remarks>
/// Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.
/// </remarks>
/// <returns>A value, in milliseconds, that determines how long the stream will attempt to write before timing out.</returns>
/// <value>The write timeout.</value>
public override int WriteTimeout {
get { return Stream.WriteTimeout; }
set { Stream.WriteTimeout = value; }
}
/// <summary>
/// Get or set the position within the current stream.
/// </summary>
/// <remarks>
/// Gets or sets the position within the current stream.
/// </remarks>
/// <returns>The current position within the stream.</returns>
/// <value>The position of the stream.</value>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support seeking.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
public override long Position {
get { return Stream.Position; }
set { Stream.Position = value; }
}
/// <summary>
/// Get the length of the stream, in bytes.
/// </summary>
/// <remarks>
/// Gets the length of the stream, in bytes.
/// </remarks>
/// <returns>A long value representing the length of the stream in bytes.</returns>
/// <value>The length of the stream.</value>
/// <exception cref="System.NotSupportedException">
/// The stream does not support seeking.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
public override long Length {
get { return Stream.Length; }
}
void Poll (SelectMode mode, CancellationToken cancellationToken)
{
#if NETFX_CORE
cancellationToken.ThrowIfCancellationRequested ();
#else
if (!cancellationToken.CanBeCanceled)
return;
if (Socket != null) {
do {
cancellationToken.ThrowIfCancellationRequested ();
// wait 1/4 second and then re-check for cancellation
} while (!Socket.Poll (250000, mode));
} else {
cancellationToken.ThrowIfCancellationRequested ();
}
#endif
}
unsafe int ReadAhead (CancellationToken cancellationToken)
{
int left = inputEnd - inputIndex;
int start = inputStart;
int end = inputEnd;
int nread;
if (left > 0) {
int index = inputIndex;
// attempt to align the end of the remaining input with ReadAheadSize
if (index >= start) {
start -= Math.Min (ReadAheadSize, left);
Buffer.BlockCopy (input, index, input, start, left);
index = start;
start += left;
} else if (index > 0) {
int shift = Math.Min (index, end - start);
Buffer.BlockCopy (input, index, input, index - shift, left);
index -= shift;
start = index + left;
} else {
// we can't shift...
start = end;
}
inputIndex = index;
inputEnd = start;
} else {
inputIndex = start;
inputEnd = start;
}
end = input.Length - PadSize;
try {
#if !NETFX_CORE
bool buffered = Stream is SslStream;
#else
bool buffered = true;
#endif
if (buffered) {
cancellationToken.ThrowIfCancellationRequested ();
nread = Stream.Read (input, start, end - start);
} else {
Poll (SelectMode.SelectRead, cancellationToken);
nread = Stream.Read (input, start, end - start);
}
if (nread > 0) {
logger.LogServer (input, start, nread);
inputEnd += nread;
} else {
throw new Pop3ProtocolException ("The POP3 server has unexpectedly disconnected.");
}
} catch {
IsConnected = false;
throw;
}
return inputEnd - inputIndex;
}
static void ValidateArguments (byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException ("offset");
if (count < 0 || count > (buffer.Length - offset))
throw new ArgumentOutOfRangeException ("count");
}
void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException ("Pop3Stream");
}
unsafe bool NeedInput (byte* inptr, int inputLeft)
{
if (inputLeft == 2 && *inptr == (byte) '.' && *(inptr + 1) == '\n')
return false;
return true;
}
/// <summary>
/// Reads a sequence of bytes from the stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <remarks>
/// Reads a sequence of bytes from the stream and advances the position
/// within the stream by the number of bytes read.
/// </remarks>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
/// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The buffer offset.</param>
/// <param name="count">The number of bytes to read.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
/// <para>-or-</para>
/// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
/// at the specified <paramref name="offset"/>.</para>
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The stream is in line mode (see <see cref="Pop3StreamMode.Line"/>).
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public int Read (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckDisposed ();
ValidateArguments (buffer, offset, count);
if (Mode != Pop3StreamMode.Data)
throw new InvalidOperationException ();
if (IsEndOfData || count == 0)
return 0;
unsafe {
fixed (byte* inbuf = input, bufptr = buffer) {
byte* outbuf = bufptr + offset;
byte* outend = outbuf + count;
byte* outptr = outbuf;
byte* inptr, inend;
int inputLeft;
do {
inputLeft = inputEnd - inputIndex;
inptr = inbuf + inputIndex;
// we need at least 3 bytes: ".\r\n"
if (inputLeft < 3 && (midline || NeedInput (inptr, inputLeft))) {
if (outptr > outbuf)
break;
ReadAhead (cancellationToken);
inptr = inbuf + inputIndex;
}
inend = inbuf + inputEnd;
*inend = (byte) '\n';
while (inptr < inend) {
if (midline) {
// read until end-of-line
while (outptr < outend && *inptr != (byte) '\n')
*outptr++ = *inptr++;
if (inptr == inend || outptr == outend)
break;
*outptr++ = *inptr++;
midline = false;
}
if (inptr == inend)
break;
if (*inptr == (byte) '.') {
inputLeft = (int) (inend - inptr);
if (inputLeft >= 3 && *(inptr + 1) == (byte) '\r' && *(inptr + 2) == (byte) '\n') {
IsEndOfData = true;
midline = false;
inptr += 3;
break;
}
if (inputLeft >= 2 && *(inptr + 1) == (byte) '\n') {
IsEndOfData = true;
midline = false;
inptr += 2;
break;
}
if (inputLeft == 1 || (inputLeft == 2 && *(inptr + 1) == (byte) '\r')) {
// not enough data...
break;
}
if (*(inptr + 1) == (byte) '.')
inptr++;
}
midline = true;
}
inputIndex = (int) (inptr - inbuf);
} while (outptr < outend && !IsEndOfData);
return (int) (outptr - outbuf);
}
}
}
/// <summary>
/// Reads a sequence of bytes from the stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <remarks>
/// Reads a sequence of bytes from the stream and advances the position
/// within the stream by the number of bytes read.
/// </remarks>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
/// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The buffer offset.</param>
/// <param name="count">The number of bytes to read.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
/// <para>-or-</para>
/// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
/// at the specified <paramref name="offset"/>.</para>
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The stream is in line mode (see <see cref="Pop3StreamMode.Line"/>).
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override int Read (byte[] buffer, int offset, int count)
{
return Read (buffer, offset, count, CancellationToken.None);
}
/// <summary>
/// Reads a single line of input from the stream.
/// </summary>
/// <remarks>
/// This method should be called in a loop until it returns <c>true</c>.
/// </remarks>
/// <returns><c>true</c>, if reading the line is complete, <c>false</c> otherwise.</returns>
/// <param name="buffer">The buffer containing the line data.</param>
/// <param name="offset">The offset into the buffer containing bytes read.</param>
/// <param name="count">The number of bytes read.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
internal bool ReadLine (out byte[] buffer, out int offset, out int count, CancellationToken cancellationToken)
{
CheckDisposed ();
unsafe {
fixed (byte* inbuf = input) {
byte* start, inptr, inend;
if (inputIndex == inputEnd)
ReadAhead (cancellationToken);
offset = inputIndex;
buffer = input;
start = inbuf + inputIndex;
inend = inbuf + inputEnd;
*inend = (byte) '\n';
inptr = start;
// FIXME: use SIMD to optimize this
while (*inptr != (byte) '\n')
inptr++;
inputIndex = (int) (inptr - inbuf);
count = (int) (inptr - start);
if (inptr == inend) {
midline = true;
return false;
}
// consume the '\n'
midline = false;
inputIndex++;
count++;
return true;
}
}
}
/// <summary>
/// Writes a sequence of bytes to the stream and advances the current
/// position within this stream by the number of bytes written.
/// </summary>
/// <remarks>
/// Writes a sequence of bytes to the stream and advances the current
/// position within this stream by the number of bytes written.
/// </remarks>
/// <param name='buffer'>The buffer to write.</param>
/// <param name='offset'>The offset of the first byte to write.</param>
/// <param name='count'>The number of bytes to write.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
/// <para>-or-</para>
/// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
/// at the specified <paramref name="offset"/>.</para>
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support writing.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public void Write (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckDisposed ();
ValidateArguments (buffer, offset, count);
try {
int index = offset;
int left = count;
while (left > 0) {
int n = Math.Min (BlockSize - outputIndex, left);
if (outputIndex > 0 || n < BlockSize) {
// append the data to the output buffer
Buffer.BlockCopy (buffer, index, output, outputIndex, n);
outputIndex += n;
index += n;
left -= n;
}
if (outputIndex == BlockSize) {
// flush the output buffer
Poll (SelectMode.SelectWrite, cancellationToken);
Stream.Write (output, 0, BlockSize);
logger.LogClient (output, 0, BlockSize);
outputIndex = 0;
}
if (outputIndex == 0) {
// write blocks of data to the stream without buffering
while (left >= BlockSize) {
Poll (SelectMode.SelectWrite, cancellationToken);
Stream.Write (buffer, index, BlockSize);
logger.LogClient (buffer, index, BlockSize);
index += BlockSize;
left -= BlockSize;
}
}
}
} catch {
IsConnected = false;
throw;
}
IsEndOfData = false;
}
/// <summary>
/// Writes a sequence of bytes to the stream and advances the current
/// position within this stream by the number of bytes written.
/// </summary>
/// <remarks>
/// Writes a sequence of bytes to the stream and advances the current
/// position within this stream by the number of bytes written.
/// </remarks>
/// <param name='buffer'>The buffer to write.</param>
/// <param name='offset'>The offset of the first byte to write.</param>
/// <param name='count'>The number of bytes to write.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
/// <para>-or-</para>
/// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
/// at the specified <paramref name="offset"/>.</para>
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support writing.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override void Write (byte[] buffer, int offset, int count)
{
Write (buffer, offset, count, CancellationToken.None);
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written
/// to the underlying device.
/// </summary>
/// <remarks>
/// Clears all buffers for this stream and causes any buffered data to be written
/// to the underlying device.
/// </remarks>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support writing.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public void Flush (CancellationToken cancellationToken)
{
CheckDisposed ();
if (outputIndex == 0)
return;
try {
Poll (SelectMode.SelectWrite, cancellationToken);
Stream.Write (output, 0, outputIndex);
Stream.Flush ();
logger.LogClient (output, 0, outputIndex);
outputIndex = 0;
} catch {
IsConnected = false;
throw;
}
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written
/// to the underlying device.
/// </summary>
/// <remarks>
/// Clears all buffers for this stream and causes any buffered data to be written
/// to the underlying device.
/// </remarks>
/// <exception cref="System.ObjectDisposedException">
/// The stream has been disposed.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The stream does not support writing.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override void Flush ()
{
Flush (CancellationToken.None);
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <returns>The new position within the stream.</returns>
/// <param name="offset">The offset into the stream relative to the <paramref name="origin"/>.</param>
/// <param name="origin">The origin to seek from.</param>
/// <exception cref="System.NotSupportedException">
/// The stream does not support seeking.
/// </exception>
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ();
}
/// <summary>
/// Sets the length of the stream.
/// </summary>
/// <param name="value">The desired length of the stream in bytes.</param>
/// <exception cref="System.NotSupportedException">
/// The stream does not support setting the length.
/// </exception>
public override void SetLength (long value)
{
throw new NotSupportedException ();
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="Pop3Stream"/> and
/// optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only the unmanaged resources.</param>
protected override void Dispose (bool disposing)
{
if (disposing && !disposed) {
IsConnected = false;
Stream.Dispose ();
}
disposed = true;
base.Dispose (disposing);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing OpenID Connect Providers.
/// </summary>
internal partial class OpenIdConnectProvidersOperations : IServiceOperations<ApiManagementClient>, IOpenIdConnectProvidersOperations
{
/// <summary>
/// Initializes a new instance of the OpenIdConnectProvidersOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal OpenIdConnectProvidersOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates new OpenID Connect Provider.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='opid'>
/// Required. Identifier of the OpenID Connect Provider.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </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> CreateAsync(string resourceGroupName, string serviceName, string opid, OpenidConnectProviderCreateContract parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (opid == null)
{
throw new ArgumentNullException("opid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.ClientId == null)
{
throw new ArgumentNullException("parameters.ClientId");
}
if (parameters.MetadataEndpoint == null)
{
throw new ArgumentNullException("parameters.MetadataEndpoint");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Name.Length > 50)
{
throw new ArgumentOutOfRangeException("parameters.Name");
}
// 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("serviceName", serviceName);
tracingParameters.Add("opid", opid);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/openidConnectProviders/";
url = url + Uri.EscapeDataString(opid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
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 openidConnectProviderCreateContractValue = new JObject();
requestDoc = openidConnectProviderCreateContractValue;
openidConnectProviderCreateContractValue["name"] = parameters.Name;
if (parameters.Description != null)
{
openidConnectProviderCreateContractValue["description"] = parameters.Description;
}
openidConnectProviderCreateContractValue["metadataEndpoint"] = parameters.MetadataEndpoint;
openidConnectProviderCreateContractValue["clientId"] = parameters.ClientId;
if (parameters.ClientSecret != null)
{
openidConnectProviderCreateContractValue["clientSecret"] = parameters.ClientSecret;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes specific OpenID Connect Provider of the Api Management
/// service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='opid'>
/// Required. Identifier of the OpenID Connect Provider.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string opid, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (opid == null)
{
throw new ArgumentNullException("opid");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// 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("serviceName", serviceName);
tracingParameters.Add("opid", opid);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/openidConnectProviders/";
url = url + Uri.EscapeDataString(opid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// 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.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets specific OpenID Connect Provider.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='opid'>
/// Required. Identifier of the OpenID Connect Provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get OpenID Connect Provider operation response details.
/// </returns>
public async Task<OpenIdConnectProviderGetResponse> GetAsync(string resourceGroupName, string serviceName, string opid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (opid == null)
{
throw new ArgumentNullException("opid");
}
// 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("serviceName", serviceName);
tracingParameters.Add("opid", opid);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/openidConnectProviders/";
url = url + Uri.EscapeDataString(opid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
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
OpenIdConnectProviderGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OpenIdConnectProviderGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
OpenidConnectProviderContract valueInstance = new OpenidConnectProviderContract();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.IdPath = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
valueInstance.Name = nameInstance;
}
JToken descriptionValue = responseDoc["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
valueInstance.Description = descriptionInstance;
}
JToken metadataEndpointValue = responseDoc["metadataEndpoint"];
if (metadataEndpointValue != null && metadataEndpointValue.Type != JTokenType.Null)
{
string metadataEndpointInstance = ((string)metadataEndpointValue);
valueInstance.MetadataEndpoint = metadataEndpointInstance;
}
JToken clientIdValue = responseDoc["clientId"];
if (clientIdValue != null && clientIdValue.Type != JTokenType.Null)
{
string clientIdInstance = ((string)clientIdValue);
valueInstance.ClientId = clientIdInstance;
}
JToken clientSecretValue = responseDoc["clientSecret"];
if (clientSecretValue != null && clientSecretValue.Type != JTokenType.Null)
{
string clientSecretInstance = ((string)clientSecretValue);
valueInstance.ClientSecret = clientSecretInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
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>
/// List all OpenID Connect Providers.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List OpenIdProviders operation response details.
/// </returns>
public async Task<OpenIdConnectProvidersListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// 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("serviceName", serviceName);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/openidConnectProviders";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
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
OpenIdConnectProvidersListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OpenIdConnectProvidersListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
OpenIdConnectProviderPaged resultInstance = new OpenIdConnectProviderPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
OpenidConnectProviderContract openidConnectProviderContractInstance = new OpenidConnectProviderContract();
resultInstance.Values.Add(openidConnectProviderContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
openidConnectProviderContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
openidConnectProviderContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
openidConnectProviderContractInstance.Description = descriptionInstance;
}
JToken metadataEndpointValue = valueValue["metadataEndpoint"];
if (metadataEndpointValue != null && metadataEndpointValue.Type != JTokenType.Null)
{
string metadataEndpointInstance = ((string)metadataEndpointValue);
openidConnectProviderContractInstance.MetadataEndpoint = metadataEndpointInstance;
}
JToken clientIdValue = valueValue["clientId"];
if (clientIdValue != null && clientIdValue.Type != JTokenType.Null)
{
string clientIdInstance = ((string)clientIdValue);
openidConnectProviderContractInstance.ClientId = clientIdInstance;
}
JToken clientSecretValue = valueValue["clientSecret"];
if (clientSecretValue != null && clientSecretValue.Type != JTokenType.Null)
{
string clientSecretInstance = ((string)clientSecretValue);
openidConnectProviderContractInstance.ClientSecret = clientSecretInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.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>
/// List next OpenID Connect Providers page.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List OpenIdProviders operation response details.
/// </returns>
public async Task<OpenIdConnectProvidersListResponse> 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
OpenIdConnectProvidersListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OpenIdConnectProvidersListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
OpenIdConnectProviderPaged resultInstance = new OpenIdConnectProviderPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
OpenidConnectProviderContract openidConnectProviderContractInstance = new OpenidConnectProviderContract();
resultInstance.Values.Add(openidConnectProviderContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
openidConnectProviderContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
openidConnectProviderContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
openidConnectProviderContractInstance.Description = descriptionInstance;
}
JToken metadataEndpointValue = valueValue["metadataEndpoint"];
if (metadataEndpointValue != null && metadataEndpointValue.Type != JTokenType.Null)
{
string metadataEndpointInstance = ((string)metadataEndpointValue);
openidConnectProviderContractInstance.MetadataEndpoint = metadataEndpointInstance;
}
JToken clientIdValue = valueValue["clientId"];
if (clientIdValue != null && clientIdValue.Type != JTokenType.Null)
{
string clientIdInstance = ((string)clientIdValue);
openidConnectProviderContractInstance.ClientId = clientIdInstance;
}
JToken clientSecretValue = valueValue["clientSecret"];
if (clientSecretValue != null && clientSecretValue.Type != JTokenType.Null)
{
string clientSecretInstance = ((string)clientSecretValue);
openidConnectProviderContractInstance.ClientSecret = clientSecretInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.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>
/// Patches specific OpenID Connect Provider.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='opid'>
/// Required. Identifier of the OpenID Connect Provider.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </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> UpdateAsync(string resourceGroupName, string serviceName, string opid, OpenidConnectProviderUpdateContract parameters, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (opid == null)
{
throw new ArgumentNullException("opid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name != null && parameters.Name.Length > 50)
{
throw new ArgumentOutOfRangeException("parameters.Name");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// 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("serviceName", serviceName);
tracingParameters.Add("opid", opid);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/openidConnectProviders/";
url = url + Uri.EscapeDataString(opid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject openidConnectProviderUpdateContractValue = new JObject();
requestDoc = openidConnectProviderUpdateContractValue;
if (parameters.Name != null)
{
openidConnectProviderUpdateContractValue["name"] = parameters.Name;
}
if (parameters.Description != null)
{
openidConnectProviderUpdateContractValue["description"] = parameters.Description;
}
if (parameters.MetadataEndpoint != null)
{
openidConnectProviderUpdateContractValue["metadataEndpoint"] = parameters.MetadataEndpoint;
}
if (parameters.ClientId != null)
{
openidConnectProviderUpdateContractValue["clientId"] = parameters.ClientId;
}
if (parameters.ClientSecret != null)
{
openidConnectProviderUpdateContractValue["clientSecret"] = parameters.ClientSecret;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ObjectStateEntry.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Metadata.Edm;
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Collections;
namespace System.Data.Objects
{
// Detached - nothing
// Added - _entity & _currentValues only for shadowState
// Unchanged - _entity & _currentValues only for shadowState
// Unchanged -> Deleted - _entity & _currentValues only for shadowState
// Modified - _currentValues & _modifiedFields + _originalValues only on change
// Modified -> Deleted - _currentValues & _modifiedFields + _originalValues only on change
/// <summary>
/// Represets either a entity, entity stub or relationship
/// </summary>
public abstract class ObjectStateEntry : IEntityStateEntry, IEntityChangeTracker
{
#region common entry fields
internal ObjectStateManager _cache;
internal EntitySetBase _entitySet;
internal EntityState _state;
#endregion
#region Constructor
// ObjectStateEntry will not be detached and creation will be handled from ObjectStateManager
internal ObjectStateEntry(ObjectStateManager cache, EntitySet entitySet, EntityState state)
{
Debug.Assert(cache != null, "cache cannot be null.");
_cache = cache;
_entitySet = entitySet;
_state = state;
}
#endregion // Constructor
#region Public members
/// <summary>
/// ObjectStateManager property of ObjectStateEntry.
/// </summary>
/// <param></param>
/// <returns> ObjectStateManager </returns>
public ObjectStateManager ObjectStateManager
{
get
{
ValidateState();
return _cache;
}
}
/// <summary> Extent property of ObjectStateEntry. </summary>
/// <param></param>
/// <returns> Extent </returns>
public EntitySetBase EntitySet
{
get
{
ValidateState();
return _entitySet;
}
}
/// <summary>
/// State property of ObjectStateEntry.
/// </summary>
/// <param></param>
/// <returns> DataRowState </returns>
public EntityState State
{
get
{
return _state;
}
internal set
{
_state = value;
}
}
/// <summary>
/// Entity property of ObjectStateEntry.
/// </summary>
/// <param></param>
/// <returns> The entity encapsulated by this entry. </returns>
abstract public object Entity { get; }
/// <summary>
/// The EntityKey associated with the ObjectStateEntry
/// </summary>
abstract public EntityKey EntityKey { get; internal set; }
/// <summary>
/// Determines if this ObjectStateEntry represents a relationship
/// </summary>
abstract public bool IsRelationship { get; }
/// <summary>
/// Gets bit array indicating which properties are modified.
/// </summary>
abstract internal BitArray ModifiedProperties { get; }
BitArray IEntityStateEntry.ModifiedProperties { get { return this.ModifiedProperties; } }
/// <summary>
/// Original values of entity
/// </summary>
/// <param></param>
/// <returns> DbDataRecord </returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // don't have debugger view expand this
abstract public DbDataRecord OriginalValues { get; }
abstract public OriginalValueRecord GetUpdatableOriginalValues();
/// <summary>
/// Current values of entity/ DataRow
/// </summary>
/// <param></param>
/// <returns> DbUpdatableDataRecord </returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // don't have debugger view expand this
abstract public CurrentValueRecord CurrentValues { get; }
/// <summary>
/// API to accept the current values as original values and mark the entity as Unchanged.
/// </summary>
/// <param></param>
/// <returns></returns>
abstract public void AcceptChanges();
/// <summary>
/// API to mark the entity deleted. if entity is in added state, it will be detached
/// </summary>
/// <param></param>
/// <returns> </returns>
abstract public void Delete();
/// <summary>
/// API to return properties that are marked modified
/// </summary>
/// <param> </param>
/// <returns> IEnumerable of modified properties names, names are in term of c-space </returns>
abstract public IEnumerable<string> GetModifiedProperties();
/// <summary>
/// set the state to Modified.
/// </summary>
/// <param></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException">If State is not Modified or Unchanged</exception>
///
abstract public void SetModified();
/// <summary>
/// Marks specified property as modified.
/// </summary>
/// <param name="propertyName">This API recognizes the names in terms of OSpace</param>
/// <exception cref="InvalidOperationException">If State is not Modified or Unchanged</exception>
///
abstract public void SetModifiedProperty(string propertyName);
/// <summary>
/// Rejects any changes made to the property with the given name since the property was last loaded,
/// attached, saved, or changes were accepted. The orginal value of the property is stored and the
/// property will no longer be marked as modified.
/// </summary>
/// <remarks>
/// If the result is that no properties of the entity are marked as modified, then the entity will
/// be marked as Unchanged.
/// Changes to properties can only rejected for entities that are in the Modified or Unchanged state.
/// Calling this method for entities in other states (Added, Deleted, or Detached) will result in
/// an exception being thrown.
/// Rejecting changes to properties of an Unchanged entity or unchanged properties of a Modifed
/// is a no-op.
/// </remarks>
/// <param name="propertyName">The name of the property to change.</param>
abstract public void RejectPropertyChanges(string propertyName);
/// <summary>
/// Uses DetectChanges to determine whether or not the current value of the property with the given
/// name is different from its original value. Note that this may be different from the property being
/// marked as modified since a property which has not changed can still be marked as modified.
/// </summary>
/// <remarks>
/// For complex properties, a new instance of the complex object which has all the same property
/// values as the original instance is not considered to be different by this method.
/// </remarks>
/// <param name="propertyName">The name of the property.</param>
/// <returns>True if the property has changed; false otherwise.</returns>
abstract public bool IsPropertyChanged(string propertyName);
/// <summary>
/// Returns the RelationshipManager for the entity represented by this ObjectStateEntry.
/// Note that a RelationshipManager objects can only be returned if this entry represents a
/// full entity. Key-only entries (stubs) and entries representing relationships do not
/// have associated RelationshipManagers.
/// </summary>
/// <exception cref="InvalidOperationException">The entry is a stub or represents a relationship</exception>
abstract public RelationshipManager RelationshipManager
{
get;
}
/// <summary>
/// Changes state of the entry to the specified <paramref name="state"/>
/// </summary>
/// <param name="state">The requested state</param>
abstract public void ChangeState(EntityState state);
/// <summary>
/// Apply modified properties to the original object.
/// </summary>
/// <param name="current">object with modified properties</param>
abstract public void ApplyCurrentValues(object currentEntity);
/// <summary>
/// Apply original values to the entity.
/// </summary>
/// <param name="original">The object with original values</param>
abstract public void ApplyOriginalValues(object originalEntity);
#endregion // Public members
#region IEntityStateEntry
IEntityStateManager IEntityStateEntry.StateManager
{
get
{
return (IEntityStateManager)this.ObjectStateManager;
}
}
// must explicitly implement this because interface is internal & so is the property on the
// class itself -- apparently the compiler won't let anything marked as internal be part of
// an interface (even if the interface is also internal)
bool IEntityStateEntry.IsKeyEntry
{
get
{
return this.IsKeyEntry;
}
}
#endregion // IEntityStateEntry
#region Public IEntityChangeTracker
/// <summary>
/// Used to report that a scalar entity property is about to change
/// The current value of the specified property is cached when this method is called.
/// </summary>
/// <param name="entityMemberName">The name of the entity property that is changing</param>
void IEntityChangeTracker.EntityMemberChanging(string entityMemberName)
{
this.EntityMemberChanging(entityMemberName);
}
/// <summary>
/// Used to report that a scalar entity property has been changed
/// The property value that was cached during EntityMemberChanging is now
/// added to OriginalValues
/// </summary>
/// <param name="entityMemberName">The name of the entity property that has changing</param>
void IEntityChangeTracker.EntityMemberChanged(string entityMemberName)
{
this.EntityMemberChanged(entityMemberName);
}
/// <summary>
/// Used to report that a complex property is about to change
/// The current value of the specified property is cached when this method is called.
/// </summary>
/// <param name="entityMemberName">The name of the top-level entity property that is changing</param>
/// <param name="complexObject">The complex object that contains the property that is changing</param>
/// <param name="complexObjectMemberName">The name of the property that is changing on complexObject</param>
void IEntityChangeTracker.EntityComplexMemberChanging(string entityMemberName, object complexObject, string complexObjectMemberName)
{
this.EntityComplexMemberChanging(entityMemberName, complexObject, complexObjectMemberName);
}
/// <summary>
/// Used to report that a complex property has been changed
/// The property value that was cached during EntityMemberChanging is now added to OriginalValues
/// </summary>
/// <param name="entityMemberName">The name of the top-level entity property that has changed</param>
/// <param name="complexObject">The complex object that contains the property that changed</param>
/// <param name="complexObjectMemberName">The name of the property that changed on complexObject</param>
void IEntityChangeTracker.EntityComplexMemberChanged(string entityMemberName, object complexObject, string complexObjectMemberName)
{
this.EntityComplexMemberChanged(entityMemberName, complexObject, complexObjectMemberName);
}
/// <summary>
/// Returns the EntityState from the ObjectStateEntry
/// </summary>
EntityState IEntityChangeTracker.EntityState
{
get
{
return this.State;
}
}
#endregion // IEntityChangeTracker
#region Internal members
abstract internal bool IsKeyEntry { get; }
abstract internal int GetFieldCount(StateManagerTypeMetadata metadata);
abstract internal Type GetFieldType(int ordinal, StateManagerTypeMetadata metadata);
abstract internal string GetCLayerName(int ordinal, StateManagerTypeMetadata metadata);
abstract internal int GetOrdinalforCLayerName(string name, StateManagerTypeMetadata metadata);
abstract internal void RevertDelete();
abstract internal void SetModifiedAll();
abstract internal void EntityMemberChanging(string entityMemberName);
abstract internal void EntityMemberChanged(string entityMemberName);
abstract internal void EntityComplexMemberChanging(string entityMemberName, object complexObject, string complexObjectMemberName);
abstract internal void EntityComplexMemberChanged(string entityMemberName, object complexObject, string complexObjectMemberName);
/// <summary>
/// Reuse or create a new (Entity)DataRecordInfo.
/// </summary>
abstract internal DataRecordInfo GetDataRecordInfo(StateManagerTypeMetadata metadata, object userObject);
virtual internal void Reset()
{
_cache = null;
_entitySet = null;
_state = EntityState.Detached;
}
internal void ValidateState()
{
if (_state == EntityState.Detached)
{
throw EntityUtil.ObjectStateEntryinInvalidState();
}
Debug.Assert(null != _cache, "null ObjectStateManager");
Debug.Assert(null != _entitySet, "null EntitySetBase");
}
#endregion // Internal members
}
internal struct StateManagerValue
{
internal StateManagerMemberMetadata memberMetadata;
internal object userObject;
internal object originalValue;
internal StateManagerValue(StateManagerMemberMetadata metadata, object instance, object value)
{
memberMetadata = metadata;
userObject = instance;
originalValue = value;
}
}
internal enum ObjectStateValueRecord
{
OriginalReadonly = 0,
CurrentUpdatable = 1,
OriginalUpdatableInternal = 2,
OriginalUpdatablePublic = 3,
}
// This class is used in Referential Integrity Constraints feature.
// It is used to get around the problem of enumerating dictionary contents,
// but allowing update of the value without breaking the enumerator.
internal sealed class IntBox
{
private int val;
internal IntBox(int val)
{
this.val = val;
}
internal int Value
{
get
{
return val;
}
set
{
val = value;
}
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenMetaverse;
using Npgsql;
namespace OpenSim.Data.PGSQL
{
public class PGSQLGroupsData : IGroupsData
{
private PGSqlGroupsGroupsHandler m_Groups;
private PGSqlGroupsMembershipHandler m_Membership;
private PGSqlGroupsRolesHandler m_Roles;
private PGSqlGroupsRoleMembershipHandler m_RoleMembership;
private PGSqlGroupsInvitesHandler m_Invites;
private PGSqlGroupsNoticesHandler m_Notices;
private PGSqlGroupsPrincipalsHandler m_Principals;
public PGSQLGroupsData(string connectionString, string realm)
{
m_Groups = new PGSqlGroupsGroupsHandler(connectionString, realm + "_groups", realm + "_Store");
m_Membership = new PGSqlGroupsMembershipHandler(connectionString, realm + "_membership");
m_Roles = new PGSqlGroupsRolesHandler(connectionString, realm + "_roles");
m_RoleMembership = new PGSqlGroupsRoleMembershipHandler(connectionString, realm + "_rolemembership");
m_Invites = new PGSqlGroupsInvitesHandler(connectionString, realm + "_invites");
m_Notices = new PGSqlGroupsNoticesHandler(connectionString, realm + "_notices");
m_Principals = new PGSqlGroupsPrincipalsHandler(connectionString, realm + "_principals");
}
#region groups table
public bool StoreGroup(GroupData data)
{
return m_Groups.Store(data);
}
public GroupData RetrieveGroup(UUID groupID)
{
GroupData[] groups = m_Groups.Get("GroupID", groupID.ToString());
if (groups.Length > 0)
return groups[0];
return null;
}
public GroupData RetrieveGroup(string name)
{
GroupData[] groups = m_Groups.Get("Name", name);
if (groups.Length > 0)
return groups[0];
return null;
}
public GroupData[] RetrieveGroups(string pattern)
{
if (string.IsNullOrEmpty(pattern)) // True for where clause
{
pattern = " true ORDER BY lower(\"Name\") LIMIT 100";
return m_Groups.Get(pattern);
}
else
{
pattern = " lower(\"Name\") LIKE lower('%:pattern%') ORDER BY lower(\"Name\") LIMIT 100";
return m_Groups.Get(pattern, new NpgsqlParameter("pattern", pattern));
}
}
public bool DeleteGroup(UUID groupID)
{
return m_Groups.Delete("GroupID", groupID.ToString());
}
public int GroupsCount()
{
return (int)m_Groups.GetCount(" \"Location\" = \"\"");
}
#endregion
#region membership table
public MembershipData[] RetrieveMembers(UUID groupID)
{
return m_Membership.Get("GroupID", groupID.ToString());
}
public MembershipData RetrieveMember(UUID groupID, string pricipalID)
{
MembershipData[] m = m_Membership.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), pricipalID });
if (m != null && m.Length > 0)
return m[0];
return null;
}
public MembershipData[] RetrieveMemberships(string pricipalID)
{
return m_Membership.Get("PrincipalID", pricipalID.ToString());
}
public bool StoreMember(MembershipData data)
{
return m_Membership.Store(data);
}
public bool DeleteMember(UUID groupID, string pricipalID)
{
return m_Membership.Delete(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), pricipalID });
}
public int MemberCount(UUID groupID)
{
return (int)m_Membership.GetCount("GroupID", groupID.ToString());
}
#endregion
#region roles table
public bool StoreRole(RoleData data)
{
return m_Roles.Store(data);
}
public RoleData RetrieveRole(UUID groupID, UUID roleID)
{
RoleData[] data = m_Roles.Get(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
if (data != null && data.Length > 0)
return data[0];
return null;
}
public RoleData[] RetrieveRoles(UUID groupID)
{
//return m_Roles.RetrieveRoles(groupID);
return m_Roles.Get("GroupID", groupID.ToString());
}
public bool DeleteRole(UUID groupID, UUID roleID)
{
return m_Roles.Delete(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
}
public int RoleCount(UUID groupID)
{
return (int)m_Roles.GetCount("GroupID", groupID.ToString());
}
#endregion
#region rolememberhip table
public RoleMembershipData[] RetrieveRolesMembers(UUID groupID)
{
RoleMembershipData[] data = m_RoleMembership.Get("GroupID", groupID.ToString());
return data;
}
public RoleMembershipData[] RetrieveRoleMembers(UUID groupID, UUID roleID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
return data;
}
public RoleMembershipData[] RetrieveMemberRoles(UUID groupID, string principalID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID.ToString() });
return data;
}
public RoleMembershipData RetrieveRoleMember(UUID groupID, UUID roleID, string principalID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID", "PrincipalID" },
new string[] { groupID.ToString(), roleID.ToString(), principalID.ToString() });
if (data != null && data.Length > 0)
return data[0];
return null;
}
public int RoleMemberCount(UUID groupID, UUID roleID)
{
return (int)m_RoleMembership.GetCount(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
}
public bool StoreRoleMember(RoleMembershipData data)
{
return m_RoleMembership.Store(data);
}
public bool DeleteRoleMember(RoleMembershipData data)
{
return m_RoleMembership.Delete(new string[] { "GroupID", "RoleID", "PrincipalID"},
new string[] { data.GroupID.ToString(), data.RoleID.ToString(), data.PrincipalID });
}
public bool DeleteMemberAllRoles(UUID groupID, string principalID)
{
return m_RoleMembership.Delete(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID });
}
#endregion
#region principals table
public bool StorePrincipal(PrincipalData data)
{
return m_Principals.Store(data);
}
public PrincipalData RetrievePrincipal(string principalID)
{
PrincipalData[] p = m_Principals.Get("PrincipalID", principalID);
if (p != null && p.Length > 0)
return p[0];
return null;
}
public bool DeletePrincipal(string principalID)
{
return m_Principals.Delete("PrincipalID", principalID);
}
#endregion
#region invites table
public bool StoreInvitation(InvitationData data)
{
return m_Invites.Store(data);
}
public InvitationData RetrieveInvitation(UUID inviteID)
{
InvitationData[] invites = m_Invites.Get("InviteID", inviteID.ToString());
if (invites != null && invites.Length > 0)
return invites[0];
return null;
}
public InvitationData RetrieveInvitation(UUID groupID, string principalID)
{
InvitationData[] invites = m_Invites.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID });
if (invites != null && invites.Length > 0)
return invites[0];
return null;
}
public bool DeleteInvite(UUID inviteID)
{
return m_Invites.Delete("InviteID", inviteID.ToString());
}
public void DeleteOldInvites()
{
m_Invites.DeleteOld();
}
#endregion
#region notices table
public bool StoreNotice(NoticeData data)
{
return m_Notices.Store(data);
}
public NoticeData RetrieveNotice(UUID noticeID)
{
NoticeData[] notices = m_Notices.Get("NoticeID", noticeID.ToString());
if (notices != null && notices.Length > 0)
return notices[0];
return null;
}
public NoticeData[] RetrieveNotices(UUID groupID)
{
NoticeData[] notices = m_Notices.Get("GroupID", groupID.ToString());
return notices;
}
public bool DeleteNotice(UUID noticeID)
{
return m_Notices.Delete("NoticeID", noticeID.ToString());
}
public void DeleteOldNotices()
{
m_Notices.DeleteOld();
}
#endregion
#region combinations
public MembershipData RetrievePrincipalGroupMembership(string principalID, UUID groupID)
{
// TODO
return null;
}
public MembershipData[] RetrievePrincipalGroupMemberships(string principalID)
{
// TODO
return null;
}
#endregion
}
public class PGSqlGroupsGroupsHandler : PGSQLGenericTableHandler<GroupData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public PGSqlGroupsGroupsHandler(string connectionString, string realm, string store)
: base(connectionString, realm, store)
{
}
}
public class PGSqlGroupsMembershipHandler : PGSQLGenericTableHandler<MembershipData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public PGSqlGroupsMembershipHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class PGSqlGroupsRolesHandler : PGSQLGenericTableHandler<RoleData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public PGSqlGroupsRolesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class PGSqlGroupsRoleMembershipHandler : PGSQLGenericTableHandler<RoleMembershipData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public PGSqlGroupsRoleMembershipHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class PGSqlGroupsInvitesHandler : PGSQLGenericTableHandler<InvitationData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public PGSqlGroupsInvitesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
public void DeleteOld()
{
uint now = (uint)Util.UnixTimeSinceEpoch();
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where \"TMStamp\" < :tstamp", m_Realm);
cmd.Parameters.AddWithValue("tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old
ExecuteNonQuery(cmd);
}
}
}
public class PGSqlGroupsNoticesHandler : PGSQLGenericTableHandler<NoticeData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public PGSqlGroupsNoticesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
public void DeleteOld()
{
uint now = (uint)Util.UnixTimeSinceEpoch();
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where \"TMStamp\" < :tstamp", m_Realm);
cmd.Parameters.AddWithValue("tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old
ExecuteNonQuery(cmd);
}
}
}
public class PGSqlGroupsPrincipalsHandler : PGSQLGenericTableHandler<PrincipalData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public PGSqlGroupsPrincipalsHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
}
| |
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* 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 holder is ArangoDB GmbH, Cologne, Germany
*/
namespace ArangoDB
{
using global::ArangoDB.Entity;
using global::ArangoDB.Internal;
using global::ArangoDB.Internal.VelocyStream;
using global::ArangoDB.Model;
using global::ArangoDB.Velocystream;
/// <author>Mark - mark at arangodb.com</author>
public class ArangoEdgeCollection : InternalArangoEdgeCollection
<ArangoExecutorSync, Response,
ConnectionSync>
{
protected internal ArangoEdgeCollection(ArangoGraph graph, string name
)
: base(graph.executor(), graph.db(), graph.name(), name)
{
}
/// <summary>Creates a new edge in the collection</summary>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#create-an-edge">API Documentation</a>
/// </seealso>
/// <param name="value">A representation of a single edge (POJO, VPackSlice or String for Json)
/// </param>
/// <returns>information about the edge</returns>
/// <exception cref="ArangoDBException"/>
/// <exception cref="ArangoDBException"/>
public virtual EdgeEntity insertEdge<T>(T value)
{
return this.executor.execute(this.insertEdgeRequest(value, new EdgeCreateOptions
()), this.insertEdgeResponseDeserializer(value));
}
/// <summary>Creates a new edge in the collection</summary>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#create-an-edge">API Documentation</a>
/// </seealso>
/// <param name="value">A representation of a single edge (POJO, VPackSlice or String for Json)
/// </param>
/// <param name="options">Additional options, can be null</param>
/// <returns>information about the edge</returns>
/// <exception cref="ArangoDBException"/>
/// <exception cref="ArangoDBException"/>
public virtual EdgeEntity insertEdge<T>(T value, EdgeCreateOptions
options)
{
return this.executor.execute(this.insertEdgeRequest(value, options), this.insertEdgeResponseDeserializer
(value));
}
/// <summary>Fetches an existing edge</summary>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#get-an-edge">API Documentation</a>
/// </seealso>
/// <param name="key">The key of the edge</param>
/// <param name="type">The type of the edge-document (POJO class, VPackSlice or String for Json)
/// </param>
/// <returns>the edge identified by the key</returns>
/// <exception cref="ArangoDBException"/>
/// <exception cref="com.arangodb.ArangoDBException"/>
public virtual T getEdge<T>(string key)
{
System.Type type = typeof(T);
return this.executor.execute(this.getEdgeRequest(key, new DocumentReadOptions
()), getEdgeResponseDeserializer(type));
}
/// <summary>Fetches an existing edge</summary>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#get-an-edge">API Documentation</a>
/// </seealso>
/// <param name="key">The key of the edge</param>
/// <param name="type">The type of the edge-document (POJO class, VPackSlice or String for Json)
/// </param>
/// <param name="options">Additional options, can be null</param>
/// <returns>the edge identified by the key</returns>
/// <exception cref="ArangoDBException"/>
/// <exception cref="com.arangodb.ArangoDBException"/>
public virtual T getEdge<T>(string key, DocumentReadOptions options
)
{
System.Type type = typeof(T);
return this.executor.execute(this.getEdgeRequest(key, options), getEdgeResponseDeserializer
(type));
}
/// <summary>
/// Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is
/// violated
/// </summary>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#replace-an-edge">API Documentation</a>
/// </seealso>
/// <param name="key">The key of the edge</param>
/// <param name="type">The type of the edge-document (POJO class, VPackSlice or String for Json)
/// </param>
/// <returns>information about the edge</returns>
/// <exception cref="ArangoDBException"/>
/// <exception cref="com.arangodb.ArangoDBException"/>
public virtual EdgeUpdateEntity replaceEdge<T>(string key, T
value)
{
return this.executor.execute(this.replaceEdgeRequest(key, value, new EdgeReplaceOptions
()), this.replaceEdgeResponseDeserializer(value));
}
/// <summary>
/// Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is
/// violated
/// </summary>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#replace-an-edge">API Documentation</a>
/// </seealso>
/// <param name="key">The key of the edge</param>
/// <param name="type">The type of the edge-document (POJO class, VPackSlice or String for Json)
/// </param>
/// <param name="options">Additional options, can be null</param>
/// <returns>information about the edge</returns>
/// <exception cref="ArangoDBException"/>
/// <exception cref="com.arangodb.ArangoDBException"/>
public virtual EdgeUpdateEntity replaceEdge<T>(string key, T
value, EdgeReplaceOptions options)
{
return this.executor.execute(this.replaceEdgeRequest(key, value, options), this.replaceEdgeResponseDeserializer
(value));
}
/// <summary>Partially updates the edge identified by document-key.</summary>
/// <remarks>
/// Partially updates the edge identified by document-key. The value must contain a document with the attributes to
/// patch (the patch document). All attributes from the patch document will be added to the existing document if they
/// do not yet exist, and overwritten in the existing document if they do exist there.
/// </remarks>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#modify-an-edge">API Documentation</a>
/// </seealso>
/// <param name="key">The key of the edge</param>
/// <param name="type">The type of the edge-document (POJO class, VPackSlice or String for Json)
/// </param>
/// <returns>information about the edge</returns>
/// <exception cref="ArangoDBException"/>
/// <exception cref="com.arangodb.ArangoDBException"/>
public virtual EdgeUpdateEntity updateEdge<T>(string key, T value
)
{
return this.executor.execute(this.updateEdgeRequest(key, value, new EdgeUpdateOptions
()), this.updateEdgeResponseDeserializer(value));
}
/// <summary>Partially updates the edge identified by document-key.</summary>
/// <remarks>
/// Partially updates the edge identified by document-key. The value must contain a document with the attributes to
/// patch (the patch document). All attributes from the patch document will be added to the existing document if they
/// do not yet exist, and overwritten in the existing document if they do exist there.
/// </remarks>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#modify-an-edge">API Documentation</a>
/// </seealso>
/// <param name="key">The key of the edge</param>
/// <param name="type">The type of the edge-document (POJO class, VPackSlice or String for Json)
/// </param>
/// <param name="options">Additional options, can be null</param>
/// <returns>information about the edge</returns>
/// <exception cref="ArangoDBException"/>
/// <exception cref="com.arangodb.ArangoDBException"/>
public virtual EdgeUpdateEntity updateEdge<T>(string key, T value
, EdgeUpdateOptions options)
{
return this.executor.execute(this.updateEdgeRequest(key, value, options), this.updateEdgeResponseDeserializer
(value));
}
/// <summary>Removes a edge</summary>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#remove-an-edge">API Documentation</a>
/// </seealso>
/// <param name="key">The key of the edge</param>
/// <exception cref="ArangoDBException"/>
/// <exception cref="ArangoDBException"/>
public virtual void deleteEdge(string key)
{
this.executor.execute(this.deleteEdgeRequest(key, new EdgeDeleteOptions(
)), typeof(java.lang.Void));
}
/// <summary>Removes a edge</summary>
/// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Edges.html#remove-an-edge">API Documentation</a>
/// </seealso>
/// <param name="key">The key of the edge</param>
/// <param name="options">Additional options, can be null</param>
/// <exception cref="ArangoDBException"/>
/// <exception cref="ArangoDBException"/>
public virtual void deleteEdge(string key, EdgeDeleteOptions options
)
{
this.executor.execute(this.deleteEdgeRequest(key, options),
typeof(java.lang.Void));
}
}
}
| |
// 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 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Linq;
using System.Collections.Generic;
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 Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SubscriptionInMethodOperations operations.
/// </summary>
internal partial class SubscriptionInMethodOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISubscriptionInMethodOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionInMethodOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SubscriptionInMethodOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// This should appear as a method parameter, use value '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> PostMethodLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = null, client-side validation should prevent you from
/// making this call
/// </summary>
/// <param name='subscriptionId'>
/// This should appear as a method parameter, use value null, client-side
/// validation should prvenet the call
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> PostMethodLocalNullWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/null/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// Should appear as a method parameter -use value '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> PostPathLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostPathLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/path/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// The subscriptionId, which appears in the path, the value is always
/// '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> PostSwaggerLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostSwaggerLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/swagger/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: This is the value class representing a Unicode character
** Char methods until we create this functionality.
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Char : IComparable, IConvertible
, IComparable<Char>, IEquatable<Char>
{
//
// Member Variables
//
internal char m_value;
//
// Public Constants
//
// The maximum character value.
public const char MaxValue = (char)0xFFFF;
// The minimum character value.
public const char MinValue = (char)0x00;
// Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space.
private readonly static byte[] categoryForLatin1 = {
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F
(byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027
(byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F
(byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037
(byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F
(byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F
(byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF
(byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF
};
// Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement.
private static bool IsLatin1(char ch)
{
return (ch <= '\x00ff');
}
// Return true for all characters below or equal U+007f, which is ASCII.
private static bool IsAscii(char ch)
{
return (ch <= '\x007f');
}
// Return the Unicode category for Unicode character <= 0x00ff.
private static UnicodeCategory GetLatin1UnicodeCategory(char ch)
{
Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
return (UnicodeCategory)(categoryForLatin1[(int)ch]);
}
//
// Private Constants
//
//
// Overriden Instance Methods
//
// Calculate a hashcode for a 2 byte Unicode character.
public override int GetHashCode()
{
return (int)m_value | ((int)m_value << 16);
}
// Used for comparing two boxed Char objects.
//
public override bool Equals(Object obj)
{
if (!(obj is Char))
{
return false;
}
return (m_value == ((Char)obj).m_value);
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(Char obj)
{
return m_value == obj;
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Char, this method throws an ArgumentException.
//
[Pure]
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (!(value is Char))
{
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeChar"));
}
return (m_value - ((Char)value).m_value);
}
[Pure]
public int CompareTo(Char value)
{
return (m_value - value);
}
// Overrides System.Object.ToString.
[Pure]
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Char.ToString(m_value);
}
[Pure]
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Char.ToString(m_value);
}
//
// Formatting Methods
//
/*===================================ToString===================================
**This static methods takes a character and returns the String representation of it.
==============================================================================*/
// Provides a string representation of a character.
[Pure]
public static string ToString(char c) => string.CreateFromChar(c);
public static char Parse(String s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
if (s.Length != 1)
{
throw new FormatException(Environment.GetResourceString("Format_NeedSingleChar"));
}
return s[0];
}
public static bool TryParse(String s, out Char result)
{
result = '\0';
if (s == null)
{
return false;
}
if (s.Length != 1)
{
return false;
}
result = s[0];
return true;
}
//
// Static Methods
//
/*=================================ISDIGIT======================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a digit. **
==============================================================================*/
// Determines whether a character is a digit.
[Pure]
public static bool IsDigit(char c)
{
if (IsLatin1(c))
{
return (c >= '0' && c <= '9');
}
return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber);
}
/*=================================CheckLetter=====================================
** Check if the specified UnicodeCategory belongs to the letter categories.
==============================================================================*/
internal static bool CheckLetter(UnicodeCategory uc)
{
switch (uc)
{
case (UnicodeCategory.UppercaseLetter):
case (UnicodeCategory.LowercaseLetter):
case (UnicodeCategory.TitlecaseLetter):
case (UnicodeCategory.ModifierLetter):
case (UnicodeCategory.OtherLetter):
return (true);
}
return (false);
}
/*=================================ISLETTER=====================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a letter. **
==============================================================================*/
// Determines whether a character is a letter.
[Pure]
public static bool IsLetter(char c)
{
if (IsLatin1(c))
{
if (IsAscii(c))
{
c |= (char)0x20;
return ((c >= 'a' && c <= 'z'));
}
return (CheckLetter(GetLatin1UnicodeCategory(c)));
}
return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c)));
}
private static bool IsWhiteSpaceLatin1(char c)
{
// There are characters which belong to UnicodeCategory.Control but are considered as white spaces.
// We use code point comparisons for these characters here as a temporary fix.
// U+0009 = <control> HORIZONTAL TAB
// U+000a = <control> LINE FEED
// U+000b = <control> VERTICAL TAB
// U+000c = <contorl> FORM FEED
// U+000d = <control> CARRIAGE RETURN
// U+0085 = <control> NEXT LINE
// U+00a0 = NO-BREAK SPACE
if ((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085')
{
return (true);
}
return (false);
}
/*===============================ISWHITESPACE===================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a whitespace character. **
==============================================================================*/
// Determines whether a character is whitespace.
[Pure]
public static bool IsWhiteSpace(char c)
{
if (IsLatin1(c))
{
return (IsWhiteSpaceLatin1(c));
}
return CharUnicodeInfo.IsWhiteSpace(c);
}
/*===================================IsUpper====================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an uppercase character.
==============================================================================*/
// Determines whether a character is upper-case.
[Pure]
public static bool IsUpper(char c)
{
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= 'A' && c <= 'Z');
}
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
}
return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
}
/*===================================IsLower====================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an lowercase character.
==============================================================================*/
// Determines whether a character is lower-case.
[Pure]
public static bool IsLower(char c)
{
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= 'a' && c <= 'z');
}
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
}
return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
}
internal static bool CheckPunctuation(UnicodeCategory uc)
{
switch (uc)
{
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.OtherPunctuation:
return (true);
}
return (false);
}
/*================================IsPunctuation=================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an punctuation mark
==============================================================================*/
// Determines whether a character is a punctuation mark.
[Pure]
public static bool IsPunctuation(char c)
{
if (IsLatin1(c))
{
return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
}
return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c)));
}
/*=================================CheckLetterOrDigit=====================================
** Check if the specified UnicodeCategory belongs to the letter or digit categories.
==============================================================================*/
internal static bool CheckLetterOrDigit(UnicodeCategory uc)
{
switch (uc)
{
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.DecimalDigitNumber:
return (true);
}
return (false);
}
// Determines whether a character is a letter or a digit.
[Pure]
public static bool IsLetterOrDigit(char c)
{
if (IsLatin1(c))
{
return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c)));
}
return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c)));
}
/*===================================ToUpper====================================
**
==============================================================================*/
// Converts a character to upper-case for the specified culture.
// <;<;Not fully implemented>;>;
public static char ToUpper(char c, CultureInfo culture)
{
if (culture == null)
throw new ArgumentNullException(nameof(culture));
Contract.EndContractBlock();
return culture.TextInfo.ToUpper(c);
}
/*=================================TOUPPER======================================
**A wrapper for Char.toUpperCase. Converts character c to its **
**uppercase equivalent. If c is already an uppercase character or is not an **
**alphabetic, nothing happens. **
==============================================================================*/
// Converts a character to upper-case for the default culture.
//
public static char ToUpper(char c)
{
return ToUpper(c, CultureInfo.CurrentCulture);
}
// Converts a character to upper-case for invariant culture.
public static char ToUpperInvariant(char c)
{
return ToUpper(c, CultureInfo.InvariantCulture);
}
/*===================================ToLower====================================
**
==============================================================================*/
// Converts a character to lower-case for the specified culture.
// <;<;Not fully implemented>;>;
public static char ToLower(char c, CultureInfo culture)
{
if (culture == null)
throw new ArgumentNullException(nameof(culture));
Contract.EndContractBlock();
return culture.TextInfo.ToLower(c);
}
/*=================================TOLOWER======================================
**A wrapper for Char.toLowerCase. Converts character c to its **
**lowercase equivalent. If c is already a lowercase character or is not an **
**alphabetic, nothing happens. **
==============================================================================*/
// Converts a character to lower-case for the default culture.
public static char ToLower(char c)
{
return ToLower(c, CultureInfo.CurrentCulture);
}
// Converts a character to lower-case for invariant culture.
public static char ToLowerInvariant(char c)
{
return ToLower(c, CultureInfo.InvariantCulture);
}
//
// IConvertible implementation
//
[Pure]
public TypeCode GetTypeCode()
{
return TypeCode.Char;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Boolean"));
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider)
{
return m_value;
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Single"));
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Double"));
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Decimal"));
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
public static bool IsControl(char c)
{
if (IsLatin1(c))
{
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
}
return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control);
}
public static bool IsControl(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control);
}
public static bool IsDigit(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (c >= '0' && c <= '9');
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber);
}
public static bool IsLetter(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
if (IsAscii(c))
{
c |= (char)0x20;
return ((c >= 'a' && c <= 'z'));
}
return (CheckLetter(GetLatin1UnicodeCategory(c)));
}
return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
public static bool IsLetterOrDigit(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return CheckLetterOrDigit(GetLatin1UnicodeCategory(c));
}
return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index));
}
public static bool IsLower(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= 'a' && c <= 'z');
}
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter);
}
/*=================================CheckNumber=====================================
** Check if the specified UnicodeCategory belongs to the number categories.
==============================================================================*/
internal static bool CheckNumber(UnicodeCategory uc)
{
switch (uc)
{
case (UnicodeCategory.DecimalDigitNumber):
case (UnicodeCategory.LetterNumber):
case (UnicodeCategory.OtherNumber):
return (true);
}
return (false);
}
public static bool IsNumber(char c)
{
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= '0' && c <= '9');
}
return (CheckNumber(GetLatin1UnicodeCategory(c)));
}
return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c)));
}
public static bool IsNumber(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= '0' && c <= '9');
}
return (CheckNumber(GetLatin1UnicodeCategory(c)));
}
return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
////////////////////////////////////////////////////////////////////////
//
// IsPunctuation
//
// Determines if the given character is a punctuation character.
//
////////////////////////////////////////////////////////////////////////
public static bool IsPunctuation(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
}
return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
/*================================= CheckSeparator ============================
** Check if the specified UnicodeCategory belongs to the seprator categories.
==============================================================================*/
internal static bool CheckSeparator(UnicodeCategory uc)
{
switch (uc)
{
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
return (true);
}
return (false);
}
private static bool IsSeparatorLatin1(char c)
{
// U+00a0 = NO-BREAK SPACE
// There is no LineSeparator or ParagraphSeparator in Latin 1 range.
return (c == '\x0020' || c == '\x00a0');
}
public static bool IsSeparator(char c)
{
if (IsLatin1(c))
{
return (IsSeparatorLatin1(c));
}
return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c)));
}
public static bool IsSeparator(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (IsSeparatorLatin1(c));
}
return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
[Pure]
public static bool IsSurrogate(char c)
{
return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END);
}
[Pure]
public static bool IsSurrogate(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return (IsSurrogate(s[index]));
}
/*================================= CheckSymbol ============================
** Check if the specified UnicodeCategory belongs to the symbol categories.
==============================================================================*/
internal static bool CheckSymbol(UnicodeCategory uc)
{
switch (uc)
{
case (UnicodeCategory.MathSymbol):
case (UnicodeCategory.CurrencySymbol):
case (UnicodeCategory.ModifierSymbol):
case (UnicodeCategory.OtherSymbol):
return (true);
}
return (false);
}
public static bool IsSymbol(char c)
{
if (IsLatin1(c))
{
return (CheckSymbol(GetLatin1UnicodeCategory(c)));
}
return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c)));
}
public static bool IsSymbol(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (IsLatin1(s[index]))
{
return (CheckSymbol(GetLatin1UnicodeCategory(s[index])));
}
return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
public static bool IsUpper(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= 'A' && c <= 'Z');
}
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter);
}
public static bool IsWhiteSpace(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (IsLatin1(s[index]))
{
return IsWhiteSpaceLatin1(s[index]);
}
return CharUnicodeInfo.IsWhiteSpace(s, index);
}
public static UnicodeCategory GetUnicodeCategory(char c)
{
if (IsLatin1(c))
{
return (GetLatin1UnicodeCategory(c));
}
return CharUnicodeInfo.InternalGetUnicodeCategory(c);
}
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (IsLatin1(s[index]))
{
return (GetLatin1UnicodeCategory(s[index]));
}
return CharUnicodeInfo.InternalGetUnicodeCategory(s, index);
}
public static double GetNumericValue(char c)
{
return CharUnicodeInfo.GetNumericValue(c);
}
public static double GetNumericValue(String s, int index)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return CharUnicodeInfo.GetNumericValue(s, index);
}
/*================================= IsHighSurrogate ============================
** Check if a char is a high surrogate.
==============================================================================*/
[Pure]
public static bool IsHighSurrogate(char c)
{
return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END));
}
[Pure]
public static bool IsHighSurrogate(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return (IsHighSurrogate(s[index]));
}
/*================================= IsLowSurrogate ============================
** Check if a char is a low surrogate.
==============================================================================*/
[Pure]
public static bool IsLowSurrogate(char c)
{
return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END));
}
[Pure]
public static bool IsLowSurrogate(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return (IsLowSurrogate(s[index]));
}
/*================================= IsSurrogatePair ============================
** Check if the string specified by the index starts with a surrogate pair.
==============================================================================*/
[Pure]
public static bool IsSurrogatePair(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (index + 1 < s.Length)
{
return (IsSurrogatePair(s[index], s[index + 1]));
}
return (false);
}
[Pure]
public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate)
{
return ((highSurrogate >= CharUnicodeInfo.HIGH_SURROGATE_START && highSurrogate <= CharUnicodeInfo.HIGH_SURROGATE_END) &&
(lowSurrogate >= CharUnicodeInfo.LOW_SURROGATE_START && lowSurrogate <= CharUnicodeInfo.LOW_SURROGATE_END));
}
internal const int UNICODE_PLANE00_END = 0x00ffff;
// The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
internal const int UNICODE_PLANE01_START = 0x10000;
// The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode.
// Plane 16 contains 0x100000 ~ 0x10ffff.
internal const int UNICODE_PLANE16_END = 0x10ffff;
internal const int HIGH_SURROGATE_START = 0x00d800;
internal const int LOW_SURROGATE_END = 0x00dfff;
/*================================= ConvertFromUtf32 ============================
** Convert an UTF32 value into a surrogate pair.
==============================================================================*/
public static String ConvertFromUtf32(int utf32)
{
// For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They
// are considered as irregular code unit sequence, but they are not illegal.
if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END))
{
throw new ArgumentOutOfRangeException(nameof(utf32), Environment.GetResourceString("ArgumentOutOfRange_InvalidUTF32"));
}
Contract.EndContractBlock();
if (utf32 < UNICODE_PLANE01_START)
{
// This is a BMP character.
return (Char.ToString((char)utf32));
}
unsafe
{
// This is a supplementary character. Convert it to a surrogate pair in UTF-16.
utf32 -= UNICODE_PLANE01_START;
uint surrogate = 0; // allocate 2 chars worth of stack space
char* address = (char*)&surrogate;
address[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START);
address[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START);
return new string(address, 0, 2);
}
}
/*=============================ConvertToUtf32===================================
** Convert a surrogate pair to UTF32 value
==============================================================================*/
public static int ConvertToUtf32(char highSurrogate, char lowSurrogate)
{
if (!IsHighSurrogate(highSurrogate))
{
throw new ArgumentOutOfRangeException(nameof(highSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidHighSurrogate"));
}
if (!IsLowSurrogate(lowSurrogate))
{
throw new ArgumentOutOfRangeException(nameof(lowSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidLowSurrogate"));
}
Contract.EndContractBlock();
return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START);
}
/*=============================ConvertToUtf32===================================
** Convert a character or a surrogate pair starting at index of the specified string
** to UTF32 value.
** The char pointed by index should be a surrogate pair or a BMP character.
** This method throws if a high-surrogate is not followed by a low surrogate.
** This method throws if a low surrogate is seen without preceding a high-surrogate.
==============================================================================*/
public static int ConvertToUtf32(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
// Check if the character at index is a high surrogate.
int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x7ff)
{
// Found a surrogate char.
if (temp1 <= 0x3ff)
{
// Found a high surrogate.
if (index < s.Length - 1)
{
int temp2 = (int)s[index + 1] - CharUnicodeInfo.LOW_SURROGATE_START;
if (temp2 >= 0 && temp2 <= 0x3ff)
{
// Found a low surrogate.
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s));
}
}
else
{
// Found a high surrogate at the end of the string.
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s));
}
}
else
{
// Find a low surrogate at the character pointed by index.
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidLowSurrogate", index), nameof(s));
}
}
// Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters.
return ((int)s[index]);
}
}
}
| |
#pragma warning disable 169 // ReSharper disable InconsistentNaming
#pragma warning disable IDE1006 // Naming Styles
namespace NEventStore
{
using System;
using System.Collections.Generic;
using System.Linq;
using NEventStore.Persistence;
using NEventStore.Persistence.AcceptanceTests;
using NEventStore.Persistence.AcceptanceTests.BDD;
using FluentAssertions;
#if MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
#if NUNIT
using NUnit.Framework;
#endif
#if XUNIT
using Xunit;
using Xunit.Should;
#endif
public class OptimisticPipelineHookTests
{
#if MSTEST
[TestClass]
#endif
public class when_committing_with_a_sequence_beyond_the_known_end_of_a_stream : using_commit_hooks
{
private const int HeadStreamRevision = 5;
private const int HeadCommitSequence = 1;
private const int ExpectedNextCommitSequence = HeadCommitSequence + 1;
private const int BeyondEndOfStreamCommitSequence = ExpectedNextCommitSequence + 1;
private ICommit _alreadyCommitted;
private CommitAttempt _beyondEndOfStream;
private Exception _thrown;
protected override void Context()
{
_alreadyCommitted = BuildCommitStub(1, HeadStreamRevision, HeadCommitSequence);
_beyondEndOfStream = BuildCommitAttemptStub(HeadStreamRevision + 1, BeyondEndOfStreamCommitSequence);
Hook.PostCommit(_alreadyCommitted);
}
protected override void Because()
{
_thrown = Catch.Exception(() => Hook.PreCommit(_beyondEndOfStream));
}
[Fact]
public void should_throw_a_PersistenceException()
{
_thrown.Should().BeOfType<StorageException>();
}
}
#if MSTEST
[TestClass]
#endif
public class when_committing_with_a_revision_beyond_the_known_end_of_a_stream : using_commit_hooks
{
private const int HeadCommitSequence = 1;
private const int HeadStreamRevision = 1;
private const int NumberOfEventsBeingCommitted = 1;
private const int ExpectedNextStreamRevision = HeadStreamRevision + 1 + NumberOfEventsBeingCommitted;
private const int BeyondEndOfStreamRevision = ExpectedNextStreamRevision + 1;
private ICommit _alreadyCommitted;
private CommitAttempt _beyondEndOfStream;
private Exception _thrown;
protected override void Context()
{
_alreadyCommitted = BuildCommitStub(1, HeadStreamRevision, HeadCommitSequence);
_beyondEndOfStream = BuildCommitAttemptStub(BeyondEndOfStreamRevision, HeadCommitSequence + 1);
Hook.PostCommit(_alreadyCommitted);
}
protected override void Because()
{
_thrown = Catch.Exception(() => Hook.PreCommit(_beyondEndOfStream));
}
[Fact]
public void should_throw_a_PersistenceException()
{
_thrown.Should().BeOfType<StorageException>();
}
}
#if MSTEST
[TestClass]
#endif
public class when_committing_with_a_sequence_less_or_equal_to_the_most_recent_sequence_for_the_stream : using_commit_hooks
{
private const int HeadStreamRevision = 42;
private const int HeadCommitSequence = 42;
private const int DupliateCommitSequence = HeadCommitSequence;
private CommitAttempt Attempt;
private ICommit Committed;
private Exception thrown;
protected override void Context()
{
Committed = BuildCommitStub(1, HeadStreamRevision, HeadCommitSequence);
Attempt = BuildCommitAttemptStub(HeadStreamRevision + 1, DupliateCommitSequence);
Hook.PostCommit(Committed);
}
protected override void Because()
{
thrown = Catch.Exception(() => Hook.PreCommit(Attempt));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
thrown.Should().BeOfType<ConcurrencyException>();
}
[Fact]
public void ConcurrencyException_should_have_good_message()
{
thrown.Message.Should().Contain(Attempt.StreamId);
thrown.Message.Should().Contain("CommitSequence [" + Attempt.CommitSequence);
}
}
#if MSTEST
[TestClass]
#endif
public class when_committing_with_a_revision_less_or_equal_to_than_the_most_recent_revision_read_for_the_stream : using_commit_hooks
{
private const int HeadStreamRevision = 3;
private const int HeadCommitSequence = 2;
private const int DuplicateStreamRevision = HeadStreamRevision;
private ICommit _committed;
private CommitAttempt _failedAttempt;
private Exception _thrown;
protected override void Context()
{
_committed = BuildCommitStub(1, HeadStreamRevision, HeadCommitSequence);
_failedAttempt = BuildCommitAttemptStub(DuplicateStreamRevision, HeadCommitSequence + 1);
Hook.PostCommit(_committed);
}
protected override void Because()
{
_thrown = Catch.Exception(() => Hook.PreCommit(_failedAttempt));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
_thrown.Should().BeOfType<ConcurrencyException>();
}
[Fact]
public void ConcurrencyException_should_have_good_message()
{
_thrown.Message.Should().Contain(_failedAttempt.StreamId);
_thrown.Message.Should().Contain("StreamRevision [" + _failedAttempt.CommitSequence);
}
}
#if MSTEST
[TestClass]
#endif
public class when_committing_with_a_commit_sequence_less_than_or_equal_to_the_most_recent_commit_for_the_stream : using_commit_hooks
{
private const int DuplicateCommitSequence = 1;
private CommitAttempt _failedAttempt;
private ICommit _successfulAttempt;
private Exception _thrown;
protected override void Context()
{
_successfulAttempt = BuildCommitStub(1, 1, DuplicateCommitSequence);
_failedAttempt = BuildCommitAttemptStub(2, DuplicateCommitSequence);
Hook.PostCommit(_successfulAttempt);
}
protected override void Because()
{
_thrown = Catch.Exception(() => Hook.PreCommit(_failedAttempt));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
_thrown.Should().BeOfType<ConcurrencyException>();
}
[Fact]
public void ConcurrencyException_should_have_good_message()
{
_thrown.Message.Should().Contain(_failedAttempt.StreamId);
_thrown.Message.Should().Contain("CommitSequence [" + _failedAttempt.CommitSequence);
}
}
#if MSTEST
[TestClass]
#endif
public class when_committing_with_a_stream_revision_less_than_or_equal_to_the_most_recent_commit_for_the_stream : using_commit_hooks
{
private const int DuplicateStreamRevision = 2;
private CommitAttempt _failedAttempt;
private ICommit _successfulAttempt;
private Exception _thrown;
protected override void Context()
{
_successfulAttempt = BuildCommitStub(1, DuplicateStreamRevision, 1);
_failedAttempt = BuildCommitAttemptStub(DuplicateStreamRevision, 2);
Hook.PostCommit(_successfulAttempt);
}
protected override void Because()
{
_thrown = Catch.Exception(() => Hook.PreCommit(_failedAttempt));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
_thrown.Should().BeOfType<ConcurrencyException>();
}
[Fact]
public void Concurrency_exception_should_have_good_message()
{
_thrown.Message.Should().Contain(_failedAttempt.StreamId);
_thrown.Message.Should().Contain(_failedAttempt.StreamRevision.ToString());
}
}
public class when_tracking_commits : SpecificationBase
{
private const int MaxStreamsToTrack = 2;
private ICommit[] _trackedCommitAttempts;
private OptimisticPipelineHook _hook;
protected override void Context()
{
_trackedCommitAttempts = new[]
{
BuildCommit(1, Guid.NewGuid(), Guid.NewGuid()),
BuildCommit(2, Guid.NewGuid(), Guid.NewGuid()),
BuildCommit(3, Guid.NewGuid(), Guid.NewGuid())
};
_hook = new OptimisticPipelineHook(MaxStreamsToTrack);
}
protected override void Because()
{
foreach (var commit in _trackedCommitAttempts)
{
_hook.Track(commit);
}
}
[Fact]
public void should_only_contain_streams_explicitly_tracked()
{
ICommit untracked = BuildCommit(4, Guid.Empty, _trackedCommitAttempts[0].CommitId);
_hook.Contains(untracked).Should().BeFalse();
}
[Fact]
public void should_find_tracked_streams()
{
var lastCommit = _trackedCommitAttempts.Last();
ICommit stillTracked = BuildCommit(lastCommit.CheckpointToken, lastCommit.StreamId, lastCommit.CommitId);
_hook.Contains(stillTracked).Should().BeTrue();
}
[Fact]
public void should_only_track_the_specified_number_of_streams()
{
var firstCommit = _trackedCommitAttempts[0];
ICommit droppedFromTracking = BuildCommit(firstCommit.CheckpointToken, firstCommit.StreamId, firstCommit.CommitId);
_hook.Contains(droppedFromTracking).Should().BeFalse();
}
private ICommit BuildCommit(long checkpointToken, Guid streamId, Guid commitId)
{
return BuildCommit(checkpointToken, streamId.ToString(), commitId);
}
private ICommit BuildCommit(long checkpointToken, string streamId, Guid commitId)
{
return new Commit(Bucket.Default, streamId, 1, commitId, 1, SystemTime.UtcNow, checkpointToken, null, null);
}
}
#if MSTEST
[TestClass]
#endif
public class when_purging : SpecificationBase
{
private ICommit _trackedCommit;
private OptimisticPipelineHook _hook;
protected override void Context()
{
_trackedCommit = BuildCommit(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
_hook = new OptimisticPipelineHook();
_hook.Track(_trackedCommit);
}
protected override void Because()
{
_hook.OnPurge();
}
[Fact]
public void should_not_track_commit()
{
_hook.Contains(_trackedCommit).Should().BeFalse();
}
private ICommit BuildCommit(Guid bucketId, Guid streamId, Guid commitId)
{
return new Commit(bucketId.ToString(), streamId.ToString(), 0, commitId, 0, SystemTime.UtcNow,
1, null, null);
}
}
#if MSTEST
[TestClass]
#endif
public class when_purging_a_bucket : SpecificationBase
{
private ICommit _trackedCommitBucket1;
private ICommit _trackedCommitBucket2;
private OptimisticPipelineHook _hook;
protected override void Context()
{
_trackedCommitBucket1 = BuildCommit(1, Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
_trackedCommitBucket2 = BuildCommit(2, Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
_hook = new OptimisticPipelineHook();
_hook.Track(_trackedCommitBucket1);
_hook.Track(_trackedCommitBucket2);
}
protected override void Because()
{
_hook.OnPurge(_trackedCommitBucket1.BucketId);
}
[Fact]
public void should_not_track_the_commit_in_bucket()
{
_hook.Contains(_trackedCommitBucket1).Should().BeFalse();
}
[Fact]
public void should_track_the_commit_in_other_bucket()
{
_hook.Contains(_trackedCommitBucket2).Should().BeTrue();
}
private ICommit BuildCommit(long checkpointToken, Guid bucketId, Guid streamId, Guid commitId)
{
return new Commit(bucketId.ToString(), streamId.ToString(), 0, commitId, 0, SystemTime.UtcNow,
checkpointToken, null, null);
}
}
#if MSTEST
[TestClass]
#endif
public class when_deleting_a_stream : SpecificationBase
{
private ICommit _trackedCommit;
private ICommit _trackedCommitDeleted;
private OptimisticPipelineHook _hook;
private readonly Guid _bucketId = Guid.NewGuid();
private readonly Guid _streamIdDeleted = Guid.NewGuid();
protected override void Context()
{
_trackedCommit = BuildCommit(1, _bucketId, Guid.NewGuid(), Guid.NewGuid());
_trackedCommitDeleted = BuildCommit(2, _bucketId, _streamIdDeleted, Guid.NewGuid());
_hook = new OptimisticPipelineHook();
_hook.Track(_trackedCommit);
_hook.Track(_trackedCommitDeleted);
}
protected override void Because()
{
_hook.OnDeleteStream(_trackedCommitDeleted.BucketId, _trackedCommitDeleted.StreamId);
}
[Fact]
public void should_not_track_the_commit_in_the_deleted_stream()
{
_hook.Contains(_trackedCommitDeleted).Should().BeFalse();
}
[Fact]
public void should_track_the_commit_that_is_not_in_the_deleted_stream()
{
_hook.Contains(_trackedCommit).Should().BeTrue();
}
private ICommit BuildCommit(long checkpointToken, Guid bucketId, Guid streamId, Guid commitId)
{
return new Commit(bucketId.ToString(), streamId.ToString(), 0, commitId, 0, SystemTime.UtcNow,
checkpointToken, null, null);
}
}
public abstract class using_commit_hooks : SpecificationBase
{
protected readonly OptimisticPipelineHook Hook = new OptimisticPipelineHook();
private readonly string _streamId = Guid.NewGuid().ToString();
protected CommitAttempt BuildCommitAttempt(Guid commitId)
{
return new CommitAttempt(_streamId, 1, commitId, 1, SystemTime.UtcNow, null, null);
}
protected ICommit BuildCommitStub(long checkpointToken, int streamRevision, int commitSequence)
{
List<EventMessage> events = new[] { new EventMessage() }.ToList();
return new Commit(Bucket.Default, _streamId, streamRevision, Guid.NewGuid(), commitSequence, SystemTime.UtcNow, checkpointToken, null, events);
}
protected CommitAttempt BuildCommitAttemptStub(int streamRevision, int commitSequence)
{
EventMessage[] events = new[] { new EventMessage() };
return new CommitAttempt(Bucket.Default, _streamId, streamRevision, Guid.NewGuid(), commitSequence, SystemTime.UtcNow, null, events);
}
protected ICommit BuildCommitStub(long checkpointToken, Guid commitId, int streamRevision, int commitSequence)
{
List<EventMessage> events = new[] { new EventMessage() }.ToList();
return new Commit(Bucket.Default, _streamId, streamRevision, commitId, commitSequence, SystemTime.UtcNow, checkpointToken, null, events);
}
}
}
}
#pragma warning restore 169 // ReSharper enable InconsistentNaming
#pragma warning restore IDE1006 // Naming Styles
| |
//
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Content;
using Android.Content.Res;
using Android.Database;
using Android.Provider;
using StructuredName = Android.Provider.ContactsContract.CommonDataKinds.StructuredName;
using StructuredPostal = Android.Provider.ContactsContract.CommonDataKinds.StructuredPostal;
using CommonColumns = Android.Provider.ContactsContract.CommonDataKinds.CommonColumns;
using Uri = Android.Net.Uri;
using InstantMessaging = Android.Provider.ContactsContract.CommonDataKinds.Im;
using OrganizationData = Android.Provider.ContactsContract.CommonDataKinds.Organization;
using WebsiteData = Android.Provider.ContactsContract.CommonDataKinds.Website;
using Relation = Android.Provider.ContactsContract.CommonDataKinds.Relation;
using Contacts.Plugin.Abstractions;
using System.Threading.Tasks;
namespace Contacts.Plugin
{
internal static class ContactHelper
{
internal static IEnumerable<Task<Contact>> GetContacts(bool rawContacts, ContentResolver content, Resources resources)
{
Uri curi = (rawContacts)
? ContactsContract.RawContacts.ContentUri
: ContactsContract.Contacts.ContentUri;
ICursor cursor = null;
try
{
cursor = content.Query(curi, null, null, null, null);
if (cursor == null)
yield break;
Task.Run(()=>{
try
{
return GetContacts(cursor, rawContacts, content, resources, 256);
}
finally
{
if (cursor != null)
cursor.Close();
}
});
}
finally
{
}
}
internal static IEnumerable<Contact> GetContacts(ICursor cursor, bool rawContacts, ContentResolver content, Resources resources, int batchSize)
{
if (cursor == null)
yield break;
string column = (rawContacts)
? ContactsContract.RawContactsColumns.ContactId
: ContactsContract.ContactsColumns.LookupKey;
string[] ids = new string[batchSize];
int columnIndex = cursor.GetColumnIndex(column);
HashSet<string> uniques = new HashSet<string>();
int i = 0;
while (cursor.MoveToNext())
{
if (i == batchSize)
{
i = 0;
foreach (Contact c in GetContacts(rawContacts, content, resources, ids))
yield return c;
}
string id = cursor.GetString(columnIndex);
if (uniques.Contains(id))
continue;
uniques.Add(id);
ids[i++] = id;
}
if (i > 0)
{
foreach (Contact c in GetContacts(rawContacts, content, resources, ids.Take(i).ToArray()))
yield return c;
}
}
internal static IEnumerable<Contact> GetContacts(bool rawContacts, ContentResolver content, Resources resources, string[] ids)
{
ICursor c = null;
string column = (rawContacts)
? ContactsContract.RawContactsColumns.ContactId
: ContactsContract.ContactsColumns.LookupKey;
StringBuilder whereb = new StringBuilder();
for (int i = 0; i < ids.Length; i++)
{
if (i > 0)
whereb.Append(" OR ");
whereb.Append(column);
whereb.Append("=?");
}
int x = 0;
var map = new Dictionary<string, Contact>(ids.Length);
try
{
Contact currentContact = null;
c = content.Query(ContactsContract.Data.ContentUri, null, whereb.ToString(), ids, ContactsContract.ContactsColumns.LookupKey);
if (c == null)
yield break;
int idIndex = c.GetColumnIndex(column);
int dnIndex = c.GetColumnIndex(ContactsContract.ContactsColumns.DisplayName);
while (c.MoveToNext())
{
string id = c.GetString(idIndex);
if (currentContact == null || currentContact.Id != id)
{
// We need to yield these in the original ID order
if (currentContact != null)
{
if (currentContact.Id == ids[x])
{
yield return currentContact;
x++;
}
else
map.Add(currentContact.Id, currentContact);
}
currentContact = new Contact(id, !rawContacts)
{
Tag = content
};
currentContact.DisplayName = c.GetString(dnIndex);
}
FillContactWithRow(resources, currentContact, c);
}
if (currentContact != null)
map.Add(currentContact.Id, currentContact);
for (; x < ids.Length; x++)
yield return map[ids[x]];
}
finally
{
if (c != null)
c.Close();
}
}
internal static Contact GetContact(bool rawContact, ContentResolver content, Resources resources, ICursor cursor)
{
string id = (rawContact)
? cursor.GetString(cursor.GetColumnIndex(ContactsContract.RawContactsColumns.ContactId))
: cursor.GetString(cursor.GetColumnIndex(ContactsContract.ContactsColumns.LookupKey));
var contact = new Contact(id, !rawContact)
{
Tag = content
};
contact.DisplayName = GetString(cursor, ContactsContract.ContactsColumns.DisplayName);
FillContactExtras(rawContact, content, resources, id, contact);
return contact;
}
internal static void FillContactExtras(bool rawContact, ContentResolver content, Resources resources, string recordId, Contact contact)
{
ICursor c = null;
string column = (rawContact)
? ContactsContract.RawContactsColumns.ContactId
: ContactsContract.ContactsColumns.LookupKey;
try
{
c = content.Query(ContactsContract.Data.ContentUri, null, column + " = ?", new[] { recordId }, null);
if (c == null)
return;
while (c.MoveToNext())
FillContactWithRow(resources, contact, c);
}
finally
{
if (c != null)
c.Close();
}
}
private static void FillContactWithRow(Resources resources, Contact contact, ICursor c)
{
string dataType = c.GetString(c.GetColumnIndex(ContactsContract.DataColumns.Mimetype));
switch (dataType)
{
case ContactsContract.CommonDataKinds.Nickname.ContentItemType:
contact.Nickname = c.GetString(c.GetColumnIndex(ContactsContract.CommonDataKinds.Nickname.Name));
break;
case StructuredName.ContentItemType:
contact.Prefix = c.GetString(StructuredName.Prefix);
contact.FirstName = c.GetString(StructuredName.GivenName);
contact.MiddleName = c.GetString(StructuredName.MiddleName);
contact.LastName = c.GetString(StructuredName.FamilyName);
contact.Suffix = c.GetString(StructuredName.Suffix);
break;
case ContactsContract.CommonDataKinds.Phone.ContentItemType:
contact.Phones.Add(GetPhone(c, resources));
break;
case ContactsContract.CommonDataKinds.Email.ContentItemType:
contact.Emails.Add(GetEmail(c, resources));
break;
case ContactsContract.CommonDataKinds.Note.ContentItemType:
contact.Notes.Add(GetNote(c, resources));
break;
case ContactsContract.CommonDataKinds.Organization.ContentItemType:
contact.Organizations.Add(GetOrganization(c, resources));
break;
case StructuredPostal.ContentItemType:
contact.Addresses.Add(GetAddress(c, resources));
break;
case InstantMessaging.ContentItemType:
contact.InstantMessagingAccounts.Add(GetImAccount(c, resources));
break;
case WebsiteData.ContentItemType:
contact.Websites.Add(GetWebsite(c, resources));
break;
case Relation.ContentItemType:
contact.Relationships.Add(GetRelationship(c, resources));
break;
}
}
internal static Note GetNote(ICursor c, Resources resources)
{
return new Note { Contents = GetString(c, ContactsContract.DataColumns.Data1) };
}
internal static Relationship GetRelationship(ICursor c, Resources resources)
{
Relationship r = new Relationship { Name = c.GetString(Relation.Name) };
RelationDataKind rtype = (RelationDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type));
switch (rtype)
{
case RelationDataKind.DomesticPartner:
case RelationDataKind.Spouse:
case RelationDataKind.Friend:
r.Type = RelationshipType.SignificantOther;
break;
case RelationDataKind.Child:
r.Type = RelationshipType.Child;
break;
default:
r.Type = RelationshipType.Other;
break;
}
return r;
}
internal static InstantMessagingAccount GetImAccount(ICursor c, Resources resources)
{
InstantMessagingAccount ima = new InstantMessagingAccount();
ima.Account = c.GetString(CommonColumns.Data);
//IMTypeDataKind imKind = (IMTypeDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type));
//ima.Type = imKind.ToInstantMessagingType();
//ima.Label = InstantMessaging.GetTypeLabel (resources, imKind, c.GetString (CommonColumns.Label));
IMProtocolDataKind serviceKind = (IMProtocolDataKind)c.GetInt(c.GetColumnIndex(InstantMessaging.Protocol));
ima.Service = serviceKind.ToInstantMessagingService();
ima.ServiceLabel = (serviceKind != IMProtocolDataKind.Custom)
? InstantMessaging.GetProtocolLabel(resources, serviceKind, String.Empty)
: c.GetString(InstantMessaging.CustomProtocol);
return ima;
}
internal static Address GetAddress(ICursor c, Resources resources)
{
Address a = new Address();
a.Country = c.GetString(StructuredPostal.Country);
a.Region = c.GetString(StructuredPostal.Region);
a.City = c.GetString(StructuredPostal.City);
a.PostalCode = c.GetString(StructuredPostal.Postcode);
AddressDataKind kind = (AddressDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type));
a.Type = kind.ToAddressType();
a.Label = (kind != AddressDataKind.Custom)
? StructuredPostal.GetTypeLabel(resources, kind, String.Empty)
: c.GetString(CommonColumns.Label);
string street = c.GetString(StructuredPostal.Street);
string pobox = c.GetString(StructuredPostal.Pobox);
if (street != null)
a.StreetAddress = street;
if (pobox != null)
{
if (street != null)
a.StreetAddress += Environment.NewLine;
a.StreetAddress += pobox;
}
return a;
}
internal static Phone GetPhone(ICursor c, Resources resources)
{
Phone p = new Phone();
p.Number = GetString(c, ContactsContract.CommonDataKinds.Phone.Number);
PhoneDataKind pkind = (PhoneDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type));
p.Type = pkind.ToPhoneType();
p.Label = (pkind != PhoneDataKind.Custom)
? ContactsContract.CommonDataKinds.Phone.GetTypeLabel(resources, pkind, String.Empty)
: c.GetString(CommonColumns.Label);
return p;
}
internal static Email GetEmail(ICursor c, Resources resources)
{
Email e = new Email();
e.Address = c.GetString(ContactsContract.DataColumns.Data1);
EmailDataKind ekind = (EmailDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type));
e.Type = ekind.ToEmailType();
e.Label = (ekind != EmailDataKind.Custom)
? ContactsContract.CommonDataKinds.Email.GetTypeLabel(resources, ekind, String.Empty)
: c.GetString(CommonColumns.Label);
return e;
}
internal static Organization GetOrganization(ICursor c, Resources resources)
{
Organization o = new Organization();
o.Name = c.GetString(OrganizationData.Company);
o.ContactTitle = c.GetString(OrganizationData.Title);
OrganizationDataKind d = (OrganizationDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type));
o.Type = d.ToOrganizationType();
o.Label = (d != OrganizationDataKind.Custom)
? OrganizationData.GetTypeLabel(resources, d, String.Empty)
: c.GetString(CommonColumns.Label);
return o;
}
internal static Website GetWebsite(ICursor c, Resources resources)
{
Website w = new Website();
w.Address = c.GetString(WebsiteData.Url);
//WebsiteDataKind kind = (WebsiteDataKind)c.GetInt (c.GetColumnIndex (CommonColumns.Type));
//w.Type = kind.ToWebsiteType();
//w.Label = (kind != WebsiteDataKind.Custom)
// ? resources.GetString ((int) kind)
// : c.GetString (CommonColumns.Label);
return w;
}
//internal static WebsiteType ToWebsiteType (this WebsiteDataKind websiteKind)
//{
// switch (websiteKind)
// {
// case WebsiteDataKind.Work:
// return WebsiteType.Work;
// case WebsiteDataKind.Home:
// return WebsiteType.Home;
// default:
// return WebsiteType.Other;
// }
//}
internal static string GetString(this ICursor c, string colName)
{
return c.GetString(c.GetColumnIndex(colName));
}
internal static AddressType ToAddressType(this AddressDataKind addressKind)
{
switch (addressKind)
{
case AddressDataKind.Home:
return AddressType.Home;
case AddressDataKind.Work:
return AddressType.Work;
default:
return AddressType.Other;
}
}
internal static EmailType ToEmailType(this EmailDataKind emailKind)
{
switch (emailKind)
{
case EmailDataKind.Home:
return EmailType.Home;
case EmailDataKind.Work:
return EmailType.Work;
default:
return EmailType.Other;
}
}
internal static PhoneType ToPhoneType(this PhoneDataKind phoneKind)
{
switch (phoneKind)
{
case PhoneDataKind.Home:
return PhoneType.Home;
case PhoneDataKind.Mobile:
return PhoneType.Mobile;
case PhoneDataKind.FaxHome:
return PhoneType.HomeFax;
case PhoneDataKind.Work:
return PhoneType.Work;
case PhoneDataKind.FaxWork:
return PhoneType.WorkFax;
case PhoneDataKind.Pager:
case PhoneDataKind.WorkPager:
return PhoneType.Pager;
default:
return PhoneType.Other;
}
}
internal static OrganizationType ToOrganizationType(this OrganizationDataKind organizationKind)
{
switch (organizationKind)
{
case OrganizationDataKind.Work:
return OrganizationType.Work;
default:
return OrganizationType.Other;
}
}
internal static InstantMessagingService ToInstantMessagingService(this IMProtocolDataKind protocolKind)
{
switch (protocolKind)
{
case IMProtocolDataKind.Aim:
return InstantMessagingService.Aim;
case IMProtocolDataKind.Msn:
return InstantMessagingService.Msn;
case IMProtocolDataKind.Yahoo:
return InstantMessagingService.Yahoo;
case IMProtocolDataKind.Jabber:
return InstantMessagingService.Jabber;
case IMProtocolDataKind.Icq:
return InstantMessagingService.Icq;
default:
return InstantMessagingService.Other;
}
}
//internal static InstantMessagingType ToInstantMessagingType (this IMTypeDataKind imKind)
//{
// switch (imKind)
// {
// case IMTypeDataKind.Home:
// return InstantMessagingType.Home;
// case IMTypeDataKind.Work:
// return InstantMessagingType.Work;
// default:
// return InstantMessagingType.Other;
// }
//}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org 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.
*/
using System;
using System.Collections.Generic;
namespace OpenMetaverse
{
/// <summary>
/// Exception class to identify inventory exceptions
/// </summary>
public class InventoryException : Exception
{
public InventoryException(string message)
: base(message) { }
}
/// <summary>
/// Responsible for maintaining inventory structure. Inventory constructs nodes
/// and manages node children as is necessary to maintain a coherant hirarchy.
/// Other classes should not manipulate or create InventoryNodes explicitly. When
/// A node's parent changes (when a folder is moved, for example) simply pass
/// Inventory the updated InventoryFolder and it will make the appropriate changes
/// to its internal representation.
/// </summary>
public class Inventory
{
/// <summary>
/// Delegate to use for the OnInventoryObjectUpdated event.
/// </summary>
/// <param name="oldObject">The state of the InventoryObject before the update occured.</param>
/// <param name="newObject">The state of the InventoryObject after the update occured.</param>
public delegate void InventoryObjectUpdated(InventoryBase oldObject, InventoryBase newObject);
/// <summary>
/// Delegate to use for the OnInventoryObjectRemoved event.
/// </summary>
/// <param name="obj">The InventoryObject that was removed.</param>
public delegate void InventoryObjectRemoved(InventoryBase obj);
/// <summary>
/// Delegate to use for the OnInventoryObjectUpdated event.
/// </summary>
/// <param name="obj">The InventoryObject that has been stored.</param>
public delegate void InventoryObjectAdded(InventoryBase obj);
/// <summary>
/// Called when an InventoryObject's state is changed.
/// </summary>
public event InventoryObjectUpdated OnInventoryObjectUpdated;
/// <summary>
/// Called when an item or folder is removed from inventory.
/// </summary>
public event InventoryObjectRemoved OnInventoryObjectRemoved;
/// <summary>
/// Called when an item is first added to the local inventory store.
/// This will occur most frequently when we're initially downloading
/// the inventory from the server.
///
/// This will also fire when another avatar or object offers us inventory
/// </summary>
public event InventoryObjectAdded OnInventoryObjectAdded;
/// <summary>
/// The root folder of this avatars inventory
/// </summary>
public InventoryFolder RootFolder
{
get { return RootNode.Data as InventoryFolder; }
set
{
UpdateNodeFor(value);
_RootNode = Items[value.UUID];
}
}
/// <summary>
/// The default shared library folder
/// </summary>
public InventoryFolder LibraryFolder
{
get { return LibraryRootNode.Data as InventoryFolder; }
set
{
UpdateNodeFor(value);
_LibraryRootNode = Items[value.UUID];
}
}
private InventoryNode _LibraryRootNode;
private InventoryNode _RootNode;
/// <summary>
/// The root node of the avatars inventory
/// </summary>
public InventoryNode RootNode
{
get
{
if (_RootNode == null)
throw new InventoryException("Root node unknown. Are you completely logged in?");
return _RootNode;
}
}
/// <summary>
/// The root node of the default shared library
/// </summary>
public InventoryNode LibraryRootNode
{
get
{
if (_LibraryRootNode == null)
throw new InventoryException("Library Root node unknown. Are you completely logged in?");
return _LibraryRootNode;
}
}
public UUID Owner {
get { return _Owner; }
}
private UUID _Owner;
private GridClient Client;
//private InventoryManager Manager;
private Dictionary<UUID, InventoryNode> Items = new Dictionary<UUID, InventoryNode>();
public Inventory(GridClient client, InventoryManager manager)
: this(client, manager, client.Self.AgentID) { }
public Inventory(GridClient client, InventoryManager manager, UUID owner)
{
Client = client;
//Manager = manager;
_Owner = owner;
if (owner == UUID.Zero)
Logger.Log("Inventory owned by nobody!", Helpers.LogLevel.Warning, Client);
Items = new Dictionary<UUID, InventoryNode>();
}
public List<InventoryBase> GetContents(InventoryFolder folder)
{
return GetContents(folder.UUID);
}
/// <summary>
/// Returns the contents of the specified folder
/// </summary>
/// <param name="folder">A folder's UUID</param>
/// <returns>The contents of the folder corresponding to <code>folder</code></returns>
/// <exception cref="InventoryException">When <code>folder</code> does not exist in the inventory</exception>
public List<InventoryBase> GetContents(UUID folder)
{
InventoryNode folderNode;
if (!Items.TryGetValue(folder, out folderNode))
throw new InventoryException("Unknown folder: " + folder);
lock (folderNode.Nodes.SyncRoot)
{
List<InventoryBase> contents = new List<InventoryBase>(folderNode.Nodes.Count);
foreach (InventoryNode node in folderNode.Nodes.Values)
{
contents.Add(node.Data);
}
return contents;
}
}
/// <summary>
/// Updates the state of the InventoryNode and inventory data structure that
/// is responsible for the InventoryObject. If the item was previously not added to inventory,
/// it adds the item, and updates structure accordingly. If it was, it updates the
/// InventoryNode, changing the parent node if <code>item.parentUUID</code> does
/// not match <code>node.Parent.Data.UUID</code>.
///
/// You can not set the inventory root folder using this method
/// </summary>
/// <param name="item">The InventoryObject to store</param>
public void UpdateNodeFor(InventoryBase item)
{
lock (Items)
{
InventoryNode itemParent = null;
if (item.ParentUUID != UUID.Zero && !Items.TryGetValue(item.ParentUUID, out itemParent))
{
// OK, we have no data on the parent, let's create a fake one.
InventoryFolder fakeParent = new InventoryFolder(item.ParentUUID);
fakeParent.DescendentCount = 1; // Dear god, please forgive me.
itemParent = new InventoryNode(fakeParent);
Items[item.ParentUUID] = itemParent;
// Unfortunately, this breaks the nice unified tree
// while we're waiting for the parent's data to come in.
// As soon as we get the parent, the tree repairs itself.
Logger.DebugLog("Attempting to update inventory child of " +
item.ParentUUID.ToString() + " when we have no local reference to that folder", Client);
if (Client.Settings.FETCH_MISSING_INVENTORY)
{
// Fetch the parent
List<UUID> fetchreq = new List<UUID>(1);
fetchreq.Add(item.ParentUUID);
//Manager.FetchInventory(fetchreq); // we cant fetch folder data! :-O
}
}
InventoryNode itemNode;
if (Items.TryGetValue(item.UUID, out itemNode)) // We're updating.
{
InventoryNode oldParent = itemNode.Parent;
// Handle parent change
if (oldParent == null || itemParent == null || itemParent.Data.UUID != oldParent.Data.UUID)
{
if (oldParent != null)
{
lock (oldParent.Nodes.SyncRoot)
oldParent.Nodes.Remove(item.UUID);
}
if (itemParent != null)
{
lock (itemParent.Nodes.SyncRoot)
itemParent.Nodes[item.UUID] = itemNode;
}
}
itemNode.Parent = itemParent;
if (item != itemNode.Data)
FireOnInventoryObjectUpdated(itemNode.Data, item);
itemNode.Data = item;
}
else // We're adding.
{
itemNode = new InventoryNode(item, itemParent);
Items.Add(item.UUID, itemNode);
FireOnInventoryObjectAdded(item);
}
}
}
public InventoryNode GetNodeFor(UUID uuid)
{
return Items[uuid];
}
/// <summary>
/// Removes the InventoryObject and all related node data from Inventory.
/// </summary>
/// <param name="item">The InventoryObject to remove.</param>
public void RemoveNodeFor(InventoryBase item)
{
lock (Items)
{
InventoryNode node;
if (Items.TryGetValue(item.UUID, out node))
{
if (node.Parent != null)
lock (node.Parent.Nodes.SyncRoot)
node.Parent.Nodes.Remove(item.UUID);
Items.Remove(item.UUID);
FireOnInventoryObjectRemoved(item);
}
// In case there's a new parent:
InventoryNode newParent;
if (Items.TryGetValue(item.ParentUUID, out newParent))
{
lock (newParent.Nodes.SyncRoot)
newParent.Nodes.Remove(item.UUID);
}
}
}
/// <summary>
/// Used to find out if Inventory contains the InventoryObject
/// specified by <code>uuid</code>.
/// </summary>
/// <param name="uuid">The UUID to check.</param>
/// <returns>true if inventory contains uuid, false otherwise</returns>
public bool Contains(UUID uuid)
{
return Items.ContainsKey(uuid);
}
public bool Contains(InventoryBase obj)
{
return Contains(obj.UUID);
}
#region Operators
/// <summary>
/// By using the bracket operator on this class, the program can get the
/// InventoryObject designated by the specified uuid. If the value for the corresponding
/// UUID is null, the call is equivelant to a call to <code>RemoveNodeFor(this[uuid])</code>.
/// If the value is non-null, it is equivelant to a call to <code>UpdateNodeFor(value)</code>,
/// the uuid parameter is ignored.
/// </summary>
/// <param name="uuid">The UUID of the InventoryObject to get or set, ignored if set to non-null value.</param>
/// <returns>The InventoryObject corresponding to <code>uuid</code>.</returns>
public InventoryBase this[UUID uuid]
{
get
{
InventoryNode node = Items[uuid];
return node.Data;
}
set
{
if (value != null)
{
// Log a warning if there is a UUID mismatch, this will cause problems
if (value.UUID != uuid)
Logger.Log("Inventory[uuid]: uuid " + uuid.ToString() + " is not equal to value.UUID " +
value.UUID.ToString(), Helpers.LogLevel.Warning, Client);
UpdateNodeFor(value);
}
else
{
InventoryNode node;
if (Items.TryGetValue(uuid, out node))
{
RemoveNodeFor(node.Data);
}
}
}
}
#endregion Operators
#region Event Firing
protected void FireOnInventoryObjectUpdated(InventoryBase oldObject, InventoryBase newObject)
{
if (OnInventoryObjectUpdated != null)
{
try { OnInventoryObjectUpdated(oldObject, newObject); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
protected void FireOnInventoryObjectRemoved(InventoryBase obj)
{
if (OnInventoryObjectRemoved != null)
{
try { OnInventoryObjectRemoved(obj); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
protected void FireOnInventoryObjectAdded(InventoryBase obj)
{
if (OnInventoryObjectAdded != null)
{
try { OnInventoryObjectAdded(obj); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Models.Membership
{
/// <summary>
/// Represents a backoffice user
/// </summary>
[Serializable]
[DataContract(IsReference = true)]
public class User : EntityBase, IUser, IProfile
{
/// <summary>
/// Constructor for creating a new/empty user
/// </summary>
public User(GlobalSettings globalSettings)
{
SessionTimeout = 60;
_userGroups = new HashSet<IReadOnlyUserGroup>();
_language = globalSettings.DefaultUILanguage;
_isApproved = true;
_isLockedOut = false;
_startContentIds = new int[] { };
_startMediaIds = new int[] { };
//cannot be null
_rawPasswordValue = "";
}
/// <summary>
/// Constructor for creating a new/empty user
/// </summary>
/// <param name="name"></param>
/// <param name="email"></param>
/// <param name="username"></param>
/// <param name="rawPasswordValue"></param>
public User(GlobalSettings globalSettings, string name, string email, string username, string rawPasswordValue)
: this(globalSettings)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(name));
if (string.IsNullOrWhiteSpace(email)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(email));
if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(username));
if (string.IsNullOrEmpty(rawPasswordValue)) throw new ArgumentException("Value cannot be null or empty.", nameof(rawPasswordValue));
_name = name;
_email = email;
_username = username;
_rawPasswordValue = rawPasswordValue;
_userGroups = new HashSet<IReadOnlyUserGroup>();
_isApproved = true;
_isLockedOut = false;
_startContentIds = new int[] { };
_startMediaIds = new int[] { };
}
/// <summary>
/// Constructor for creating a new User instance for an existing user
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
/// <param name="email"></param>
/// <param name="username"></param>
/// <param name="rawPasswordValue"></param>
/// <param name="passwordConfig"></param>
/// <param name="userGroups"></param>
/// <param name="startContentIds"></param>
/// <param name="startMediaIds"></param>
public User(GlobalSettings globalSettings, int id, string name, string email, string username,
string rawPasswordValue, string passwordConfig,
IEnumerable<IReadOnlyUserGroup> userGroups, int[] startContentIds, int[] startMediaIds)
: this(globalSettings)
{
//we allow whitespace for this value so just check null
if (rawPasswordValue == null) throw new ArgumentNullException(nameof(rawPasswordValue));
if (userGroups == null) throw new ArgumentNullException(nameof(userGroups));
if (startContentIds == null) throw new ArgumentNullException(nameof(startContentIds));
if (startMediaIds == null) throw new ArgumentNullException(nameof(startMediaIds));
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(name));
if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(username));
Id = id;
_name = name;
_email = email;
_username = username;
_rawPasswordValue = rawPasswordValue;
_passwordConfig = passwordConfig;
_userGroups = new HashSet<IReadOnlyUserGroup>(userGroups);
_isApproved = true;
_isLockedOut = false;
_startContentIds = startContentIds;
_startMediaIds = startMediaIds;
}
private string _name;
private string _securityStamp;
private string _avatar;
private string _tourData;
private int _sessionTimeout;
private int[] _startContentIds;
private int[] _startMediaIds;
private int _failedLoginAttempts;
private string _username;
private DateTime? _emailConfirmedDate;
private DateTime? _invitedDate;
private string _email;
private string _rawPasswordValue;
private string _passwordConfig;
private IEnumerable<string> _allowedSections;
private HashSet<IReadOnlyUserGroup> _userGroups;
private bool _isApproved;
private bool _isLockedOut;
private string _language;
private DateTime _lastPasswordChangedDate;
private DateTime _lastLoginDate;
private DateTime _lastLockoutDate;
//Custom comparer for enumerable
private static readonly DelegateEqualityComparer<IEnumerable<int>> IntegerEnumerableComparer =
new DelegateEqualityComparer<IEnumerable<int>>(
(enum1, enum2) => enum1.UnsortedSequenceEqual(enum2),
enum1 => enum1.GetHashCode());
[DataMember]
public DateTime? EmailConfirmedDate
{
get => _emailConfirmedDate;
set => SetPropertyValueAndDetectChanges(value, ref _emailConfirmedDate, nameof(EmailConfirmedDate));
}
[DataMember]
public DateTime? InvitedDate
{
get => _invitedDate;
set => SetPropertyValueAndDetectChanges(value, ref _invitedDate, nameof(InvitedDate));
}
[DataMember]
public string Username
{
get => _username;
set => SetPropertyValueAndDetectChanges(value, ref _username, nameof(Username));
}
[DataMember]
public string Email
{
get => _email;
set => SetPropertyValueAndDetectChanges(value, ref _email, nameof(Email));
}
[IgnoreDataMember]
public string RawPasswordValue
{
get => _rawPasswordValue;
set => SetPropertyValueAndDetectChanges(value, ref _rawPasswordValue, nameof(RawPasswordValue));
}
[IgnoreDataMember]
public string PasswordConfiguration
{
get => _passwordConfig;
set => SetPropertyValueAndDetectChanges(value, ref _passwordConfig, nameof(PasswordConfiguration));
}
[DataMember]
public bool IsApproved
{
get => _isApproved;
set => SetPropertyValueAndDetectChanges(value, ref _isApproved, nameof(IsApproved));
}
[IgnoreDataMember]
public bool IsLockedOut
{
get => _isLockedOut;
set => SetPropertyValueAndDetectChanges(value, ref _isLockedOut, nameof(IsLockedOut));
}
[IgnoreDataMember]
public DateTime LastLoginDate
{
get => _lastLoginDate;
set => SetPropertyValueAndDetectChanges(value, ref _lastLoginDate, nameof(LastLoginDate));
}
[IgnoreDataMember]
public DateTime LastPasswordChangeDate
{
get => _lastPasswordChangedDate;
set => SetPropertyValueAndDetectChanges(value, ref _lastPasswordChangedDate, nameof(LastPasswordChangeDate));
}
[IgnoreDataMember]
public DateTime LastLockoutDate
{
get => _lastLockoutDate;
set => SetPropertyValueAndDetectChanges(value, ref _lastLockoutDate, nameof(LastLockoutDate));
}
[IgnoreDataMember]
public int FailedPasswordAttempts
{
get => _failedLoginAttempts;
set => SetPropertyValueAndDetectChanges(value, ref _failedLoginAttempts, nameof(FailedPasswordAttempts));
}
[IgnoreDataMember]
public string Comments { get; set; }
public UserState UserState
{
get
{
if (LastLoginDate == default && IsApproved == false && InvitedDate != null)
return UserState.Invited;
if (IsLockedOut)
return UserState.LockedOut;
if (IsApproved == false)
return UserState.Disabled;
// User is not disabled or locked and has never logged in before
if (LastLoginDate == default && IsApproved && IsLockedOut == false)
return UserState.Inactive;
return UserState.Active;
}
}
[DataMember]
public string Name
{
get => _name;
set => SetPropertyValueAndDetectChanges(value, ref _name, nameof(Name));
}
public IEnumerable<string> AllowedSections
{
get { return _allowedSections ?? (_allowedSections = new List<string>(_userGroups.SelectMany(x => x.AllowedSections).Distinct())); }
}
public IProfile ProfileData => new WrappedUserProfile(this);
/// <summary>
/// The security stamp used by ASP.Net identity
/// </summary>
[IgnoreDataMember]
public string SecurityStamp
{
get => _securityStamp;
set => SetPropertyValueAndDetectChanges(value, ref _securityStamp, nameof(SecurityStamp));
}
[DataMember]
public string Avatar
{
get => _avatar;
set => SetPropertyValueAndDetectChanges(value, ref _avatar, nameof(Avatar));
}
/// <summary>
/// A Json blob stored for recording tour data for a user
/// </summary>
[DataMember]
public string TourData
{
get => _tourData;
set => SetPropertyValueAndDetectChanges(value, ref _tourData, nameof(TourData));
}
/// <summary>
/// Gets or sets the session timeout.
/// </summary>
/// <value>
/// The session timeout.
/// </value>
[DataMember]
public int SessionTimeout
{
get => _sessionTimeout;
set => SetPropertyValueAndDetectChanges(value, ref _sessionTimeout, nameof(SessionTimeout));
}
/// <summary>
/// Gets or sets the start content id.
/// </summary>
/// <value>
/// The start content id.
/// </value>
[DataMember]
[DoNotClone]
public int[] StartContentIds
{
get => _startContentIds;
set => SetPropertyValueAndDetectChanges(value, ref _startContentIds, nameof(StartContentIds), IntegerEnumerableComparer);
}
/// <summary>
/// Gets or sets the start media id.
/// </summary>
/// <value>
/// The start media id.
/// </value>
[DataMember]
[DoNotClone]
public int[] StartMediaIds
{
get => _startMediaIds;
set => SetPropertyValueAndDetectChanges(value, ref _startMediaIds, nameof(StartMediaIds), IntegerEnumerableComparer);
}
[DataMember]
public string Language
{
get => _language;
set => SetPropertyValueAndDetectChanges(value, ref _language, nameof(Language));
}
/// <summary>
/// Gets the groups that user is part of
/// </summary>
[DataMember]
public IEnumerable<IReadOnlyUserGroup> Groups => _userGroups;
public void RemoveGroup(string group)
{
foreach (var userGroup in _userGroups.ToArray())
{
if (userGroup.Alias == group)
{
_userGroups.Remove(userGroup);
//reset this flag so it's rebuilt with the assigned groups
_allowedSections = null;
OnPropertyChanged(nameof(Groups));
}
}
}
public void ClearGroups()
{
if (_userGroups.Count > 0)
{
_userGroups.Clear();
//reset this flag so it's rebuilt with the assigned groups
_allowedSections = null;
OnPropertyChanged(nameof(Groups));
}
}
public void AddGroup(IReadOnlyUserGroup group)
{
if (_userGroups.Add(group))
{
//reset this flag so it's rebuilt with the assigned groups
_allowedSections = null;
OnPropertyChanged(nameof(Groups));
}
}
protected override void PerformDeepClone(object clone)
{
base.PerformDeepClone(clone);
var clonedEntity = (User)clone;
//manually clone the start node props
clonedEntity._startContentIds = _startContentIds.ToArray();
clonedEntity._startMediaIds = _startMediaIds.ToArray();
//need to create new collections otherwise they'll get copied by ref
clonedEntity._userGroups = new HashSet<IReadOnlyUserGroup>(_userGroups);
clonedEntity._allowedSections = _allowedSections != null ? new List<string>(_allowedSections) : null;
}
/// <summary>
/// Internal class used to wrap the user in a profile
/// </summary>
private class WrappedUserProfile : IProfile
{
private readonly IUser _user;
public WrappedUserProfile(IUser user)
{
_user = user;
}
public int Id => _user.Id;
public string Name => _user.Name;
private bool Equals(WrappedUserProfile other)
{
return _user.Equals(other._user);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((WrappedUserProfile) obj);
}
public override int GetHashCode()
{
return _user.GetHashCode();
}
}
}
}
| |
#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
using System;
using System.Collections.Generic;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
internal enum State
{
Start = 0,
Property = 1,
ObjectStart = 2,
Object = 3,
ArrayStart = 4,
Array = 5,
ConstructorStart = 6,
Constructor = 7,
Closed = 8,
Error = 9
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] StateArray;
internal static readonly State[][] StateArrayTempate = new[]
{
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }
};
internal static State[][] BuildStateArray()
{
var allStates = StateArrayTempate.ToList();
var errorStates = StateArrayTempate[0];
var valueStates = StateArrayTempate[7];
foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken)))
{
if (allStates.Count <= (int)valueToken)
{
switch (valueToken)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
allStates.Add(valueStates);
break;
default:
allStates.Add(errorStates);
break;
}
}
}
return allStates.ToArray();
}
static JsonWriter()
{
StateArray = BuildStateArray();
}
private List<JsonPosition> _stack;
private JsonPosition _currentPosition;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get
{
int depth = (_stack != null) ? _stack.Count : 0;
if (Peek() != JsonContainerType.None)
{
depth++;
}
return depth;
}
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
internal string ContainerPath
{
get
{
if (_currentPosition.Type == JsonContainerType.None || _stack == null)
{
return string.Empty;
}
return JsonPosition.BuildPath(_stack, null);
}
}
/// <summary>
/// Gets the path of the writer.
/// </summary>
public string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
{
return string.Empty;
}
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack, current);
}
}
private DateFormatHandling _dateFormatHandling;
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string _dateFormatString;
private CultureInfo _culture;
/// <summary>
/// Indicates how JSON text output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set
{
if (value < Formatting.None || value > Formatting.Indented)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_formatting = value;
}
}
/// <summary>
/// Get or set how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling; }
set
{
if (value < DateFormatHandling.IsoDateFormat || value > DateFormatHandling.MicrosoftDateFormat)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateFormatHandling = value;
}
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when writing JSON text.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Get or set how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get { return _stringEscapeHandling; }
set
{
if (value < StringEscapeHandling.Default || value > StringEscapeHandling.EscapeHtml)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_stringEscapeHandling = value;
OnStringEscapeHandlingChanged();
}
}
internal virtual void OnStringEscapeHandlingChanged()
{
// hacky but there is a calculated value that relies on StringEscapeHandling
}
/// <summary>
/// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>,
/// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>,
/// are written to JSON text.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get { return _floatFormatHandling; }
set
{
if (value < FloatFormatHandling.String || value > FloatFormatHandling.DefaultValue)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_floatFormatHandling = value;
}
}
/// <summary>
/// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString; }
set { _dateFormatString = value; }
}
/// <summary>
/// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_currentState = State.Start;
_formatting = Formatting.None;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
CloseOutput = true;
}
internal void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
{
_currentPosition.Position++;
}
}
private void Push(JsonContainerType value)
{
if (_currentPosition.Type != JsonContainerType.None)
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
}
_currentPosition = new JsonPosition(value);
}
private JsonContainerType Pop()
{
JsonPosition oldPosition = _currentPosition;
if (_stack != null && _stack.Count > 0)
{
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
_currentPosition = new JsonPosition();
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public virtual void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
}
/// <summary>
/// Writes the end of a JSON object.
/// </summary>
public virtual void WriteEndObject()
{
InternalWriteEnd(JsonContainerType.Object);
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public virtual void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
InternalWriteEnd(JsonContainerType.Array);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
InternalWriteEnd(JsonContainerType.Constructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
InternalWritePropertyName(name);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public virtual void WritePropertyName(string name, bool escape)
{
WritePropertyName(name);
}
/// <summary>
/// Writes the end of the current JSON object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true, true, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
WriteToken(reader, writeChildren, true, true);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token and its value.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
/// <param name="value">
/// The value to write.
/// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>.
/// A null value can be passed to the method for token's that don't have a value, e.g. <see cref="JsonToken.StartObject"/>.</param>
public void WriteToken(JsonToken token, object value)
{
WriteTokenInternal(token, value);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
public void WriteToken(JsonToken token)
{
WriteTokenInternal(token, null);
}
internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments)
{
int initialDepth;
if (reader.TokenType == JsonToken.None)
{
initialDepth = -1;
}
else if (!JsonTokenUtils.IsStartToken(reader.TokenType))
{
initialDepth = reader.Depth + 1;
}
else
{
initialDepth = reader.Depth;
}
WriteToken(reader, initialDepth, writeChildren, writeDateConstructorAsDate, writeComments);
}
internal void WriteToken(JsonReader reader, int initialDepth, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments)
{
do
{
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
{
WriteConstructorDate(reader);
}
else
{
if (reader.TokenType != JsonToken.Comment || writeComments)
{
WriteTokenInternal(reader.TokenType, reader.Value);
}
}
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
}
private void WriteTokenInternal(JsonToken tokenType, object value)
{
switch (tokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
ValidationUtils.ArgumentNotNull(value, "value");
WriteStartConstructor(value.ToString());
break;
case JsonToken.PropertyName:
ValidationUtils.ArgumentNotNull(value, "value");
WritePropertyName(value.ToString());
break;
case JsonToken.Comment:
WriteComment((value != null) ? value.ToString() : null);
break;
case JsonToken.Integer:
ValidationUtils.ArgumentNotNull(value, "value");
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
if (value is BigInteger)
{
WriteValue((BigInteger)value);
}
else
#endif
{
WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
ValidationUtils.ArgumentNotNull(value, "value");
if (value is decimal)
{
WriteValue((decimal)value);
}
else if (value is double)
{
WriteValue((double)value);
}
else if (value is float)
{
WriteValue((float)value);
}
else
{
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.String:
ValidationUtils.ArgumentNotNull(value, "value");
WriteValue(value.ToString());
break;
case JsonToken.Boolean:
ValidationUtils.ArgumentNotNull(value, "value");
WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
ValidationUtils.ArgumentNotNull(value, "value");
#if !NET20
if (value is DateTimeOffset)
{
WriteValue((DateTimeOffset)value);
}
else
#endif
{
WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Raw:
WriteRawValue((value != null) ? value.ToString() : null);
break;
case JsonToken.Bytes:
ValidationUtils.ArgumentNotNull(value, "value");
if (value is Guid)
{
WriteValue((Guid)value);
}
else
{
WriteValue((byte[])value);
}
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", tokenType, "Unexpected token type.");
}
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
{
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
}
if (reader.TokenType != JsonToken.Integer)
{
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null);
}
long ticks = (long)reader.Value;
DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
{
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
}
if (reader.TokenType != JsonToken.EndConstructor)
{
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null);
}
WriteValue(date);
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
WriteEndObject();
break;
case JsonContainerType.Array:
WriteEndArray();
break;
case JsonContainerType.Constructor:
WriteEndConstructor();
break;
default:
throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null);
}
}
private void AutoCompleteAll()
{
while (Top > 0)
{
WriteEnd();
}
}
private JsonToken GetCloseTokenForType(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
return JsonToken.EndObject;
case JsonContainerType.Array:
return JsonToken.EndArray;
case JsonContainerType.Constructor:
return JsonToken.EndConstructor;
default:
throw JsonWriterException.Create(this, "No close token for type: " + type, null);
}
}
private void AutoCompleteClose(JsonContainerType type)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
if (_currentPosition.Type == type)
{
levelsToComplete = 1;
}
else
{
int top = Top - 2;
for (int i = top; i >= 0; i--)
{
int currentLevel = top - i;
if (_stack[currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
}
}
}
if (levelsToComplete == 0)
{
throw JsonWriterException.Create(this, "No token to close.", null);
}
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState == State.Property)
{
WriteNull();
}
if (_formatting == Formatting.Indented)
{
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
{
WriteIndent();
}
}
WriteEnd(token);
JsonContainerType currentLevelType = Peek();
switch (currentLevelType)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Array;
break;
case JsonContainerType.None:
_currentState = State.Start;
break;
default:
throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
}
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
// gets new state based on the current state and what is being written
State newState = StateArray[(int)tokenBeingWritten][(int)_currentState];
if (newState == State.Error)
{
throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null);
}
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
if (_formatting == Formatting.Indented)
{
if (_currentState == State.Property)
{
WriteIndentSpace();
}
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart)
|| (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start))
{
WriteIndent();
}
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
InternalWriteValue(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
InternalWriteRaw();
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
}
#if !NET20
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#if !NET20
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{Guid}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{TimeSpan}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.Bytes);
}
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.String);
}
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
}
else
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
{
throw CreateUnsupportedTypeException(this, value);
}
#endif
WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value);
}
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
InternalWriteComment();
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_currentState != State.Closed)
{
Close();
}
}
internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value)
{
switch (typeCode)
{
case PrimitiveTypeCode.Char:
writer.WriteValue((char)value);
break;
case PrimitiveTypeCode.CharNullable:
writer.WriteValue((value == null) ? (char?)null : (char)value);
break;
case PrimitiveTypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case PrimitiveTypeCode.BooleanNullable:
writer.WriteValue((value == null) ? (bool?)null : (bool)value);
break;
case PrimitiveTypeCode.SByte:
writer.WriteValue((sbyte)value);
break;
case PrimitiveTypeCode.SByteNullable:
writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value);
break;
case PrimitiveTypeCode.Int16:
writer.WriteValue((short)value);
break;
case PrimitiveTypeCode.Int16Nullable:
writer.WriteValue((value == null) ? (short?)null : (short)value);
break;
case PrimitiveTypeCode.UInt16:
writer.WriteValue((ushort)value);
break;
case PrimitiveTypeCode.UInt16Nullable:
writer.WriteValue((value == null) ? (ushort?)null : (ushort)value);
break;
case PrimitiveTypeCode.Int32:
writer.WriteValue((int)value);
break;
case PrimitiveTypeCode.Int32Nullable:
writer.WriteValue((value == null) ? (int?)null : (int)value);
break;
case PrimitiveTypeCode.Byte:
writer.WriteValue((byte)value);
break;
case PrimitiveTypeCode.ByteNullable:
writer.WriteValue((value == null) ? (byte?)null : (byte)value);
break;
case PrimitiveTypeCode.UInt32:
writer.WriteValue((uint)value);
break;
case PrimitiveTypeCode.UInt32Nullable:
writer.WriteValue((value == null) ? (uint?)null : (uint)value);
break;
case PrimitiveTypeCode.Int64:
writer.WriteValue((long)value);
break;
case PrimitiveTypeCode.Int64Nullable:
writer.WriteValue((value == null) ? (long?)null : (long)value);
break;
case PrimitiveTypeCode.UInt64:
writer.WriteValue((ulong)value);
break;
case PrimitiveTypeCode.UInt64Nullable:
writer.WriteValue((value == null) ? (ulong?)null : (ulong)value);
break;
case PrimitiveTypeCode.Single:
writer.WriteValue((float)value);
break;
case PrimitiveTypeCode.SingleNullable:
writer.WriteValue((value == null) ? (float?)null : (float)value);
break;
case PrimitiveTypeCode.Double:
writer.WriteValue((double)value);
break;
case PrimitiveTypeCode.DoubleNullable:
writer.WriteValue((value == null) ? (double?)null : (double)value);
break;
case PrimitiveTypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case PrimitiveTypeCode.DateTimeNullable:
writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value);
break;
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
writer.WriteValue((DateTimeOffset)value);
break;
case PrimitiveTypeCode.DateTimeOffsetNullable:
writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value);
break;
#endif
case PrimitiveTypeCode.Decimal:
writer.WriteValue((decimal)value);
break;
case PrimitiveTypeCode.DecimalNullable:
writer.WriteValue((value == null) ? (decimal?)null : (decimal)value);
break;
case PrimitiveTypeCode.Guid:
writer.WriteValue((Guid)value);
break;
case PrimitiveTypeCode.GuidNullable:
writer.WriteValue((value == null) ? (Guid?)null : (Guid)value);
break;
case PrimitiveTypeCode.TimeSpan:
writer.WriteValue((TimeSpan)value);
break;
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
break;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
break;
case PrimitiveTypeCode.BigIntegerNullable:
// this will call to WriteValue(object)
writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value);
break;
#endif
case PrimitiveTypeCode.Uri:
writer.WriteValue((Uri)value);
break;
case PrimitiveTypeCode.String:
writer.WriteValue((string)value);
break;
case PrimitiveTypeCode.Bytes:
writer.WriteValue((byte[])value);
break;
#if !(PORTABLE || DOTNET)
case PrimitiveTypeCode.DBNull:
writer.WriteNull();
break;
#endif
default:
#if !PORTABLE
if (value is IConvertible)
{
// the value is a non-standard IConvertible
// convert to the underlying value and retry
IConvertible convertable = (IConvertible)value;
TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertable);
// if convertable has an underlying typecode of Object then attempt to convert it to a string
PrimitiveTypeCode resolvedTypeCode = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? PrimitiveTypeCode.String : typeInformation.TypeCode;
Type resolvedType = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? typeof(string) : typeInformation.Type;
object convertedValue = convertable.ToType(resolvedType, CultureInfo.InvariantCulture);
WriteValue(writer, resolvedTypeCode, convertedValue);
break;
}
else
#endif
{
throw CreateUnsupportedTypeException(writer, value);
}
}
}
private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value)
{
return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
/// <summary>
/// Sets the state of the JsonWriter,
/// </summary>
/// <param name="token">The JsonToken being written.</param>
/// <param name="value">The value being written.</param>
protected void SetWriteState(JsonToken token, object value)
{
switch (token)
{
case JsonToken.StartObject:
InternalWriteStart(token, JsonContainerType.Object);
break;
case JsonToken.StartArray:
InternalWriteStart(token, JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
InternalWriteStart(token, JsonContainerType.Constructor);
break;
case JsonToken.PropertyName:
if (!(value is string))
{
throw new ArgumentException("A name is required when setting property name state.", nameof(value));
}
InternalWritePropertyName((string)value);
break;
case JsonToken.Comment:
InternalWriteComment();
break;
case JsonToken.Raw:
InternalWriteRaw();
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Null:
case JsonToken.Undefined:
InternalWriteValue(token);
break;
case JsonToken.EndObject:
InternalWriteEnd(JsonContainerType.Object);
break;
case JsonToken.EndArray:
InternalWriteEnd(JsonContainerType.Array);
break;
case JsonToken.EndConstructor:
InternalWriteEnd(JsonContainerType.Constructor);
break;
default:
throw new ArgumentOutOfRangeException(nameof(token));
}
}
internal void InternalWriteEnd(JsonContainerType container)
{
AutoCompleteClose(container);
}
internal void InternalWritePropertyName(string name)
{
_currentPosition.PropertyName = name;
AutoComplete(JsonToken.PropertyName);
}
internal void InternalWriteRaw()
{
}
internal void InternalWriteStart(JsonToken token, JsonContainerType container)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
Push(container);
}
internal void InternalWriteValue(JsonToken token)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
}
internal void InternalWriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
{
throw JsonWriterException.Create(this, "Only white space characters should be used.", null);
}
}
}
internal void InternalWriteComment()
{
AutoComplete(JsonToken.Comment);
}
}
}
| |
//
// Copyright 2012-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Android.App;
using Android.Net.Http;
using Android.Webkit;
using Android.OS;
using System.Threading.Tasks;
using SimpleAuth.Droid;
namespace SimpleAuth
{
[Activity(Label = "Web Authenticator")]
public class WebAuthenticatorActivity : Activity
{
WebView webView;
public static string UserAgent = "";
internal class State : Java.Lang.Object
{
public WebAuthenticator Authenticator;
}
internal static readonly ActivityStateRepository<State> StateRepo = new ActivityStateRepository<State>();
State state;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
//
// Load the state either from a configuration change or from the intent.
//
state = LastNonConfigurationInstance as State;
if (state == null && Intent.HasExtra("StateKey"))
{
var stateKey = Intent.GetStringExtra("StateKey");
state = StateRepo.Remove(stateKey);
}
if (state == null)
{
Finish();
return;
}
MonitorAuthenticator();
Title = state.Authenticator.Title;
//
// Build the UI
//
webView = new WebView(this)
{
Id = 42,
};
if (!string.IsNullOrWhiteSpace(UserAgent))
{
webView.Settings.UserAgentString = UserAgent;
webView.Settings.LoadWithOverviewMode = true;
}
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new Client(this));
SetContentView(webView);
//
// Restore the UI state or start over
//
if (savedInstanceState != null)
{
webView.RestoreState(savedInstanceState);
}
else
{
if (Intent.GetBooleanExtra("ClearCookies", true))
ClearCookies();
BeginLoadingInitialUrl();
}
}
async Task MonitorAuthenticator()
{
try
{
await state.Authenticator.GetAuthCode();
if (state.Authenticator.HasCompleted)
{
SetResult(Result.Ok);
Finish();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Task loadingTask;
async Task BeginLoadingInitialUrl()
{
if (state.Authenticator.ClearCookiesBeforeLogin)
ClearCookies();
if (loadingTask == null || loadingTask.IsCompleted)
{
loadingTask = RealLoading();
}
await loadingTask;
}
async Task RealLoading()
{
if (this.state.Authenticator.ClearCookiesBeforeLogin)
ClearCookies();
//
// Begin displaying the page
//
try
{
var url = await state.Authenticator.GetInitialUrl();
if (url == null)
return;
webView.LoadUrl(url.AbsoluteUri);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return;
}
}
public void ClearCookies()
{
Android.Webkit.CookieSyncManager.CreateInstance(Android.App.Application.Context);
Android.Webkit.CookieManager.Instance.RemoveAllCookie();
}
public override void OnBackPressed()
{
Finish();
state.Authenticator.OnCancelled();
}
public override Java.Lang.Object OnRetainNonConfigurationInstance()
{
return state;
}
protected override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState);
webView.SaveState(outState);
}
void BeginProgress(string message)
{
webView.Enabled = false;
}
void EndProgress()
{
webView.Enabled = true;
}
class Client : WebViewClient
{
WebAuthenticatorActivity activity;
HashSet<SslCertificate> sslContinue;
Dictionary<SslCertificate, List<SslErrorHandler>> inProgress;
public Client(WebAuthenticatorActivity activity)
{
this.activity = activity;
}
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
Console.WriteLine(url);
return false;
}
public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
var uri = new Uri(url);
activity.state.Authenticator.CheckUrl(uri, GetCookies(url));
activity.BeginProgress(uri.Authority);
}
public override void OnPageFinished(WebView view, string url)
{
var uri = new Uri(url);
activity.state.Authenticator.CheckUrl(uri,GetCookies(url));
activity.EndProgress();
}
System.Net.Cookie[] GetCookies(string url)
{
Android.Webkit.CookieSyncManager.CreateInstance(this.activity);
var cookies = CookieManager.Instance.GetCookie (url);
var cookiePairs = cookies?.Split('&') ?? new string[0];
return cookiePairs.Select(x =>
{
var parts = x.Split('=');
if (parts[0].Contains(":"))
parts[0] = parts[0].Substring(0, parts[0].IndexOf(":"));
try{
return new Cookie
{
Name = parts[0],
Value = parts[1],
};
}
catch(Exception ex)
{
Console.WriteLine(ex);
return null;
}
})?.Where(x=> x != null).ToArray() ?? new Cookie[0];
}
class SslCertificateEqualityComparer
: IEqualityComparer<SslCertificate>
{
public bool Equals(SslCertificate x, SslCertificate y)
{
return Equals(x.IssuedTo, y.IssuedTo) && Equals(x.IssuedBy, y.IssuedBy) && x.ValidNotBeforeDate.Equals(y.ValidNotBeforeDate) && x.ValidNotAfterDate.Equals(y.ValidNotAfterDate);
}
bool Equals(SslCertificate.DName x, SslCertificate.DName y)
{
if (ReferenceEquals(x, y))
return true;
if (ReferenceEquals(x, y) || ReferenceEquals(null, y))
return false;
return x.GetDName().Equals(y.GetDName());
}
public int GetHashCode(SslCertificate obj)
{
unchecked
{
int hashCode = GetHashCode(obj.IssuedTo);
hashCode = (hashCode * 397) ^ GetHashCode(obj.IssuedBy);
hashCode = (hashCode * 397) ^ obj.ValidNotBeforeDate.GetHashCode();
hashCode = (hashCode * 397) ^ obj.ValidNotAfterDate.GetHashCode();
return hashCode;
}
}
int GetHashCode(SslCertificate.DName dname)
{
return dname.GetDName().GetHashCode();
}
}
public override void OnReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
{
if (sslContinue == null)
{
var certComparer = new SslCertificateEqualityComparer();
sslContinue = new HashSet<SslCertificate>(certComparer);
inProgress = new Dictionary<SslCertificate, List<SslErrorHandler>>(certComparer);
}
List<SslErrorHandler> handlers;
if (inProgress.TryGetValue(error.Certificate, out handlers))
{
handlers.Add(handler);
return;
}
if (sslContinue.Contains(error.Certificate))
{
handler.Proceed();
return;
}
inProgress[error.Certificate] = new List<SslErrorHandler>();
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.SetTitle("Security warning");
builder.SetIcon(Android.Resource.Drawable.IcDialogAlert);
builder.SetMessage("There are problems with the security certificate for this site.");
builder.SetNegativeButton("Go back", (sender, args) => {
UpdateInProgressHandlers(error.Certificate, h => h.Cancel());
handler.Cancel();
});
builder.SetPositiveButton("Continue", (sender, args) => {
sslContinue.Add(error.Certificate);
UpdateInProgressHandlers(error.Certificate, h => h.Proceed());
handler.Proceed();
});
builder.Create().Show();
}
void UpdateInProgressHandlers(SslCertificate certificate, Action<SslErrorHandler> update)
{
List<SslErrorHandler> inProgressHandlers;
if (!this.inProgress.TryGetValue(certificate, out inProgressHandlers))
return;
foreach (SslErrorHandler sslErrorHandler in inProgressHandlers)
update(sslErrorHandler);
inProgressHandlers.Clear();
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using FluentAssertions;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
namespace Microsoft.DotNet.Cli.Utils.Tests
{
public class GivenAProjectPathCommandResolver
{
private static readonly string s_testProjectDirectory = Path.Combine(AppContext.BaseDirectory, "testprojectdirectory");
[Fact]
public void It_returns_null_when_CommandName_is_null()
{
var projectPathCommandResolver = SetupPlatformProjectPathCommandResolver(forceGeneric: true);
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = null,
CommandArguments = new string[] { "" },
ProjectDirectory = "/some/directory"
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_ProjectDirectory_is_null()
{
var projectPathCommandResolver = SetupPlatformProjectPathCommandResolver(forceGeneric: true);
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "command",
CommandArguments = new string[] { "" },
ProjectDirectory = null
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_CommandName_does_not_exist_in_ProjectDirectory()
{
var projectPathCommandResolver = SetupPlatformProjectPathCommandResolver(forceGeneric: true);
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "nonexistent-command",
CommandArguments = null,
ProjectDirectory = s_testProjectDirectory
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_null_when_CommandName_exists_in_a_subdirectory_of_ProjectDirectory()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var projectPathCommandResolver = SetupPlatformProjectPathCommandResolver(environment, forceGeneric: true);
var testDir = Path.Combine(s_testProjectDirectory, "projectpathtestsubdir");
CommandResolverTestUtils.CreateNonRunnableTestCommand(testDir, "projectpathtestsubdircommand", ".exe");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "projectpathtestsubdircommand",
CommandArguments = null,
ProjectDirectory = s_testProjectDirectory
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().BeNull();
}
[Fact]
public void It_returns_a_CommandSpec_with_CommandName_as_FileName_when_CommandName_exists_in_ProjectDirectory()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var projectPathCommandResolver = SetupPlatformProjectPathCommandResolver(environment, forceGeneric: true);
CommandResolverTestUtils.CreateNonRunnableTestCommand(s_testProjectDirectory, "projectpathtestcommand1", ".exe");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "projectpathtestcommand1",
CommandArguments = null,
ProjectDirectory = s_testProjectDirectory
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFile = Path.GetFileNameWithoutExtension(result.Path);
commandFile.Should().Be("projectpathtestcommand1");
}
[Fact]
public void It_escapes_CommandArguments_when_returning_a_CommandSpec()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var projectPathCommandResolver = SetupPlatformProjectPathCommandResolver(environment, forceGeneric: true);
CommandResolverTestUtils.CreateNonRunnableTestCommand(s_testProjectDirectory, "projectpathtestcommand1", ".exe");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "projectpathtestcommand1",
CommandArguments = new[] { "arg with space" },
ProjectDirectory = s_testProjectDirectory
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Be("\"arg with space\"");
}
[Fact]
public void It_resolves_commands_with_extensions_defined_in_InferredExtensions()
{
var extensions = new string[] { ".sh", ".cmd", ".foo", ".exe" };
var projectPathCommandResolver = SetupPlatformProjectPathCommandResolver(forceGeneric: true);
foreach (var extension in extensions)
{
var extensionTestDir = Path.Combine(s_testProjectDirectory, "testext" + extension);
CommandResolverTestUtils.CreateNonRunnableTestCommand(extensionTestDir, "projectpathexttest", extension);
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "projectpathexttest",
CommandArguments = null,
ProjectDirectory = extensionTestDir,
InferredExtensions = extensions
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFileName = Path.GetFileName(result.Path);
commandFileName.Should().Be("projectpathexttest" + extension);
}
}
[Fact]
public void It_returns_a_CommandSpec_with_Args_as_stringEmpty_when_returning_a_CommandSpec_and_CommandArguments_are_null()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var projectPathCommandResolver = SetupPlatformProjectPathCommandResolver(environment, forceGeneric: true);
CommandResolverTestUtils.CreateNonRunnableTestCommand(s_testProjectDirectory, "projectpathtestcommand1", ".exe");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "projectpathtestcommand1",
CommandArguments = null,
ProjectDirectory = s_testProjectDirectory
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
result.Args.Should().Be(string.Empty);
}
[Fact]
public void It_prefers_EXE_over_CMD_when_two_command_candidates_exist_and_using_WindowsExePreferredCommandSpecFactory()
{
var environment = CommandResolverTestUtils.SetupEnvironmentProviderWhichFindsExtensions(".exe");
var platformCommandSpecFactory = new WindowsExePreferredCommandSpecFactory();
var projectPathCommandResolver = new ProjectPathCommandResolver(environment, platformCommandSpecFactory);
CommandResolverTestUtils.CreateNonRunnableTestCommand(s_testProjectDirectory, "projectpathtestcommand1", ".exe");
CommandResolverTestUtils.CreateNonRunnableTestCommand(s_testProjectDirectory, "projectpathtestcommand1", ".cmd");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "projectpathtestcommand1",
CommandArguments = null,
ProjectDirectory = s_testProjectDirectory
};
var result = projectPathCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFile = Path.GetFileName(result.Path);
commandFile.Should().Be("projectpathtestcommand1.exe");
}
public void It_wraps_command_with_CMD_EXE_when_command_has_CMD_Extension_and_using_WindowsExePreferredCommandSpecFactory()
{
var environment = new EnvironmentProvider(new[] { ".cmd" });
var platformCommandSpecFactory = new WindowsExePreferredCommandSpecFactory();
var pathCommandResolver = new PathCommandResolver(environment, platformCommandSpecFactory);
var testCommandPath =
CommandResolverTestUtils.CreateNonRunnableTestCommand(s_testProjectDirectory, "cmdWrapCommand", ".cmd");
var commandResolverArguments = new CommandResolverArguments()
{
CommandName = "cmdWrapCommand",
CommandArguments = null
};
var result = pathCommandResolver.Resolve(commandResolverArguments);
result.Should().NotBeNull();
var commandFile = Path.GetFileName(result.Path);
commandFile.Should().Be("cmd.exe");
result.Args.Should().Contain(testCommandPath);
}
private ProjectPathCommandResolver SetupPlatformProjectPathCommandResolver(
IEnvironmentProvider environment = null,
bool forceGeneric = false)
{
environment = environment ?? new EnvironmentProvider();
IPlatformCommandSpecFactory platformCommandSpecFactory = new GenericPlatformCommandSpecFactory();
if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows
&& !forceGeneric)
{
platformCommandSpecFactory = new WindowsExePreferredCommandSpecFactory();
}
var projectPathCommandResolver = new ProjectPathCommandResolver(environment, platformCommandSpecFactory);
return projectPathCommandResolver;
}
}
}
| |
//
// MenuItemBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using System.Collections.Generic;
namespace Xwt.GtkBackend
{
public class MenuItemBackend: IMenuItemBackend
{
IMenuItemEventSink eventSink;
Gtk.MenuItem item;
Gtk.Label label;
List<MenuItemEvent> enabledEvents;
bool changingCheck;
ApplicationContext context;
public KeyAccelerator Accelerator {
get {
return null;
}
set {
}
}
public MenuItemBackend ()
: this (new Gtk.ImageMenuItem (""))
{
}
public MenuItemBackend (Gtk.MenuItem item)
{
this.item = item;
label = (Gtk.Label) item.Child;
item.ShowAll ();
}
public Gtk.MenuItem MenuItem {
get { return item; }
}
public void Initialize (IMenuItemEventSink eventSink)
{
this.eventSink = eventSink;
}
public void SetSubmenu (IMenuBackend menu)
{
if (menu == null)
item.Submenu = null;
else {
Gtk.Menu m = ((MenuBackend)menu).Menu;
item.Submenu = m;
}
}
ImageDescription? defImage, selImage;
public void SetImage (ImageDescription image)
{
Gtk.ImageMenuItem it = item as Gtk.ImageMenuItem;
if (it == null)
return;
if (!image.IsNull) {
if (defImage == null)
item.StateChanged += ImageMenuItemStateChanged;
defImage = image;
selImage = new ImageDescription {
Backend = image.Backend,
Size = image.Size,
Alpha = image.Alpha,
Styles = image.Styles.Add ("sel")
};
var img = new ImageBox (context, image);
img.ShowAll ();
it.Image = img;
GtkWorkarounds.ForceImageOnMenuItem (it);
} else {
if (defImage.HasValue) {
item.StateChanged -= ImageMenuItemStateChanged;
defImage = selImage = null;
}
it.Image = null;
}
}
void ImageMenuItemStateChanged (object o, Gtk.StateChangedArgs args)
{
var it = item as Gtk.ImageMenuItem;
var image = it?.Image as ImageBox;
if (image == null || selImage == null || defImage == null)
return;
if (it.State == Gtk.StateType.Prelight)
image.Image = selImage.Value;
else if (args.PreviousState == Gtk.StateType.Prelight)
image.Image = defImage.Value;
}
public string Label {
get {
return label != null ? (label.UseUnderline ? label.LabelProp : label.Text) : "";
}
set {
if (label.UseUnderline)
label.TextWithMnemonic = value;
else
label.Text = value;
}
}
public string TooltipText {
get {
return item.TooltipText;
}
set {
item.TooltipText = value;
}
}
public bool UseMnemonic {
get { return label.UseUnderline; }
set { label.UseUnderline = value; }
}
public bool Sensitive {
get {
return item.Sensitive;
}
set {
item.Sensitive = value;
}
}
public bool Visible {
get {
return item.Visible;
}
set {
item.Visible = value;
}
}
public bool Checked {
get { return (item is Gtk.CheckMenuItem) && ((Gtk.CheckMenuItem)item).Active; }
set {
if (item is Gtk.CheckMenuItem) {
changingCheck = true;
((Gtk.CheckMenuItem)item).Active = value;
changingCheck = false;
}
}
}
/* public void SetType (MenuItemType type)
{
string text = label.Text;
Gtk.MenuItem newItem = null;
switch (type) {
case MenuItemType.Normal:
if (!(item is Gtk.ImageMenuItem))
newItem = new Gtk.ImageMenuItem (text);
break;
case MenuItemType.CheckBox:
if (item.GetType () != typeof(Gtk.CheckMenuItem))
newItem = new Gtk.CheckMenuItem (text);
break;
case MenuItemType.RadioButton:
if (!(item is Gtk.RadioMenuItem))
newItem = new Gtk.RadioMenuItem (text);
break;
}
if (newItem != null) {
if ((newItem is Gtk.CheckMenuItem) && (item is Gtk.CheckMenuItem))
((Gtk.CheckMenuItem)item).Active = ((Gtk.CheckMenuItem)newItem).Active;
newItem.Sensitive = item.Sensitive;
if (item.Parent != null) {
Gtk.Menu m = (Gtk.Menu)item.Parent;
int pos = Array.IndexOf (m.Children, item);
m.Insert (newItem, pos);
m.Remove (item);
}
newItem.ShowAll ();
if (!item.Visible)
newItem.Hide ();
if (enabledEvents != null) {
foreach (var ob in enabledEvents)
DisableEvent (ob);
}
item = newItem;
label = (Gtk.Label) item.Child;
if (enabledEvents != null) {
foreach (var ob in enabledEvents)
EnableEvent (ob);
}
}
}*/
public void InitializeBackend (object frontend, ApplicationContext context)
{
this.context = context;
}
public void EnableEvent (object eventId)
{
if (eventId is MenuItemEvent) {
if (enabledEvents == null)
enabledEvents = new List<MenuItemEvent> ();
enabledEvents.Add ((MenuItemEvent)eventId);
if ((MenuItemEvent)eventId == MenuItemEvent.Clicked)
item.Activated += HandleItemActivated;
}
}
public void DisableEvent (object eventId)
{
if (eventId is MenuItemEvent) {
enabledEvents.Remove ((MenuItemEvent)eventId);
if ((MenuItemEvent)eventId == MenuItemEvent.Clicked)
item.Activated -= HandleItemActivated;
}
}
void HandleItemActivated (object sender, EventArgs e)
{
if (!changingCheck) {
context.InvokeUserCode (eventSink.OnClicked);
}
}
}
}
| |
// 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.Language.V1.Snippets
{
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedLanguageServiceClientSnippets
{
/// <summary>Snippet for AnalyzeSentiment</summary>
public void AnalyzeSentimentRequestObject()
{
// Snippet: AnalyzeSentiment(AnalyzeSentimentRequest, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSentimentAsync</summary>
public async Task AnalyzeSentimentRequestObjectAsync()
{
// Snippet: AnalyzeSentimentAsync(AnalyzeSentimentRequest, CallSettings)
// Additional: AnalyzeSentimentAsync(AnalyzeSentimentRequest, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSentiment</summary>
public void AnalyzeSentiment1()
{
// Snippet: AnalyzeSentiment(Document, EncodingType, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeSentimentAsync</summary>
public async Task AnalyzeSentiment1Async()
{
// Snippet: AnalyzeSentimentAsync(Document, EncodingType, CallSettings)
// Additional: AnalyzeSentimentAsync(Document, EncodingType, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeSentiment</summary>
public void AnalyzeSentiment2()
{
// Snippet: AnalyzeSentiment(Document, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(document);
// End snippet
}
/// <summary>Snippet for AnalyzeSentimentAsync</summary>
public async Task AnalyzeSentiment2Async()
{
// Snippet: AnalyzeSentimentAsync(Document, CallSettings)
// Additional: AnalyzeSentimentAsync(Document, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(document);
// End snippet
}
/// <summary>Snippet for AnalyzeEntities</summary>
public void AnalyzeEntitiesRequestObject()
{
// Snippet: AnalyzeEntities(AnalyzeEntitiesRequest, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitiesAsync</summary>
public async Task AnalyzeEntitiesRequestObjectAsync()
{
// Snippet: AnalyzeEntitiesAsync(AnalyzeEntitiesRequest, CallSettings)
// Additional: AnalyzeEntitiesAsync(AnalyzeEntitiesRequest, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntities</summary>
public void AnalyzeEntities1()
{
// Snippet: AnalyzeEntities(Document, EncodingType, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitiesAsync</summary>
public async Task AnalyzeEntities1Async()
{
// Snippet: AnalyzeEntitiesAsync(Document, EncodingType, CallSettings)
// Additional: AnalyzeEntitiesAsync(Document, EncodingType, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntities</summary>
public void AnalyzeEntities2()
{
// Snippet: AnalyzeEntities(Document, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(document);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitiesAsync</summary>
public async Task AnalyzeEntities2Async()
{
// Snippet: AnalyzeEntitiesAsync(Document, CallSettings)
// Additional: AnalyzeEntitiesAsync(Document, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(document);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentiment</summary>
public void AnalyzeEntitySentimentRequestObject()
{
// Snippet: AnalyzeEntitySentiment(AnalyzeEntitySentimentRequest, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentimentAsync</summary>
public async Task AnalyzeEntitySentimentRequestObjectAsync()
{
// Snippet: AnalyzeEntitySentimentAsync(AnalyzeEntitySentimentRequest, CallSettings)
// Additional: AnalyzeEntitySentimentAsync(AnalyzeEntitySentimentRequest, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentiment</summary>
public void AnalyzeEntitySentiment1()
{
// Snippet: AnalyzeEntitySentiment(Document, EncodingType, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentimentAsync</summary>
public async Task AnalyzeEntitySentiment1Async()
{
// Snippet: AnalyzeEntitySentimentAsync(Document, EncodingType, CallSettings)
// Additional: AnalyzeEntitySentimentAsync(Document, EncodingType, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentiment</summary>
public void AnalyzeEntitySentiment2()
{
// Snippet: AnalyzeEntitySentiment(Document, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(document);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentimentAsync</summary>
public async Task AnalyzeEntitySentiment2Async()
{
// Snippet: AnalyzeEntitySentimentAsync(Document, CallSettings)
// Additional: AnalyzeEntitySentimentAsync(Document, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(document);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntax</summary>
public void AnalyzeSyntaxRequestObject()
{
// Snippet: AnalyzeSyntax(AnalyzeSyntaxRequest, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntaxAsync</summary>
public async Task AnalyzeSyntaxRequestObjectAsync()
{
// Snippet: AnalyzeSyntaxAsync(AnalyzeSyntaxRequest, CallSettings)
// Additional: AnalyzeSyntaxAsync(AnalyzeSyntaxRequest, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntax</summary>
public void AnalyzeSyntax1()
{
// Snippet: AnalyzeSyntax(Document, EncodingType, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntaxAsync</summary>
public async Task AnalyzeSyntax1Async()
{
// Snippet: AnalyzeSyntaxAsync(Document, EncodingType, CallSettings)
// Additional: AnalyzeSyntaxAsync(Document, EncodingType, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntax</summary>
public void AnalyzeSyntax2()
{
// Snippet: AnalyzeSyntax(Document, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(document);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntaxAsync</summary>
public async Task AnalyzeSyntax2Async()
{
// Snippet: AnalyzeSyntaxAsync(Document, CallSettings)
// Additional: AnalyzeSyntaxAsync(Document, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(document);
// End snippet
}
/// <summary>Snippet for ClassifyText</summary>
public void ClassifyTextRequestObject()
{
// Snippet: ClassifyText(ClassifyTextRequest, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
ClassifyTextRequest request = new ClassifyTextRequest
{
Document = new Document(),
};
// Make the request
ClassifyTextResponse response = languageServiceClient.ClassifyText(request);
// End snippet
}
/// <summary>Snippet for ClassifyTextAsync</summary>
public async Task ClassifyTextRequestObjectAsync()
{
// Snippet: ClassifyTextAsync(ClassifyTextRequest, CallSettings)
// Additional: ClassifyTextAsync(ClassifyTextRequest, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
ClassifyTextRequest request = new ClassifyTextRequest
{
Document = new Document(),
};
// Make the request
ClassifyTextResponse response = await languageServiceClient.ClassifyTextAsync(request);
// End snippet
}
/// <summary>Snippet for ClassifyText</summary>
public void ClassifyText()
{
// Snippet: ClassifyText(Document, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
ClassifyTextResponse response = languageServiceClient.ClassifyText(document);
// End snippet
}
/// <summary>Snippet for ClassifyTextAsync</summary>
public async Task ClassifyTextAsync()
{
// Snippet: ClassifyTextAsync(Document, CallSettings)
// Additional: ClassifyTextAsync(Document, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
ClassifyTextResponse response = await languageServiceClient.ClassifyTextAsync(document);
// End snippet
}
/// <summary>Snippet for AnnotateText</summary>
public void AnnotateTextRequestObject()
{
// Snippet: AnnotateText(AnnotateTextRequest, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = new Document(),
Features = new AnnotateTextRequest.Types.Features(),
EncodingType = EncodingType.None,
};
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(request);
// End snippet
}
/// <summary>Snippet for AnnotateTextAsync</summary>
public async Task AnnotateTextRequestObjectAsync()
{
// Snippet: AnnotateTextAsync(AnnotateTextRequest, CallSettings)
// Additional: AnnotateTextAsync(AnnotateTextRequest, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = new Document(),
Features = new AnnotateTextRequest.Types.Features(),
EncodingType = EncodingType.None,
};
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(request);
// End snippet
}
/// <summary>Snippet for AnnotateText</summary>
public void AnnotateText1()
{
// Snippet: AnnotateText(Document, AnnotateTextRequest.Types.Features, EncodingType, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
EncodingType encodingType = EncodingType.None;
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(document, features, encodingType);
// End snippet
}
/// <summary>Snippet for AnnotateTextAsync</summary>
public async Task AnnotateText1Async()
{
// Snippet: AnnotateTextAsync(Document, AnnotateTextRequest.Types.Features, EncodingType, CallSettings)
// Additional: AnnotateTextAsync(Document, AnnotateTextRequest.Types.Features, EncodingType, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
EncodingType encodingType = EncodingType.None;
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(document, features, encodingType);
// End snippet
}
/// <summary>Snippet for AnnotateText</summary>
public void AnnotateText2()
{
// Snippet: AnnotateText(Document, AnnotateTextRequest.Types.Features, CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(document, features);
// End snippet
}
/// <summary>Snippet for AnnotateTextAsync</summary>
public async Task AnnotateText2Async()
{
// Snippet: AnnotateTextAsync(Document, AnnotateTextRequest.Types.Features, CallSettings)
// Additional: AnnotateTextAsync(Document, AnnotateTextRequest.Types.Features, CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(document, features);
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;
using System.Web.Routing;
using Kudu.Contracts.Infrastructure;
using Kudu.Contracts.Jobs;
using Kudu.Contracts.Settings;
using Kudu.Contracts.SiteExtensions;
using Kudu.Contracts.SourceControl;
using Kudu.Contracts.Tracing;
using Kudu.Core;
using Kudu.Core.Commands;
using Kudu.Core.Deployment;
using Kudu.Core.Deployment.Generator;
using Kudu.Core.Hooks;
using Kudu.Core.Infrastructure;
using Kudu.Core.Jobs;
using Kudu.Core.Settings;
using Kudu.Core.SiteExtensions;
using Kudu.Core.SourceControl;
using Kudu.Core.SourceControl.Git;
using Kudu.Core.SSHKey;
using Kudu.Core.Tracing;
using Kudu.Services.Diagnostics;
using Kudu.Services.GitServer;
using Kudu.Services.Infrastructure;
using Kudu.Services.Performance;
using Kudu.Services.ServiceHookHandlers;
using Kudu.Services.SSHKey;
using Kudu.Services.Web.Infrastructure;
using Kudu.Services.Web.Services;
using Kudu.Services.Web.Tracing;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Ninject;
using Ninject.Activation;
using Ninject.Web.Common;
using Owin;
using XmlSettings;
[assembly: WebActivator.PreApplicationStartMethod(typeof(Kudu.Services.Web.App_Start.NinjectServices), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(Kudu.Services.Web.App_Start.NinjectServices), "Stop")]
[assembly: OwinStartup(typeof(Kudu.Services.Web.App_Start.NinjectServices.SignalRStartup))]
namespace Kudu.Services.Web.App_Start
{
public static class NinjectServices
{
/// <summary>
/// Root directory that contains the VS target files
/// </summary>
private const string SdkRootDirectory = "msbuild";
private static readonly Bootstrapper _bootstrapper = new Bootstrapper();
// Due to a bug in Ninject we can't use Dispose to clean up LockFile so we shut it down manually
private static DeploymentLockFile _deploymentLock;
private static event Action Shutdown;
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
HttpApplication.RegisterModule(typeof(OnePerRequestHttpModule));
HttpApplication.RegisterModule(typeof(NinjectHttpModule));
_bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
if (Shutdown != null)
{
Shutdown();
}
if (_deploymentLock != null)
{
_deploymentLock.TerminateAsyncLocks();
_deploymentLock = null;
}
_bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Components.Add<INinjectHttpApplicationPlugin, NinjectHttpApplicationPlugin>();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "")]
private static void RegisterServices(IKernel kernel)
{
var serverConfiguration = new ServerConfiguration();
// Make sure %HOME% is correctly set
EnsureHomeEnvironmentVariable();
EnsureSiteBitnessEnvironmentVariable();
IEnvironment environment = GetEnvironment();
// Per request environment
kernel.Bind<IEnvironment>().ToMethod(context => GetEnvironment(context.Kernel.Get<IDeploymentSettingsManager>()))
.InRequestScope();
// General
kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current))
.InRequestScope();
kernel.Bind<IServerConfiguration>().ToConstant(serverConfiguration);
kernel.Bind<IBuildPropertyProvider>().ToConstant(new BuildPropertyProvider());
System.Func<ITracer> createTracerThunk = () => GetTracer(environment, kernel);
System.Func<ILogger> createLoggerThunk = () => GetLogger(environment, kernel);
// First try to use the current request profiler if any, otherwise create a new one
var traceFactory = new TracerFactory(() => TraceServices.CurrentRequestTracer ?? createTracerThunk());
kernel.Bind<ITracer>().ToMethod(context => TraceServices.CurrentRequestTracer ?? NullTracer.Instance);
kernel.Bind<ITraceFactory>().ToConstant(traceFactory);
TraceServices.SetTraceFactory(createTracerThunk, createLoggerThunk);
// Setup the deployment lock
string lockPath = Path.Combine(environment.SiteRootPath, Constants.LockPath);
string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile);
string statusLockPath = Path.Combine(lockPath, Constants.StatusLockFile);
string sshKeyLockPath = Path.Combine(lockPath, Constants.SSHKeyLockFile);
string hooksLockPath = Path.Combine(lockPath, Constants.HooksLockFile);
_deploymentLock = new DeploymentLockFile(deploymentLockPath, kernel.Get<ITraceFactory>());
_deploymentLock.InitializeAsyncLocks();
var statusLock = new LockFile(statusLockPath, kernel.Get<ITraceFactory>());
var sshKeyLock = new LockFile(sshKeyLockPath, kernel.Get<ITraceFactory>());
var hooksLock = new LockFile(hooksLockPath, kernel.Get<ITraceFactory>());
kernel.Bind<IOperationLock>().ToConstant(sshKeyLock).WhenInjectedInto<SSHKeyController>();
kernel.Bind<IOperationLock>().ToConstant(statusLock).WhenInjectedInto<DeploymentStatusManager>();
kernel.Bind<IOperationLock>().ToConstant(hooksLock).WhenInjectedInto<WebHooksManager>();
kernel.Bind<IOperationLock>().ToConstant(_deploymentLock);
var shutdownDetector = new ShutdownDetector();
shutdownDetector.Initialize();
IDeploymentSettingsManager noContextDeploymentsSettingsManager =
new DeploymentSettingsManager(new XmlSettings.Settings(GetSettingsPath(environment)));
var noContextTraceFactory = new TracerFactory(() => GetTracerWithoutContext(environment, noContextDeploymentsSettingsManager));
kernel.Bind<IAnalytics>().ToMethod(context => new Analytics(context.Kernel.Get<IDeploymentSettingsManager>(),
context.Kernel.Get<IServerConfiguration>(),
noContextTraceFactory));
// Trace unhandled (crash) exceptions.
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
var ex = args.ExceptionObject as Exception;
if (ex != null)
{
kernel.Get<IAnalytics>().UnexpectedException(ex);
}
};
// Trace shutdown event
// Cannot use shutdownDetector.Token.Register because of race condition
// with NinjectServices.Stop via WebActivator.ApplicationShutdownMethodAttribute
Shutdown += () => TraceShutdown(environment, noContextDeploymentsSettingsManager);
// LogStream service
// The hooks and log stream start endpoint are low traffic end-points. Re-using it to avoid creating another lock
var logStreamManagerLock = hooksLock;
kernel.Bind<LogStreamManager>().ToMethod(context => new LogStreamManager(Path.Combine(environment.RootPath, Constants.LogFilesPath),
context.Kernel.Get<IEnvironment>(),
context.Kernel.Get<IDeploymentSettingsManager>(),
context.Kernel.Get<ITracer>(),
shutdownDetector,
logStreamManagerLock));
kernel.Bind<InfoRefsController>().ToMethod(context => new InfoRefsController(t => context.Kernel.Get(t)))
.InRequestScope();
kernel.Bind<CustomGitRepositoryHandler>().ToMethod(context => new CustomGitRepositoryHandler(t => context.Kernel.Get(t)))
.InRequestScope();
// Deployment Service
kernel.Bind<ISettings>().ToMethod(context => new XmlSettings.Settings(GetSettingsPath(environment)))
.InRequestScope();
kernel.Bind<IDeploymentSettingsManager>().To<DeploymentSettingsManager>()
.InRequestScope();
kernel.Bind<IDeploymentStatusManager>().To<DeploymentStatusManager>()
.InRequestScope();
kernel.Bind<ISiteBuilderFactory>().To<SiteBuilderFactory>()
.InRequestScope();
kernel.Bind<IWebHooksManager>().To<WebHooksManager>()
.InRequestScope();
ITriggeredJobsManager triggeredJobsManager = new TriggeredJobsManager(
noContextTraceFactory,
kernel.Get<IEnvironment>(),
kernel.Get<IDeploymentSettingsManager>(),
kernel.Get<IAnalytics>(),
kernel.Get<IWebHooksManager>());
kernel.Bind<ITriggeredJobsManager>().ToConstant(triggeredJobsManager)
.InTransientScope();
IContinuousJobsManager continuousJobManager = new ContinuousJobsManager(
noContextTraceFactory,
kernel.Get<IEnvironment>(),
kernel.Get<IDeploymentSettingsManager>(),
kernel.Get<IAnalytics>());
triggeredJobsManager.CleanupDeletedJobs();
continuousJobManager.CleanupDeletedJobs();
kernel.Bind<IContinuousJobsManager>().ToConstant(continuousJobManager)
.InTransientScope();
kernel.Bind<ILogger>().ToMethod(context => GetLogger(environment, context.Kernel))
.InRequestScope();
kernel.Bind<IDeploymentManager>().To<DeploymentManager>()
.InRequestScope();
kernel.Bind<IAutoSwapHandler>().To<AutoSwapHandler>()
.InRequestScope();
kernel.Bind<ISSHKeyManager>().To<SSHKeyManager>()
.InRequestScope();
kernel.Bind<IRepositoryFactory>().ToMethod(context => _deploymentLock.RepositoryFactory = new RepositoryFactory(context.Kernel.Get<IEnvironment>(),
context.Kernel.Get<IDeploymentSettingsManager>(),
context.Kernel.Get<ITraceFactory>(),
context.Kernel.Get<HttpContextBase>()))
.InRequestScope();
kernel.Bind<IApplicationLogsReader>().To<ApplicationLogsReader>()
.InSingletonScope();
// Git server
kernel.Bind<IDeploymentEnvironment>().To<DeploymentEnvrionment>();
kernel.Bind<IGitServer>().ToMethod(context => new GitExeServer(context.Kernel.Get<IEnvironment>(),
_deploymentLock,
GetRequestTraceFile(context.Kernel),
context.Kernel.Get<IRepositoryFactory>(),
context.Kernel.Get<IDeploymentEnvironment>(),
context.Kernel.Get<IDeploymentSettingsManager>(),
context.Kernel.Get<ITraceFactory>()))
.InRequestScope();
// Git Servicehook parsers
kernel.Bind<IServiceHookHandler>().To<GenericHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<GitHubHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<BitbucketHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<DropboxHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<CodePlexHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<CodebaseHqHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<GitlabHqHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<GitHubCompatHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<KilnHgHandler>().InRequestScope();
// SiteExtensions
kernel.Bind<ISiteExtensionManager>().To<SiteExtensionManager>().InRequestScope();
// Command executor
kernel.Bind<ICommandExecutor>().ToMethod(context => GetCommandExecutor(environment, context))
.InRequestScope();
MigrateSite(environment, noContextDeploymentsSettingsManager);
RemoveOldTracePath(environment);
// Temporary fix for https://github.com/npm/npm/issues/5905
EnsureNpmGlobalDirectory();
RegisterRoutes(kernel, RouteTable.Routes);
// Register the default hubs route: ~/signalr
GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel);
GlobalConfiguration.Configuration.Filters.Add(
new TraceDeprecatedActionAttribute(
kernel.Get<IAnalytics>(),
kernel.Get<ITraceFactory>()));
GlobalConfiguration.Configuration.Filters.Add(new EnsureRequestIdHandlerAttribute());
}
public static class SignalRStartup
{
public static void Configuration(IAppBuilder app)
{
app.MapSignalR<PersistentCommandController>("/api/commandstream");
app.MapSignalR("/api/filesystemhub", new HubConfiguration());
}
}
public class SignalRNinjectDependencyResolver : DefaultDependencyResolver
{
private readonly IKernel _kernel;
public SignalRNinjectDependencyResolver(IKernel kernel)
{
_kernel = kernel;
}
public override object GetService(Type serviceType)
{
return _kernel.TryGet(serviceType) ?? base.GetService(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
return System.Linq.Enumerable.Concat(_kernel.GetAll(serviceType), base.GetServices(serviceType));
}
}
public static void RegisterRoutes(IKernel kernel, RouteCollection routes)
{
var configuration = kernel.Get<IServerConfiguration>();
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
var jsonFormatter = new JsonMediaTypeFormatter();
GlobalConfiguration.Configuration.Formatters.Add(jsonFormatter);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectWebApiDependencyResolver(kernel);
GlobalConfiguration.Configuration.Filters.Add(new TraceExceptionFilterAttribute());
// Git Service
routes.MapHttpRoute("git-info-refs-root", "info/refs", new { controller = "InfoRefs", action = "Execute" });
routes.MapHttpRoute("git-info-refs", configuration.GitServerRoot + "/info/refs", new { controller = "InfoRefs", action = "Execute" });
// Push url
routes.MapHandler<ReceivePackHandler>(kernel, "git-receive-pack-root", "git-receive-pack", deprecated: false);
routes.MapHandler<ReceivePackHandler>(kernel, "git-receive-pack", configuration.GitServerRoot + "/git-receive-pack", deprecated: false);
// Fetch Hook
routes.MapHandler<FetchHandler>(kernel, "fetch", "deploy", deprecated: false);
// Clone url
routes.MapHandler<UploadPackHandler>(kernel, "git-upload-pack-root", "git-upload-pack", deprecated: false);
routes.MapHandler<UploadPackHandler>(kernel, "git-upload-pack", configuration.GitServerRoot + "/git-upload-pack", deprecated: false);
// Custom GIT repositories, which can be served from any directory that has a git repo
routes.MapHandler<CustomGitRepositoryHandler>(kernel, "git-custom-repository", "git/{*path}", deprecated: false);
// Scm (deployment repository)
routes.MapHttpRouteDual("scm-info", "scm/info", new { controller = "LiveScm", action = "GetRepositoryInfo" });
routes.MapHttpRouteDual("scm-clean", "scm/clean", new { controller = "LiveScm", action = "Clean" });
routes.MapHttpRouteDual("scm-delete", "scm", new { controller = "LiveScm", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
// Scm files editor
routes.MapHttpRouteDual("scm-get-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") });
routes.MapHttpRouteDual("scm-put-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRouteDual("scm-delete-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "DeleteItem" }, new { verb = new HttpMethodConstraint("DELETE") });
// Live files editor
routes.MapHttpRouteDual("vfs-get-files", "vfs/{*path}", new { controller = "Vfs", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") });
routes.MapHttpRouteDual("vfs-put-files", "vfs/{*path}", new { controller = "Vfs", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRouteDual("vfs-delete-files", "vfs/{*path}", new { controller = "Vfs", action = "DeleteItem" }, new { verb = new HttpMethodConstraint("DELETE") });
// Zip file handler
routes.MapHttpRouteDual("zip-get-files", "zip/{*path}", new { controller = "Zip", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") });
routes.MapHttpRouteDual("zip-put-files", "zip/{*path}", new { controller = "Zip", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") });
// Live Command Line
routes.MapHttpRouteDual("execute-command", "command", new { controller = "Command", action = "ExecuteCommand" }, new { verb = new HttpMethodConstraint("POST") });
// Deployments
routes.MapHttpRouteDual("all-deployments", "deployments", new { controller = "Deployment", action = "GetDeployResults" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("one-deployment-get", "deployments/{id}", new { controller = "Deployment", action = "GetResult" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("one-deployment-put", "deployments/{id}", new { controller = "Deployment", action = "Deploy", id = RouteParameter.Optional }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRouteDual("one-deployment-delete", "deployments/{id}", new { controller = "Deployment", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpRouteDual("one-deployment-log", "deployments/{id}/log", new { controller = "Deployment", action = "GetLogEntry" });
routes.MapHttpRouteDual("one-deployment-log-details", "deployments/{id}/log/{logId}", new { controller = "Deployment", action = "GetLogEntryDetails" });
// Deployment script
routes.MapHttpRoute("get-deployment-script", "api/deploymentscript", new { controller = "Deployment", action = "GetDeploymentScript" }, new { verb = new HttpMethodConstraint("GET") });
// SSHKey
routes.MapHttpRouteDual("get-sshkey", "sshkey", new { controller = "SSHKey", action = "GetPublicKey" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("put-sshkey", "sshkey", new { controller = "SSHKey", action = "SetPrivateKey" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRouteDual("delete-sshkey", "sshkey", new { controller = "SSHKey", action = "DeleteKeyPair" }, new { verb = new HttpMethodConstraint("DELETE") });
// Environment
routes.MapHttpRouteDual("get-env", "environment", new { controller = "Environment", action = "Get" }, new { verb = new HttpMethodConstraint("GET") });
// Settings
routes.MapHttpRouteDual("set-setting", "settings", new { controller = "Settings", action = "Set" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpRoute("get-all-settings-old", "settings", new { controller = "Settings", action = "GetAll" }, new { verb = new HttpMethodConstraint("GET") }, deprecated: true);
routes.MapHttpRoute("get-all-settings", "api/settings", new { controller = "Settings", action = "GetAll", version = 2 }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("get-setting", "settings/{key}", new { controller = "Settings", action = "Get" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("delete-setting", "settings/{key}", new { controller = "Settings", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
// Diagnostics
routes.MapHttpRouteDual("diagnostics", "dump", new { controller = "Diagnostics", action = "GetLog" });
routes.MapHttpRouteDual("diagnostics-set-setting", "diagnostics/settings", new { controller = "Diagnostics", action = "Set" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpRouteDual("diagnostics-get-all-settings", "diagnostics/settings", new { controller = "Diagnostics", action = "GetAll" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("diagnostics-get-setting", "diagnostics/settings/{key}", new { controller = "Diagnostics", action = "Get" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("diagnostics-delete-setting", "diagnostics/settings/{key}", new { controller = "Diagnostics", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
// Logs
routes.MapHandlerDual<LogStreamHandler>(kernel, "logstream", "logstream/{*path}");
routes.MapHttpRoute("recent-logs", "api/logs/recent", new { controller = "Diagnostics", action = "GetRecentLogs" }, new { verb = new HttpMethodConstraint("GET") });
// Processes
routes.MapHttpProcessesRoute("all-processes", "", new { controller = "Process", action = "GetAllProcesses" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("one-process-get", "/{id}", new { controller = "Process", action = "GetProcess" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("one-process-delete", "/{id}", new { controller = "Process", action = "KillProcess" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpProcessesRoute("one-process-dump", "/{id}/dump", new { controller = "Process", action = "MiniDump" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("all-threads", "/{id}/threads", new { controller = "Process", action = "GetAllThreads" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("one-process-thread", "/{processId}/threads/{threadId}", new { controller = "Process", action = "GetThread" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("all-modules", "/{id}/modules", new { controller = "Process", action = "GetAllModules" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("one-process-module", "/{id}/modules/{baseAddress}", new { controller = "Process", action = "GetModule" }, new { verb = new HttpMethodConstraint("GET") });
// Runtime
routes.MapHttpRouteDual("runtime", "diagnostics/runtime", new { controller = "Runtime", action = "GetRuntimeVersions" }, new { verb = new HttpMethodConstraint("GET") });
// Hooks
routes.MapHttpRouteDual("unsubscribe-hook", "hooks/{id}", new { controller = "WebHooks", action = "Unsubscribe" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpRouteDual("get-hook", "hooks/{id}", new { controller = "WebHooks", action = "GetWebHook" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("publish-hooks", "hooks/publish/{hookEventType}", new { controller = "WebHooks", action = "PublishEvent" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpRouteDual("get-hooks", "hooks", new { controller = "WebHooks", action = "GetWebHooks" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("subscribe-hook", "hooks", new { controller = "WebHooks", action = "Subscribe" }, new { verb = new HttpMethodConstraint("POST") });
// Jobs
routes.MapHttpWebJobsRoute("list-all-jobs", "", "", new { controller = "Jobs", action = "ListAllJobs" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("list-triggered-jobs", "triggered", "", new { controller = "Jobs", action = "ListTriggeredJobs" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("get-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "GetTriggeredJob" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("invoke-triggered-job", "triggered", "/{jobName}/run", new { controller = "Jobs", action = "InvokeTriggeredJob" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpWebJobsRoute("get-triggered-job-history", "triggered", "/{jobName}/history", new { controller = "Jobs", action = "GetTriggeredJobHistory" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("get-triggered-job-run", "triggered", "/{jobName}/history/{runId}", new { controller = "Jobs", action = "GetTriggeredJobRun" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("create-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "CreateTriggeredJob" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpWebJobsRoute("remove-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "RemoveTriggeredJob" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpWebJobsRoute("get-triggered-job-settings", "triggered", "/{jobName}/settings", new { controller = "Jobs", action = "GetTriggeredJobSettings" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("set-triggered-job-settings", "triggered", "/{jobName}/settings", new { controller = "Jobs", action = "SetTriggeredJobSettings" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpWebJobsRoute("list-continuous-jobs", "continuous", "", new { controller = "Jobs", action = "ListContinuousJobs" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("get-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "GetContinuousJob" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("disable-continuous-job", "continuous", "/{jobName}/stop", new { controller = "Jobs", action = "DisableContinuousJob" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpWebJobsRoute("enable-continuous-job", "continuous", "/{jobName}/start", new { controller = "Jobs", action = "EnableContinuousJob" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpWebJobsRoute("create-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "CreateContinuousJob" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpWebJobsRoute("remove-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "RemoveContinuousJob" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpWebJobsRoute("get-continuous-job-settings", "continuous", "/{jobName}/settings", new { controller = "Jobs", action = "GetContinuousJobSettings" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("set-continuous-job-settings", "continuous", "/{jobName}/settings", new { controller = "Jobs", action = "SetContinuousJobSettings" }, new { verb = new HttpMethodConstraint("PUT") });
// Web Jobs as microservice
routes.MapHttpRoute("list-triggered-jobs-swagger", "api/triggeredwebjobsswagger", new { controller = "Jobs", action = "ListTriggeredJobsInSwaggerFormat" }, new { verb = new HttpMethodConstraint("GET") });
// SiteExtensions
routes.MapHttpRoute("api-get-remote-extensions", "api/extensionfeed", new { controller = "SiteExtension", action = "GetRemoteExtensions" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("api-get-remote-extension", "api/extensionfeed/{id}", new { controller = "SiteExtension", action = "GetRemoteExtension" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("api-get-local-extensions", "api/siteextensions", new { controller = "SiteExtension", action = "GetLocalExtensions" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("api-get-local-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "GetLocalExtension" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("api-uninstall-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "UninstallExtension" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpRoute("api-install-update-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "InstallExtension" }, new { verb = new HttpMethodConstraint("PUT") });
// catch all unregistered url to properly handle not found
// this is to work arounf the issue in TraceModule where we see double OnBeginRequest call
// for the same request (404 and then 200 statusCode).
routes.MapHttpRoute("error-404", "{*path}", new { controller = "Error404", action = "Handle" });
}
// remove old LogFiles/Git trace
private static void RemoveOldTracePath(IEnvironment environment)
{
FileSystemHelpers.DeleteDirectorySafe(Path.Combine(environment.LogFilesPath, "Git"), ignoreErrors: true);
}
// Perform migration tasks to deal with legacy sites that had different file layout
private static void MigrateSite(IEnvironment environment, IDeploymentSettingsManager settings)
{
try
{
MoveOldSSHFolder(environment);
}
catch (Exception e)
{
ITracer tracer = GetTracerWithoutContext(environment, settings);
tracer.Trace("Failed to move legacy .ssh folder: {0}", e.Message);
}
}
// .ssh folder used to be under /site, and is now at the root
private static void MoveOldSSHFolder(IEnvironment environment)
{
var oldSSHDirInfo = new DirectoryInfo(Path.Combine(environment.SiteRootPath, Constants.SSHKeyPath));
if (oldSSHDirInfo.Exists)
{
string newSSHFolder = Path.Combine(environment.RootPath, Constants.SSHKeyPath);
if (!Directory.Exists(newSSHFolder))
{
Directory.CreateDirectory(newSSHFolder);
}
foreach (FileInfo file in oldSSHDirInfo.EnumerateFiles())
{
// Copy the file to the new folder, unless it already exists
string newFile = Path.Combine(newSSHFolder, file.Name);
if (!File.Exists(newFile))
{
file.CopyTo(newFile, overwrite: true);
}
}
// Delete the old folder
oldSSHDirInfo.Delete(recursive: true);
}
}
private static void EnsureNpmGlobalDirectory()
{
try
{
string appData = System.Environment.GetEnvironmentVariable("APPDATA");
FileSystemHelpers.EnsureDirectory(Path.Combine(appData, "npm"));
// discovered while adding npm 2.1.17
// this is to work around below issue with the very first npm install
// npm ERR! uid must be an unsigned int
FileSystemHelpers.EnsureDirectory(Path.Combine(appData, "npm-cache"));
}
catch
{
// no op
}
}
private static ITracer GetTracer(IEnvironment environment, IKernel kernel)
{
TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel();
if (level > TraceLevel.Off && TraceServices.CurrentRequestTraceFile != null)
{
string textPath = Path.Combine(environment.TracePath, TraceServices.CurrentRequestTraceFile);
return new CascadeTracer(new XmlTracer(environment.TracePath, level), new TextTracer(textPath, level));
}
return NullTracer.Instance;
}
private static ITracer GetTracerWithoutContext(IEnvironment environment, IDeploymentSettingsManager settings)
{
TraceLevel level = settings.GetTraceLevel();
if (level > TraceLevel.Off)
{
return new XmlTracer(environment.TracePath, level);
}
return NullTracer.Instance;
}
private static void TraceShutdown(IEnvironment environment, IDeploymentSettingsManager settings)
{
ITracer tracer = GetTracerWithoutContext(environment, settings);
var attribs = new Dictionary<string, string>();
// Add an attribute containing the process, AppDomain and Thread ids to help debugging
attribs.Add("pid", String.Format("{0},{1},{2}",
Process.GetCurrentProcess().Id,
AppDomain.CurrentDomain.Id.ToString(),
System.Threading.Thread.CurrentThread.ManagedThreadId));
attribs.Add("uptime", TraceModule.UpTime.ToString());
attribs.Add("lastrequesttime", TraceModule.LastRequestTime.ToString());
tracer.Trace(XmlTracer.ProcessShutdownTrace, attribs);
}
private static ILogger GetLogger(IEnvironment environment, IKernel kernel)
{
TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel();
if (level > TraceLevel.Off && TraceServices.CurrentRequestTraceFile != null)
{
string textPath = Path.Combine(environment.DeploymentTracePath, TraceServices.CurrentRequestTraceFile);
return new TextLogger(textPath);
}
return NullLogger.Instance;
}
private static string GetRequestTraceFile(IKernel kernel)
{
TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel();
if (level > TraceLevel.Off)
{
return TraceServices.CurrentRequestTraceFile;
}
return null;
}
private static ICommandExecutor GetCommandExecutor(IEnvironment environment, IContext context)
{
if (System.String.IsNullOrEmpty(environment.RepositoryPath))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return new CommandExecutor(environment.RootPath, environment, context.Kernel.Get<IDeploymentSettingsManager>(), TraceServices.CurrentRequestTracer);
}
private static string GetSettingsPath(IEnvironment environment)
{
return Path.Combine(environment.DeploymentsPath, Constants.DeploySettingsPath);
}
private static void EnsureHomeEnvironmentVariable()
{
// If MapPath("/_app") returns a valid folder, set %HOME% to that, regardless of
// it current value. This is the non-Azure code path.
string path = HostingEnvironment.MapPath(Constants.MappedSite);
if (Directory.Exists(path))
{
path = Path.GetFullPath(path);
System.Environment.SetEnvironmentVariable("HOME", path);
}
}
private static void EnsureSiteBitnessEnvironmentVariable()
{
if (System.Environment.GetEnvironmentVariable("SITE_BITNESS") == null)
{
System.Environment.SetEnvironmentVariable("SITE_BITNESS", System.Environment.Is64BitProcess ? Constants.X64Bit : Constants.X86Bit);
}
}
private static IEnvironment GetEnvironment(IDeploymentSettingsManager settings = null)
{
string root = PathResolver.ResolveRootPath();
string siteRoot = Path.Combine(root, Constants.SiteFolder);
string repositoryPath = Path.Combine(siteRoot, settings == null ? Constants.RepositoryPath : settings.GetRepositoryPath());
return new Kudu.Core.Environment(
root,
HttpRuntime.BinDirectory,
repositoryPath);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Certificates.Generation;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.AspNetCore.Server.Kestrel.Https.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Server.Kestrel.Core
{
/// <summary>
/// Provides programmatic configuration of Kestrel-specific features.
/// </summary>
public class KestrelServerOptions
{
// internal to fast-path header decoding when RequestHeaderEncodingSelector is unchanged.
internal static readonly Func<string, Encoding?> DefaultHeaderEncodingSelector = _ => null;
private Func<string, Encoding?> _requestHeaderEncodingSelector = DefaultHeaderEncodingSelector;
private Func<string, Encoding?> _responseHeaderEncodingSelector = DefaultHeaderEncodingSelector;
// The following two lists configure the endpoints that Kestrel should listen to. If both lists are empty, the "urls" config setting (e.g. UseUrls) is used.
internal List<ListenOptions> CodeBackedListenOptions { get; } = new List<ListenOptions>();
internal List<ListenOptions> ConfigurationBackedListenOptions { get; } = new List<ListenOptions>();
internal IEnumerable<ListenOptions> ListenOptions => CodeBackedListenOptions.Concat(ConfigurationBackedListenOptions);
// For testing and debugging.
internal List<ListenOptions> OptionsInUse { get; } = new List<ListenOptions>();
/// <summary>
/// Gets or sets whether the <c>Server</c> header should be included in each response.
/// </summary>
/// <remarks>
/// Defaults to true.
/// </remarks>
public bool AddServerHeader { get; set; } = true;
/// <summary>
/// Gets or sets a value that controls whether dynamic compression of response headers is allowed.
/// For more information about the security considerations of HPack dynamic header compression, visit
/// https://tools.ietf.org/html/rfc7541#section-7.
/// </summary>
/// <remarks>
/// Defaults to true.
/// </remarks>
public bool AllowResponseHeaderCompression { get; set; } = true;
/// <summary>
/// Gets or sets a value that controls whether synchronous IO is allowed for the <see cref="HttpContext.Request"/> and <see cref="HttpContext.Response"/>
/// </summary>
/// <remarks>
/// Defaults to false.
/// </remarks>
public bool AllowSynchronousIO { get; set; }
/// <summary>
/// Gets or sets a value that controls how the `:scheme` field for HTTP/2 and HTTP/3 requests is validated.
/// <para>
/// If <c>false</c> then the `:scheme` field for HTTP/2 and HTTP/3 requests must exactly match the transport (e.g. https for TLS
/// connections, http for non-TLS). If <c>true</c> then the `:scheme` field for HTTP/2 and HTTP/3 requests can be set to alternate values
/// and this will be reflected by `HttpRequest.Scheme`. The Scheme must still be valid according to
/// https://datatracker.ietf.org/doc/html/rfc3986/#section-3.1. Only enable this when working with a trusted proxy. This can be used in
/// scenarios such as proxies converting from alternate protocols. See https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2.3.
/// Applications that enable this should validate an expected scheme is provided before using it.
/// </para>
/// </summary>
/// <remarks>
/// Defaults to <c>false</c>.
/// </remarks>
public bool AllowAlternateSchemes { get; set; }
/// <summary>
/// Gets or sets a value that controls whether the string values materialized
/// will be reused across requests; if they match, or if the strings will always be reallocated.
/// </summary>
/// <remarks>
/// Defaults to false.
/// </remarks>
public bool DisableStringReuse { get; set; }
/// <summary>
/// Controls whether to return the "Alt-Svc" header from an HTTP/2 or lower response for HTTP/3.
/// </summary>
/// <remarks>
/// Defaults to false.
/// </remarks>
[Obsolete($"This property is obsolete and will be removed in a future version. It no longer has any impact on runtime behavior. Use {nameof(Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions)}.{nameof(Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions.DisableAltSvcHeader)} to configure \"Alt-Svc\" behavior.", error: true)]
public bool EnableAltSvc { get; set; }
/// <summary>
/// Gets or sets a callback that returns the <see cref="Encoding"/> to decode the value for the specified request header name,
/// or <see langword="null"/> to use the default <see cref="UTF8Encoding"/>.
/// </summary>
public Func<string, Encoding?> RequestHeaderEncodingSelector
{
get => _requestHeaderEncodingSelector;
set => _requestHeaderEncodingSelector = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Gets or sets a callback that returns the <see cref="Encoding"/> to encode the value for the specified response header
/// or trailer name, or <see langword="null"/> to use the default <see cref="ASCIIEncoding"/>.
/// </summary>
public Func<string, Encoding?> ResponseHeaderEncodingSelector
{
get => _responseHeaderEncodingSelector;
set => _responseHeaderEncodingSelector = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Enables the Listen options callback to resolve and use services registered by the application during startup.
/// Typically initialized by UseKestrel().
/// </summary>
public IServiceProvider ApplicationServices { get; set; } = default!; // This should typically be set
/// <summary>
/// Provides access to request limit options.
/// </summary>
public KestrelServerLimits Limits { get; } = new KestrelServerLimits();
/// <summary>
/// Provides a configuration source where endpoints will be loaded from on server start.
/// The default is <see langword="null"/>.
/// </summary>
public KestrelConfigurationLoader? ConfigurationLoader { get; set; }
/// <summary>
/// A default configuration action for all endpoints. Use for Listen, configuration, the default url, and URLs.
/// </summary>
private Action<ListenOptions> EndpointDefaults { get; set; } = _ => { };
/// <summary>
/// A default configuration action for all https endpoints.
/// </summary>
private Action<HttpsConnectionAdapterOptions> HttpsDefaults { get; set; } = _ => { };
/// <summary>
/// The default server certificate for https endpoints. This is applied lazily after HttpsDefaults and user options.
/// </summary>
internal X509Certificate2? DefaultCertificate { get; set; }
/// <summary>
/// Has the default dev certificate load been attempted?
/// </summary>
internal bool IsDevCertLoaded { get; set; }
/// <summary>
/// Specifies a configuration Action to run for each newly created endpoint. Calling this again will replace
/// the prior action.
/// </summary>
public void ConfigureEndpointDefaults(Action<ListenOptions> configureOptions)
{
EndpointDefaults = configureOptions ?? throw new ArgumentNullException(nameof(configureOptions));
}
internal void ApplyEndpointDefaults(ListenOptions listenOptions)
{
listenOptions.KestrelServerOptions = this;
ConfigurationLoader?.ApplyEndpointDefaults(listenOptions);
EndpointDefaults(listenOptions);
}
/// <summary>
/// Specifies a configuration Action to run for each newly created https endpoint. Calling this again will replace
/// the prior action.
/// </summary>
public void ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions> configureOptions)
{
HttpsDefaults = configureOptions ?? throw new ArgumentNullException(nameof(configureOptions));
}
internal void ApplyHttpsDefaults(HttpsConnectionAdapterOptions httpsOptions)
{
ConfigurationLoader?.ApplyHttpsDefaults(httpsOptions);
HttpsDefaults(httpsOptions);
}
internal void ApplyDefaultCert(HttpsConnectionAdapterOptions httpsOptions)
{
if (httpsOptions.ServerCertificate != null || httpsOptions.ServerCertificateSelector != null)
{
return;
}
EnsureDefaultCert();
httpsOptions.ServerCertificate = DefaultCertificate;
}
internal void Serialize(Utf8JsonWriter writer)
{
writer.WritePropertyName(nameof(AllowSynchronousIO));
writer.WriteBooleanValue(AllowSynchronousIO);
writer.WritePropertyName(nameof(AddServerHeader));
writer.WriteBooleanValue(AddServerHeader);
writer.WritePropertyName(nameof(AllowAlternateSchemes));
writer.WriteBooleanValue(AllowAlternateSchemes);
writer.WritePropertyName(nameof(AllowResponseHeaderCompression));
writer.WriteBooleanValue(AllowResponseHeaderCompression);
writer.WritePropertyName(nameof(EnableAltSvc));
writer.WriteBooleanValue(EnableAltSvc);
writer.WritePropertyName(nameof(IsDevCertLoaded));
writer.WriteBooleanValue(IsDevCertLoaded);
writer.WriteString(nameof(RequestHeaderEncodingSelector), RequestHeaderEncodingSelector == DefaultHeaderEncodingSelector ? "default" : "configured");
writer.WriteString(nameof(ResponseHeaderEncodingSelector), ResponseHeaderEncodingSelector == DefaultHeaderEncodingSelector ? "default" : "configured");
// Limits
writer.WritePropertyName(nameof(Limits));
writer.WriteStartObject();
Limits.Serialize(writer);
writer.WriteEndObject();
// ListenOptions
writer.WritePropertyName(nameof(ListenOptions));
writer.WriteStartArray();
foreach (var listenOptions in OptionsInUse)
{
writer.WriteStartObject();
writer.WriteString("Address", listenOptions.GetDisplayName());
writer.WritePropertyName(nameof(listenOptions.IsTls));
writer.WriteBooleanValue(listenOptions.IsTls);
writer.WriteString(nameof(listenOptions.Protocols), listenOptions.Protocols.ToString());
writer.WriteEndObject();
}
writer.WriteEndArray();
}
private void EnsureDefaultCert()
{
if (DefaultCertificate == null && !IsDevCertLoaded)
{
IsDevCertLoaded = true; // Only try once
var logger = ApplicationServices!.GetRequiredService<ILogger<KestrelServer>>();
try
{
DefaultCertificate = CertificateManager.Instance.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true)
.FirstOrDefault();
if (DefaultCertificate != null)
{
var status = CertificateManager.Instance.CheckCertificateState(DefaultCertificate, interactive: false);
if (!status.Success)
{
// Display a warning indicating to the user that a prompt might appear and provide instructions on what to do in that
// case. The underlying implementation of this check is specific to Mac OS and is handled within CheckCertificateState.
// Kestrel must NEVER cause a UI prompt on a production system. We only attempt this here because Mac OS is not supported
// in production.
Debug.Assert(status.FailureMessage != null, "Status with a failure result must have a message.");
logger.DeveloperCertificateFirstRun(status.FailureMessage);
// Now that we've displayed a warning in the logs so that the user gets a notification that a prompt might appear, try
// and access the certificate key, which might trigger a prompt.
status = CertificateManager.Instance.CheckCertificateState(DefaultCertificate, interactive: true);
if (!status.Success)
{
logger.BadDeveloperCertificateState();
}
}
logger.LocatedDevelopmentCertificate(DefaultCertificate);
}
else
{
logger.UnableToLocateDevelopmentCertificate();
}
}
catch
{
logger.UnableToLocateDevelopmentCertificate();
}
}
}
/// <summary>
/// Creates a configuration loader for setting up Kestrel.
/// </summary>
/// <returns>A <see cref="KestrelConfigurationLoader"/> for configuring endpoints.</returns>
public KestrelConfigurationLoader Configure() => Configure(new ConfigurationBuilder().Build());
/// <summary>
/// Creates a configuration loader for setting up Kestrel that takes an <see cref="IConfiguration"/> as input.
/// This configuration must be scoped to the configuration section for Kestrel.
/// Call <see cref="Configure(IConfiguration, bool)"/> to enable dynamic endpoint binding updates.
/// </summary>
/// <param name="config">The configuration section for Kestrel.</param>
/// <returns>A <see cref="KestrelConfigurationLoader"/> for further endpoint configuration.</returns>
public KestrelConfigurationLoader Configure(IConfiguration config) => Configure(config, reloadOnChange: false);
/// <summary>
/// Creates a configuration loader for setting up Kestrel that takes an <see cref="IConfiguration"/> as input.
/// This configuration must be scoped to the configuration section for Kestrel.
/// </summary>
/// <param name="config">The configuration section for Kestrel.</param>
/// <param name="reloadOnChange">
/// If <see langword="true"/>, Kestrel will dynamically update endpoint bindings when configuration changes.
/// This will only reload endpoints defined in the "Endpoints" section of your <paramref name="config"/>. Endpoints defined in code will not be reloaded.
/// </param>
/// <returns>A <see cref="KestrelConfigurationLoader"/> for further endpoint configuration.</returns>
public KestrelConfigurationLoader Configure(IConfiguration config, bool reloadOnChange)
{
if (ApplicationServices is null)
{
throw new InvalidOperationException($"{nameof(ApplicationServices)} must not be null. This is normally set automatically via {nameof(IConfigureOptions<KestrelServerOptions>)}.");
}
var hostEnvironment = ApplicationServices.GetRequiredService<IHostEnvironment>();
var logger = ApplicationServices.GetRequiredService<ILogger<KestrelServer>>();
var httpsLogger = ApplicationServices.GetRequiredService<ILogger<HttpsConnectionMiddleware>>();
var loader = new KestrelConfigurationLoader(this, config, hostEnvironment, reloadOnChange, logger, httpsLogger);
ConfigurationLoader = loader;
return loader;
}
/// <summary>
/// Bind to given IP address and port.
/// </summary>
public void Listen(IPAddress address, int port)
{
Listen(address, port, _ => { });
}
/// <summary>
/// Bind to given IP address and port.
/// The callback configures endpoint-specific settings.
/// </summary>
public void Listen(IPAddress address, int port, Action<ListenOptions> configure)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
Listen(new IPEndPoint(address, port), configure);
}
/// <summary>
/// Bind to the given IP endpoint.
/// </summary>
public void Listen(IPEndPoint endPoint)
{
Listen((EndPoint)endPoint);
}
/// <summary>
/// Bind to the given endpoint.
/// </summary>
/// <param name="endPoint"></param>
public void Listen(EndPoint endPoint)
{
Listen(endPoint, _ => { });
}
/// <summary>
/// Bind to given IP address and port.
/// The callback configures endpoint-specific settings.
/// </summary>
public void Listen(IPEndPoint endPoint, Action<ListenOptions> configure)
{
Listen((EndPoint)endPoint, configure);
}
/// <summary>
/// Bind to the given endpoint.
/// The callback configures endpoint-specific settings.
/// </summary>
public void Listen(EndPoint endPoint, Action<ListenOptions> configure)
{
if (endPoint == null)
{
throw new ArgumentNullException(nameof(endPoint));
}
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
var listenOptions = new ListenOptions(endPoint);
ApplyEndpointDefaults(listenOptions);
configure(listenOptions);
CodeBackedListenOptions.Add(listenOptions);
}
/// <summary>
/// Listens on ::1 and 127.0.0.1 with the given port. Requesting a dynamic port by specifying 0 is not supported
/// for this type of endpoint.
/// </summary>
public void ListenLocalhost(int port) => ListenLocalhost(port, options => { });
/// <summary>
/// Listens on ::1 and 127.0.0.1 with the given port. Requesting a dynamic port by specifying 0 is not supported
/// for this type of endpoint.
/// </summary>
public void ListenLocalhost(int port, Action<ListenOptions> configure)
{
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
var listenOptions = new LocalhostListenOptions(port);
ApplyEndpointDefaults(listenOptions);
configure(listenOptions);
CodeBackedListenOptions.Add(listenOptions);
}
/// <summary>
/// Listens on all IPs using IPv6 [::], or IPv4 0.0.0.0 if IPv6 is not supported.
/// </summary>
public void ListenAnyIP(int port) => ListenAnyIP(port, options => { });
/// <summary>
/// Listens on all IPs using IPv6 [::], or IPv4 0.0.0.0 if IPv6 is not supported.
/// </summary>
public void ListenAnyIP(int port, Action<ListenOptions> configure)
{
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
var listenOptions = new AnyIPListenOptions(port);
ApplyEndpointDefaults(listenOptions);
configure(listenOptions);
CodeBackedListenOptions.Add(listenOptions);
}
/// <summary>
/// Bind to given Unix domain socket path.
/// </summary>
public void ListenUnixSocket(string socketPath)
{
ListenUnixSocket(socketPath, _ => { });
}
/// <summary>
/// Bind to given Unix domain socket path.
/// Specify callback to configure endpoint-specific settings.
/// </summary>
public void ListenUnixSocket(string socketPath, Action<ListenOptions> configure)
{
if (socketPath == null)
{
throw new ArgumentNullException(nameof(socketPath));
}
if (!Path.IsPathRooted(socketPath))
{
throw new ArgumentException(CoreStrings.UnixSocketPathMustBeAbsolute, nameof(socketPath));
}
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
var listenOptions = new ListenOptions(socketPath);
ApplyEndpointDefaults(listenOptions);
configure(listenOptions);
CodeBackedListenOptions.Add(listenOptions);
}
/// <summary>
/// Open a socket file descriptor.
/// </summary>
public void ListenHandle(ulong handle)
{
ListenHandle(handle, _ => { });
}
/// <summary>
/// Open a socket file descriptor.
/// The callback configures endpoint-specific settings.
/// </summary>
public void ListenHandle(ulong handle, Action<ListenOptions> configure)
{
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
var listenOptions = new ListenOptions(handle);
ApplyEndpointDefaults(listenOptions);
configure(listenOptions);
CodeBackedListenOptions.Add(listenOptions);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using System.Linq;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace Aurora.Framework
{
public struct WearableItem
{
public UUID AssetID;
public UUID ItemID;
public WearableItem(UUID itemID, UUID assetID)
{
ItemID = itemID;
AssetID = assetID;
}
}
public class AvatarWearable : IDataTransferable
{
// these are guessed at by the list here -
// http://wiki.secondlife.com/wiki/Avatar_Appearance. We'll
// correct them over time for when were are wrong.
public static readonly int BODY;
public static readonly int SKIN = 1;
public static readonly int HAIR = 2;
public static readonly int EYES = 3;
public static readonly int SHIRT = 4;
public static readonly int PANTS = 5;
public static readonly int SHOES = 6;
public static readonly int SOCKS = 7;
public static readonly int JACKET = 8;
public static readonly int GLOVES = 9;
public static readonly int UNDERSHIRT = 10;
public static readonly int UNDERPANTS = 11;
public static readonly int SKIRT = 12;
public static readonly int ALPHA = 13;
public static readonly int TATTOO = 14;
public static readonly int PHYSICS = 15;
public static readonly int MAX_WEARABLES = 16;
public static readonly UUID DEFAULT_BODY_ITEM = new UUID("66c41e39-38f9-f75a-024e-585989bfaba9");
public static readonly UUID DEFAULT_BODY_ASSET = new UUID("66c41e39-38f9-f75a-024e-585989bfab73");
public static readonly UUID DEFAULT_HAIR_ITEM = new UUID("d342e6c1-b9d2-11dc-95ff-0800200c9a66");
public static readonly UUID DEFAULT_HAIR_ASSET = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66");
public static readonly UUID DEFAULT_SKIN_ITEM = new UUID("77c41e39-38f9-f75a-024e-585989bfabc9");
public static readonly UUID DEFAULT_SKIN_ASSET = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb");
public static readonly UUID DEFAULT_EYES_ITEM = new UUID("4d3af499-976b-400a-a04a-f13df0babc0b");
public static readonly UUID DEFAULT_EYES_ASSET = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7");
public static readonly UUID DEFAULT_SHIRT_ITEM = new UUID("77c41e39-38f9-f75a-0000-585989bf0000");
public static readonly UUID DEFAULT_SHIRT_ASSET = new UUID("00000000-38f9-1111-024e-222222111110");
public static readonly UUID DEFAULT_PANTS_ITEM = new UUID("77c41e39-38f9-f75a-0000-5859892f1111");
public static readonly UUID DEFAULT_PANTS_ASSET = new UUID("00000000-38f9-1111-024e-222222111120");
// public static readonly UUID DEFAULT_ALPHA_ITEM = new UUID("bfb9923c-4838-4d2d-bf07-608c5b1165c8");
// public static readonly UUID DEFAULT_ALPHA_ASSET = new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594");
// public static readonly UUID DEFAULT_TATTOO_ITEM = new UUID("c47e22bd-3021-4ba4-82aa-2b5cb34d35e1");
// public static readonly UUID DEFAULT_TATTOO_ASSET = new UUID("00000000-0000-2222-3333-100000001007");
public int MaxItems = 5;
protected List<UUID> m_ids = new List<UUID>();
protected Dictionary<UUID, UUID> m_items = new Dictionary<UUID, UUID>();
public AvatarWearable()
{
}
public AvatarWearable(UUID itemID, UUID assetID)
{
Wear(itemID, assetID);
}
public AvatarWearable(OSDArray args)
{
Unpack(args);
}
public int Count
{
get { return m_ids.Count; }
}
public WearableItem this[int idx]
{
get
{
if (idx >= m_ids.Count || idx < 0)
return new WearableItem(UUID.Zero, UUID.Zero);
return new WearableItem(m_ids[idx], m_items[m_ids[idx]]);
}
}
public static AvatarWearable[] DefaultWearables
{
get
{
AvatarWearable[] defaultWearables = new AvatarWearable[MAX_WEARABLES]; //should be 16 of these
for (int i = 0; i < MAX_WEARABLES; i++)
{
defaultWearables[i] = new AvatarWearable();
}
// Body
defaultWearables[BODY].Add(DEFAULT_BODY_ITEM, DEFAULT_BODY_ASSET);
// Hair
defaultWearables[HAIR].Add(DEFAULT_HAIR_ITEM, DEFAULT_HAIR_ASSET);
// Skin
defaultWearables[SKIN].Add(DEFAULT_SKIN_ITEM, DEFAULT_SKIN_ASSET);
// Eyes
defaultWearables[EYES].Add(DEFAULT_EYES_ITEM, DEFAULT_EYES_ASSET);
// Shirt
defaultWearables[SHIRT].Add(DEFAULT_SHIRT_ITEM, DEFAULT_SHIRT_ASSET);
// Pants
defaultWearables[PANTS].Add(DEFAULT_PANTS_ITEM, DEFAULT_PANTS_ASSET);
// Eyes
defaultWearables[EYES].Add(DEFAULT_EYES_ITEM, DEFAULT_EYES_ASSET);
// // Alpha
// defaultWearables[ALPHA].Add(DEFAULT_ALPHA_ITEM, DEFAULT_ALPHA_ASSET);
// // Tattoo
// defaultWearables[TATTOO].Add(DEFAULT_TATTOO_ITEM, DEFAULT_TATTOO_ASSET);
return defaultWearables;
}
}
public Dictionary<UUID, UUID> GetItems()
{
#if (!ISWIN)
Dictionary<UUID, UUID> dictionary = new Dictionary<UUID, UUID>();
foreach (KeyValuePair<UUID, UUID> item in m_items)
dictionary.Add(item.Key, item.Value);
return dictionary;
#else
return m_items.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
#endif
}
public override OSDMap ToOSD()
{
OSDMap map = new OSDMap();
map["Value"] = Pack();
return map;
}
public OSD Pack()
{
OSDArray wearlist = new OSDArray();
foreach (UUID id in m_ids)
{
OSDMap weardata = new OSDMap();
weardata["item"] = OSD.FromUUID(id);
weardata["asset"] = OSD.FromUUID(m_items[id]);
wearlist.Add(weardata);
}
return wearlist;
}
public override void FromOSD(OSDMap map)
{
Unpack((OSDArray)map["Value"]);
}
public void Unpack(OSDArray args)
{
Clear();
foreach (OSDMap weardata in args)
{
Add(weardata["item"].AsUUID(), weardata["asset"].AsUUID());
}
}
public void Add(UUID itemID, UUID assetID)
{
if (itemID == UUID.Zero)
return;
if (m_items.ContainsKey(itemID))
{
m_items[itemID] = assetID;
return;
}
if (MaxItems != 0 && m_ids.Count >= MaxItems)
return;
m_ids.Add(itemID);
m_items[itemID] = assetID;
}
public void Wear(WearableItem item)
{
Wear(item.ItemID, item.AssetID);
}
public void Wear(UUID itemID, UUID assetID)
{
Clear();
Add(itemID, assetID);
}
public void Clear()
{
m_ids.Clear();
m_items.Clear();
}
public void RemoveItem(UUID itemID)
{
if (m_items.ContainsKey(itemID))
{
m_ids.Remove(itemID);
m_items.Remove(itemID);
}
}
public void RemoveAsset(UUID assetID)
{
UUID itemID = UUID.Zero;
#if (!ISWIN)
foreach (KeyValuePair<UUID, UUID> kvp in m_items)
{
if (kvp.Value == assetID)
{
itemID = kvp.Key;
break;
}
}
#else
foreach (KeyValuePair<UUID, UUID> kvp in m_items.Where(kvp => kvp.Value == assetID))
{
itemID = kvp.Key;
break;
}
#endif
if (itemID != UUID.Zero)
{
m_ids.Remove(itemID);
m_items.Remove(itemID);
}
}
public UUID GetAsset(UUID itemID)
{
if (!m_items.ContainsKey(itemID))
return UUID.Zero;
return m_items[itemID];
}
public UUID GetItem(UUID assetID)
{
if (!m_items.ContainsValue(assetID))
return UUID.Zero;
#if (!ISWIN)
foreach (KeyValuePair<UUID, UUID> kvp in m_items)
{
if (kvp.Value == assetID)
{
return kvp.Key;
}
}
#else
foreach (KeyValuePair<UUID, UUID> kvp in m_items.Where(kvp => kvp.Value == assetID))
{
return kvp.Key;
}
#endif
return UUID.Zero;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Internal.TypeSystem;
namespace Internal.JitInterface
{
internal unsafe partial class CorInfoImpl
{
private struct IntrinsicKey
{
public string MethodName;
public string TypeNamespace;
public string TypeName;
public bool Equals(IntrinsicKey other)
{
return (MethodName == other.MethodName) &&
(TypeNamespace == other.TypeNamespace) &&
(TypeName == other.TypeName);
}
public override int GetHashCode()
{
return MethodName.GetHashCode() +
((TypeNamespace != null) ? TypeNamespace.GetHashCode() : 0) +
((TypeName != null) ? TypeName.GetHashCode() : 0);
}
}
private class IntrinsicEntry
{
public IntrinsicKey Key;
public CorInfoIntrinsics Id;
}
private class IntrinsicHashtable : LockFreeReaderHashtable<IntrinsicKey, IntrinsicEntry>
{
protected override bool CompareKeyToValue(IntrinsicKey key, IntrinsicEntry value)
{
return key.Equals(value.Key);
}
protected override bool CompareValueToValue(IntrinsicEntry value1, IntrinsicEntry value2)
{
return value1.Key.Equals(value2.Key);
}
protected override IntrinsicEntry CreateValueFromKey(IntrinsicKey key)
{
Debug.Assert(false, "CreateValueFromKey not supported");
return null;
}
protected override int GetKeyHashCode(IntrinsicKey key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(IntrinsicEntry value)
{
return value.Key.GetHashCode();
}
public void Add(CorInfoIntrinsics id, string methodName, string typeNamespace, string typeName)
{
var entry = new IntrinsicEntry();
entry.Id = id;
entry.Key.MethodName = methodName;
entry.Key.TypeNamespace = typeNamespace;
entry.Key.TypeName = typeName;
AddOrGetExisting(entry);
}
}
static IntrinsicHashtable InitializeIntrinsicHashtable()
{
IntrinsicHashtable table = new IntrinsicHashtable();
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sin, "Sin", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cos, "Cos", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sqrt, "Sqrt", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Abs, "Abs", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Round, "Round", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cosh, "Cosh", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sinh, "Sinh", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tan, "Tan", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tanh, "Tanh", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Asin, "Asin", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Acos, "Acos", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan, "Atan", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan2, "Atan2", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Log10, "Log10", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Pow, "Pow", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Exp, "Exp", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Ceiling, "Ceiling", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Floor, "Floor", "System", "Math");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetChar, null, null, null); // unused
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_GetDimLength, "GetLength", "System", "Array"); // not handled
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Get, "Get", null, null);
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Address, "Address", null, null);
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Set, "Set", null, null);
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StringGetChar, "get_Chars", "System", "String");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StringLength, "get_Length", "System", "String");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray, "InitializeArray", "System.Runtime.CompilerServices", "RuntimeHelpers");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetTypeFromHandle, "GetTypeFromHandle", "System", "Type");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal, "GetValueInternal", "System", "RuntimeTypeHandle");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeEQ, "op_Equality", "System", "Type"); // not in .NET Core
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeNEQ, "op_Inequality", "System", "Type"); // not in .NET Core
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Object_GetType, "GetType", "System", "Object");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContext, "GetStubContext", "System.StubHelpers", "StubHelpers"); // interop-specific
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr, "GetStubContextAddr", "System.StubHelpers", "StubHelpers"); // interop-specific
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetNDirectTarget, "GetNDirectTarget", "System.StubHelpers", "StubHelpers"); // interop-specific
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedAdd32, "Add", System.Threading", "Interlocked"); // unused
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedAdd64, "Add", System.Threading", "Interlocked"); // unused
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32, "ExchangeAdd", "System.Threading", "Interlocked");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd64, "ExchangeAdd", "System.Threading", "Interlocked"); // ambiguous match
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32, "Exchange", "System.Threading", "Interlocked");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg64, "Exchange", "System.Threading", "Interlocked"); // ambiguous match
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32, "CompareExchange", "System.Threading", "Interlocked");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg64, "CompareExchange", "System.Threading", "Interlocked"); // ambiguous match
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_MemoryBarrier, "MemoryBarrier", "System.Threading", "Interlocked");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetCurrentManagedThread, "GetCurrentThreadNative", "System", "Thread"); // not in .NET Core
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetManagedThreadId, "get_ManagedThreadId", "System", "Thread"); // not in .NET Core
// If this assert fails, make sure to add the new intrinsics to the table above and update the expected count below.
Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_Count == 45);
return table;
}
static IntrinsicHashtable s_IntrinsicHashtable = InitializeIntrinsicHashtable();
private CorInfoIntrinsics getIntrinsicID(CORINFO_METHOD_STRUCT_* ftn, ref bool pMustExpand)
{
pMustExpand = false;
var method = HandleToObject(ftn);
Debug.Assert(method.IsIntrinsic);
IntrinsicKey key = new IntrinsicKey();
key.MethodName = method.Name;
var metadataType = method.OwningType as MetadataType;
if (metadataType != null)
{
key.TypeNamespace = metadataType.Namespace;
key.TypeName = metadataType.Name;
}
IntrinsicEntry entry;
if (!s_IntrinsicHashtable.TryGetValue(key, out entry))
return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal;
// Some intrinsics need further disambiguation
CorInfoIntrinsics id = entry.Id;
switch (id)
{
case CorInfoIntrinsics.CORINFO_INTRINSIC_Abs:
{
// RyuJIT handles floating point overloads only
var returnTypeCategory = method.Signature.ReturnType.Category;
if (returnTypeCategory != TypeFlags.Double && returnTypeCategory != TypeFlags.Single)
return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal;
}
break;
case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Get:
case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Address:
case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Set:
if (!method.OwningType.IsArray)
return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal;
break;
case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32:
case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32:
case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32:
{
// RyuJIT handles int32 and int64 overloads only
var returnTypeCategory = method.Signature.ReturnType.Category;
if (returnTypeCategory != TypeFlags.Int32 && returnTypeCategory != TypeFlags.Int64 && returnTypeCategory != TypeFlags.IntPtr)
return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal;
// int64 overloads have different ids
if (returnTypeCategory == TypeFlags.Int64)
{
Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd64);
Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg64);
Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg64);
id = (CorInfoIntrinsics)((int)id + 1);
}
}
break;
// TODO: Implementation of pMustExpand in RyuJIT is not correct
// case CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal:
// case CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray:
// pMustExpand = true;
// break;
default:
break;
}
return id;
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Rc.Models;
namespace Rc.Migrations
{
[DbContext(typeof(RcContext))]
partial class RcContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348");
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("Rc.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("Rc.Models.Article", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CategoryId");
b.Property<string>("Content");
b.Property<DateTime>("CreatedDate");
b.Property<string>("CreatedUserId");
b.Property<DateTime?>("DeletedDate");
b.Property<string>("DeletedUserId");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsDraft");
b.Property<string>("Markdown");
b.Property<string>("PicUrl");
b.Property<string>("Summary");
b.Property<string>("Title")
.IsRequired();
b.Property<DateTime?>("UpdatedDate");
b.Property<string>("UpdatedUserId");
b.HasKey("Id");
});
modelBuilder.Entity("Rc.Models.ArticleTag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("ArticleId");
b.Property<int>("TagId");
b.HasKey("Id");
});
modelBuilder.Entity("Rc.Models.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired();
b.Property<int>("Sort");
b.HasKey("Id");
});
modelBuilder.Entity("Rc.Models.Tag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Rc.Models.Article", b =>
{
b.HasOne("Rc.Models.Category")
.WithMany()
.HasForeignKey("CategoryId");
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("CreatedUserId");
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("DeletedUserId");
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UpdatedUserId");
});
modelBuilder.Entity("Rc.Models.ArticleTag", b =>
{
b.HasOne("Rc.Models.Article")
.WithMany()
.HasForeignKey("ArticleId");
b.HasOne("Rc.Models.Tag")
.WithMany()
.HasForeignKey("TagId");
});
}
}
}
| |
using AutoMapper;
using ReMi.BusinessEntities.ReleaseExecution;
using ReMi.Common.Constants.ReleaseExecution;
using ReMi.Common.Constants.ReleasePlan;
using ReMi.DataEntities.Api;
using ReMi.DataEntities.Auth;
using ReMi.DataEntities.BusinessRules;
using ReMi.DataEntities.Evt;
using ReMi.DataEntities.ExecPoll;
using ReMi.DataEntities.Metrics;
using ReMi.DataEntities.ProductRequests;
using ReMi.DataEntities.Products;
using ReMi.DataEntities.ReleaseCalendar;
using ReMi.DataEntities.ReleasePlan;
using System;
using System.Linq;
using ReMi.BusinessEntities.DeploymentTool;
using ReMi.Common.Constants.ReleaseCalendar;
using ReMi.Common.Utils.Enums;
using ReMi.DataEntities.Plugins;
using ReleaseJob = ReMi.DataEntities.ReleasePlan.ReleaseJob;
namespace ReMi.DataAccess.AutoMapper
{
public class DataEntityToBusinessEntityMappingProfile : Profile
{
public override string ProfileName
{
get { return "DataEntityToBusinessEntityMapping"; }
}
protected override void Configure()
{
Mapper.CreateMap<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>()
.ForMember(target => target.Products, option => option.MapFrom(source => source.ReleaseProducts.Select(o => o.Product.Description)))
.ForMember(target => target.StartTime,
option => option.MapFrom(source => source.StartTime.ToLocalTime()))
.ForMember(target => target.OriginalStartTime,
option => option.MapFrom(source => source.OriginalStartTime.ToLocalTime()))
.ForMember(target => target.ApprovedOn,
option =>
option.MapFrom(
source =>
source.Metrics.Any() && source.Metrics.Any(x => x.MetricType == MetricType.Approve && x.ExecutedOn.HasValue)
? source.Metrics.First(x => x.MetricType == MetricType.Approve).ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.ReleaseTypeDescription,
option => option.MapFrom(source => EnumDescriptionHelper.GetDescription(source.ReleaseType)))
.ForMember(target => target.ReleaseDecision,
option => option.MapFrom(source => EnumDescriptionHelper.GetDescription(source.ReleaseDecision)))
.ForMember(target => target.EndTime,
option =>
option.MapFrom(
source => source.Metrics.Any(x => x.MetricType == MetricType.EndTime && x.ExecutedOn.HasValue)
? source.Metrics.First(x => x.MetricType == MetricType.EndTime).ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.ClosedOn,
option =>
option.MapFrom(
source => source.Metrics.Any() && source.Metrics.Any(x => x.MetricType == MetricType.Close && x.ExecutedOn.HasValue)
? source.Metrics.First(x => x.MetricType == MetricType.Close).ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.SignedOff,
option =>
option.MapFrom(
source => source.Metrics.Any() && source.Metrics.Any(x => x.MetricType == MetricType.SignOff && x.ExecutedOn.HasValue)
? source.Metrics.First(x => x.MetricType == MetricType.SignOff).ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.Status, option => option.MapFrom(
source => !source.Metrics.Any()
? EnumDescriptionHelper.GetDescription(ReleaseStatus.Opened)
: source.Metrics.Any(x => x.MetricType == MetricType.Close && x.ExecutedOn.HasValue)
? EnumDescriptionHelper.GetDescription(ReleaseStatus.Closed)
: source.Metrics.Any(x => x.MetricType == MetricType.SignOff && x.ExecutedOn.HasValue)
? EnumDescriptionHelper.GetDescription(ReleaseStatus.SignedOff)
: source.Metrics.Any(x => x.MetricType == MetricType.Approve && x.ExecutedOn.HasValue)
? EnumDescriptionHelper.GetDescription(ReleaseStatus.Approved)
: EnumDescriptionHelper.GetDescription(ReleaseStatus.Opened)))
.ForMember(target => target.Issues,
option =>
option.MapFrom(
source => source.Metrics.Any() && source.Metrics.Any(x => x.MetricType == MetricType.Approve && x.ExecutedOn.HasValue)
? source.ReleaseNotes.Issues : null))
.ForMember(target => target.ReleaseNotes, o => o.Ignore());
Mapper.CreateMap<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindowView>()
.ForMember(target => target.Products,
option => option.MapFrom(source => source.ReleaseProducts.Select(o => o.Product.Description)))
.ForMember(target => target.StartTime,
option => option.MapFrom(source => source.StartTime.ToLocalTime()))
.ForMember(target => target.EndTime,
option =>
option.MapFrom(
source =>
source.Metrics.Any(x => x.MetricType == MetricType.EndTime && x.ExecutedOn.HasValue)
? source.Metrics.First(x => x.MetricType == MetricType.EndTime)
.ExecutedOn.Value.ToLocalTime()
: (DateTime?) null))
.ForMember(target => target.Status, option => option.MapFrom(
source => !source.Metrics.Any()
? EnumDescriptionHelper.GetDescription(ReleaseStatus.Opened)
: source.Metrics.Any(x => x.MetricType == MetricType.Close && x.ExecutedOn.HasValue)
? EnumDescriptionHelper.GetDescription(ReleaseStatus.Closed)
: source.Metrics.Any(x => x.MetricType == MetricType.SignOff && x.ExecutedOn.HasValue)
? EnumDescriptionHelper.GetDescription(ReleaseStatus.SignedOff)
: source.Metrics.Any(x => x.MetricType == MetricType.Approve && x.ExecutedOn.HasValue)
? EnumDescriptionHelper.GetDescription(ReleaseStatus.Approved)
: EnumDescriptionHelper.GetDescription(ReleaseStatus.Opened)))
.ForMember(target => target.IsMaintenance,
options => options.MapFrom(source => source.ReleaseType.ToEnumDescription<ReleaseType, ReleaseTypeDescription>().IsMaintenance));
Mapper.CreateMap<CommandExecution, BusinessEntities.ExecPoll.CommandExecution>()
.ForMember(
target => target.State,
option => option.MapFrom(source => source.CommandHistory.LastOrDefault() != null ?
(BusinessEntities.ExecPoll.CommandStateType)((int)source.CommandHistory.Last().State) :
BusinessEntities.ExecPoll.CommandStateType.NotRegistered))
.ForMember(
target => target.Details,
option => option.MapFrom(source =>
source.CommandHistory.LastOrDefault() != null ? source.CommandHistory.Last().Details : null));
Mapper.CreateMap<Role, BusinessEntities.Auth.Role>();
Mapper.CreateMap<Account, BusinessEntities.Auth.Account>()
.ForMember(target => target.Products,
option => option.MapFrom(source => source.AccountProducts == null || !source.AccountProducts.Any() ?
Enumerable.Empty<BusinessEntities.Products.ProductView>() :
source.AccountProducts.Select(Mapper.Map<AccountProduct, BusinessEntities.Products.ProductView>).ToArray()));
Mapper.CreateMap<Session, BusinessEntities.Auth.Session>()
.ForMember(target => target.AccountId, option => option.MapFrom(source => source.Account.ExternalId));
Mapper.CreateMap<Event, BusinessEntities.Evt.Event>()
.ForMember(target => target.State, option => option.MapFrom(source => source.EventHistory.LastOrDefault() != null ? source.EventHistory.Last().State : EventStateType.NotRegistered));
Mapper.CreateMap<ReleaseTask, BusinessEntities.ReleasePlan.ReleaseTaskView>()
.ForMember(target => target.ReleaseWindowId, option => option.MapFrom(x => x.ReleaseWindow.ExternalId))
.ForMember(target => target.CreatedBy, option => option.MapFrom(source => source.CreatedBy.FullName))
.ForMember(target => target.CompletedOn,
option =>
option.MapFrom(
source =>
source.CompletedOn != null ? source.CompletedOn.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.Assignee, option => option.MapFrom(source => source.Assignee.FullName))
.ForMember(target => target.AssigneeExternalId,
option => option.MapFrom(source => source.Assignee.ExternalId))
.ForMember(target => target.ReceiptConfirmedOn,
option =>
option.MapFrom(
source => source.ReceiptConfirmedOn == null ? (DateTime?)null : source.ReceiptConfirmedOn.Value.ToLocalTime()))
;
Mapper.CreateMap<ReleaseTask, BusinessEntities.ReleasePlan.ReleaseTask>()
.ForMember(target => target.ReleaseWindowId, option => option.MapFrom(x => x.ReleaseWindow.ExternalId))
.ForMember(target => target.CreatedBy, option => option.MapFrom(source => source.CreatedBy != null ? source.CreatedBy.FullName : null))
.ForMember(target => target.CreatedByExternalId, option => option.MapFrom(source => source.CreatedBy != null ? source.CreatedBy.ExternalId : (Guid?)null))
.ForMember(target => target.CreatedOn, option => option.MapFrom(source => source.CreatedOn.ToLocalTime()))
.ForMember(target => target.CompletedOn, option => option.MapFrom(source => source.CompletedOn != null ? source.CompletedOn.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.Assignee, option => option.MapFrom(source => source.Assignee != null ? source.Assignee.FullName : null))
.ForMember(target => target.HelpDeskTicketReference, option => option.MapFrom(source => source.HelpDeskReference))
.ForMember(target => target.HelpDeskTicketUrl, option => option.MapFrom(source => source.HelpDeskUrl))
.ForMember(target => target.AssigneeExternalId, option => option.MapFrom(source => source.Assignee != null ? source.Assignee.ExternalId : (Guid?)null));
Mapper.CreateMap<ReleaseTaskAttachment, BusinessEntities.ReleasePlan.ReleaseTaskAttachment>()
.ForMember(x => x.ReleaseTaskId, o => o.Ignore());
Mapper.CreateMap<ReleaseTaskAttachment, BusinessEntities.ReleasePlan.ReleaseTaskAttachmentView>()
.ForMember(x => x.ServerName, o => o.Ignore())
.ForMember(x => x.Size, o => o.MapFrom(source => source.Attachment.Length))
.ForMember(x => x.Type, o => o.Ignore());
Mapper.CreateMap<Product, BusinessEntities.Products.Product>();
Mapper.CreateMap<BusinessUnit, BusinessEntities.Products.BusinessUnit>()
.ForMember(target => target.Packages, option => option.Ignore());
Mapper.CreateMap<AccountProduct, BusinessEntities.Products.ProductView>()
.ForMember(target => target.Name, option => option.MapFrom(source => source.Product.Description))
.ForMember(target => target.ExternalId, option => option.MapFrom(source => source.Product.ExternalId));
Mapper.CreateMap<Product, BusinessEntities.Products.ProductView>()
.ForMember(target => target.Name, option => option.MapFrom(source => source.Description));
Mapper.CreateMap<ReleaseApprover, BusinessEntities.ReleasePlan.ReleaseApprover>()
.ForMember(target => target.ApprovedOn, option => option.MapFrom(source => source.ApprovedOn.HasValue ? source.ApprovedOn.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.Account, option => option.MapFrom(source => source.Account))
.ForMember(target => target.ReleaseWindowId, option => option.MapFrom(source => source.ReleaseWindow.ExternalId));
Mapper.CreateMap<ReleaseContent, BusinessEntities.ReleasePlan.ReleaseContentTicket>()
.ForMember(target => target.TicketId, option => option.MapFrom(source => source.TicketId))
.ForMember(target => target.Risk, option => option.MapFrom(source => source.TicketRisk))
.ForMember(target => target.TicketDescription, option => option.MapFrom(source => source.Description))
.ForMember(target => target.TicketName, option => option.MapFrom(source => source.TicketKey))
.ForMember(target => target.LastChangedByAccount, option => option.MapFrom(source => source.LastChangedByAccount.ExternalId));
Mapper.CreateMap<Command, BusinessEntities.Api.Command>()
.ForMember(target => target.Description, option => option.MapFrom(source => source.Description))
.ForMember(target => target.Group, option => option.MapFrom(source => source.Group))
.ForMember(target => target.IsBackground, option => option.MapFrom(source => source.IsBackground))
.ForMember(target => target.Name, option => option.MapFrom(source => source.Name))
.ForMember(target => target.Roles, option => option.MapFrom(source => source.CommandPermissions.Select(x => x.Role)))
.ForMember(target => target.HasRuleApplied, option => option.MapFrom(source => source.Rule != null))
.ForMember(target => target.Description, option => option.MapFrom(source => source.Description));
Mapper.CreateMap<Query, BusinessEntities.Api.Query>()
.ForMember(target => target.Description, option => option.MapFrom(source => source.Description))
.ForMember(target => target.Group, option => option.MapFrom(source => source.Group))
.ForMember(target => target.IsStatic, option => option.MapFrom(source => source.IsStatic))
.ForMember(target => target.Name, option => option.MapFrom(source => source.Name))
.ForMember(target => target.Roles, option => option.MapFrom(source => source.QueryPermissions.Select(x => x.Role)))
.ForMember(target => target.HasRuleApplied, option => option.MapFrom(source => source.Rule != null))
.ForMember(target => target.Description, option => option.MapFrom(source => source.Description));
Mapper.CreateMap<Role, BusinessEntities.Auth.Role>();
Mapper.CreateMap<DataEntities.ReleaseExecution.SignOff, SignOff>()
.ForMember(target => target.Signer, option => option.MapFrom(source => source.Account))
.ForMember(target => target.SignedOff, option => option.MapFrom(source => source.SignedOff.HasValue));
Mapper.CreateMap<Metric, BusinessEntities.Metrics.Metric>()
.ForMember(target => target.ExecutedOn,
option =>
option.MapFrom(
source =>
source.ExecutedOn != null ? source.ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.Order,
option =>
option.MapFrom(
source => EnumDescriptionHelper.GetOrder(source.MetricType)));
Mapper.CreateMap<ReleaseJob, BusinessEntities.DeploymentTool.ReleaseJob>();
Mapper.CreateMap<ReleaseDeploymentMeasurement, JobMeasurement>()
.ForMember(target => target.ChildSteps, option => option.Ignore())
.ForMember(target => target.StartTime, option => option.MapFrom(source => source.StartTime != null ? source.StartTime.Value.ToLocalTime() : (DateTime?)null))
.ForMember(target => target.FinishTime, option => option.MapFrom(source => source.FinishTime != null ? source.FinishTime.Value.ToLocalTime() : (DateTime?)null));
Mapper.CreateMap<BusinessRuleParameter, BusinessEntities.BusinessRules.BusinessRuleParameter>();
Mapper.CreateMap<BusinessRuleTestData, BusinessEntities.BusinessRules.BusinessRuleTestData>();
Mapper.CreateMap<BusinessRuleDescription, BusinessEntities.BusinessRules.BusinessRuleDescription>();
Mapper.CreateMap<BusinessRuleAccountTestData, BusinessEntities.BusinessRules.BusinessRuleAccountTestData>();
Mapper.CreateMap<BusinessRuleDescription, BusinessEntities.BusinessRules.BusinessRuleView>()
.ForMember(target => target.CodeBeggining,
option => option.MapFrom(source => string.IsNullOrEmpty(source.Script)
? string.Empty
: source.Script.Length >= 30 ? source.Script.Substring(0, 30) + " ..." : source.Script));
Mapper.CreateMap<ProductRequestGroupAssignee, BusinessEntities.Auth.Account>()
.ConvertUsing(requestAssignee => Mapper.Map<Account, BusinessEntities.Auth.Account>(requestAssignee.Account));
Mapper.CreateMap<ProductRequestType, BusinessEntities.ProductRequests.ProductRequestType>();
Mapper.CreateMap<ProductRequestGroup, BusinessEntities.ProductRequests.ProductRequestGroup>()
.ForMember(target => target.ProductRequestTypeId, option => option.MapFrom(source => source.RequestType.ExternalId))
.ForMember(target => target.Assignees, option => option.MapFrom(source => source.Assignees));
Mapper.CreateMap<ProductRequestTask, BusinessEntities.ProductRequests.ProductRequestTask>()
.ForMember(target => target.ProductRequestGroupId, option => option.MapFrom(source => source.RequestGroup.ExternalId));
Mapper.CreateMap<ProductRequestRegistrationTask, BusinessEntities.ProductRequests.ProductRequestRegistrationTask>()
.ForMember(target => target.ProductRequestTaskId, option => option.MapFrom(source => source.ProductRequestTask.ExternalId))
.ForMember(target => target.LastChangedByAccountId, option => option.MapFrom(source => source.LastChangedBy != null ? source.LastChangedBy.ExternalId : new Guid?()))
.ForMember(target => target.LastChangedBy, option => option.MapFrom(source => source.LastChangedBy != null ? source.LastChangedBy.FullName : null))
.ForMember(target => target.LastChangedOn, option => option.MapFrom(source => source.LastChangedOn.HasValue ? source.LastChangedOn.Value.ToLocalTime() : new DateTime?()));
Mapper.CreateMap<ProductRequestRegistration, BusinessEntities.ProductRequests.ProductRequestRegistration>()
.ForMember(target => target.ProductRequestTypeId, option => option.MapFrom(source => source.ProductRequestType.ExternalId))
.ForMember(target => target.ProductRequestType, option => option.MapFrom(source => source.ProductRequestType.Name))
.ForMember(target => target.CreatedByAccountId, option => option.MapFrom(source => source.CreatedBy.ExternalId))
.ForMember(target => target.CreatedBy, option => option.MapFrom(source => source.CreatedBy.FullName))
.ForMember(target => target.CreatedOn, option => option.MapFrom(source => source.CreatedOn.ToLocalTime()))
.ForMember(target => target.Status, option => option.ResolveUsing<TasksToProductRequestRegistrationStatusResolver>().FromMember(source => source.Tasks));
Mapper.CreateMap<PluginConfiguration, BusinessEntities.Plugins.GlobalPluginConfiguration>()
.ForMember(target => target.PluginId, option => option.MapFrom(source => source.Plugin != null ? source.Plugin.ExternalId : (Guid?)null));
Mapper.CreateMap<PluginPackageConfiguration, BusinessEntities.Plugins.PackagePluginConfiguration>()
.ForMember(target => target.PackageId, option => option.MapFrom(source => source.Package.ExternalId))
.ForMember(target => target.PackageName, option => option.MapFrom(source => source.Package.Description))
.ForMember(target => target.BusinessUnit, option => option.MapFrom(source => source.Package.BusinessUnit.Description))
.ForMember(target => target.PluginId, option => option.MapFrom(source => source.Plugin != null ? source.Plugin.ExternalId : (Guid?)null));
Mapper.CreateMap<DataEntities.Plugins.Plugin, BusinessEntities.Plugins.Plugin>()
.ForMember(target => target.PluginId, option => option.MapFrom(source => source.ExternalId))
.ForMember(target => target.PluginKey, option => option.MapFrom(source => source.Key))
.ForMember(target => target.PluginTypes,
option => option.MapFrom(source => source.PluginType.ToFlagList()));
}
}
}
| |
//#define ENABLE_BUILD_LOG
using UnityEditor;
using UnityEngine;
using Noesis;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Text.RegularExpressions;
[InitializeOnLoad]
public class NoesisPostProcessor : AssetPostprocessor
{
private static string DelayedBuildKey = "NoesisDelayedBuild";
static NoesisPostProcessor()
{
if (UnityEditorInternal.InternalEditorUtility.inBatchMode)
{
return;
}
if (EditorPrefs.GetBool(DelayedBuildKey))
{
if (EditorApplication.isPlaying)
{
DelayedBuildAfterPlay();
}
else
{
Build();
}
}
}
private static void TouchCodeBehind(string asset, ref bool doBuild)
{
if (File.Exists(asset))
{
string text = File.ReadAllText(asset);
string pattern = @"\[(\s*Noesis\s*.)\s*UserControlSource\s*\(\s*\""(.*)\""\s*\)\s*\]";
var match = Regex.Match(text, pattern);
if (match.Success)
{
var xaml = Application.dataPath + "/../" + match.Groups[2];
if (File.Exists(xaml))
{
System.IO.File.SetLastWriteTimeUtc(xaml, DateTime.UtcNow);
doBuild = true;
}
}
}
}
private static bool IsFont(string extension)
{
return extension == ".ttf" || extension == ".otf";
}
private static bool IsImage(string extension)
{
return extension == ".tga" || extension == ".png" || extension == ".jpg" || extension == ".gif" || extension == ".dds";
}
private static void OnAssetDeleted(string asset)
{
if (asset.StartsWith("Assets/StreamingAssets")) return;
#if ENABLE_BUILD_LOG
Debug.Log(" - " + asset);
#endif
BuildToolKernel.RemoveAsset(asset);
}
private static void OnAssetAdded(string asset, ref bool doBuild)
{
if (asset.StartsWith("Assets/StreamingAssets")) return;
#if ENABLE_BUILD_LOG
Debug.Log(" + " + asset);
#endif
string extension = System.IO.Path.GetExtension(asset).ToLower();
if (extension == ".xaml")
{
BuildToolKernel.AddAsset(asset);
doBuild = true;
}
else if (extension == ".cs")
{
TouchCodeBehind(asset, ref doBuild);
}
else
{
// Normally the build process is only fired if any tracked resource is modified. But when there are errors
// pending to be fixed, the tracker of resources may be incomplete and we have to build inconditionally
if (BuildToolKernel.PendingErrors())
{
if (IsFont(extension) || IsImage(extension))
{
doBuild = true;
}
}
else if (BuildToolKernel.AssetExists(asset))
{
doBuild = true;
}
}
}
private static void OnAssetMoved(string from, string to, ref bool doBuild)
{
#if ENABLE_BUILD_LOG
Debug.Log(from + " -> " + to);
#endif
string extension = System.IO.Path.GetExtension(from).ToLower();
if (IsFont(extension))
{
BuildToolKernel.RenameAsset(from, to);
}
OnAssetDeleted(from);
OnAssetAdded(to, ref doBuild);
}
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets,
string[] movedAssets, string[] movedFromPath)
{
if (UnityEditorInternal.InternalEditorUtility.inBatchMode)
{
return;
}
#if ENABLE_BUILD_LOG
Debug.Log(String.Format("ProcessAssets: ADD={0} | REM={1} | MOV={2}",
importedAssets.Length, deletedAssets.Length, movedAssets.Length));
#endif
bool doBuild = false;
for (int i = 0; i < movedAssets.Length; ++i)
{
OnAssetMoved(movedFromPath[i], movedAssets[i], ref doBuild);
}
foreach (string asset in deletedAssets)
{
OnAssetDeleted(asset);
}
foreach (string asset in importedAssets)
{
OnAssetAdded(asset, ref doBuild);
}
if (doBuild)
{
// If we are in play mode we need to delay the build
if (EditorApplication.isPlaying)
{
DelayedBuildAfterPlay();
}
// Also, is scripts are being compiled (HOLD ON dialog) we have to wait
else if (EditorApplication.isCompiling)
{
DelayedBuildAfterCompile();
}
else
{
Build();
}
}
}
private void OnPreprocessTexture()
{
// Disable texture compression on documentation folder. A better approach would be having a way to tell Unity that
// this folder should be ignored. But it doesn't seem to be a way do to that.
if (assetPath.StartsWith("Assets/NoesisGUI/Doc"))
{
TextureImporter importer = assetImporter as TextureImporter;
importer.mipmapEnabled = false;
importer.textureFormat = TextureImporterFormat.RGBA32;
}
}
private static void DelayedBuildAfterCompile()
{
EditorPrefs.SetBool(DelayedBuildKey, true);
}
private static bool _delayedBuildRegistered = false;
private static void DelayedBuildAfterPlay()
{
if (!_delayedBuildRegistered)
{
#if ENABLE_BUILD_LOG
Debug.Log("Delayed Build registered");
#endif
_delayedBuildRegistered = true;
EditorApplication.playmodeStateChanged += DelayedBuild;
}
}
private static void DelayedBuild()
{
if (!EditorApplication.isPlaying)
{
_delayedBuildRegistered = false;
EditorApplication.playmodeStateChanged -= DelayedBuild;
Build();
}
}
private static void Build()
{
#if ENABLE_BUILD_LOG
Debug.Log("Building...");
#endif
EditorPrefs.DeleteKey(DelayedBuildKey);
#if !ENABLE_BUILD_LOG
NoesisSettings.ClearLog();
#endif
BuildToolKernel.BuildBegin();
foreach (string platform in NoesisSettings.ActivePlatforms)
{
Build(platform);
}
UpdateNoesisGUIPaths();
#if ENABLE_BUILD_LOG
Debug.Log("Building [done]");
#endif
}
private static void Build(string platform)
{
using (BuildToolKernel builder = new BuildToolKernel(platform))
{
builder.BuildIncremental();
}
}
private static void UpdateNoesisGUIPaths()
{
UnityEngine.Object[] objs = UnityEngine.Object.FindObjectsOfType(typeof(NoesisGUIPanel));
foreach (UnityEngine.Object obj in objs)
{
NoesisGUIPanel noesisGUI = (NoesisGUIPanel)obj;
NoesisGUIPanelEditor.UpdateXamlPath(noesisGUI, noesisGUI._xaml);
NoesisGUIPanelEditor.UpdateStylePath(noesisGUI, noesisGUI._style);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A vector of type T with 3 components.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct gvec3<T> : IEnumerable<T>, IEquatable<gvec3<T>>
{
#region Fields
/// <summary>
/// x-component
/// </summary>
public T x;
/// <summary>
/// y-component
/// </summary>
public T y;
/// <summary>
/// z-component
/// </summary>
public T z;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public gvec3(T x, T y, T z)
{
this.x = x;
this.y = y;
this.z = z;
}
/// <summary>
/// all-same-value constructor
/// </summary>
public gvec3(T v)
{
this.x = v;
this.y = v;
this.z = v;
}
/// <summary>
/// from-vector constructor (empty fields are zero/false)
/// </summary>
public gvec3(gvec2<T> v)
{
this.x = v.x;
this.y = v.y;
this.z = default(T);
}
/// <summary>
/// from-vector-and-value constructor
/// </summary>
public gvec3(gvec2<T> v, T z)
{
this.x = v.x;
this.y = v.y;
this.z = z;
}
/// <summary>
/// from-vector constructor
/// </summary>
public gvec3(gvec3<T> v)
{
this.x = v.x;
this.y = v.y;
this.z = v.z;
}
/// <summary>
/// from-vector constructor (additional fields are truncated)
/// </summary>
public gvec3(gvec4<T> v)
{
this.x = v.x;
this.y = v.y;
this.z = v.z;
}
/// <summary>
/// Generic from-array constructor (superfluous values are ignored, missing values are zero-filled).
/// </summary>
public gvec3(Object[] v)
{
var c = v.Length;
this.x = c < 0 ? default(T) : (T)v[0];
this.y = c < 1 ? default(T) : (T)v[1];
this.z = c < 2 ? default(T) : (T)v[2];
}
/// <summary>
/// From-array constructor (superfluous values are ignored, missing values are zero-filled).
/// </summary>
public gvec3(T[] v)
{
var c = v.Length;
this.x = c < 0 ? default(T) : v[0];
this.y = c < 1 ? default(T) : v[1];
this.z = c < 2 ? default(T) : v[2];
}
/// <summary>
/// From-array constructor with base index (superfluous values are ignored, missing values are zero-filled).
/// </summary>
public gvec3(T[] v, int startIndex)
{
var c = v.Length;
this.x = c + startIndex < 0 ? default(T) : v[0 + startIndex];
this.y = c + startIndex < 1 ? default(T) : v[1 + startIndex];
this.z = c + startIndex < 2 ? default(T) : v[2 + startIndex];
}
/// <summary>
/// From-IEnumerable constructor (superfluous values are ignored, missing values are zero-filled).
/// </summary>
public gvec3(IEnumerable<T> v)
: this(new List<T>(v).ToArray())
{
}
#endregion
#region Explicit Operators
/// <summary>
/// Explicitly converts this to a gvec2.
/// </summary>
public static explicit operator gvec2<T>(gvec3<T> v) => new gvec2<T>((T)v.x, (T)v.y);
/// <summary>
/// Explicitly converts this to a gvec4. (Higher components are zeroed)
/// </summary>
public static explicit operator gvec4<T>(gvec3<T> v) => new gvec4<T>((T)v.x, (T)v.y, (T)v.z, default(T));
/// <summary>
/// Explicitly converts this to a T array.
/// </summary>
public static explicit operator T[](gvec3<T> v) => new [] { v.x, v.y, v.z };
/// <summary>
/// Explicitly converts this to a generic object array.
/// </summary>
public static explicit operator Object[](gvec3<T> v) => new Object[] { v.x, v.y, v.z };
#endregion
#region Indexer
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public T this[int index]
{
get
{
switch (index)
{
case 0: return x;
case 1: return y;
case 2: return z;
default: throw new ArgumentOutOfRangeException("index");
}
}
set
{
switch (index)
{
case 0: x = value; break;
case 1: y = value; break;
case 2: z = value; break;
default: throw new ArgumentOutOfRangeException("index");
}
}
}
#endregion
#region Properties
/// <summary>
/// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)
/// </summary>
public swizzle_gvec3<T> swizzle => new swizzle_gvec3<T>(x, y, z);
/// <summary>
/// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public gvec2<T> xy
{
get
{
return new gvec2<T>(x, y);
}
set
{
x = value.x;
y = value.y;
}
}
/// <summary>
/// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public gvec2<T> xz
{
get
{
return new gvec2<T>(x, z);
}
set
{
x = value.x;
z = value.y;
}
}
/// <summary>
/// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public gvec2<T> yz
{
get
{
return new gvec2<T>(y, z);
}
set
{
y = value.x;
z = value.y;
}
}
/// <summary>
/// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public gvec3<T> xyz
{
get
{
return new gvec3<T>(x, y, z);
}
set
{
x = value.x;
y = value.y;
z = value.z;
}
}
/// <summary>
/// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public gvec2<T> rg
{
get
{
return new gvec2<T>(x, y);
}
set
{
x = value.x;
y = value.y;
}
}
/// <summary>
/// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public gvec2<T> rb
{
get
{
return new gvec2<T>(x, z);
}
set
{
x = value.x;
z = value.y;
}
}
/// <summary>
/// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public gvec2<T> gb
{
get
{
return new gvec2<T>(y, z);
}
set
{
y = value.x;
z = value.y;
}
}
/// <summary>
/// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public gvec3<T> rgb
{
get
{
return new gvec3<T>(x, y, z);
}
set
{
x = value.x;
y = value.y;
z = value.z;
}
}
/// <summary>
/// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public T r
{
get
{
return x;
}
set
{
x = value;
}
}
/// <summary>
/// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public T g
{
get
{
return y;
}
set
{
y = value;
}
}
/// <summary>
/// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property.
/// </summary>
public T b
{
get
{
return z;
}
set
{
z = value;
}
}
/// <summary>
/// Returns an array with all values
/// </summary>
public T[] Values => new[] { x, y, z };
/// <summary>
/// Returns the number of components (3).
/// </summary>
public int Count => 3;
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero vector
/// </summary>
public static gvec3<T> Zero { get; } = new gvec3<T>(default(T), default(T), default(T));
#endregion
#region Operators
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator==(gvec3<T> lhs, gvec3<T> rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator!=(gvec3<T> lhs, gvec3<T> rhs) => !lhs.Equals(rhs);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
yield return x;
yield return y;
yield return z;
}
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Returns a string representation of this vector using ', ' as a seperator.
/// </summary>
public override string ToString() => ToString(", ");
/// <summary>
/// Returns a string representation of this vector using a provided seperator.
/// </summary>
public string ToString(string sep) => ((x + sep + y) + sep + z);
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(gvec3<T> rhs) => ((EqualityComparer<T>.Default.Equals(x, rhs.x) && EqualityComparer<T>.Default.Equals(y, rhs.y)) && EqualityComparer<T>.Default.Equals(z, rhs.z));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is gvec3<T> && Equals((gvec3<T>) obj);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((EqualityComparer<T>.Default.GetHashCode(x)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(y)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(z);
}
}
#endregion
#region Component-Wise Static Functions
/// <summary>
/// Returns a bvec3 from component-wise application of Equal (EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec3 Equal(gvec3<T> lhs, gvec3<T> rhs) => new bvec3(EqualityComparer<T>.Default.Equals(lhs.x, rhs.x), EqualityComparer<T>.Default.Equals(lhs.y, rhs.y), EqualityComparer<T>.Default.Equals(lhs.z, rhs.z));
/// <summary>
/// Returns a bvec3 from component-wise application of Equal (EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec3 Equal(gvec3<T> lhs, T rhs) => new bvec3(EqualityComparer<T>.Default.Equals(lhs.x, rhs), EqualityComparer<T>.Default.Equals(lhs.y, rhs), EqualityComparer<T>.Default.Equals(lhs.z, rhs));
/// <summary>
/// Returns a bvec3 from component-wise application of Equal (EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec3 Equal(T lhs, gvec3<T> rhs) => new bvec3(EqualityComparer<T>.Default.Equals(lhs, rhs.x), EqualityComparer<T>.Default.Equals(lhs, rhs.y), EqualityComparer<T>.Default.Equals(lhs, rhs.z));
/// <summary>
/// Returns a bvec from the application of Equal (EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec3 Equal(T lhs, T rhs) => new bvec3(EqualityComparer<T>.Default.Equals(lhs, rhs));
/// <summary>
/// Returns a bvec3 from component-wise application of NotEqual (!EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec3 NotEqual(gvec3<T> lhs, gvec3<T> rhs) => new bvec3(!EqualityComparer<T>.Default.Equals(lhs.x, rhs.x), !EqualityComparer<T>.Default.Equals(lhs.y, rhs.y), !EqualityComparer<T>.Default.Equals(lhs.z, rhs.z));
/// <summary>
/// Returns a bvec3 from component-wise application of NotEqual (!EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec3 NotEqual(gvec3<T> lhs, T rhs) => new bvec3(!EqualityComparer<T>.Default.Equals(lhs.x, rhs), !EqualityComparer<T>.Default.Equals(lhs.y, rhs), !EqualityComparer<T>.Default.Equals(lhs.z, rhs));
/// <summary>
/// Returns a bvec3 from component-wise application of NotEqual (!EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec3 NotEqual(T lhs, gvec3<T> rhs) => new bvec3(!EqualityComparer<T>.Default.Equals(lhs, rhs.x), !EqualityComparer<T>.Default.Equals(lhs, rhs.y), !EqualityComparer<T>.Default.Equals(lhs, rhs.z));
/// <summary>
/// Returns a bvec from the application of NotEqual (!EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec3 NotEqual(T lhs, T rhs) => new bvec3(!EqualityComparer<T>.Default.Equals(lhs, rhs));
#endregion
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
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
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using Axiom.Core;
using Axiom.Configuration;
namespace Axiom.Graphics {
///<summary>
/// Base composition technique, can be subclassed in plugins.
///</summary>
public class CompositionTechnique {
#region Fields
///<summary>
/// Parent compositor
///</summary>
protected Compositor parent;
///<summary>
/// Local texture definitions
///</summary>
protected List<CompositionTextureDefinition> textureDefinitions;
///<summary>
/// Intermediate target passes
///</summary>
protected List<CompositionTargetPass> targetPasses;
///<summary>
/// Output target pass (can be only one)
///</summary>
protected CompositionTargetPass outputTarget;
///<summary>
/// List of instances
///</summary>
protected List<CompositorInstance> instances;
#endregion Fields
#region Constructor
public CompositionTechnique(Compositor parent) {
this.parent = parent;
textureDefinitions = new List<CompositionTextureDefinition>();
targetPasses = new List<CompositionTargetPass>();
outputTarget = new CompositionTargetPass(this);
instances = new List<CompositorInstance>();
}
#endregion Constructor
#region Properties
///<summary>
/// Get the compositor parent
///</summary>
public Compositor Parent {
get { return parent; }
}
///<summary>
/// Get list of texture definitions
///</summary>
public List<CompositionTextureDefinition> TextureDefinitions {
get { return textureDefinitions; }
}
///<summary>
/// Get output (final) target pass
///</summary>
public CompositionTargetPass OutputTarget {
get { return outputTarget; }
}
///<summary>
/// Get the target passes
///</summary>
public List<CompositionTargetPass> TargetPasses {
get { return targetPasses; }
}
#endregion Properties
#region Methods
///<summary>
/// Create a new local texture definition, and return a pointer to it.
///</summary>
///<param name="name">Name of the local texture</param>
public CompositionTextureDefinition CreateTextureDefinition(string name) {
CompositionTextureDefinition t = new CompositionTextureDefinition();
t.Name = name;
textureDefinitions.Add(t);
return t;
}
///<summary>
/// Remove and destroy a local texture definition.
///</summary>
public void RemoveTextureDefinition(int idx) {
textureDefinitions.RemoveAt(idx);
}
///<summary>
/// Get a local texture definition.
///</summary>
public CompositionTextureDefinition GetTextureDefinition(int idx) {
return textureDefinitions[idx];
}
///<summary>
/// Remove all Texture Definitions
///</summary>
public void RemoveAllTextureDefinitions() {
textureDefinitions.Clear();
}
///<summary>
/// Create a new target pass, and return a pointer to it.
///</summary>
public CompositionTargetPass CreateTargetPass() {
CompositionTargetPass t = new CompositionTargetPass(this);
targetPasses.Add(t);
return t;
}
///<summary>
/// Remove a target pass. It will also be destroyed.
///</summary>
public void RemoveTargetPass(int idx) {
targetPasses.RemoveAt(idx);
}
///<summary>
/// Get a target pass.
///</summary>
public CompositionTargetPass GetTargetPass(int idx) {
return targetPasses[idx];
}
///<summary>
/// Remove all target passes.
///</summary>
public void RemoveAllTargetPasses() {
targetPasses.Clear();
}
///<summary>
/// Determine if this technique is supported on the current rendering device.
///</summary>
///<param name="allowTextureDegradation">True to accept a reduction in texture depth<param>
public virtual bool IsSupported(bool allowTextureDegradation) {
// A technique is supported if all materials referenced have a supported
// technique, and the intermediate texture formats requested are supported
// Material support is a cast-iron requirement, but if no texture formats
// are directly supported we can let the rendersystem create the closest
// match for the least demanding technique
// Check output target pass is supported
if (!outputTarget.IsSupported)
return false;
// Check all target passes is supported
foreach (CompositionTargetPass targetPass in targetPasses) {
if (!targetPass.IsSupported)
return false;
}
TextureManager texMgr = TextureManager.Instance;
foreach (CompositionTextureDefinition td in textureDefinitions)
{
// Check whether equivalent supported
if(allowTextureDegradation) {
// Don't care about exact format so long as something is supported
if(texMgr.GetNativeFormat(TextureType.TwoD, td.Format,
TextureUsage.RenderTarget) == Axiom.Media.PixelFormat.Unknown)
return false;
}
else {
// Need a format which is the same number of bits to pass
if (!texMgr.IsEquivalentFormatSupported(TextureType.TwoD, td.Format, TextureUsage.RenderTarget))
return false;
}
}
// Must be ok
return true;
}
///<summary>
/// Create an instance of this technique.
///</summary>
public virtual CompositorInstance CreateInstance(CompositorChain chain) {
CompositorInstance mew = new CompositorInstance(parent, this, chain);
instances.Add(mew);
return mew;
}
///<summary>
/// Destroy an instance of this technique.
///</summary>
public virtual void DestroyInstance(CompositorInstance instance) {
instances.Remove(instance);
}
#endregion Methods
}
public class CompositionTextureDefinition {
#region Fields
protected string name;
protected int width = 0; // 0 means adapt to target width
protected int height = 0; // 0 means adapt to target height
protected Axiom.Media.PixelFormat format = Axiom.Media.PixelFormat.A8R8G8B8;
#endregion Fields
#region Constructor
public CompositionTextureDefinition() {
}
#endregion Constructor
#region Properties
public string Name {
get { return name; }
set { name = value; }
}
public int Width {
get { return width; }
set { width = value; }
}
public int Height {
get { return height; }
set { height = value; }
}
public Axiom.Media.PixelFormat Format {
get { return format; }
set { format = value; }
}
#endregion Properties
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NFluent;
using WireMock.Handlers;
using WireMock.Models;
using WireMock.ResponseBuilders;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using Xunit;
#if NET452
using Microsoft.Owin;
#else
using Microsoft.AspNetCore.Http;
#endif
namespace WireMock.Net.Tests.ResponseBuilders
{
public class ResponseWithTransformerTests
{
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
private const string ClientIp = "::1";
public ResponseWithTransformerTests()
{
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
_settings.FileSystemHandler = filesystemHandlerMock.Object;
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithNullBody_ShouldNotThrowException(TransformerType transformerType)
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, "GET", ClientIp);
var responseBuilder = Response.Create().WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
response.Message.BodyData.Should().BeNull();
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_UrlPathVerb(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "whatever",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POSt", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test {{request.Url}} {{request.Path}} {{request.Method}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt");
}
[Theory]
[InlineData(TransformerType.Handlebars, "Get")]
[InlineData(TransformerType.Handlebars, "Post")]
[InlineData(TransformerType.Scriban, "Get")]
[InlineData(TransformerType.Scriban, "Post")]
[InlineData(TransformerType.ScribanDotLiquid, "Get")]
[InlineData(TransformerType.ScribanDotLiquid, "Post")]
public async Task Response_ProvideResponse_Transformer_UrlPath(TransformerType transformerType, string httpMethod)
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, httpMethod, ClientIp);
var responseBuilder = Response.Create()
.WithBody("url={{request.Url}} absoluteurl={{request.AbsoluteUrl}} path={{request.Path}} absolutepath={{request.AbsolutePath}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("url=http://localhost/a/b absoluteurl=http://localhost/wiremock/a/b path=/a/b absolutepath=/wiremock/a/b");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_PathSegments()
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, "POST", ClientIp);
var responseBuilder = Response.Create()
.WithBody("{{request.PathSegments.[0]}} {{request.AbsolutePathSegments.[0]}}")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("a wiremock");
}
[Theory(Skip = "Invalid token `OpenBracket`")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_PathSegments(TransformerType transformerType)
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, "POST", ClientIp);
var responseBuilder = Response.Create()
.WithBody("{{request.PathSegments.[0]}} {{request.AbsolutePathSegments.[0]}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("a wiremock");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Query()
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=1&a=2&b=5"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test keya=1,2 idx=1 idx=2 keyb=5");
}
[Theory(Skip = "Invalid token `OpenBracket`")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_Query(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=1&a=2&b=5"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test keya=1 idx=1 idx=2 keyb=5");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_StatusCode()
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=400"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithStatusCode("{{request.query.a}}")
.WithBody("test")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals("400");
}
[Theory(Skip = "WireMockList is not supported by Scriban")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_StatusCode(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=400"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithStatusCode("{{request.Query.a}}")
.WithBody("test")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals("400");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_StatusCodeIsNull(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=400"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals(null);
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Header()
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
var responseBuilder = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}").WithBody("test").WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.Headers).ContainsKey("x");
Check.That(response.Message.Headers["x"]).ContainsExactly("text/plain");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Headers()
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
var responseBuilder = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}", "{{request.url}}").WithBody("test").WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.Headers).ContainsKey("x");
Check.That(response.Message.Headers["x"]).Contains("text/plain");
Check.That(response.Message.Headers["x"]).Contains("http://localhost/foo");
}
[Theory(Skip = "WireMockList is not supported by Scriban")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_Headers(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
var responseBuilder = Response.Create().WithHeader("x", "{{request.Headers[\"Content-Type\"]}}", "{{request.Url}}").WithBody("test").WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.Headers).ContainsKey("x");
Check.That(response.Message.Headers["x"]).Contains("text/plain");
Check.That(response.Message.Headers["x"]).Contains("http://localhost/foo");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_Origin_Port_Protocol_Host(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test {{request.Origin}} {{request.Port}} {{request.Protocol}} {{request.Host}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test http://localhost:1234 1234 http localhost");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_ResultAsObject(TransformerType transformerType)
{
// Assign
string jsonString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"WireMock\" } ] }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson(new { x = "test {{request.Path}}" })
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_ResultAsArray(TransformerType transformerType)
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithBodyAsJson(new [] { new { x = "test" }})
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson).Should().Be("[{\"x\":\"test\"}]");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_ResultAsJArray(TransformerType transformerType)
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "GET", ClientIp);
var array = JArray.Parse("[{\"x\":\"test\"}]");
var responseBuilder = Response.Create()
.WithBodyAsJson(array)
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson).Should().Be("[{\"x\":\"test\"}]");
}
//[Theory]
//[InlineData(TransformerType.Handlebars, "a")]
//[InlineData(TransformerType.Handlebars, "42")]
//[InlineData(TransformerType.Handlebars, "{")]
//[InlineData(TransformerType.Handlebars, "]")]
//[InlineData(TransformerType.Handlebars, " ")]
//public async Task Response_ProvideResponse_Transformer_WithBodyAsJsonWithExtraQuotes_AndSpecialOption_MakesAString_ResultAsObject(TransformerType transformerType, string text)
//{
// string jsonString = $"{{ \"x\": \"{text}\" }}";
// var bodyData = new BodyData
// {
// BodyAsJson = JsonConvert.DeserializeObject(jsonString),
// DetectedBodyType = BodyType.Json,
// Encoding = Encoding.UTF8
// };
// var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
// var responseBuilder = Response.Create()
// .WithBodyAsJson(new { text = "\"{{request.bodyAsJson.x}}\"" })
// .WithTransformer(transformerType, false, ReplaceNodeOptions.Default);
// // Act
// var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// // Assert
// JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson).Should().Be($"{{\"text\":\"{text}\"}}");
//}
[Theory]
[InlineData(TransformerType.Handlebars, "\"\"", "\"\"")]
[InlineData(TransformerType.Handlebars, "\"a\"", "\"a\"")]
[InlineData(TransformerType.Handlebars, "\" \"", "\" \"")]
[InlineData(TransformerType.Handlebars, "\"'\"", "\"'\"")]
[InlineData(TransformerType.Handlebars, "\"false\"", "false")] // bool is special
[InlineData(TransformerType.Handlebars, "false", "false")]
[InlineData(TransformerType.Handlebars, "\"true\"", "true")] // bool is special
[InlineData(TransformerType.Handlebars, "true", "true")]
[InlineData(TransformerType.Handlebars, "\"-42\"", "-42")] // todo
[InlineData(TransformerType.Handlebars, "-42", "-42")]
[InlineData(TransformerType.Handlebars, "\"2147483647\"", "2147483647")] // todo
[InlineData(TransformerType.Handlebars, "2147483647", "2147483647")]
[InlineData(TransformerType.Handlebars, "\"9223372036854775807\"", "9223372036854775807")] // todo
[InlineData(TransformerType.Handlebars, "9223372036854775807", "9223372036854775807")]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_And_ReplaceNodeOptionsKeep(TransformerType transformerType, string value, string expected)
{
string jsonString = $"{{ \"x\": {value} }}";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson(new { text = "{{request.bodyAsJson.x}}" })
.WithTransformer(transformerType, false, ReplaceNodeOptions.None);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson).Should().Be($"{{\"text\":{expected}}}");
}
[Theory]
[InlineData(TransformerType.Handlebars, "\"\"", "\"\"")]
[InlineData(TransformerType.Handlebars, "\"a\"", "\"a\"")]
[InlineData(TransformerType.Handlebars, "\" \"", "\" \"")]
[InlineData(TransformerType.Handlebars, "\"'\"", "\"'\"")]
[InlineData(TransformerType.Handlebars, "\"false\"", "false")] // bool is special
[InlineData(TransformerType.Handlebars, "false", "false")]
[InlineData(TransformerType.Handlebars, "\"true\"", "true")] // bool is special
[InlineData(TransformerType.Handlebars, "true", "true")]
[InlineData(TransformerType.Handlebars, "\"-42\"", "\"-42\"")]
[InlineData(TransformerType.Handlebars, "-42", "\"-42\"")]
[InlineData(TransformerType.Handlebars, "\"2147483647\"", "\"2147483647\"")]
[InlineData(TransformerType.Handlebars, "2147483647", "\"2147483647\"")]
[InlineData(TransformerType.Handlebars, "\"9223372036854775807\"", "\"9223372036854775807\"")]
[InlineData(TransformerType.Handlebars, "9223372036854775807", "\"9223372036854775807\"")]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJsonWithExtraQuotes_AlwaysMakesString(TransformerType transformerType, string value, string expected)
{
string jsonString = $"{{ \"x\": {value} }}";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson(new { text = "\"{{request.bodyAsJson.x}}\"" })
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson).Should().Be($"{{\"text\":{expected}}}");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
//[InlineData(TransformerType.Scriban)] Scriban cannot access dynamic Json Objects
//[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_ResultAsArray(TransformerType transformerType)
{
// Assign
string jsonString = "{ \"a\": \"test 1\", \"b\": \"test 2\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_array"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson(new[] { "first", "{{request.path}}", "{{request.bodyAsJson.a}}", "{{request.bodyAsJson.b}}", "last" })
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("[\"first\",\"/foo_array\",\"test 1\",\"test 2\",\"last\"]");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_WithBodyAsFile()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithTransformer()
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
}
[Theory(Skip = @"Does not work in Scriban --> c:\\[""1""]\\test.xml")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_WithBodyAsFile(TransformerType transformerType)
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithTransformer(transformerType)
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
//[InlineData(TransformerType.Scriban)] ["c:\\["1"]\\test.xml"]
//[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_And_TransformContentFromBodyAsFile(TransformerType transformerType)
{
// Assign
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("<xml MyUniqueNumber=\"{{request.query.MyUniqueNumber}}\"></xml>");
_settings.FileSystemHandler = filesystemHandlerMock.Object;
var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithTransformer(transformerType, true)
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
Check.That(response.Message.BodyData.DetectedBodyType).Equals(BodyType.String);
Check.That(response.Message.BodyData.BodyAsString).Equals("<xml MyUniqueNumber=\"1\"></xml>");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_ResultAsNormalString(TransformerType transformerType)
{
// Assign
string jsonString = "{ \"name\": \"WireMock\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson("test")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("\"test\"");
}
[Fact(Skip = "todo...")]
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsTemplatedString()
{
// Assign
string jsonString = "{ \"name\": \"WireMock\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson("{{{request.BodyAsJson}}}")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("{\"name\":\"WireMock\"}");
}
[Theory(Skip = "{{{ }}} Does not work in Scriban")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_WithBodyAsJson_ResultAsTemplatedString(TransformerType transformerType)
{
// Assign
string jsonString = "{ \"name\": \"WireMock\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson("{{{request.BodyAsJson}}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("{\"name\":\"WireMock\"}");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsString_KeepsEncoding(TransformerType transformerType)
{
// Assign
const string text = "my-text";
Encoding enc = Encoding.Unicode;
var bodyData = new BodyData
{
BodyAsString = text,
DetectedBodyType = BodyType.String,
Encoding = enc
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBody("{{request.Body}}", BodyDestinationFormat.SameAsSource, enc)
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
response.Message.BodyData.BodyAsString.Should().Be(text);
response.Message.BodyData.Encoding.Should().Be(enc);
}
}
}
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Michael Ruck (grover) <[email protected]>
*/
using Mosa.Compiler.Metadata.Tables;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Mosa.Compiler.Metadata
{
/// <summary>
/// Provides convenient access to the provider table heap.
/// </summary>
public sealed class TableHeap : Heap
{
#region Types
/// <summary>
/// Delegate used to determine the record sizes with the given heap size.
/// </summary>
/// <param name="heap">The table heap making the request.</param>
/// <returns>The size of the record for the given heap sizes.</returns>
private delegate int SizeofDelegate(IMetadataProvider heap);
#endregion Types
#region Static members
private static readonly int[][] IndexTables = new[]
{
new[] { (int)TableType.TypeDef, (int)TableType.TypeRef, (int)TableType.TypeSpec },
new[] { (int)TableType.Field, (int)TableType.Param, (int)TableType.Property },
new[] { (int)TableType.MethodDef, (int)TableType.Field, (int)TableType.TypeRef, (int)TableType.TypeDef, (int)TableType.Param, (int)TableType.InterfaceImpl, (int)TableType.MemberRef, (int)TableType.Module, /*(int)TableTypes.Permission,*/ (int)TableType.Property, (int)TableType.Event, (int)TableType.StandAloneSig, (int)TableType.ModuleRef, (int)TableType.TypeSpec, (int)TableType.Assembly, (int)TableType.AssemblyRef, (int)TableType.File, (int)TableType.ExportedType, (int)TableType.ManifestResource },
new[] { (int)TableType.Field, (int)TableType.Param },
new[] { (int)TableType.TypeDef, (int)TableType.MethodDef, (int)TableType.Assembly },
new[] { (int)TableType.TypeDef, (int)TableType.TypeRef, (int)TableType.ModuleRef, (int)TableType.MethodDef, (int)TableType.TypeSpec },
new[] { (int)TableType.Event, (int)TableType.Property },
new[] { (int)TableType.MethodDef, (int)TableType.MemberRef },
new[] { (int)TableType.Field, (int)TableType.MethodDef },
new[] { (int)TableType.File, (int)TableType.AssemblyRef, (int)TableType.ExportedType },
new[] { -1, -1, (int)TableType.MethodDef, (int)TableType.MemberRef, -1 },
new[] { (int)TableType.Module, (int)TableType.ModuleRef, (int)TableType.AssemblyRef, (int)TableType.TypeRef },
new[] { (int)TableType.TypeDef, (int)TableType.MethodDef }
};
private static readonly int[] IndexBits = new[] {
2, 2, 5, 1, 2, 3, 1, 1, 1, 2, 3, 2, 1
};
private const int TableCount = ((int)TableType.GenericParamConstraint >> 24) + 1;
#endregion Static members
#region Data members
/// <summary>
/// Holds size flags for the provider heap.
/// </summary>
public byte _heapSize;
/// <summary>
/// Determines the tables, which are available in the heap.
/// </summary>
public long _valid;
/// <summary>
/// Determines the tables, which are sorted.
/// </summary>
public long _sorted;
/// <summary>
/// Holds the row counts.
/// </summary>
private int[] _rowCounts;
/// <summary>
/// Holds offsets into the heap, where the corresponding table starts.
/// </summary>
private int[] _tableOffsets;
/// <summary>
/// Size of a single record in the table.
/// </summary>
private int[] _recordSize;
/// <summary>
/// Size of the corresponding indexes.
/// </summary>
private int[] _indexSize;
private IMetadataProvider _metadataProvider;
#endregion Data members
#region Construction
/// <summary>
/// Initializes a new instance of the <see cref="TableHeap"/> class.
/// </summary>
/// <param name="provider">The provider buffer to use for the heap.</param>
/// <param name="metadata">The metadata.</param>
/// <param name="offset">The offset into the provider buffer, where the table heap starts.</param>
/// <param name="size">The size of the table heap in bytes.</param>
public TableHeap(IMetadataProvider provider, byte[] metadata, int offset, int size)
: base(metadata, offset, size)
{
// Table offset calculation
int nextTableOffset = offset;
// Retrieve the member data values
using (var reader = new BinaryReader(new MemoryStream(metadata), Encoding.UTF8))
{
reader.BaseStream.Position = offset;
reader.ReadUInt32();
if (2 != reader.ReadByte() || 0 != reader.ReadByte())
throw new BadImageFormatException();
_heapSize = reader.ReadByte();
reader.ReadByte();
_valid = reader.ReadInt64();
_sorted = reader.ReadInt64();
// Adjust the table offset for the header so far
nextTableOffset += 4 + 2 + 1 + 1 + 8 + 8;
CreateRowCountArray(reader, ref nextTableOffset);
CalculateIndexSizes();
CalculateHeapIndexSizes();
CalculateRecordSizes();
CalculateTableOffsets(ref nextTableOffset);
}
_metadataProvider = provider;
}
private void CreateRowCountArray(BinaryReader reader, ref int nextTableOffset)
{
_rowCounts = new int[TableCount];
for (long valid = _valid, i = 0; 0 != valid; valid >>= 1, i++)
{
if (1 != (valid & 1))
continue;
_rowCounts[i] = reader.ReadInt32();
nextTableOffset += 4;
}
}
private void CalculateIndexSizes()
{
_indexSize = new int[(int)IndexType.IndexCount];
for (int i = 0; i < (int)IndexType.CodedIndexCount; i++)
{
int maxrows = 0;
for (int table = 0; table < IndexTables[i].Length; table++)
{
if (-1 != IndexTables[i][table] && maxrows < _rowCounts[(IndexTables[i][table] >> 24)])
{
maxrows = _rowCounts[(IndexTables[i][table] >> 24)];
}
}
_indexSize[i] = (maxrows < (1 << (16 - IndexBits[i])) ? 2 : 4);
}
}
private void CalculateHeapIndexSizes()
{
_indexSize[(int)IndexType.StringHeap] = 2 + 2 * (_heapSize & 1);
_indexSize[(int)IndexType.GuidHeap] = 2 + (_heapSize & 2);
_indexSize[(int)IndexType.BlobHeap] = (0 == (_heapSize & 4) ? 2 : 4);
}
private void CalculateRecordSizes()
{
_recordSize = CalculateRecordSizes(TableCount);
}
private void CalculateTableOffsets(ref int nextTableOffset)
{
_tableOffsets = new int[TableCount];
for (int i = 0; i < TableCount; i++)
{
if (0 == _rowCounts[i])
continue;
_tableOffsets[i] = nextTableOffset;
nextTableOffset += _recordSize[i] * _rowCounts[i];
}
}
private int[] CalculateRecordSizes(int tableCount)
{
int[] sizes = new int[tableCount];
int sheapIdx = GetIndexSize(IndexType.StringHeap);
int gheapIdx = GetIndexSize(IndexType.GuidHeap);
int bheapIdx = GetIndexSize(IndexType.BlobHeap);
sizes[(int)TableType.Module >> 24] = (2 + sheapIdx + 3 * gheapIdx);
sizes[(int)TableType.TypeRef >> 24] = (GetIndexSize(IndexType.ResolutionScope) + 2 * sheapIdx);
sizes[(int)TableType.TypeDef >> 24] = (4 + 2 * sheapIdx + GetIndexSize(IndexType.TypeDefOrRef) + GetIndexSize(TableType.Field) + GetIndexSize(TableType.MethodDef));
sizes[(int)TableType.Field >> 24] = (2 + sheapIdx + bheapIdx);
sizes[(int)TableType.MethodDef >> 24] = (4 + 2 + 2 + sheapIdx + bheapIdx + GetIndexSize(TableType.Param));
sizes[(int)TableType.Param >> 24] = (2 + 2 + sheapIdx);
sizes[(int)TableType.InterfaceImpl >> 24] = (GetIndexSize(TableType.TypeDef) + GetIndexSize(IndexType.TypeDefOrRef));
sizes[(int)TableType.MemberRef >> 24] = (GetIndexSize(IndexType.MemberRefParent) + sheapIdx + bheapIdx);
sizes[(int)TableType.Constant >> 24] = (2 + GetIndexSize(IndexType.HasConstant) + bheapIdx);
sizes[(int)TableType.CustomAttribute >> 24] = (GetIndexSize(IndexType.HasCustomAttribute) + GetIndexSize(IndexType.CustomAttributeType) + bheapIdx);
sizes[(int)TableType.FieldMarshal >> 24] = (GetIndexSize(IndexType.HasFieldMarshal) + bheapIdx);
sizes[(int)TableType.DeclSecurity >> 24] = (2 + GetIndexSize(IndexType.HasDeclSecurity) + bheapIdx);
sizes[(int)TableType.ClassLayout >> 24] = (2 + 4 + GetIndexSize(TableType.TypeDef));
sizes[(int)TableType.FieldLayout >> 24] = (4 + GetIndexSize(TableType.Field));
sizes[(int)TableType.StandAloneSig >> 24] = (bheapIdx);
sizes[(int)TableType.EventMap >> 24] = (GetIndexSize(TableType.TypeDef) + GetIndexSize(TableType.Event));
sizes[(int)TableType.Event >> 24] = (2 + sheapIdx + GetIndexSize(IndexType.TypeDefOrRef));
sizes[(int)TableType.PropertyMap >> 24] = (GetIndexSize(TableType.TypeDef) + GetIndexSize(TableType.Property));
sizes[(int)TableType.Property >> 24] = (2 + sheapIdx + bheapIdx);
sizes[(int)TableType.MethodSemantics >> 24] = (2 + GetIndexSize(TableType.MethodDef) + GetIndexSize(IndexType.HasSemantics));
sizes[(int)TableType.MethodImpl >> 24] = (GetIndexSize(TableType.TypeDef) + 2 * GetIndexSize(IndexType.MethodDefOrRef));
sizes[(int)TableType.ModuleRef >> 24] = (sheapIdx);
sizes[(int)TableType.TypeSpec >> 24] = (bheapIdx);
sizes[(int)TableType.ImplMap >> 24] = (2 + GetIndexSize(IndexType.MemberForwarded) + sheapIdx + GetIndexSize(TableType.ModuleRef));
sizes[(int)TableType.FieldRVA >> 24] = (4 + GetIndexSize(TableType.Field));
sizes[(int)TableType.Assembly >> 24] = (4 + 2 + 2 + 2 + 2 + 4 + bheapIdx + 2 * sheapIdx);
sizes[(int)TableType.AssemblyProcessor >> 24] = (4);
sizes[(int)TableType.AssemblyOS >> 24] = (4 + 4 + 4);
sizes[(int)TableType.AssemblyRef >> 24] = (2 + 2 + 2 + 2 + 4 + 2 * bheapIdx + 2 * sheapIdx);
sizes[(int)TableType.AssemblyRefProcessor >> 24] = (4 + GetIndexSize(TableType.AssemblyRef));
sizes[(int)TableType.AssemblyRefOS >> 24] = (4 + 4 + 4 + GetIndexSize(TableType.AssemblyRef));
sizes[(int)TableType.File >> 24] = (4 + sheapIdx + bheapIdx);
sizes[(int)TableType.ExportedType >> 24] = (4 + 4 + 2 * sheapIdx + GetIndexSize(IndexType.Implementation));
sizes[(int)TableType.ManifestResource >> 24] = (4 + 4 + sheapIdx + GetIndexSize(IndexType.Implementation));
sizes[(int)TableType.NestedClass >> 24] = (2 * GetIndexSize(TableType.TypeDef));
sizes[(int)TableType.GenericParam >> 24] = (2 + 2 + GetIndexSize(IndexType.TypeOrMethodDef) + sheapIdx);
sizes[(int)TableType.MethodSpec >> 24] = (GetIndexSize(IndexType.MethodDefOrRef) + bheapIdx);
sizes[(int)TableType.GenericParamConstraint >> 24] = (GetIndexSize(TableType.GenericParam) + GetIndexSize(IndexType.TypeDefOrRef));
return sizes;
}
#endregion Construction
#region Properties
/// <summary>
/// Determines the number of tables in the provider.
/// </summary>
public int Count
{
get
{
int result = 0;
long valid = _valid;
while (0 != valid)
{
result += (int)(valid & 1);
valid >>= 1;
}
return result;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Determines the size of indexes into the named heap.
/// </summary>
/// <param name="index">The heap type to retrieve the index size for.</param>
/// <returns>The size of an index in bytes into the requested index type in bytes.</returns>
private int GetIndexSize(IndexType index)
{
if (0 > index || index >= IndexType.IndexCount)
throw new ArgumentException(@"Invalid index type specified.", @"index");
return _indexSize[(int)index];
}
/// <summary>
/// Determines the size of an index into the named table.
/// </summary>
/// <param name="tokenTypes">The table to determine the index for.</param>
/// <returns>The index size in bytes.</returns>
private int GetIndexSize(TableType table)
{
int _table = (int)table >> 24;
if (_table < 0 || _table > TableCount)
throw new ArgumentException(@"Invalid token type.");
if (_rowCounts[_table] > 65535)
return 4;
return 2;
}
/// <summary>
/// Read and decode an index value from the reader.
/// </summary>
/// <param name="reader">The reader to read From.</param>
/// <param name="index">The index type to read.</param>
/// <returns>The index value.</returns>
private HeapIndexToken ReadHeapToken(BinaryReader reader, IndexType index)
{
var value = (HeapIndexToken)(GetIndexSize(index) == 2 ? (0x0000FFFF & (int)reader.ReadInt16()) : reader.ReadInt32());
switch (index)
{
case IndexType.StringHeap:
value |= HeapIndexToken.String;
break;
case IndexType.GuidHeap:
value |= HeapIndexToken.Guid;
break;
case IndexType.BlobHeap:
value |= HeapIndexToken.Blob;
break;
default:
throw new ArgumentException(@"Invalid IndexType.");
}
return value;
}
private Token ReadMetadataToken(BinaryReader reader, IndexType index)
{
int value = (GetIndexSize(index) == 2) ? (0x0000FFFF & (int)reader.ReadInt16()) : reader.ReadInt32();
Debug.Assert(index < IndexType.CodedIndexCount);
int bits = IndexBits[(int)index];
int mask = 1;
for (int i = 1; i < bits; i++) mask = (mask << 1) | 1;
// Get the table
int table = (int)value & mask;
// Correct the value
value = ((int)value >> bits);
return new Token((TableType)IndexTables[(int)index][table], value);
}
/// <summary>
/// Read and decode an index value from the reader.
/// </summary>
/// <param name="reader">The reader to read From.</param>
/// <param name="table">The index type to read.</param>
/// <returns>The index value.</returns>
private Token ReadIndexValue(BinaryReader reader, TableType table)
{
return new Token(table, GetIndexSize(table) == 2 ? reader.ReadInt16() : reader.ReadInt32());
}
private BinaryReader CreateReaderForToken(Token token)
{
if (token.RID > GetRowCount(token.Table))
throw new ArgumentException(@"Row is out of bounds.", @"token");
if (token.RID == 0)
throw new ArgumentException(@"Invalid row index.", @"token");
int tableIdx = (int)(token.Table) >> 24;
int tableOffset = _tableOffsets[tableIdx] + ((int)(token.RID - 1) * _recordSize[tableIdx]);
var reader = new BinaryReader(new MemoryStream(Metadata), Encoding.UTF8);
reader.BaseStream.Position = tableOffset;
return reader;
}
#endregion Methods
#region IMetadataProvider members
/// <summary>
/// Gets the rows.
/// </summary>
/// <param name="table">The table.</param>
/// <returns></returns>
public int GetRowCount(TableType table)
{
return _rowCounts[((int)table >> 24)];
}
/// <summary>
/// Retrieves the number of rows in a specified table.
/// </summary>
/// <param name="token">The metadata token.</param>
/// <returns>The row count in the table.</returns>
/// <exception cref="System.ArgumentException">Invalid token type specified for table.</exception>
public Token GetMaxTokenValue(TableType table)
{
return new Token(table, _rowCounts[((int)table >> 24)]);
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public ModuleRow ReadModuleRow(Token token)
{
if (token.Table != TableType.Module)
throw new ArgumentException("Invalid token type for ModuleRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new ModuleRow(
reader.ReadUInt16(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.GuidHeap),
ReadHeapToken(reader, IndexType.GuidHeap),
ReadHeapToken(reader, IndexType.GuidHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public TypeRefRow ReadTypeRefRow(Token token)
{
if (token.Table != TableType.TypeRef)
throw new ArgumentException("Invalid token type for TypeRefRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new TypeRefRow(
ReadMetadataToken(reader, IndexType.ResolutionScope),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.StringHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public TypeDefRow ReadTypeDefRow(Token token)
{
if (token.Table != TableType.TypeDef)
throw new ArgumentException("Invalid token type for TypeDefRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new TypeDefRow(
(TypeAttributes)reader.ReadUInt32(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.StringHeap),
ReadMetadataToken(reader, IndexType.TypeDefOrRef),
ReadIndexValue(reader, TableType.Field),
ReadIndexValue(reader, TableType.MethodDef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public FieldRow ReadFieldRow(Token token)
{
if (token.Table != TableType.Field)
throw new ArgumentException("Invalid token type for FieldRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new FieldRow(
(FieldAttributes)reader.ReadUInt16(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public MethodDefRow ReadMethodDefRow(Token token)
{
if (token.Table != TableType.MethodDef)
throw new ArgumentException("Invalid token type for MethodDefRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new MethodDefRow(
reader.ReadUInt32(),
(MethodImplAttributes)reader.ReadUInt16(),
(MethodAttributes)reader.ReadUInt16(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.BlobHeap),
ReadIndexValue(reader, TableType.Param)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public ParamRow ReadParamRow(Token token)
{
if (token.Table != TableType.Param)
throw new ArgumentException("Invalid token type for ParamRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new ParamRow(
(ParameterAttributes)reader.ReadUInt16(),
reader.ReadInt16(),
ReadHeapToken(reader, IndexType.StringHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public InterfaceImplRow ReadInterfaceImplRow(Token token)
{
if (token.Table != TableType.InterfaceImpl)
throw new ArgumentException("Invalid token type for InterfaceImplRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new InterfaceImplRow(
ReadIndexValue(reader, TableType.TypeDef),
ReadMetadataToken(reader, IndexType.TypeDefOrRef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public MemberRefRow ReadMemberRefRow(Token token)
{
if (token.Table != TableType.MemberRef)
throw new ArgumentException("Invalid token type for MemberRefRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new MemberRefRow(
ReadMetadataToken(reader, IndexType.MemberRefParent),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public ConstantRow ReadConstantRow(Token token)
{
if (token.Table != TableType.Constant)
throw new ArgumentException("Invalid token type for ConstantRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
var cet = (CilElementType)reader.ReadByte();
reader.ReadByte();
return new ConstantRow(
cet,
ReadMetadataToken(reader, IndexType.HasConstant),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public CustomAttributeRow ReadCustomAttributeRow(Token token)
{
if (token.Table != TableType.CustomAttribute)
throw new ArgumentException("Invalid token type for CustomAttributeRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new CustomAttributeRow(
ReadMetadataToken(reader, IndexType.HasCustomAttribute),
ReadMetadataToken(reader, IndexType.CustomAttributeType),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public FieldMarshalRow ReadFieldMarshalRow(Token token)
{
if (token.Table != TableType.FieldMarshal)
throw new ArgumentException("Invalid token type for FieldMarshalRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new FieldMarshalRow(
ReadMetadataToken(reader, IndexType.HasFieldMarshal),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public DeclSecurityRow ReadDeclSecurityRow(Token token)
{
if (token.Table != TableType.DeclSecurity)
throw new ArgumentException("Invalid token type for DeclSecurityRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new DeclSecurityRow(
(System.Security.Permissions.SecurityAction)reader.ReadUInt16(),
ReadMetadataToken(reader, IndexType.HasDeclSecurity),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public ClassLayoutRow ReadClassLayoutRow(Token token)
{
if (token.Table != TableType.ClassLayout)
throw new ArgumentException("Invalid token type for ClassLayoutRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new ClassLayoutRow(
reader.ReadInt16(),
reader.ReadInt32(),
ReadIndexValue(reader, TableType.TypeDef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public FieldLayoutRow ReadFieldLayoutRow(Token token)
{
if (token.Table != TableType.FieldLayout)
throw new ArgumentException("Invalid token type for FieldLayoutRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new FieldLayoutRow(
reader.ReadUInt32(),
ReadIndexValue(reader, TableType.Field)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public StandAloneSigRow ReadStandAloneSigRow(Token token)
{
if (token.Table != TableType.StandAloneSig)
throw new ArgumentException("Invalid token type for StandAloneSigRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new StandAloneSigRow(
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public EventMapRow ReadEventMapRow(Token token)
{
if (token.Table != TableType.EventMap)
throw new ArgumentException("Invalid token type for EventMapRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new EventMapRow(
ReadIndexValue(reader, TableType.TypeDef),
ReadIndexValue(reader, TableType.Event)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public EventRow ReadEventRow(Token token)
{
if (token.Table != TableType.Event)
throw new ArgumentException("Invalid token type for EventRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new EventRow(
(EventAttributes)reader.ReadUInt16(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadMetadataToken(reader, IndexType.TypeDefOrRef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public PropertyMapRow ReadPropertyMapRow(Token token)
{
if (token.Table != TableType.PropertyMap)
throw new ArgumentException("Invalid token type for PropertyMapRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new PropertyMapRow(
ReadIndexValue(reader, TableType.TypeDef),
ReadIndexValue(reader, TableType.Property)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public PropertyRow ReadPropertyRow(Token token)
{
if (token.Table != TableType.Property)
throw new ArgumentException("Invalid token type for PropertyRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new PropertyRow(
(PropertyAttributes)reader.ReadUInt16(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public MethodSemanticsRow ReadMethodSemanticsRow(Token token)
{
using (var reader = CreateReaderForToken(token))
{
if (token.Table != TableType.MethodSemantics)
throw new ArgumentException("Invalid token type for MethodSemanticsRow.", @"token");
return new MethodSemanticsRow(
(MethodSemanticsAttributes)reader.ReadInt16(),
ReadIndexValue(reader, TableType.MethodDef),
ReadMetadataToken(reader, IndexType.HasSemantics)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public MethodImplRow ReadMethodImplRow(Token token)
{
if (token.Table != TableType.MethodImpl)
throw new ArgumentException("Invalid token type for MethodImplRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new MethodImplRow(
ReadIndexValue(reader, TableType.TypeDef),
ReadMetadataToken(reader, IndexType.MethodDefOrRef),
ReadMetadataToken(reader, IndexType.MethodDefOrRef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public ModuleRefRow ReadModuleRefRow(Token token)
{
if (token.Table != TableType.ModuleRef)
throw new ArgumentException("Invalid token type for ModuleRefRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new ModuleRefRow(
ReadHeapToken(reader, IndexType.StringHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public TypeSpecRow ReadTypeSpecRow(Token token)
{
if (token.Table != TableType.TypeSpec)
throw new ArgumentException("Invalid token type for TypeSpecRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new TypeSpecRow(
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public ImplMapRow ReadImplMapRow(Token token)
{
if (token.Table != TableType.ImplMap)
throw new ArgumentException("Invalid token type for ImplMapRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new ImplMapRow(
(PInvokeAttributes)reader.ReadUInt16(),
ReadMetadataToken(reader, IndexType.MemberForwarded),
ReadHeapToken(reader, IndexType.StringHeap),
ReadIndexValue(reader, TableType.ModuleRef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public FieldRVARow ReadFieldRVARow(Token token)
{
if (token.Table != TableType.FieldRVA)
throw new ArgumentException("Invalid token type for FieldRVARow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new FieldRVARow(
reader.ReadUInt32(),
ReadIndexValue(reader, TableType.Field)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public AssemblyRow ReadAssemblyRow(Token token)
{
if (token.Table != TableType.Assembly)
throw new ArgumentException("Invalid token type for AssemblyRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new AssemblyRow(
(AssemblyHashAlgorithm)reader.ReadUInt32(),
reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadUInt16(),
(AssemblyAttributes)reader.ReadUInt32(),
ReadHeapToken(reader, IndexType.BlobHeap),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.StringHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public AssemblyProcessorRow ReadAssemblyProcessorRow(Token token)
{
if (token.Table != TableType.AssemblyProcessor)
throw new ArgumentException("Invalid token type for AssemblyProcessorRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new AssemblyProcessorRow(
reader.ReadUInt32()
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public AssemblyOSRow ReadAssemblyOSRow(Token token)
{
if (token.Table != TableType.AssemblyOS)
throw new ArgumentException("Invalid token type for AssemblyOSRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new AssemblyOSRow(
reader.ReadInt32(),
reader.ReadInt32(),
reader.ReadInt32()
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public AssemblyRefRow ReadAssemblyRefRow(Token token)
{
if (token.Table != TableType.AssemblyRef)
throw new ArgumentException("Invalid token type for AssemblyRefRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new AssemblyRefRow(
reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadUInt16(),
(AssemblyAttributes)reader.ReadUInt32(),
ReadHeapToken(reader, IndexType.BlobHeap),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public AssemblyRefProcessorRow ReadAssemblyRefProcessorRow(Token token)
{
if (token.Table != TableType.AssemblyRefProcessor)
throw new ArgumentException("Invalid token type for AssemblyRefProcessorRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new AssemblyRefProcessorRow(
reader.ReadUInt32(),
ReadIndexValue(reader, TableType.AssemblyRef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public AssemblyRefOSRow ReadAssemblyRefOSRow(Token token)
{
if (token.Table != TableType.AssemblyRefOS)
throw new ArgumentException("Invalid token type for AssemblyRefOSRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new AssemblyRefOSRow(
reader.ReadUInt32(),
reader.ReadUInt32(),
reader.ReadUInt32(),
ReadIndexValue(reader, TableType.AssemblyRef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public FileRow ReadFileRow(Token token)
{
if (token.Table != TableType.File)
throw new ArgumentException("Invalid token type for FileRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new FileRow(
(FileAttributes)reader.ReadUInt32(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public ExportedTypeRow ReadExportedTypeRow(Token token)
{
if (token.Table != TableType.ExportedType)
throw new ArgumentException("Invalid token type for ExportedTypeRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new ExportedTypeRow(
(TypeAttributes)reader.ReadUInt32(),
(HeapIndexToken)reader.ReadUInt32(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadHeapToken(reader, IndexType.StringHeap),
ReadMetadataToken(reader, IndexType.Implementation)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public ManifestResourceRow ReadManifestResourceRow(Token token)
{
if (token.Table != TableType.ManifestResource)
throw new ArgumentException("Invalid token type for ManifestResourceRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new ManifestResourceRow(
reader.ReadUInt32(),
(ManifestResourceAttributes)reader.ReadUInt32(),
ReadHeapToken(reader, IndexType.StringHeap),
ReadMetadataToken(reader, IndexType.Implementation)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public NestedClassRow ReadNestedClassRow(Token token)
{
if (token.Table != TableType.NestedClass)
throw new ArgumentException("Invalid token type for NestedClassRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new NestedClassRow(
ReadIndexValue(reader, TableType.TypeDef),
ReadIndexValue(reader, TableType.TypeDef)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public GenericParamRow ReadGenericParamRow(Token token)
{
if (token.Table != TableType.GenericParam)
throw new ArgumentException("Invalid token type for GenericParamRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new GenericParamRow(
reader.ReadUInt16(),
(GenericParameterAttributes)reader.ReadUInt16(),
ReadMetadataToken(reader, IndexType.TypeOrMethodDef),
ReadHeapToken(reader, IndexType.StringHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public MethodSpecRow ReadMethodSpecRow(Token token)
{
if (token.Table != TableType.MethodSpec)
throw new ArgumentException("Invalid token type for MethodSpecRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new MethodSpecRow(
ReadMetadataToken(reader, IndexType.MethodDefOrRef),
ReadHeapToken(reader, IndexType.BlobHeap)
);
}
}
/// <summary>
/// Reads the specified token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public GenericParamConstraintRow ReadGenericParamConstraintRow(Token token)
{
if (token.Table != TableType.GenericParamConstraint)
throw new ArgumentException("Invalid token type for GenericParamConstraintRow.", @"token");
using (var reader = CreateReaderForToken(token))
{
return new GenericParamConstraintRow(
ReadIndexValue(reader, TableType.GenericParam),
ReadMetadataToken(reader, IndexType.TypeDefOrRef)
);
}
}
#endregion IMetadataProvider members
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ValidationUtils.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Core
{
#region Namespaces
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using Microsoft.OData.Edm;
using Microsoft.OData.Core.Metadata;
#endregion Namespaces
/// <summary>
/// Class with utility methods for validating OData content (applicable for readers and writers).
/// </summary>
internal static class ValidationUtils
{
/// <summary>The set of characters that are invalid in property names.</summary>
/// <remarks>Keep this array in sync with MetadataProviderUtils.InvalidCharactersInPropertyNames in Astoria.</remarks>
internal static readonly char[] InvalidCharactersInPropertyNames = new char[] { ':', '.', '@' };
/// <summary>Maximum batch boundary length supported (not includeding leading CRLF or '-').</summary>
private const int MaxBoundaryLength = 70;
/// <summary>
/// Validates that an open property value is supported.
/// </summary>
/// <param name="propertyName">The name of the open property.</param>
/// <param name="value">The value of the open property.</param>
internal static void ValidateOpenPropertyValue(string propertyName, object value)
{
Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)");
if (value is ODataStreamReferenceValue)
{
throw new ODataException(Strings.ValidationUtils_OpenStreamProperty(propertyName));
}
}
/// <summary>
/// Validates a type kind for a value type.
/// </summary>
/// <param name="typeKind">The type kind.</param>
/// <param name="typeName">The name of the type (used for error reporting only).</param>
internal static void ValidateValueTypeKind(EdmTypeKind typeKind, string typeName)
{
Debug.Assert(typeName != null, "typeName != null");
if (typeKind != EdmTypeKind.Primitive && typeKind != EdmTypeKind.Enum && typeKind != EdmTypeKind.Complex && typeKind != EdmTypeKind.Collection)
{
throw new ODataException(Strings.ValidationUtils_IncorrectValueTypeKind(typeName, typeKind.ToString()));
}
}
/// <summary>
/// Validates that <paramref name="collectionTypeName"/> is a valid type name for a collection and returns its item type name.
/// </summary>
/// <param name="collectionTypeName">The name of the collection type.</param>
/// <returns>The item type name for the <paramref name="collectionTypeName"/>.</returns>
internal static string ValidateCollectionTypeName(string collectionTypeName)
{
string itemTypeName = EdmLibraryExtensions.GetCollectionItemTypeName(collectionTypeName);
if (itemTypeName == null)
{
throw new ODataException(Strings.ValidationUtils_InvalidCollectionTypeName(collectionTypeName));
}
return itemTypeName;
}
/// <summary>
/// Validates that the <paramref name="payloadEntityTypeReference"/> is assignable to the <paramref name="expectedEntityTypeReference"/>
/// and fails if it's not.
/// </summary>
/// <param name="expectedEntityTypeReference">The expected entity type reference, the base type of the entities expected.</param>
/// <param name="payloadEntityTypeReference">The payload entity type reference to validate.</param>
internal static void ValidateEntityTypeIsAssignable(IEdmEntityTypeReference expectedEntityTypeReference, IEdmEntityTypeReference payloadEntityTypeReference)
{
Debug.Assert(expectedEntityTypeReference != null, "expectedEntityTypeReference != null");
Debug.Assert(payloadEntityTypeReference != null, "payloadEntityTypeReference != null");
// Entity types must be assignable
if (!EdmLibraryExtensions.IsAssignableFrom(expectedEntityTypeReference.EntityDefinition(), payloadEntityTypeReference.EntityDefinition()))
{
throw new ODataException(Strings.ValidationUtils_EntryTypeNotAssignableToExpectedType(payloadEntityTypeReference.ODataFullName(), expectedEntityTypeReference.ODataFullName()));
}
}
/// <summary>
/// Validates that the <paramref name="payloadComplexType"/> is assignable to the <paramref name="expectedComplexType"/>
/// and fails if it's not.
/// </summary>
/// <param name="expectedComplexType">The expected complex type reference, the base type of the ComplexType expected.</param>
/// <param name="payloadComplexType">The payload complex type reference to validate.</param>
internal static void ValidateComplexTypeIsAssignable(IEdmComplexType expectedComplexType, IEdmComplexType payloadComplexType)
{
Debug.Assert(expectedComplexType != null, "expectedComplexType != null");
Debug.Assert(payloadComplexType != null, "payloadComplexType != null");
// Complex types could be assignable
if (!EdmLibraryExtensions.IsAssignableFrom(expectedComplexType, payloadComplexType))
{
throw new ODataException(Strings.ValidationUtils_IncompatibleType(payloadComplexType.ODataFullName(), expectedComplexType.ODataFullName()));
}
}
/// <summary>
/// Validates that the <paramref name="typeReference"/> represents a collection type.
/// </summary>
/// <param name="typeReference">The type reference to validate.</param>
/// <returns>The <see cref="IEdmCollectionTypeReference"/> instance representing the collection passed as <paramref name="typeReference"/>.</returns>
internal static IEdmCollectionTypeReference ValidateCollectionType(IEdmTypeReference typeReference)
{
IEdmCollectionTypeReference collectionTypeReference = typeReference.AsCollectionOrNull();
if (collectionTypeReference != null && !typeReference.IsNonEntityCollectionType())
{
throw new ODataException(Strings.ValidationUtils_InvalidCollectionTypeReference(typeReference.TypeKind()));
}
return collectionTypeReference;
}
/// <summary>
/// Validates an item of a collection to ensure it is not of collection and stream reference types.
/// </summary>
/// <param name="item">The collection item.</param>
/// <param name="isNullable">True if the items in the collection are nullable, false otherwise.</param>
internal static void ValidateCollectionItem(object item, bool isNullable)
{
if (!isNullable && item == null)
{
throw new ODataException(Strings.ValidationUtils_NonNullableCollectionElementsMustNotBeNull);
}
if (item is ODataCollectionValue)
{
throw new ODataException(Strings.ValidationUtils_NestedCollectionsAreNotSupported);
}
if (item is ODataStreamReferenceValue)
{
throw new ODataException(Strings.ValidationUtils_StreamReferenceValuesNotSupportedInCollections);
}
}
/// <summary>
/// Validates a null collection item against the expected type.
/// </summary>
/// <param name="expectedItemType">The expected item type or null if no expected item type exists.</param>
/// <param name="writerBehavior">The <see cref="ODataWriterBehavior"/> instance controlling the behavior of the writer.</param>
internal static void ValidateNullCollectionItem(IEdmTypeReference expectedItemType, ODataWriterBehavior writerBehavior)
{
if (expectedItemType != null)
{
if (expectedItemType.IsODataPrimitiveTypeKind())
{
// WCF DS allows null values for non-nullable primitive types, so we need to check for a knob which enables this behavior.
// See the description of ODataWriterBehavior.AllowNullValuesForNonNullablePrimitiveTypes for more details.
if (!expectedItemType.IsNullable && !writerBehavior.AllowNullValuesForNonNullablePrimitiveTypes)
{
throw new ODataException(Strings.ValidationUtils_NullCollectionItemForNonNullableType(expectedItemType.ODataFullName()));
}
}
}
}
/// <summary>
/// Validates a stream reference property to ensure it's not null and its name if correct.
/// </summary>
/// <param name="streamProperty">The stream reference property to validate.</param>
/// <param name="edmProperty">Property metadata to validate against.</param>
internal static void ValidateStreamReferenceProperty(ODataProperty streamProperty, IEdmProperty edmProperty)
{
Debug.Assert(streamProperty != null, "streamProperty != null");
Debug.Assert(!string.IsNullOrEmpty(streamProperty.Name), "!string.IsNullOrEmpty(streamProperty.Name)");
Debug.Assert(streamProperty.Value is ODataStreamReferenceValue, "This method should only be called for stream reference properties.");
Debug.Assert(edmProperty == null || edmProperty.Name == streamProperty.Name, "edmProperty == null || edmProperty.Name == streamProperty.Name");
if (edmProperty != null && !edmProperty.Type.IsStream())
{
throw new ODataException(Strings.ValidationUtils_MismatchPropertyKindForStreamProperty(streamProperty.Name));
}
}
/// <summary>
/// Increases the given recursion depth, and then verifies that it doesn't exceed the recursion depth limit.
/// </summary>
/// <param name="recursionDepth">The current depth of the payload element hierarchy.</param>
/// <param name="maxDepth">The maximum allowed recursion depth.</param>
internal static void IncreaseAndValidateRecursionDepth(ref int recursionDepth, int maxDepth)
{
recursionDepth++;
if (recursionDepth > maxDepth)
{
throw new ODataException(Strings.ValidationUtils_RecursionDepthLimitReached(maxDepth));
}
}
/// <summary>
/// Validates an <see cref="ODataOperation"/> to ensure it's not null.
/// </summary>
/// <param name="operation">The operation to ensure it's not null.</param>
/// <param name="isAction">Whether <paramref name="operation"/> is an <see cref="ODataAction"/>.</param>
internal static void ValidateOperationNotNull(ODataOperation operation, bool isAction)
{
// null action/function can not appear in the enumeration
if (operation == null)
{
string enumerableName = isAction ? "ODataEntry.Actions" : "ODataEntry.Functions";
throw new ODataException(Strings.ValidationUtils_EnumerableContainsANullItem(enumerableName));
}
}
/// <summary>
/// Validates an <see cref="ODataOperation"/> to ensure its metadata is specified and valid.
/// </summary>
/// <param name="operation">The operation to validate.</param>
internal static void ValidateOperationMetadataNotNull(ODataOperation operation)
{
Debug.Assert(operation != null, "operation != null");
// ODataOperation must have a Metadata property.
if (operation.Metadata == null)
{
throw new ODataException(Strings.ValidationUtils_ActionsAndFunctionsMustSpecifyMetadata(operation.GetType().Name));
}
}
/// <summary>
/// Validates an <see cref="ODataOperation"/> to ensure its target is specified and valid.
/// </summary>
/// <param name="operation">The operation to validate.</param>
internal static void ValidateOperationTargetNotNull(ODataOperation operation)
{
Debug.Assert(operation != null, "operation != null");
// ODataOperation must have a Target property.
if (operation.Target == null)
{
throw new ODataException(Strings.ValidationUtils_ActionsAndFunctionsMustSpecifyTarget(operation.GetType().Name));
}
}
/// <summary>
/// Validates that the specified <paramref name="entry"/> is a valid entry as per the specified type.
/// </summary>
/// <param name="entry">The entry to validate.</param>
/// <param name="entityType">Optional entity type to validate the entry against.</param>
/// <param name="model">Model containing the entity type.</param>
/// <param name="validateMediaResource">true if the validation of the default MediaResource should be done; false otherwise.</param>
/// <remarks>If the <paramref name="entityType"/> is available only entry-level tests are performed, properties and such are not validated.</remarks>
internal static void ValidateEntryMetadataResource(ODataEntry entry, IEdmEntityType entityType, IEdmModel model, bool validateMediaResource)
{
Debug.Assert(entry != null, "entry != null");
if (entityType != null)
{
Debug.Assert(model != null, "model != null");
Debug.Assert(model.IsUserModel(), "model.IsUserModel()");
if (validateMediaResource)
{
if (entry.MediaResource == null)
{
if (entityType.HasStream)
{
throw new ODataException(Strings.ValidationUtils_EntryWithoutMediaResourceAndMLEType(entityType.ODataFullName()));
}
}
else
{
if (!entityType.HasStream)
{
throw new ODataException(Strings.ValidationUtils_EntryWithMediaResourceAndNonMLEType(entityType.ODataFullName()));
}
}
}
}
}
/// <summary>
/// Validates that a given primitive value is of the expected (primitive) type.
/// </summary>
/// <param name="value">The value to check.</param>
/// <param name="expectedTypeReference">The expected type for the value.</param>
internal static void ValidateIsExpectedPrimitiveType(object value, IEdmTypeReference expectedTypeReference)
{
Debug.Assert(value != null, "value != null");
Debug.Assert(expectedTypeReference != null, "expectedTypeReference != null");
// Note that valueInstanceType is never a nullable type because GetType() on Nullable variables at runtime will always yield
// a Type object that represents the underlying type, not the Nullable type itself.
Type valueInstanceType = value.GetType();
IEdmPrimitiveTypeReference valuePrimitiveTypeReference = EdmLibraryExtensions.GetPrimitiveTypeReference(valueInstanceType);
ValidateIsExpectedPrimitiveType(value, valuePrimitiveTypeReference, expectedTypeReference);
}
/// <summary>
/// Validates that a given primitive value is of the expected (primitive) type.
/// </summary>
/// <param name="value">The value to check.</param>
/// <param name="valuePrimitiveTypeReference">The primitive type reference for the value - some callers have this already, so we save the lookup here.</param>
/// <param name="expectedTypeReference">The expected type for the value.</param>
/// <param name="bypassValidation">Bypass the validation if it is true.</param>
/// <remarks>
/// Some callers have the primitive type reference already resolved (from the value type)
/// so this method is an optimized version to not lookup the primitive type reference again.
/// </remarks>
internal static void ValidateIsExpectedPrimitiveType(object value, IEdmPrimitiveTypeReference valuePrimitiveTypeReference, IEdmTypeReference expectedTypeReference, bool bypassValidation = false)
{
Debug.Assert(value != null, "value != null");
Debug.Assert(expectedTypeReference != null, "expectedTypeReference != null");
if (bypassValidation)
{
return;
}
if (valuePrimitiveTypeReference == null)
{
throw new ODataException(Strings.ValidationUtils_UnsupportedPrimitiveType(value.GetType().FullName));
}
Debug.Assert(valuePrimitiveTypeReference.IsEquivalentTo(EdmLibraryExtensions.GetPrimitiveTypeReference(value.GetType())), "The value and valuePrimitiveTypeReference don't match.");
if (!expectedTypeReference.IsODataPrimitiveTypeKind() && !expectedTypeReference.IsODataTypeDefinitionTypeKind())
{
// non-primitive type found for primitive value.
throw new ODataException(Strings.ValidationUtils_NonPrimitiveTypeForPrimitiveValue(expectedTypeReference.ODataFullName()));
}
ValidateMetadataPrimitiveType(expectedTypeReference, valuePrimitiveTypeReference);
}
/// <summary>
/// Validates that the expected primitive type or type definition matches the actual primitive type.
/// </summary>
/// <param name="expectedTypeReference">The expected type.</param>
/// <param name="typeReferenceFromValue">The actual type.</param>
internal static void ValidateMetadataPrimitiveType(IEdmTypeReference expectedTypeReference, IEdmTypeReference typeReferenceFromValue)
{
Debug.Assert(expectedTypeReference != null && (expectedTypeReference.IsODataPrimitiveTypeKind() || expectedTypeReference.IsODataTypeDefinitionTypeKind()), "expectedTypeReference must be a primitive type or type definition.");
Debug.Assert(typeReferenceFromValue != null && typeReferenceFromValue.IsODataPrimitiveTypeKind(), "typeReferenceFromValue must be a primitive type.");
IEdmType expectedType = expectedTypeReference.Definition;
IEdmPrimitiveType typeFromValue = (IEdmPrimitiveType)typeReferenceFromValue.Definition;
// The two primitive types match if they have the same definition and either both or only the
// expected type is nullable
// NOTE: for strings and binary values we must not check nullability here because the type reference
// from the value is always nullable since C# has no way to express non-nullable strings.
// However, this codepath is only hit if the value is not 'null' so we can assign a non-null
// value to both nullable and non-nullable string/binary types.
bool nullableCompatible = expectedTypeReference.IsNullable == typeReferenceFromValue.IsNullable ||
expectedTypeReference.IsNullable && !typeReferenceFromValue.IsNullable ||
!MetadataUtilsCommon.IsODataValueType(typeReferenceFromValue);
bool typeCompatible = expectedType.IsAssignableFrom(typeFromValue);
if (!nullableCompatible || !typeCompatible)
{
// incompatible type name for value!
throw new ODataException(Strings.ValidationUtils_IncompatiblePrimitiveItemType(
typeReferenceFromValue.ODataFullName(),
typeReferenceFromValue.IsNullable,
expectedTypeReference.ODataFullName(),
expectedTypeReference.IsNullable));
}
}
/// <summary>
/// Validates a element in service document.
/// </summary>
/// <param name="serviceDocumentElement">The element in service document to validate.</param>
/// <param name="format">Format that is being validated.</param>
[SuppressMessage("DataWeb.Usage", "AC0010", Justification = "Usage of ToString is safe in this context")]
internal static void ValidateServiceDocumentElement(ODataServiceDocumentElement serviceDocumentElement, ODataFormat format)
{
if (serviceDocumentElement == null)
{
throw new ODataException(Strings.ValidationUtils_WorkspaceResourceMustNotContainNullItem);
}
// The resource collection URL must not be null;
if (serviceDocumentElement.Url == null)
{
throw new ODataException(Strings.ValidationUtils_ResourceMustSpecifyUrl);
}
if (format == ODataFormat.Json && string.IsNullOrEmpty(serviceDocumentElement.Name))
{
throw new ODataException(Strings.ValidationUtils_ResourceMustSpecifyName(serviceDocumentElement.Url.ToString()));
}
}
/// <summary>
/// Validates a service document element's Url.
/// </summary>
/// <param name="serviceDocumentUrl">The service document url to validate.</param>
internal static void ValidateServiceDocumentElementUrl(string serviceDocumentUrl)
{
// The service document URL must not be null or empty;
if (serviceDocumentUrl == null)
{
throw new ODataException(Strings.ValidationUtils_ServiceDocumentElementUrlMustNotBeNull);
}
}
/// <summary>
/// Validates that the observed type kind is the expected type kind.
/// </summary>
/// <param name="actualTypeKind">The actual type kind to compare.</param>
/// <param name="expectedTypeKind">The expected type kind to compare against.</param>
/// <param name="typeName">The name of the type to use in the error.</param>
internal static void ValidateTypeKind(EdmTypeKind actualTypeKind, EdmTypeKind expectedTypeKind, string typeName)
{
if (actualTypeKind != expectedTypeKind)
{
if (typeName == null)
{
throw new ODataException(Strings.ValidationUtils_IncorrectTypeKindNoTypeName(actualTypeKind.ToString(), expectedTypeKind.ToString()));
}
if (actualTypeKind == EdmTypeKind.TypeDefinition && expectedTypeKind == EdmTypeKind.Primitive ||
actualTypeKind == EdmTypeKind.Primitive && expectedTypeKind == EdmTypeKind.TypeDefinition)
{
return;
}
throw new ODataException(Strings.ValidationUtils_IncorrectTypeKind(typeName, expectedTypeKind.ToString(), actualTypeKind.ToString()));
}
}
/// <summary>
/// Validates that a boundary delimiter is valid (non-null, less than 70 chars, only valid chars, etc.)
/// </summary>
/// <param name="boundary">The boundary delimiter to test.</param>
internal static void ValidateBoundaryString(string boundary)
{
// Boundary string must have at least 1 and no more than 70 characters.
if (boundary == null || boundary.Length == 0 || boundary.Length > MaxBoundaryLength)
{
throw new ODataException(Strings.ValidationUtils_InvalidBatchBoundaryDelimiterLength(boundary, MaxBoundaryLength));
}
//// NOTE: we do not have to check the validity of the characters in the boundary string
//// since we check their validity when reading the boundary parameter value of the Content-Type header.
//// See HttpUtils.ReadQuotedParameterValue.
}
/// <summary>
/// Null validation of complex properties will be skipped if edm version is less than v3 and data service version exists.
/// In such cases, the provider decides what should be done if a null value is stored on a non-nullable complex property.
/// </summary>
/// <param name="model">The model containing the complex property.</param>
/// <returns>True if complex property should be validated for null values.</returns>
internal static bool ShouldValidateComplexPropertyNullValue(IEdmModel model)
{
// Null validation of complex properties will be skipped if edm version < v3 and data service version exists.
Debug.Assert(model != null, "For null validation model is required.");
Debug.Assert(model.IsUserModel(), "For complex properties, the model should be user model.");
return true;
}
/// <summary>
/// Validates that a property name is valid in OData.
/// </summary>
/// <param name="propertyName">The property name to validate.</param>
/// <returns>true if the property name is valid, otherwise false.</returns>
internal static bool IsValidPropertyName(string propertyName)
{
Debug.Assert(!string.IsNullOrEmpty(propertyName), "The ATOM or JSON reader should have verified that the property name is not null or empty.");
return propertyName.IndexOfAny(ValidationUtils.InvalidCharactersInPropertyNames) < 0;
}
/// <summary>
/// Validates a property name to check whether it contains reserved characters.
/// </summary>
/// <param name="propertyName">The property name to check.</param>
internal static void ValidatePropertyName(string propertyName)
{
Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)");
if (!IsValidPropertyName(propertyName))
{
string invalidChars = string.Join(
", ",
ValidationUtils.InvalidCharactersInPropertyNames.Select(c => string.Format(CultureInfo.InvariantCulture, "'{0}'", c)).ToArray());
throw new ODataException(Strings.ValidationUtils_PropertiesMustNotContainReservedChars(propertyName, invalidChars));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[CLSCompliant(false)]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct UInt16 : IComparable, IConvertible, IFormattable, IComparable<UInt16>, IEquatable<UInt16>
{
private ushort m_value; // Do not rename (binary serialization)
public const ushort MaxValue = (ushort)0xFFFF;
public const ushort MinValue = 0;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt16, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is UInt16)
{
return ((int)m_value - (int)(((UInt16)value).m_value));
}
throw new ArgumentException(SR.Arg_MustBeUInt16);
}
public int CompareTo(UInt16 value)
{
return ((int)m_value - (int)value);
}
public override bool Equals(Object obj)
{
if (!(obj is UInt16))
{
return false;
}
return m_value == ((UInt16)obj).m_value;
}
[NonVersionable]
public bool Equals(UInt16 obj)
{
return m_value == obj;
}
// Returns a HashCode for the UInt16
public override int GetHashCode()
{
return (int)m_value;
}
// Converts the current value to a String in base-10 with no extra padding.
public override String ToString()
{
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ushort Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ushort Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ushort Parse(String s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ushort Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ushort Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
private static ushort Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info)
{
uint i = 0;
try
{
i = Number.ParseUInt32(s, style, info);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_UInt16, e);
}
if (i > MaxValue) throw new OverflowException(SR.Overflow_UInt16);
return (ushort)i;
}
[CLSCompliant(false)]
public static bool TryParse(String s, out UInt16 result)
{
if (s == null)
{
result = 0;
return false;
}
return TryParse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt16 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, out ushort result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out UInt16 result)
{
result = 0;
UInt32 i;
if (!Number.TryParseUInt32(s, style, info, out i))
{
return false;
}
if (i > MaxValue)
{
return false;
}
result = (UInt16)i;
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.UInt16;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return m_value;
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// 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\General\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt163()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt163();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt163
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt16[] values = new UInt16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt16();
}
Vector64<UInt16> value = Vector64.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt16 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt16 insertedValue = TestLibrary.Generator.GetUInt16();
try
{
Vector64<UInt16> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt16[] values = new UInt16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt16();
}
Vector64<UInt16> value = Vector64.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.GetElement))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt16)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt16 insertedValue = TestLibrary.Generator.GetUInt16();
try
{
object result2 = typeof(Vector64)
.GetMethod(nameof(Vector64.WithElement))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector64<UInt16>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt16 result, UInt16[] values, [CallerMemberName] string method = "")
{
if (result != values[3])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.GetElement(3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector64<UInt16> result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "")
{
UInt16[] resultElements = new UInt16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt16[] result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 3) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[3] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.WithElement(3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
interface I<T>
{
int E(T t);
}
sealed class J : I<string>
{
public int E(string s)
{
return s.Length;
}
}
class K : I<string>
{
public int E(string s)
{
return s.GetHashCode();
}
}
sealed class L : K, I<object>
{
public int E(object o)
{
return o.GetHashCode();
}
}
class F
{
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsIString<T>(I<T> i)
{
return i is I<string>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsI<T,U>(I<U> i)
{
return i is I<T>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsJI<T>(J j)
{
return j is I<T>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsKI<T>(K k)
{
return k is I<T>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsLI<T>(L l)
{
return l is I<T>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsJIString(J j)
{
return j is I<string>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsKIString(K k)
{
return k is I<string>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsLIString(L l)
{
return l is I<string>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsJIObject(J j)
{
return j is I<object>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsKIObject(K k)
{
return k is I<object>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsLIObject(L l)
{
return l is I<object>;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsIStringJ(I<string> i)
{
return i is J;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsIStringK(I<string> i)
{
return i is K;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsIStringL(I<string> i)
{
return i is L;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsIJ<T>(I<T> i)
{
return i is J;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsIK<T>(I<T> i)
{
return i is K;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsIL<T>(I<T> i)
{
return i is K;
}
public static int Main()
{
var j = new J();
var k = new K();
var l = new L();
bool b0 = IsIString(j);
bool b1 = IsIString(k);
bool b2 = IsIString<string>(l);
bool b3 = IsIString<object>(l);
bool c0 = IsI<string,string>(j);
bool c1 = IsI<string,string>(k);
bool c2 = IsI<string,string>(l);
bool d0 = IsI<object,string>(j);
bool d1 = IsI<object,string>(k);
bool d2 = IsI<object,string>(l);
bool e0 = IsJI<string>(j);
bool e1 = IsKI<string>(k);
bool e2 = IsKI<string>(l);
bool e3 = IsLI<string>(l);
bool f0 = IsJIString(j);
bool f1 = IsKIString(k);
bool f2 = IsKIString(l);
bool f3 = IsLIString(l);
bool g0 = IsIStringJ(j);
bool g1 = IsIStringJ(k);
bool g2 = IsIStringJ(l);
bool g3 = IsIStringK(j);
bool g4 = IsIStringK(k);
bool g5 = IsIStringK(l);
bool g6 = IsIStringL(j);
bool g7 = IsIStringL(k);
bool g8 = IsIStringL(l);
bool h0 = IsIJ<string>(j);
bool h1 = IsIJ<string>(k);
bool h2 = IsIJ<string>(l);
bool h3 = IsIK<string>(j);
bool h4 = IsIK<string>(k);
bool h5 = IsIK<string>(l);
bool h6 = IsIL<string>(j);
bool h7 = IsIL<string>(k);
bool h8 = IsIL<string>(l);
bool j0 = IsJIObject(j);
bool j1 = IsKIObject(k);
bool j2 = IsKIObject(l);
bool j3 = IsLIObject(l);
bool pos =
b0 & b1 & b2 & b3
& c0 & c1 & c2
& d2
& e0 & e1 & e2 & e3
& f0 & f1 & f2 & f3
& g0 & g4 & g5 & g8
& h0 & h4 & h5 & h8
& j2 & j3;
bool neg =
d0 & d1
& g1 & g2 & g6 & g7
& h1 & h2 & h6 & h7
& j0 & j1;
return pos & !neg ? 100 : 0;
}
}
| |
using System;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
//using RevMobAds.iOS;
using UIKit;
namespace RevMob.iOS
{
// @protocol RevMobAdsDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface RevMobAdsDelegate
{
// @optional -(void)revmobSessionIsStarted;
[Export ("revmobSessionIsStarted")]
void RevmobSessionIsStarted ();
// @optional -(void)revmobSessionNotStartedWithError:(NSError *)error;
[Export ("revmobSessionNotStartedWithError:")]
void RevmobSessionNotStartedWithError (NSError error);
// @optional -(void)revmobAdDidReceive;
[Export ("revmobAdDidReceive")]
void RevmobAdDidReceive ();
// @optional -(void)revmobAdDidFailWithError:(NSError *)error;
[Export ("revmobAdDidFailWithError:")]
void RevmobAdDidFailWithError (NSError error);
// @optional -(void)revmobAdDisplayed;
[Export ("revmobAdDisplayed")]
void RevmobAdDisplayed ();
// @optional -(void)revmobUserClickedInTheAd;
[Export ("revmobUserClickedInTheAd")]
void RevmobUserClickedInTheAd ();
// @optional -(void)revmobUserClosedTheAd;
[Export ("revmobUserClosedTheAd")]
void RevmobUserClosedTheAd ();
// @optional -(void)revmobVideoDidLoad;
[Export ("revmobVideoDidLoad")]
void RevmobVideoDidLoad ();
// @optional -(void)revmobVideoNotCompletelyLoaded;
[Export ("revmobVideoNotCompletelyLoaded")]
void RevmobVideoNotCompletelyLoaded ();
// @optional -(void)revmobVideoDidStart;
[Export ("revmobVideoDidStart")]
void RevmobVideoDidStart ();
// @optional -(void)revmobVideoDidFinish;
[Export ("revmobVideoDidFinish")]
void RevmobVideoDidFinish ();
// @optional -(void)revmobRewardedVideoDidLoad;
[Export ("revmobRewardedVideoDidLoad")]
void RevmobRewardedVideoDidLoad ();
// @optional -(void)revmobRewardedVideoNotCompletelyLoaded;
[Export ("revmobRewardedVideoNotCompletelyLoaded")]
void RevmobRewardedVideoNotCompletelyLoaded ();
// @optional -(void)revmobRewardedVideoDidStart;
[Export ("revmobRewardedVideoDidStart")]
void RevmobRewardedVideoDidStart ();
// @optional -(void)revmobRewardedVideoDidFinish;
[Export ("revmobRewardedVideoDidFinish")]
void RevmobRewardedVideoDidFinish ();
// @optional -(void)revmobRewardedVideoComplete;
[Export ("revmobRewardedVideoComplete")]
void RevmobRewardedVideoComplete ();
// @optional -(void)revmobRewardedPreRollDisplayed;
[Export ("revmobRewardedPreRollDisplayed")]
void RevmobRewardedPreRollDisplayed ();
// @optional -(void)installDidReceive;
[Export ("installDidReceive")]
void InstallDidReceive ();
// @optional -(void)installDidFail;
[Export ("installDidFail")]
void InstallDidFail ();
}
// typedef void (^RevMobAdLinkSuccessfullHandler)(RevMobAdLink *);
delegate void RevMobAdLinkSuccessfullHandler (RevMobAdLink arg0);
// typedef void (^RevMobAdLinkFailureHandler)(RevMobAdLink *, NSError *);
delegate void RevMobAdLinkFailureHandler (RevMobAdLink arg0, NSError arg1);
// @interface RevMobAdLink : NSObject
[BaseType (typeof(NSObject))]
interface RevMobAdLink
{
[Wrap ("WeakDelegate")]
RevMobAdsDelegate Delegate { get; set; }
// @property (assign, nonatomic) id<RevMobAdsDelegate> delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
// -(void)loadAd;
[Export ("loadAd")]
void LoadAd ();
// -(void)loadWithSuccessHandler:(RevMobAdLinkSuccessfullHandler)onAdLoadedHandler andLoadFailHandler:(RevMobAdLinkFailureHandler)onAdFailedHandler;
[Export ("loadWithSuccessHandler:andLoadFailHandler:")]
void LoadWithSuccessHandler (RevMobAdLinkSuccessfullHandler onAdLoadedHandler, RevMobAdLinkFailureHandler onAdFailedHandler);
// -(void)openLink;
[Export ("openLink")]
void OpenLink ();
}
// typedef void (^RevMobBannerViewSuccessfullHandler)(RevMobBannerView *);
delegate void RevMobBannerViewSuccessfullHandler (RevMobBannerView arg0);
// typedef void (^RevMobBannerViewFailureHandler)(RevMobBannerView *, NSError *);
delegate void RevMobBannerViewFailureHandler (RevMobBannerView arg0, NSError arg1);
// typedef void (^RevMobBannerViewOnclickHandler)(RevMobBannerView *);
delegate void RevMobBannerViewOnclickHandler (RevMobBannerView arg0);
// @interface RevMobBannerView : UIView <UIWebViewDelegate>
[BaseType (typeof(UIView))]
interface RevMobBannerView : IUIWebViewDelegate
{
[Wrap ("WeakDelegate")]
RevMobAdsDelegate Delegate { get; set; }
// @property (assign, nonatomic) id<RevMobAdsDelegate> delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
// -(void)loadAd;
[Export ("loadAd")]
void LoadAd ();
// -(void)loadWithSuccessHandler:(RevMobBannerViewSuccessfullHandler)onAdLoadedHandler andLoadFailHandler:(RevMobBannerViewFailureHandler)onAdFailedHandler onClickHandler:(RevMobBannerViewOnclickHandler)onClickHandler;
[Export ("loadWithSuccessHandler:andLoadFailHandler:onClickHandler:")]
void LoadWithSuccessHandler (RevMobBannerViewSuccessfullHandler onAdLoadedHandler, RevMobBannerViewFailureHandler onAdFailedHandler, RevMobBannerViewOnclickHandler onClickHandler);
// -(void)showAd;
[Export ("showAd")]
void ShowAd ();
// -(void)showAd:(CGFloat)x y:(CGFloat)y width:(CGFloat)w height:(CGFloat)h view:(UIView *)v;
[Export ("showAd:y:width:height:view:")]
void ShowAd (nfloat x, nfloat y, nfloat w, nfloat h, UIView v);
// -(void)showAd:(CGFloat)x y:(CGFloat)y width:(CGFloat)w height:(CGFloat)h;
[Export ("showAd:y:width:height:")]
void ShowAd (nfloat x, nfloat y, nfloat w, nfloat h);
}
// typedef void (^RevMobBannerSuccessfullHandler)(RevMobBanner *);
delegate void RevMobBannerSuccessfullHandler (RevMobBanner arg0);
// typedef void (^RevMobBannerFailureHandler)(RevMobBanner *, NSError *);
delegate void RevMobBannerFailureHandler (RevMobBanner arg0, NSError arg1);
// typedef void (^RevMobBannerOnClickHandler)(RevMobBanner *);
delegate void RevMobBannerOnClickHandler (RevMobBanner arg0);
// @interface RevMobBanner : NSObject
[BaseType (typeof(NSObject))]
interface RevMobBanner
{
[Wrap ("WeakDelegate")]
RevMobAdsDelegate Delegate { get; set; }
// @property (assign, nonatomic) id<RevMobAdsDelegate> delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
// @property (assign, nonatomic) CGRect frame;
[Export ("frame", ArgumentSemantic.Assign)]
CGRect Frame { get; set; }
// @property (nonatomic, strong) NSArray * supportedInterfaceOrientations;
[Export ("supportedInterfaceOrientations", ArgumentSemantic.Strong)]
NSObject[] SupportedInterfaceOrientations { get; set; }
// -(void)loadAd;
[Export ("loadAd")]
void LoadAd ();
// -(void)loadWithSuccessHandler:(RevMobBannerSuccessfullHandler)onAdLoadedHandler andLoadFailHandler:(RevMobBannerFailureHandler)onAdFailedHandler onClickHandler:(RevMobBannerOnClickHandler)onClickHandler;
[Export ("loadWithSuccessHandler:andLoadFailHandler:onClickHandler:")]
void LoadWithSuccessHandler (RevMobBannerSuccessfullHandler onAdLoadedHandler, RevMobBannerFailureHandler onAdFailedHandler, RevMobBannerOnClickHandler onClickHandler);
// -(void)showAd;
[Export ("showAd")]
void ShowAd ();
// -(void)hideAd;
[Export ("hideAd")]
void HideAd ();
}
// typedef void (^RevMobButtonSuccessfullHandler)(RevMobButton *);
delegate void RevMobButtonSuccessfullHandler (RevMobButton arg0);
// typedef void (^RevMobButtonFailureHandler)(RevMobButton *, NSError *);
delegate void RevMobButtonFailureHandler (RevMobButton arg0, NSError arg1);
// typedef void (^RevMobButtonOnclickHandler)(RevMobButton *);
delegate void RevMobButtonOnclickHandler (RevMobButton arg0);
// @interface RevMobButton : UIButton
[BaseType (typeof(UIButton))]
interface RevMobButton
{
[Wrap ("WeakDelegate")]
RevMobAdsDelegate Delegate { get; set; }
// @property (assign, nonatomic) id<RevMobAdsDelegate> delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
// @property (readonly, atomic) RevMobButtonStatus status;
[Export ("status")]
RevMobButtonStatus Status { get; }
// -(void)loadAd;
[Export ("loadAd")]
void LoadAd ();
// -(void)loadWithSuccessHandler:(RevMobButtonSuccessfullHandler)onAdLoadedHandler andLoadFailHandler:(RevMobButtonFailureHandler)onAdFailedHandler onClickHandler:(RevMobButtonOnclickHandler)onClickHandler;
[Export ("loadWithSuccessHandler:andLoadFailHandler:onClickHandler:")]
void LoadWithSuccessHandler (RevMobButtonSuccessfullHandler onAdLoadedHandler, RevMobButtonFailureHandler onAdFailedHandler, RevMobButtonOnclickHandler onClickHandler);
}
// @interface RevMobFullscreen : NSObject
[BaseType (typeof(NSObject))]
interface RevMobFullscreen
{
[Wrap ("WeakDelegate")]
RevMobAdsDelegate Delegate { get; set; }
// @property (assign, nonatomic) id<RevMobAdsDelegate> delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
// @property (nonatomic, strong) NSArray * supportedInterfaceOrientations;
[Export ("supportedInterfaceOrientations", ArgumentSemantic.Strong)]
NSObject[] SupportedInterfaceOrientations { get; set; }
// -(void)loadVideo;
[Export ("loadVideo")]
void LoadVideo ();
// -(void)loadRewardedVideo;
[Export ("loadRewardedVideo")]
void LoadRewardedVideo ();
// -(void)loadAd;
[Export ("loadAd")]
void LoadAd ();
// -(void)loadWithSuccessHandler:(void (^)(RevMobFullscreen *))onAdLoadedHandler andLoadFailHandler:(void (^)(RevMobFullscreen *, NSError *))onAdFailedHandler;
[Export ("loadWithSuccessHandler:andLoadFailHandler:")]
void LoadWithSuccessHandler (Action<RevMobFullscreen> onAdLoadedHandler, Action<RevMobFullscreen, NSError> onAdFailedHandler);
// -(void)loadWithSuccessHandler:(void (^)(RevMobFullscreen *))onAdLoadedHandler andLoadFailHandler:(void (^)(RevMobFullscreen *, NSError *))onAdFailedHandler onClickHandler:(void (^)())onClickHandler onCloseHandler:(void (^)())onCloseHandler;
[Export ("loadWithSuccessHandler:andLoadFailHandler:onClickHandler:onCloseHandler:")]
void LoadWithSuccessHandler (Action<RevMobFullscreen> onAdLoadedHandler, Action<RevMobFullscreen, NSError> onAdFailedHandler, Action onClickHandler, Action onCloseHandler);
// -(void)showAd;
[Export ("showAd")]
void ShowAd ();
// -(void)showVideo;
[Export ("showVideo")]
void ShowVideo ();
// -(void)showRewardedVideo;
[Export ("showRewardedVideo")]
void ShowRewardedVideo ();
// -(void)hideAd;
[Export ("hideAd")]
void HideAd ();
}
// typedef void (^RevMobPopupSuccessfullHandler)(RevMobPopup *);
delegate void RevMobPopupSuccessfullHandler (RevMobPopup arg0);
// typedef void (^RevMobPopupFailureHandler)(RevMobPopup *, NSError *);
delegate void RevMobPopupFailureHandler (RevMobPopup arg0, NSError arg1);
// typedef void (^RevMobPopupOnClickHandler)(RevMobPopup *);
delegate void RevMobPopupOnClickHandler (RevMobPopup arg0);
// @interface RevMobPopup : NSObject <UIAlertViewDelegate>
[BaseType (typeof(NSObject))]
interface RevMobPopup : IUIAlertViewDelegate
{
[Wrap ("WeakDelegate")]
RevMobAdsDelegate Delegate { get; set; }
// @property (assign, nonatomic) id<RevMobAdsDelegate> delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
// -(void)loadAd;
[Export ("loadAd")]
void LoadAd ();
// -(void)loadWithSuccessHandler:(RevMobPopupSuccessfullHandler)onAdLoadedHandler andLoadFailHandler:(RevMobPopupFailureHandler)onAdFailedHandler onClickHandler:(RevMobPopupOnClickHandler)onClickHandler;
[Export ("loadWithSuccessHandler:andLoadFailHandler:onClickHandler:")]
void LoadWithSuccessHandler (RevMobPopupSuccessfullHandler onAdLoadedHandler, RevMobPopupFailureHandler onAdFailedHandler, RevMobPopupOnClickHandler onClickHandler);
// -(void)showAd;
[Export ("showAd")]
void ShowAd ();
}
// @interface RevMobAds : NSObject
[BaseType (typeof(NSObject))]
interface RevMobAds
{
[Wrap ("WeakDelegate")]
RevMobAdsDelegate Delegate { get; set; }
// @property (assign, nonatomic) id<RevMobAdsDelegate> delegate __attribute__((deprecated("")));
[NullAllowed, Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
// @property (assign, nonatomic) NSUInteger connectionTimeout;
[Export ("connectionTimeout")]
nuint ConnectionTimeout { get; set; }
// @property (assign, nonatomic) RevMobAdsTestingMode testingMode;
[Export ("testingMode", ArgumentSemantic.Assign)]
RevMobAdsTestingMode TestingMode { get; set; }
// @property (assign, nonatomic) RevMobParallaxMode parallaxMode;
[Export ("parallaxMode", ArgumentSemantic.Assign)]
RevMobParallaxMode ParallaxMode { get; set; }
// @property (assign, nonatomic) RevMobUserGender userGender;
[Export ("userGender", ArgumentSemantic.Assign)]
RevMobUserGender UserGender { get; set; }
// @property (assign, nonatomic) NSUInteger userAgeRangeMin;
[Export ("userAgeRangeMin")]
nuint UserAgeRangeMin { get; set; }
// @property (assign, nonatomic) NSUInteger userAgeRangeMax;
[Export ("userAgeRangeMax")]
nuint UserAgeRangeMax { get; set; }
// @property (nonatomic, strong) NSDate * userBirthday;
[Export ("userBirthday", ArgumentSemantic.Strong)]
NSDate UserBirthday { get; set; }
// @property (nonatomic, strong) NSArray * userInterests;
[Export ("userInterests", ArgumentSemantic.Strong)]
NSString[] UserInterests { get; set; }
// @property (nonatomic, strong) NSString * userPage;
[Export ("userPage", ArgumentSemantic.Strong)]
string UserPage { get; set; }
// +(RevMobAds *)startSessionWithAppID:(NSString *)anAppId;
[Static]
[Export ("startSessionWithAppID:")]
RevMobAds StartSessionWithAppID (string anAppId);
// +(RevMobAds *)startSessionWithAppID:(NSString *)anAppId andDelegate:(id<RevMobAdsDelegate>)adelegate;
[Static]
[Export ("startSessionWithAppID:andDelegate:")]
RevMobAds StartSessionWithAppID (string anAppId, RevMobAdsDelegate adelegate);
// +(RevMobAds *)startSessionWithAppID:(NSString *)anAppId withSuccessHandler:(void (^)())onSessionStartedHandler andFailHandler:(void (^)(NSError *))onSessionNotStartedHandler;
[Static]
[Export ("startSessionWithAppID:withSuccessHandler:andFailHandler:")]
RevMobAds StartSessionWithAppID (string anAppId, Action onSessionStartedHandler, Action<NSError> onSessionNotStartedHandler);
// +(RevMobAds *)startSessionWithAppID:(NSString *)anAppId withSuccessHandler:(void (^)())onSessionStartedHandler andFailHandler:(void (^)(NSError *))onSessionNotStartedHandler url:(NSString *)serverUrl key:(int)sessionKey;
[Static]
[Export ("startSessionWithAppID:withSuccessHandler:andFailHandler:url:key:")]
RevMobAds StartSessionWithAppID (string anAppId, Action onSessionStartedHandler, Action<NSError> onSessionNotStartedHandler, string serverUrl, int sessionKey);
// +(RevMobAds *)session;
[Static]
[Export ("session")]
RevMobAds Session { get; }
// -(void)printEnvironmentInformation;
[Export ("printEnvironmentInformation")]
void PrintEnvironmentInformation ();
// -(void)showFullscreen;
[Export ("showFullscreen")]
void ShowFullscreen ();
// -(void)showBanner;
[Export ("showBanner")]
void ShowBanner ();
// -(void)hideBanner;
[Export ("hideBanner")]
void HideBanner ();
// -(void)showPopup;
[Export ("showPopup")]
void ShowPopup ();
// -(void)openAdLinkWithDelegate:(id<RevMobAdsDelegate>)adelegate;
[Export ("openAdLinkWithDelegate:")]
void OpenAdLinkWithDelegate (RevMobAdsDelegate adelegate);
// -(RevMobFullscreen *)fullscreen;
[Export ("fullscreen")]
RevMobFullscreen Fullscreen { get; }
// -(RevMobFullscreen *)fullscreenWithPlacementId:(NSString *)placementId;
[Export ("fullscreenWithPlacementId:")]
RevMobFullscreen FullscreenWithPlacementId (string placementId);
// -(RevMobBannerView *)bannerView;
[Export ("bannerView")]
RevMobBannerView BannerView { get; }
// -(RevMobBannerView *)bannerViewWithPlacementId:(NSString *)placementId;
[Export ("bannerViewWithPlacementId:")]
RevMobBannerView BannerViewWithPlacementId (string placementId);
// -(RevMobBanner *)banner;
[Export ("banner")]
RevMobBanner Banner { get; }
// -(RevMobBanner *)bannerWithPlacementId:(NSString *)placementId;
[Export ("bannerWithPlacementId:")]
RevMobBanner BannerWithPlacementId (string placementId);
// -(RevMobButton *)button;
[Export ("button")]
RevMobButton Button { get; }
// -(RevMobButton *)buttonWithPlacementId:(NSString *)placementId;
[Export ("buttonWithPlacementId:")]
RevMobButton ButtonWithPlacementId (string placementId);
// -(RevMobButton *)buttonUnloaded;
[Export ("buttonUnloaded")]
RevMobButton ButtonUnloaded { get; }
// -(RevMobButton *)buttonUnloadedWithPlacementId:(NSString *)placementId;
[Export ("buttonUnloadedWithPlacementId:")]
RevMobButton ButtonUnloadedWithPlacementId (string placementId);
// -(RevMobAdLink *)adLink;
[Export ("adLink")]
RevMobAdLink AdLink { get; }
// -(RevMobAdLink *)adLinkWithPlacementId:(NSString *)placementId;
[Export ("adLinkWithPlacementId:")]
RevMobAdLink AdLinkWithPlacementId (string placementId);
// -(RevMobPopup *)popup;
[Export ("popup")]
RevMobPopup Popup { get; }
// -(void)openLink;
[Export ("openLink")]
void OpenLink ();
// -(RevMobPopup *)popupWithPlacementId:(NSString *)placementId;
[Export ("popupWithPlacementId:")]
RevMobPopup PopupWithPlacementId (string placementId);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Xap
{
[Serializable]
[DebuggerDisplay( "{m_name}" )]
public class Sound : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Name":
m_name = value;
break;
case "Volume":
m_volume = Parser.ParseInt( value, line );
break;
case "Pitch":
m_pitch = Parser.ParseInt( value, line );
break;
case "Priority":
m_priority = Parser.ParseInt( value, line );
break;
case "Category Entry":
// Docs appear to be wrong about how this is arranged
CategoryEntry entry = new CategoryEntry();
entry.Parse( source, ref line, OwnerProject );
m_category = entry.FindCategory();
break;
case "Effect Entry":
EffectEntry effectEntry = new EffectEntry();
effectEntry.Parse( source, ref line, OwnerProject );
foreach ( Effect effect in OwnerProject.m_globalSettings.m_effects )
{
if ( effect.m_name == effectEntry.m_name )
{
m_effects.Add( effect );
break;
}
}
break;
case "RPC Entry":
RpcEntry rpcEntry = new RpcEntry();
rpcEntry.Parse( source, ref line, OwnerProject );
m_rpcEntries.Add( rpcEntry );
break;
case "Track":
Track track = new Track();
track.Parse( source, ref line, OwnerProject );
m_tracks.Add( track );
break;
case "Comment":
m_comment = Parser.ParseComment( value, source, ref line );
break;
default:
return false;
}
return true;
}
#region Member variables
public string m_name;
public int m_volume;
public int m_pitch;
public int m_priority;
public string m_comment;
public Category m_category;
public List<Effect> m_effects = new List<Effect>();
public List<Track> m_tracks = new List<Track>();
public List<RpcEntry> m_rpcEntries = new List<RpcEntry>();
#endregion
}
[Serializable]
[DebuggerDisplay( "{m_name}" )]
public class SoundEntry : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Name":
m_name = value;
break;
case "Index":
m_index = Parser.ParseInt( value, line );
break;
// Non-interactive sound entries
case "Weight Max":
m_weightMax = Parser.ParseInt( value, line );
break;
case "Weight Min":
m_weightMin = Parser.ParseInt( value, line );
break;
// Interactive sound entries
case "Variable Min":
m_variableMin = Parser.ParseFloat( value, line );
break;
case "Variable Max":
m_variableMax = Parser.ParseFloat( value, line );
break;
case "Linger":
m_linger = Parser.ParseInt( value, line );
break;
default:
return false;
}
return true;
}
public Sound FindSound( SoundBank soundBank )
{
foreach ( Sound sound in soundBank.m_sounds )
{
if ( sound.m_name == m_name )
{
return sound;
}
}
// Not found by name, which suggests index is likely to fail too (so why
// the XAP file format insists on providing both, I don't understand)
if ( m_index >= 0 )
{
return soundBank.m_sounds[m_index];
}
return null;
}
#region Member variables
public string m_name;
public int m_index;
// Non-interactive sound entries
public int m_weightMax;
public int m_weightMin;
// Interactive sound entries
public float m_variableMin;
public float m_variableMax;
public int m_linger;
#endregion
}
[Serializable]
public class Track : Entity
{
public override bool SetProperty( string propertyName, string value, string[] source, ref int line )
{
switch ( propertyName )
{
case "Name":
m_name = value;
break;
case "Volume":
m_volume = Parser.ParseInt( value, line );
break;
case "Use Filter":
m_useFilter = Parser.ParseInt(value, line);
break;
case "RPC Curve Entry":
RpcCurveEntry entry = new RpcCurveEntry();
entry.Parse( source, ref line, OwnerProject );
RpcCurve curve = OwnerProject.m_globalSettings.m_rpcs[entry.m_rpcIndex].m_rpcCurves[entry.m_curveIndex];
m_rpcCurves.Add( curve );
break;
case "Clip Entry":
throw new NotImplementedException( "Clip Entries don't exist?" );
case "Play Wave Event":
PlayWaveEvent playWave = new PlayWaveEvent();
playWave.Parse( source, ref line, OwnerProject );
m_events.Add( playWave );
break;
case "Play Sound Event":
PlaySoundEvent playSound = new PlaySoundEvent();
playSound.Parse( source, ref line, OwnerProject );
m_events.Add( playSound );
break;
case "Stop Event":
StopEvent stop = new StopEvent();
stop.Parse( source, ref line, OwnerProject );
m_events.Add( stop );
break;
case "Branch Event": // Docs say "not supported", but I'm not sure that's true?
BranchEvent branch = new BranchEvent();
branch.Parse( source, ref line, OwnerProject );
m_events.Add( branch );
break;
case "Wait Event":
WaitEvent wait = new WaitEvent();
wait.Parse( source, ref line, OwnerProject );
m_events.Add( wait );
break;
case "Set Effect Parameter":
SetEffectParameterEvent effectParam = new SetEffectParameterEvent();
effectParam.Parse( source, ref line, OwnerProject );
m_events.Add( effectParam );
break;
case "Set Variable Event":
SetVariableEvent variable = new SetVariableEvent();
variable.Parse( source, ref line, OwnerProject );
m_events.Add( variable );
break;
case "Set Pitch Event":
SetPitchEvent pitch = new SetPitchEvent();
pitch.Parse( source, ref line, OwnerProject );
m_events.Add( pitch );
break;
case "Set Volume Event":
SetVolumeEvent volume = new SetVolumeEvent();
volume.Parse( source, ref line, OwnerProject );
m_events.Add( volume );
break;
case "Marker Event":
MarkerEvent marker = new MarkerEvent();
marker.Parse( source, ref line, OwnerProject );
m_events.Add( marker );
break;
// These are all obsolete?
case "Play Wave From Offset Event":
case "Play Wave Variation Event":
case "Set Variable Recurring Event":
case "Set Marker Recurring Event":
default:
return false;
}
return true;
}
#region Member variables
public string m_name;
public int m_volume;
public int m_useFilter;
public List<RpcCurve> m_rpcCurves = new List<RpcCurve>();
public List<EventBase> m_events = new List<EventBase>();
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Analyzer.Utilities;
using System.Collections.Generic;
using Analyzer.Utilities.Extensions;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
/// <summary>
/// CA1707: Identifiers should not contain underscores
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class IdentifiersShouldNotContainUnderscoresAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1707";
private const string Uri = "https://msdn.microsoft.com/en-us/library/ms182245.aspx";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageAssembly = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageAssembly), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNamespace = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageNamespace), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageType = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageType), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMember = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMember), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageTypeTypeParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageTypeTypeParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMethodTypeParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMethodTypeParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMemberParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDelegateParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageDelegateParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
internal static DiagnosticDescriptor AssemblyRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageAssembly,
DiagnosticCategory.Naming,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor NamespaceRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNamespace,
DiagnosticCategory.Naming,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor TypeRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageType,
DiagnosticCategory.Naming,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor MemberRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMember,
DiagnosticCategory.Naming,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor TypeTypeParameterRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageTypeTypeParameter,
DiagnosticCategory.Naming,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor MethodTypeParameterRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMethodTypeParameter,
DiagnosticCategory.Naming,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor MemberParameterRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMemberParameter,
DiagnosticCategory.Naming,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor DelegateParameterRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDelegateParameter,
DiagnosticCategory.Naming,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(AssemblyRule, NamespaceRule, TypeRule, MemberRule, TypeTypeParameterRule, MethodTypeParameterRule, MemberParameterRule, DelegateParameterRule);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterSymbolAction(symbolAnalysisContext =>
{
var symbol = symbolAnalysisContext.Symbol;
switch (symbol.Kind)
{
case SymbolKind.Namespace:
{
if (ContainsUnderScore(symbol.Name))
{
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(NamespaceRule, symbol.ToDisplayString()));
}
return;
}
case SymbolKind.NamedType:
{
var namedType = symbol as INamedTypeSymbol;
AnalyzeTypeParameters(symbolAnalysisContext, namedType.TypeParameters);
if (namedType.TypeKind == TypeKind.Delegate &&
namedType.DelegateInvokeMethod != null)
{
AnalyzeParameters(symbolAnalysisContext, namedType.DelegateInvokeMethod.Parameters);
}
if (!ContainsUnderScore(symbol.Name) || !symbol.IsPublic())
{
return;
}
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(TypeRule, symbol.ToDisplayString()));
return;
}
case SymbolKind.Field:
{
var fieldSymbol = symbol as IFieldSymbol;
if (ContainsUnderScore(symbol.Name) && symbol.IsPublic() && (fieldSymbol.IsConst || (fieldSymbol.IsStatic && fieldSymbol.IsReadOnly)))
{
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
return;
}
return;
}
default:
{
if (symbol is IMethodSymbol methodSymbol)
{
if (methodSymbol.IsOperator())
{
// Do not flag for operators.
return;
}
AnalyzeParameters(symbolAnalysisContext, methodSymbol.Parameters);
AnalyzeTypeParameters(symbolAnalysisContext, methodSymbol.TypeParameters);
}
if (symbol is IPropertySymbol propertySymbol)
{
AnalyzeParameters(symbolAnalysisContext, propertySymbol.Parameters);
}
if (!ContainsUnderScore(symbol.Name) || IsInvalidSymbol(symbol))
{
return;
}
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
return;
}
}
},
SymbolKind.Namespace, // Namespace
SymbolKind.NamedType, //Type
SymbolKind.Method, SymbolKind.Property, SymbolKind.Field, SymbolKind.Event // Members
);
analysisContext.RegisterCompilationAction(compilationAnalysisContext =>
{
var compilation = compilationAnalysisContext.Compilation;
if (ContainsUnderScore(compilation.AssemblyName))
{
compilationAnalysisContext.ReportDiagnostic(compilation.Assembly.CreateDiagnostic(AssemblyRule, compilation.AssemblyName));
}
});
}
private static bool IsInvalidSymbol(ISymbol symbol)
{
return (!(symbol.GetResultantVisibility() == SymbolVisibility.Public && !symbol.IsOverride)) ||
symbol.IsAccessorMethod() || symbol.IsImplementationOfAnyInterfaceMember();
}
private static void AnalyzeParameters(SymbolAnalysisContext symbolAnalysisContext, IEnumerable<IParameterSymbol> parameters)
{
foreach (var parameter in parameters)
{
if (ContainsUnderScore(parameter.Name))
{
var containingType = parameter.ContainingType;
// Parameter in Delegate
if (containingType.TypeKind == TypeKind.Delegate)
{
if (containingType.IsPublic())
{
symbolAnalysisContext.ReportDiagnostic(parameter.CreateDiagnostic(DelegateParameterRule, containingType.ToDisplayString(), parameter.Name));
}
}
else if (!IsInvalidSymbol(parameter.ContainingSymbol))
{
symbolAnalysisContext.ReportDiagnostic(parameter.CreateDiagnostic(MemberParameterRule, parameter.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), parameter.Name));
}
}
}
}
private static void AnalyzeTypeParameters(SymbolAnalysisContext symbolAnalysisContext, IEnumerable<ITypeParameterSymbol> typeParameters)
{
foreach (var typeParameter in typeParameters)
{
if (ContainsUnderScore(typeParameter.Name))
{
var containingSymbol = typeParameter.ContainingSymbol;
if (containingSymbol.Kind == SymbolKind.NamedType)
{
if (containingSymbol.IsPublic())
{
symbolAnalysisContext.ReportDiagnostic(typeParameter.CreateDiagnostic(TypeTypeParameterRule, containingSymbol.ToDisplayString(), typeParameter.Name));
}
}
else if (containingSymbol.Kind == SymbolKind.Method && !IsInvalidSymbol(containingSymbol))
{
symbolAnalysisContext.ReportDiagnostic(typeParameter.CreateDiagnostic(MethodTypeParameterRule, containingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), typeParameter.Name));
}
}
}
}
private static bool ContainsUnderScore(string identifier)
{
return identifier.IndexOf('_') != -1;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace DotVVM.Framework.Routing
{
/// <summary>
/// Represents the table of routes.
/// </summary>
public sealed class DotvvmRouteTable : IEnumerable<RouteBase>
{
private readonly DotvvmConfiguration configuration;
private readonly List<KeyValuePair<string, RouteBase>> list
= new List<KeyValuePair<string, RouteBase>>();
// for faster checking of duplicates when adding entries
private readonly Dictionary<string, RouteBase> dictionary
= new Dictionary<string, RouteBase>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DotvvmRouteTable> routeTableGroups
= new Dictionary<string, DotvvmRouteTable>();
private RouteTableGroup? group = null;
/// <summary>
/// Initializes a new instance of the <see cref="DotvvmRouteTable"/> class.
/// </summary>
public DotvvmRouteTable(DotvvmConfiguration configuration)
{
this.configuration = configuration;
}
/// <summary>
/// Returns RouteTable of specific group name.
/// </summary>
/// <param name="groupName">Name of the group</param>
/// <returns></returns>
public DotvvmRouteTable GetGroup(string groupName)
{
if (groupName == null)
throw new ArgumentNullException("Name of the group cannot be null!");
var group = routeTableGroups[groupName];
return group;
}
/// <summary>
/// Adds a group of routes
/// </summary>
/// <param name="groupName">Name of the group</param>
/// <param name="urlPrefix">Url prefix of added routes</param>
/// <param name="virtualPathPrefix">Virtual path prefix of added routes</param>
/// <param name="content">Contains routes to be added</param>
/// <param name="presenterFactory">Default presenter factory common to all routes in the group</param>
public void AddGroup(string groupName,
string urlPrefix,
string virtualPathPrefix,
Action<DotvvmRouteTable> content,
Func<IServiceProvider, IDotvvmPresenter>? presenterFactory = null)
{
ThrowIfFrozen();
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentNullException("Name of the group cannot be null or empty!");
}
if (routeTableGroups.ContainsKey(groupName))
{
throw new InvalidOperationException($"The group with name '{groupName}' has already been registered!");
}
urlPrefix = CombinePath(group?.UrlPrefix, urlPrefix);
virtualPathPrefix = CombinePath(group?.VirtualPathPrefix, virtualPathPrefix);
var newGroup = new DotvvmRouteTable(configuration);
newGroup.group = new RouteTableGroup(
groupName,
routeNamePrefix: group?.RouteNamePrefix + groupName + "_",
urlPrefix,
virtualPathPrefix,
addToParentRouteTable: Add,
presenterFactory);
content(newGroup);
routeTableGroups.Add(groupName, newGroup);
}
/// <summary>
/// Creates the default presenter factory.
/// </summary>
public IDotvvmPresenter GetDefaultPresenter(IServiceProvider provider)
{
if (group != null && group.PresenterFactory != null)
{
var presenter = group.PresenterFactory(provider);
if (presenter == null)
{
throw new InvalidOperationException("The presenter factory of a route " +
"group must not return null.");
}
return presenter;
}
return provider.GetRequiredService<IDotvvmPresenter>();
}
/// <summary>
/// Adds the specified route name.
/// </summary>
/// <param name="routeName">Name of the route.</param>
/// <param name="url">The URL.</param>
/// <param name="virtualPath">The virtual path of the Dothtml file.</param>
/// <param name="defaultValues">The default values.</param>
/// <param name="presenterFactory">Delegate creating the presenter handling this route</param>
public void Add(string routeName, string? url, string virtualPath, object? defaultValues = null, Func<IServiceProvider, IDotvvmPresenter>? presenterFactory = null)
{
ThrowIfFrozen();
Add(group?.RouteNamePrefix + routeName, new DotvvmRoute(CombinePath(group?.UrlPrefix, url), CombinePath(group?.VirtualPathPrefix, virtualPath), defaultValues, presenterFactory ?? GetDefaultPresenter, configuration));
}
/// <summary>
/// Adds the specified route name.
/// </summary>
/// <param name="routeName">Name of the route.</param>
/// <param name="url">The URL.</param>
/// <param name="defaultValues">The default values.</param>
/// <param name="presenterFactory">The presenter factory.</param>
public void Add(string routeName, string? url, Func<IServiceProvider, IDotvvmPresenter>? presenterFactory = null, object? defaultValues = null)
{
ThrowIfFrozen();
Add(group?.RouteNamePrefix + routeName, new DotvvmRoute(CombinePath(group?.UrlPrefix, url), group?.VirtualPathPrefix ?? "", defaultValues, presenterFactory ?? GetDefaultPresenter, configuration));
}
/// <summary>
/// Adds the specified URL redirection entry.
/// </summary>
/// <param name="routeName">Name of the redirection.</param>
/// <param name="urlPattern">URL pattern to redirect from.</param>
/// <param name="targetUrl">URL which will be used as a target for redirection.</param>
public void AddUrlRedirection(string routeName, string urlPattern, string targetUrl, object? defaultValues = null, bool permanent = false)
=> AddUrlRedirection(routeName, urlPattern, _ => targetUrl, defaultValues, permanent);
/// <summary>
/// Adds the specified URL redirection entry.
/// </summary>
/// <param name="routeName">Name of the redirection.</param>
/// <param name="urlPattern">URL pattern to redirect from.</param>
/// <param name="targetUrlProvider">URL provider to obtain context-based redirection targets.</param>
public void AddUrlRedirection(string routeName, string urlPattern, Func<IDotvvmRequestContext, string> targetUrlProvider, object? defaultValues = null, bool permanent = false)
{
ThrowIfFrozen();
IDotvvmPresenter presenterFactory(IServiceProvider serviceProvider) => new DelegatePresenter(context =>
{
var targetUrl = targetUrlProvider(context);
if (permanent)
context.RedirectToUrlPermanent(targetUrl);
else
context.RedirectToUrl(targetUrl);
});
Add(routeName, new DotvvmRoute(urlPattern, string.Empty, defaultValues, presenterFactory, configuration));
}
/// <summary>
/// Adds the specified route redirection entry.
/// </summary>
/// <param name="routeName">Name of the redirection.</param>
/// <param name="urlPattern">URL pattern to redirect from.</param>
/// <param name="targetRouteName">Route name which will be used as a target for redirection.</param>
/// <param name="urlSuffixProvider">Provider to obtain context-based URL suffix.</param>
public void AddRouteRedirection(string routeName, string urlPattern, string targetRouteName,
object? defaultValues = null, bool permanent = false, Func<IDotvvmRequestContext, Dictionary<string, object?>>? parametersProvider = null,
Func<IDotvvmRequestContext, string>? urlSuffixProvider = null)
=> AddRouteRedirection(routeName, urlPattern, _ => targetRouteName, defaultValues, permanent, parametersProvider, urlSuffixProvider);
/// <summary>
/// Adds the specified route redirection entry.
/// </summary>
/// <param name="routeName">Name of the redirection.</param>
/// <param name="urlPattern">URL pattern to redirect from.</param>
/// <param name="targetRouteNameProvider">Route name provider to obtain context-based redirection targets.</param>
/// <param name="urlSuffixProvider">Provider to obtain context-based URL suffix.</param>
public void AddRouteRedirection(string routeName, string urlPattern, Func<IDotvvmRequestContext, string> targetRouteNameProvider,
object? defaultValues = null, bool permanent = false, Func<IDotvvmRequestContext, Dictionary<string, object?>>? parametersProvider = null,
Func<IDotvvmRequestContext, string>? urlSuffixProvider = null)
{
ThrowIfFrozen();
IDotvvmPresenter presenterFactory(IServiceProvider serviceProvider) => new DelegatePresenter(context =>
{
var targetRouteName = targetRouteNameProvider(context);
var newParameterValues = parametersProvider?.Invoke(context);
var urlSuffix = urlSuffixProvider != null ? urlSuffixProvider(context) : context.HttpContext.Request.Url.Query;
if (permanent)
context.RedirectToRoutePermanent(targetRouteName, newParameterValues, urlSuffix: urlSuffix);
else
context.RedirectToRoute(targetRouteName, newParameterValues, urlSuffix: urlSuffix);
});
Add(routeName, new DotvvmRoute(urlPattern, string.Empty, defaultValues, presenterFactory, configuration));
}
/// <summary>
/// Adds the specified route name.
/// </summary>
/// <param name="routeName">Name of the route.</param>
/// <param name="url">The URL.</param>
/// <param name="presenterType">The presenter factory.</param>
/// <param name="defaultValues">The default values.</param>
public void Add(string routeName, string? url, Type presenterType, object? defaultValues = null)
{
ThrowIfFrozen();
if (!typeof(IDotvvmPresenter).IsAssignableFrom(presenterType))
{
throw new ArgumentException($@"{nameof(presenterType)} has to inherit from DotVVM.Framework.Hosting.IDotvvmPresenter.", nameof(presenterType));
}
Func<IServiceProvider, IDotvvmPresenter> presenterFactory = provider => (IDotvvmPresenter)provider.GetRequiredService(presenterType);
Add(routeName, url, presenterFactory, defaultValues);
}
/// <summary>
/// Adds the specified name.
/// </summary>
public void Add(string routeName, RouteBase route)
{
ThrowIfFrozen();
if (dictionary.ContainsKey(routeName))
{
throw new InvalidOperationException($"The route with name '{routeName}' has already been registered!");
}
// internal assign routename
route.RouteName = routeName;
group?.AddToParentRouteTable?.Invoke(routeName, route);
// The list is used for finding the routes because it keeps the ordering, the dictionary is for checking duplicates
list.Add(new KeyValuePair<string, RouteBase>(routeName, route));
dictionary.Add(routeName, route);
}
public bool Contains(string routeName)
{
return dictionary.ContainsKey(routeName);
}
public RouteBase this[string routeName]
{
get
{
if (!dictionary.TryGetValue(routeName, out var route))
{
throw new ArgumentException($"The route with name '{routeName}' does not exist!");
}
return route;
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
public IEnumerator<RouteBase> GetEnumerator()
{
return list.Select(l => l.Value).GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private string CombinePath(string? prefix, string? appendedPath)
{
if (string.IsNullOrEmpty(prefix))
{
return appendedPath ?? "";
}
if (string.IsNullOrEmpty(appendedPath))
{
return prefix!;
}
return $"{prefix}/{appendedPath}";
}
private bool isFrozen = false;
private void ThrowIfFrozen()
{
if (isFrozen)
throw FreezableUtils.Error(nameof(DotvvmRouteTable));
}
public void Freeze()
{
this.isFrozen = true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Linq.Expressions.Tests;
using Microsoft.CSharp.RuntimeBinder;
using Xunit;
namespace System.Dynamic.Tests
{
public class BinaryOperationTests
{
private class MinimumOverrideBinaryOperationBinder : BinaryOperationBinder
{
public MinimumOverrideBinaryOperationBinder(ExpressionType operation) : base(operation)
{
}
public override DynamicMetaObject FallbackBinaryOperation(
DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion)
{
throw new NotSupportedException();
}
}
private static readonly int[] SomeInt32 = {0, 1, 2, -1, int.MinValue, int.MaxValue, int.MaxValue - 1};
public static IEnumerable<object[]> CrossJoinInt32()
=> from i in SomeInt32 from j in SomeInt32 select new object[] {i, j};
private static readonly double[] SomeDouble = {0.0, 1.0, 2.0, -1.0, double.PositiveInfinity, double.NaN};
public static IEnumerable<object[]> CrossJoinDouble()
=> from i in SomeDouble from j in SomeDouble select new object[] {i, j};
public static IEnumerable<object[]> BinaryExpressionTypes()
{
yield return new object[] {ExpressionType.Add};
yield return new object[] {ExpressionType.And};
yield return new object[] {ExpressionType.Divide};
yield return new object[] {ExpressionType.Equal};
yield return new object[] {ExpressionType.ExclusiveOr};
yield return new object[] {ExpressionType.GreaterThan};
yield return new object[] {ExpressionType.GreaterThanOrEqual};
yield return new object[] {ExpressionType.LeftShift};
yield return new object[] {ExpressionType.LessThan};
yield return new object[] {ExpressionType.LessThanOrEqual};
yield return new object[] {ExpressionType.Modulo};
yield return new object[] {ExpressionType.Multiply};
yield return new object[] {ExpressionType.NotEqual};
yield return new object[] {ExpressionType.Or};
yield return new object[] {ExpressionType.Power};
yield return new object[] {ExpressionType.RightShift};
yield return new object[] {ExpressionType.Subtract};
yield return new object[] {ExpressionType.Extension};
yield return new object[] {ExpressionType.AddAssign};
yield return new object[] {ExpressionType.AndAssign};
yield return new object[] {ExpressionType.DivideAssign};
yield return new object[] {ExpressionType.ExclusiveOrAssign};
yield return new object[] {ExpressionType.LeftShiftAssign};
yield return new object[] {ExpressionType.ModuloAssign};
yield return new object[] {ExpressionType.MultiplyAssign};
yield return new object[] {ExpressionType.OrAssign};
yield return new object[] {ExpressionType.PowerAssign};
yield return new object[] {ExpressionType.RightShiftAssign};
yield return new object[] {ExpressionType.SubtractAssign};
}
public static IEnumerable<object[]> NonBinaryExpressionTypes()
{
yield return new object[] {ExpressionType.AddChecked};
yield return new object[] {ExpressionType.AndAlso};
yield return new object[] {ExpressionType.ArrayLength};
yield return new object[] {ExpressionType.ArrayIndex};
yield return new object[] {ExpressionType.Call};
yield return new object[] {ExpressionType.Coalesce};
yield return new object[] {ExpressionType.Conditional};
yield return new object[] {ExpressionType.Constant};
yield return new object[] {ExpressionType.Convert};
yield return new object[] {ExpressionType.ConvertChecked};
yield return new object[] {ExpressionType.Invoke};
yield return new object[] {ExpressionType.Lambda};
yield return new object[] {ExpressionType.ListInit};
yield return new object[] {ExpressionType.MemberAccess};
yield return new object[] {ExpressionType.MemberInit};
yield return new object[] {ExpressionType.MultiplyChecked};
yield return new object[] {ExpressionType.Negate};
yield return new object[] {ExpressionType.UnaryPlus};
yield return new object[] {ExpressionType.NegateChecked};
yield return new object[] {ExpressionType.New};
yield return new object[] {ExpressionType.NewArrayInit};
yield return new object[] {ExpressionType.NewArrayBounds};
yield return new object[] {ExpressionType.Not};
yield return new object[] {ExpressionType.OrElse};
yield return new object[] {ExpressionType.Parameter};
yield return new object[] {ExpressionType.Quote};
yield return new object[] {ExpressionType.SubtractChecked};
yield return new object[] {ExpressionType.TypeAs};
yield return new object[] {ExpressionType.TypeIs};
yield return new object[] {ExpressionType.Assign};
yield return new object[] {ExpressionType.Block};
yield return new object[] {ExpressionType.DebugInfo};
yield return new object[] {ExpressionType.Decrement};
yield return new object[] {ExpressionType.Dynamic};
yield return new object[] {ExpressionType.Default};
yield return new object[] {ExpressionType.Goto};
yield return new object[] {ExpressionType.Increment};
yield return new object[] {ExpressionType.Index};
yield return new object[] {ExpressionType.Label};
yield return new object[] {ExpressionType.RuntimeVariables};
yield return new object[] {ExpressionType.Loop};
yield return new object[] {ExpressionType.Switch};
yield return new object[] {ExpressionType.Throw};
yield return new object[] {ExpressionType.Try};
yield return new object[] {ExpressionType.Unbox};
yield return new object[] {ExpressionType.AddAssignChecked};
yield return new object[] {ExpressionType.MultiplyAssignChecked};
yield return new object[] {ExpressionType.SubtractAssignChecked};
yield return new object[] {ExpressionType.PreIncrementAssign};
yield return new object[] {ExpressionType.PreDecrementAssign};
yield return new object[] {ExpressionType.PostIncrementAssign};
yield return new object[] {ExpressionType.PostDecrementAssign};
yield return new object[] {ExpressionType.TypeEqual};
yield return new object[] {ExpressionType.OnesComplement};
yield return new object[] {ExpressionType.IsTrue};
yield return new object[] {ExpressionType.IsFalse};
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AddInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(unchecked(x + y), unchecked(dX + dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AddOvfInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x + y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX + dY));
return;
}
Assert.Equal(result, checked(dX + dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AndInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x & y, dX & dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void DivideInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
if (y == 0)
Assert.Throws<DivideByZeroException>(() => dX / dY);
else if (y == -1 && x == int.MinValue)
Assert.Throws<OverflowException>(() => dX / dY);
else
Assert.Equal(x / y, dX / dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void EqualInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x == y, dX == dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void ExclusiveOrInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x ^ y, dX ^ dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void GreaterThanInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x > y, dX > dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void GreaterThanOrEqualInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x >= y, dX >= dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void LeftShiftInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x << y, dX << dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void LessThanInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x < y, dX < dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void LessThanOrEqualInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x <= y, dX <= dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void ModuloInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
if (y == 0)
Assert.Throws<DivideByZeroException>(() => dX % dY);
else if (y == -1 && x == int.MinValue)
Assert.Throws<OverflowException>(() => dX % dY);
else
Assert.Equal(x % y, dX % dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void MultiplyInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(unchecked(x * y), unchecked(dX * dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void MultiplyOvfInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x * y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX * dY));
return;
}
Assert.Equal(result, dX * dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void NotEqualInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x != y, dX != dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void OrInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x | y, dX | dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void RightShiftInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x >> y, dX >> dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void SubtractInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(unchecked(x - y), unchecked(dX - dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void SubtractOvfInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x - y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX - dY));
return;
}
Assert.Equal(result, checked(dX - dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AddInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
unchecked
{
dX += dY;
Assert.Equal(x + y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AddOvfInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x + y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX += dY));
return;
}
checked
{
dX += dY;
}
Assert.Equal(result, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AndInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX &= dY;
Assert.Equal(x & y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void DivideInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
if (y == 0)
Assert.Throws<DivideByZeroException>(() => dX /= dY);
else if (y == -1 && x == int.MinValue)
Assert.Throws<OverflowException>(() => dX /= dY);
else
{
dX /= dY;
Assert.Equal(x / y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void ExclusiveOrInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX ^= dY;
Assert.Equal(x ^ y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void LeftShiftInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX <<= dY;
Assert.Equal(x << y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void ModuloInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
if (y == 0)
Assert.Throws<DivideByZeroException>(() => dX %= dY);
else if (y == -1 && x == int.MinValue)
Assert.Throws<OverflowException>(() => dX %= dY);
else
{
dX %= dY;
Assert.Equal(x % y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void MultiplyInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
unchecked
{
dX *= dY;
Assert.Equal(x * y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void MultiplyOvfInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x * y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX *= dY));
return;
}
dX *= dY;
Assert.Equal(result, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void OrInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX |= dY;
Assert.Equal(x | y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void RightShiftInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX >>= dY;
Assert.Equal(x >> y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void SubtractInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
unchecked
{
dX -= dY;
Assert.Equal(x - y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void SubtractOvfInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x - y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX -= dY));
return;
}
checked
{
dX -= dY;
}
Assert.Equal(result, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void AddDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x + y, dX + dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void DivideDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x / y, dX / dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void EqualDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x == y, dX == dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void GreaterThanDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x > y, dX > dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void GreaterThanOrEqualDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x >= y, dX >= dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void LessThanDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x < y, dX < dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void LessThanOrEqualDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x <= y, dX <= dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void ModuloDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x % y, dX % dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void MultiplyDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x * y, dX * dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void NotEqualDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x != y, dX != dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void SubtractDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x - y, dX - dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void AddDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX += dY;
Assert.Equal(x + y, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void DivideDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX /= dY;
Assert.Equal(x / y, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void ModuloDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX %= dY;
Assert.Equal(x % y, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void MultiplyDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX *= dY;
Assert.Equal(x * y, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void SubtractDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX -= dY;
Assert.Equal(x - y, dX);
}
[Theory, MemberData(nameof(NonBinaryExpressionTypes))]
public void NonBinaryOperations(ExpressionType type)
{
AssertExtensions.Throws<ArgumentException>("operation", () => new MinimumOverrideBinaryOperationBinder(type));
}
[Theory, MemberData(nameof(BinaryExpressionTypes))]
public void ReturnType(ExpressionType type)
{
Assert.Equal(typeof(object), new MinimumOverrideBinaryOperationBinder(type).ReturnType);
}
[Theory, MemberData(nameof(BinaryExpressionTypes))]
public void ExpressionTypeMatches(ExpressionType type)
{
Assert.Equal(type, new MinimumOverrideBinaryOperationBinder(type).Operation);
}
[Fact]
public void NullTarget()
{
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
var arg = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
AssertExtensions.Throws<ArgumentNullException>("target", () => binder.Bind(null, new[] {arg}));
}
[Fact]
public void NullArgumentArrayPassed()
{
var target = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
AssertExtensions.Throws<ArgumentNullException>("args", () => binder.Bind(target, null));
}
[Fact]
public void NoArgumentsPassed()
{
var target = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
AssertExtensions.Throws<ArgumentException>("args", () => binder.Bind(target, Array.Empty<DynamicMetaObject>()));
}
[Fact]
public void TooManyArgumentArrayPassed()
{
var target = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
var arg0 = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var arg1 = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
AssertExtensions.Throws<ArgumentException>("args", () => binder.Bind(target, new[] {arg0, arg1}));
}
[Fact]
public void SingleNullArgumentPassed()
{
var target = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
AssertExtensions.Throws<ArgumentNullException>("args", () => binder.Bind(target, new DynamicMetaObject[1]));
}
[Fact]
public void InvalidOperationForType()
{
dynamic dX = "23";
dynamic dY = "49";
Assert.Throws<RuntimeBinderException>(() => dX * dY);
dX = 23;
dY = 49;
Assert.Throws<RuntimeBinderException>(() => dX && dY);
}
[Fact]
public void LiteralDoubleNaN()
{
dynamic d = double.NaN;
Assert.False(d == double.NaN);
Assert.True(d != double.NaN);
d = 3.0;
Assert.True(double.IsNaN(d + double.NaN));
}
[Fact]
public void LiteralSingleNaN()
{
dynamic d = float.NaN;
Assert.False(d == float.NaN);
Assert.True(d != float.NaN);
d = 3.0F;
Assert.True(float.IsNaN(d + float.NaN));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void BinaryCallSiteBinder_DynamicExpression(bool useInterpreter)
{
DynamicExpression expression = DynamicExpression.Dynamic(
new BinaryCallSiteBinder(),
typeof(object),
Expression.Constant(40, typeof(object)),
Expression.Constant(2, typeof(object)));
Func<object> func = Expression.Lambda<Func<object>>(expression).Compile(useInterpreter);
Assert.Equal("42", func().ToString());
}
private class BinaryCallSiteBinder : BinaryOperationBinder
{
public BinaryCallSiteBinder() : base(ExpressionType.Add) {}
public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion)
{
return new DynamicMetaObject(
Expression.Convert(
Expression.Add(
Expression.Convert(target.Expression, typeof(int)),
Expression.Convert(arg.Expression, typeof(int))
), typeof(object)),
BindingRestrictions.GetTypeRestriction(target.Expression, typeof(int)).Merge(
BindingRestrictions.GetTypeRestriction(arg.Expression, typeof(int))
));
}
}
}
}
| |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using XenAdmin.Actions;
using XenAdmin.Network;
namespace XenAdmin.Dialogs
{
public partial class DialogWithProgress : XenDialogBase
{
private int dx = 0;
private bool shrunk = false;
List<Control> ProgressControls; //List of controls not to undock
Dictionary<Control, AnchorStyles> PreviousAnchors; //State of previous anchors (for resizing window)
/// <summary>
/// All dialog that extend this one MUST be set to the same size as this, otherwise layout will break.
/// If you want I different size, I suggest you do it in you derived forms on_load.
/// </summary>
/// <param name="connection"></param>
public DialogWithProgress(IXenConnection connection)
: base(connection)
{
InitializeComponent();
RegisterProgressControls();
}
public DialogWithProgress()
: base()
{
InitializeComponent();
RegisterProgressControls();
SucceededWithWarningDescription = String.Empty;
SucceededWithWarning = false;
}
private void RegisterProgressControls()
{
ProgressControls = new List<Control>();
ProgressControls.Add(this.ActionProgressBar);
ProgressControls.Add(this.ActionStatusLabel);
ProgressControls.Add(this.ProgressSeparator);
dx = ClientSize.Height - ProgressSeparator.Top;
}
private void Unanchor()
{
PreviousAnchors = new Dictionary<Control, AnchorStyles>();
foreach (Control control in Controls)
{
if (ProgressControls.Contains(control))
continue;
PreviousAnchors.Add(control, control.Anchor);
control.Anchor = AnchorStyles.Top | AnchorStyles.Left;
}
}
private void Reanchor()
{
foreach (Control control in Controls)
{
if (ProgressControls.Contains(control))
continue;
control.Anchor = PreviousAnchors[control];
}
}
protected void Shrink()
{
Program.AssertOnEventThread();
if (!shrunk)
{
shrunk = true;
//First, clear all the anchors.
Unanchor();
//Next, hide the progress bar and label
ClearAction();
ActionStatusLabel.Hide();
ActionProgressBar.Hide();
ProgressSeparator.Hide();
//Finnally, shrink the window and put the anchors back
MinimumSize = new Size(MinimumSize.Width, MinimumSize.Height - dx);
ClientSize = new Size(ClientSize.Width, ClientSize.Height - dx);
Reanchor();
}
}
protected void Grow(MethodInvoker afterwards)
{
Program.AssertOnEventThread();
if (shrunk)
{
shrunk = false;
//First, clear all the anchors.
Unanchor();
//Next, grow the window
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs e)
{
int expectedHeight = ClientSize.Height + dx;
while (ClientSize.Height < expectedHeight)
{
Program.Invoke(this, delegate()
{
ClientSize = new Size(ClientSize.Width, (int) (((2.0 * ClientSize.Height) / 3.0) + (expectedHeight / 3.0) + 1.0));
});
Thread.Sleep(50);
}
});
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object o, RunWorkerCompletedEventArgs e)
{
Program.Invoke(this, delegate()
{
MinimumSize = new Size(MinimumSize.Width, MinimumSize.Height + dx);
//and put the anchors back
Reanchor();
//Finnally, show the progress bar and label
ClearAction();
ActionStatusLabel.Show();
ActionProgressBar.Show();
ProgressSeparator.Show();
afterwards();
});
});
worker.RunWorkerAsync();
}
else
{
afterwards();
}
}
protected void FinalizeProgressControls(ActionBase action)
{
if (action == null)
return;
Program.AssertOnEventThread();
if (action.Succeeded)
{
if (SucceededWithWarning && !String.IsNullOrEmpty(SucceededWithWarningDescription))
SetActionLabelText(String.Format(Messages.X_WITH_WARNING_X, action.Description, SucceededWithWarningDescription), Color.OrangeRed);
else
SetActionLabelText(action.Description, Color.Green);
}
else
{
string text = action.Exception is CancelledException ? Messages.CANCELLED_BY_USER : action.Exception.Message;
SetActionLabelText(text, Color.Red);
}
}
protected bool SucceededWithWarning { private get; set; }
protected string SucceededWithWarningDescription { private get; set; }
private void SetActionLabelText(string text, Color color)
{
ExceptionToolTip.RemoveAll();
if (string.IsNullOrEmpty(text))
{
ActionStatusLabel.Text = "";
return;
}
// take first line, adding elipses if needed to show that text has been cut
string[] parts = text.Replace("\r", "").Split('\n');
string clippedText = parts[0];
if (parts.Length > 1)
clippedText = clippedText.AddEllipsis();
ActionStatusLabel.ForeColor = color;
ActionStatusLabel.Text = clippedText;
// use original text for tooltip
ExceptionToolTip.SetToolTip(ActionStatusLabel, text);
}
protected void UpdateProgressControls(ActionBase action)
{
if (action == null)
return;
Program.AssertOnEventThread();
SetActionLabelText(action.Description, SystemColors.ControlText);
ActionProgressBar.Value = action.PercentComplete;
}
private void ClearAction()
{
SetActionLabelText("", SystemColors.ControlText);
this.ActionProgressBar.Value = 0;
}
}
}
| |
// 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.ComponentModel.Design;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Versions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Setup
{
[Guid(Guids.RoslynPackageIdString)]
[PackageRegistration(UseManagedResourcesOnly = true)]
[ProvideMenuResource("Menus.ctmenu", version: 10)]
internal class RoslynPackage : Package
{
private LibraryManager _libraryManager;
private uint _libraryManagerCookie;
private VisualStudioWorkspace _workspace;
private WorkspaceFailureOutputPane _outputPane;
private IComponentModel _componentModel;
private RuleSetEventHandler _ruleSetEventHandler;
private IDisposable _solutionEventMonitor;
protected override void Initialize()
{
base.Initialize();
ForegroundThreadAffinitizedObject.Initialize();
FatalError.Handler = FailFast.OnFatalException;
FatalError.NonFatalHandler = WatsonReporter.Report;
// We also must set the FailFast handler for the compiler layer as well
var compilerAssembly = typeof(Compilation).Assembly;
var compilerFatalError = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true);
var property = compilerFatalError.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public);
var compilerFailFast = compilerAssembly.GetType(typeof(FailFast).FullName, throwOnError: true);
var method = compilerFailFast.GetMethod(nameof(FailFast.OnFatalException), BindingFlags.Static | BindingFlags.NonPublic);
property.SetValue(null, Delegate.CreateDelegate(property.PropertyType, method));
InitializePortableShim(compilerAssembly);
RegisterFindResultsLibraryManager();
var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel));
_workspace = componentModel.GetService<VisualStudioWorkspace>();
var telemetrySetupExtensions = componentModel.GetExtensions<IRoslynTelemetrySetup>();
foreach (var telemetrySetup in telemetrySetupExtensions)
{
telemetrySetup.Initialize(this);
}
// set workspace output pane
_outputPane = new WorkspaceFailureOutputPane(this, _workspace);
InitializeColors();
// load some services that have to be loaded in UI thread
LoadComponentsInUIContext();
_solutionEventMonitor = new SolutionEventMonitor(_workspace);
}
private static void InitializePortableShim(Assembly compilerAssembly)
{
// We eagerly force all of the types to be loaded within the PortableShim because there are scenarios
// in which loading types can trigger the current AppDomain's AssemblyResolve or TypeResolve events.
// If handlers of those events do anything that would cause PortableShim to be accessed recursively,
// bad things can happen. In particular, this fixes the scenario described in TFS bug #1185842.
//
// Note that the fix below is written to be as defensive as possible to do no harm if it impacts other
// scenarios.
// Initialize the PortableShim linked into the Workspaces layer.
Roslyn.Utilities.PortableShim.Initialize();
// Initialize the PortableShim linekd into the Compilers layer via reflection.
var compilerPortableShim = compilerAssembly.GetType("Roslyn.Utilities.PortableShim", throwOnError: false);
var initializeMethod = compilerPortableShim?.GetMethod(nameof(Roslyn.Utilities.PortableShim.Initialize), BindingFlags.Static | BindingFlags.NonPublic);
initializeMethod?.Invoke(null, null);
}
private void InitializeColors()
{
// Use VS color keys in order to support theming.
CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey;
CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.RenameErrorTextBrushKey = VSCodeAnalysisColors.RenameErrorTextBrushKey;
CodeAnalysisColors.RenameResolvableConflictTextBrushKey = VSCodeAnalysisColors.RenameResolvableConflictTextBrushKey;
CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey;
CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey;
CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey;
}
private void LoadComponentsInUIContext()
{
if (KnownUIContexts.SolutionExistsAndFullyLoadedContext.IsActive)
{
// if we are already in the right UI context, load it right away
LoadComponents();
}
else
{
// load them when it is a right context.
KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged += OnSolutionExistsAndFullyLoadedContext;
}
}
private void OnSolutionExistsAndFullyLoadedContext(object sender, UIContextChangedEventArgs e)
{
if (e.Activated)
{
// unsubscribe from it
KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged -= OnSolutionExistsAndFullyLoadedContext;
// load components
LoadComponents();
}
}
private void LoadComponents()
{
// we need to load it as early as possible since we can have errors from
// package from each language very early
this.ComponentModel.GetService<VisualStudioDiagnosticListTable>();
this.ComponentModel.GetService<VisualStudioTodoListTable>();
this.ComponentModel.GetService<VisualStudioTodoTaskList>();
this.ComponentModel.GetService<HACK_ThemeColorFixer>();
this.ComponentModel.GetExtensions<IReferencedSymbolsPresenter>();
this.ComponentModel.GetExtensions<INavigableItemsPresenter>();
this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>();
this.ComponentModel.GetService<VirtualMemoryNotificationListener>();
LoadAnalyzerNodeComponents();
Task.Run(() => LoadComponentsBackground());
}
private void LoadComponentsBackground()
{
// Perf: Initialize the command handlers.
var commandHandlerServiceFactory = this.ComponentModel.GetService<ICommandHandlerServiceFactory>();
commandHandlerServiceFactory.Initialize(ContentTypeNames.RoslynContentType);
this.ComponentModel.GetService<MiscellaneousTodoListTable>();
this.ComponentModel.GetService<MiscellaneousDiagnosticListTable>();
}
internal IComponentModel ComponentModel
{
get
{
if (_componentModel == null)
{
_componentModel = (IComponentModel)GetService(typeof(SComponentModel));
}
return _componentModel;
}
}
protected override void Dispose(bool disposing)
{
UnregisterFindResultsLibraryManager();
DisposeVisualStudioDocumentTrackingService();
UnregisterAnalyzerTracker();
UnregisterRuleSetEventHandler();
ReportSessionWideTelemetry();
if (_solutionEventMonitor != null)
{
_solutionEventMonitor.Dispose();
_solutionEventMonitor = null;
}
base.Dispose(disposing);
}
private void ReportSessionWideTelemetry()
{
PersistedVersionStampLogger.LogSummary();
}
private void RegisterFindResultsLibraryManager()
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
_libraryManager = new LibraryManager(this);
if (ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(_libraryManager, out _libraryManagerCookie)))
{
_libraryManagerCookie = 0;
}
((IServiceContainer)this).AddService(typeof(LibraryManager), _libraryManager, promote: true);
}
}
private void UnregisterFindResultsLibraryManager()
{
if (_libraryManagerCookie != 0)
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
objectManager.UnregisterLibrary(_libraryManagerCookie);
_libraryManagerCookie = 0;
}
((IServiceContainer)this).RemoveService(typeof(LibraryManager), promote: true);
_libraryManager = null;
}
}
private void DisposeVisualStudioDocumentTrackingService()
{
if (_workspace != null)
{
var documentTrackingService = _workspace.Services.GetService<IDocumentTrackingService>() as VisualStudioDocumentTrackingService;
documentTrackingService.Dispose();
}
}
private void LoadAnalyzerNodeComponents()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this);
_ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>();
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Register();
}
}
private void UnregisterAnalyzerTracker()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister();
}
private void UnregisterRuleSetEventHandler()
{
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Unregister();
_ruleSetEventHandler = null;
}
}
}
}
| |
// This file is a part of the Command Prompt Explorer Bar project.
//
// Copyright Pavel Zolnikov, 2002
//
// declarations of some COM interfaces and structues
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace BandObjectLib
{
abstract class ExplorerGUIDs
{
public static readonly Guid IID_IWebBrowserApp = new Guid("{0002DF05-0000-0000-C000-000000000046}");
public static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");
}
[Flags]
public enum BrowserNavConstants
{
navOpenInNewWindow = 0x1,
navOpenInBackgroundTab = 0x1000,
navNoHistory = 0x2,
navNoReadFromCache = 0x4,
navNoWriteToCache = 0x8,
navAllowAutosearch = 0x10,
navBrowserBar = 0x20,
navHyperlink = 0x40
}
[Flags]
public enum DBIM : uint
{
MINSIZE =0x0001,
MAXSIZE =0x0002,
INTEGRAL =0x0004,
ACTUAL =0x0008,
TITLE =0x0010,
MODEFLAGS =0x0020,
BKCOLOR =0x0040
}
[Flags]
public enum DBIMF : uint
{
NORMAL = 0x0001,
FIXED = 0x0002,
FIXEDBMP = 0x0004,
VARIABLEHEIGHT = 0x0008,
UNDELETEABLE = 0x0010,
DEBOSSED = 0x0020,
BKCOLOR = 0x0040,
USECHEVRON = 0x0080,
BREAK = 0x0100,
ADDTOFRONT = 0x0200,
TOPALIGN = 0x0400,
NOGRIPPER = 0x0800,
ALWAYSGRIPPER = 0x1000,
NOMARGINS = 0x2000
}
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]
public struct DESKBANDINFO
{
public DBIM dwMask;
public Point ptMinSize;
public Point ptMaxSize;
public Point ptIntegral;
public Point ptActual;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=255)]
public String wszTitle;
public DBIMF dwModeFlags;
public Int32 crBkgnd;
};
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352")]
public interface IObjectWithSite
{
void SetSite([In ,MarshalAs(UnmanagedType.IUnknown)] Object pUnkSite);
void GetSite(ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out Object ppvSite);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("00000114-0000-0000-C000-000000000046")]
public interface IOleWindow
{
void GetWindow(out System.IntPtr phwnd);
void ContextSensitiveHelp([In] bool fEnterMode);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("012dd920-7b26-11d0-8ca9-00a0c92dbfe8")]
public interface IDockingWindow
{
void GetWindow(out System.IntPtr phwnd);
void ContextSensitiveHelp([In] bool fEnterMode);
void ShowDW([In] bool fShow);
void CloseDW([In] UInt32 dwReserved);
void ResizeBorderDW(
IntPtr prcBorder,
[In, MarshalAs(UnmanagedType.IUnknown)] Object punkToolbarSite,
bool fReserved);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("EB0FE172-1A3A-11D0-89B3-00A0C90A90AC")]
public interface IDeskBand
{
void GetWindow(out System.IntPtr phwnd);
void ContextSensitiveHelp([In] bool fEnterMode);
void ShowDW([In] bool fShow);
void CloseDW([In] UInt32 dwReserved);
void ResizeBorderDW(
IntPtr prcBorder,
[In, MarshalAs(UnmanagedType.IUnknown)] Object punkToolbarSite,
bool fReserved);
void GetBandInfo(
UInt32 dwBandID,
UInt32 dwViewMode,
ref DESKBANDINFO pdbi);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("0000010c-0000-0000-C000-000000000046")]
public interface IPersist
{
void GetClassID(out Guid pClassID);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("00000109-0000-0000-C000-000000000046")]
public interface IPersistStream
{
void GetClassID(out Guid pClassID);
void IsDirty ();
void Load ([In, MarshalAs(UnmanagedType.Interface)] Object pStm);
void Save ([In, MarshalAs(UnmanagedType.Interface)] Object pStm,
[In] bool fClearDirty);
void GetSizeMax ([Out] out UInt64 pcbSize);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
public interface _IServiceProvider
{
void QueryService(
ref Guid guid,
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out Object Obj);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("68284faa-6a48-11d0-8c78-00c04fd918b4")]
public interface IInputObject
{
void UIActivateIO(Int32 fActivate, ref MSG msg);
[PreserveSig]
//[return:MarshalAs(UnmanagedType.Error)]
Int32 HasFocusIO();
[PreserveSig]
Int32 TranslateAcceleratorIO(ref MSG msg);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("f1db8392-7331-11d0-8c99-00a0c92dbfe8")]
public interface IInputObjectSite
{
[PreserveSig]
Int32 OnFocusChangeIS( [MarshalAs(UnmanagedType.IUnknown)] Object punkObj, Int32 fSetFocus);
}
public struct POINT
{
public Int32 x;
public Int32 y;
}
public struct MSG
{
public IntPtr hwnd;
public UInt32 message;
public UInt32 wParam;
public Int32 lParam;
public UInt32 time;
public POINT pt;
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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 SharpDX.DXGI;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A DepthStencilBuffer front end to <see cref="SharpDX.Direct3D11.Texture2D"/>.
/// </summary>
/// <remarks>
/// This class instantiates a <see cref="Texture2D"/> with the binding flags <see cref="BindFlags.DepthStencil"/>.
/// </remarks>
public class DepthStencilBuffer : Texture2DBase
{
internal readonly DXGI.Format DefaultViewFormat;
private DepthStencilView depthStencilView;
/// <summary>
/// Gets the <see cref="Graphics.DepthFormat"/> of this depth stencil buffer.
/// </summary>
public readonly DepthFormat DepthFormat;
/// <summary>
/// Gets a boolean value indicating if this buffer is supporting stencil.
/// </summary>
public readonly bool HasStencil;
/// <summary>
/// Gets a boolean value indicating if this buffer is supporting read-only view.
/// </summary>
public readonly bool HasReadOnlyView;
/// <summary>
/// Gets a a read-only <see cref="DepthStencilView"/>.
/// </summary>
/// <remarks>
/// This value can be null if not supported by hardware (minimum features level is 11.0)
/// </remarks>
public readonly DepthStencilView ReadOnlyView;
internal DepthStencilBuffer(GraphicsDevice device, Texture2DDescription description2D, DepthFormat depthFormat)
: base(device, description2D)
{
DepthFormat = depthFormat;
DefaultViewFormat = ComputeViewFormat(DepthFormat, out HasStencil);
Initialize(Resource);
HasReadOnlyView = InitializeViewsDelayed(out ReadOnlyView);
}
internal DepthStencilBuffer(GraphicsDevice device, Direct3D11.Texture2D texture, DepthFormat depthFormat)
: base(device, texture)
{
DepthFormat = depthFormat;
DefaultViewFormat = ComputeViewFormat(DepthFormat, out HasStencil);
Initialize(Resource);
HasReadOnlyView = InitializeViewsDelayed(out ReadOnlyView);
}
protected override void InitializeViews()
{
// Override this, because we need the DepthFormat setup in order to initialize this class
// This is caused by a bad design of the constructors/initialize sequence.
// TODO: Fix this problem
}
protected bool InitializeViewsDelayed(out DepthStencilView readOnlyView)
{
bool hasReadOnlyView = false;
readOnlyView = null;
// Perform default initialization
base.InitializeViews();
if ((Description.BindFlags & BindFlags.DepthStencil) == 0)
return hasReadOnlyView;
// Create a Depth stencil view on this texture2D
var depthStencilViewDescription = new SharpDX.Direct3D11.DepthStencilViewDescription
{
Format = (Format)DepthFormat,
Flags = SharpDX.Direct3D11.DepthStencilViewFlags.None,
};
if (Description.ArraySize <= 1)
{
depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2D;
depthStencilViewDescription.Texture2D = new DepthStencilViewDescription.Texture2DResource
{
MipSlice = 0
};
}
else
{
depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2DArray;
depthStencilViewDescription.Texture2DArray = new DepthStencilViewDescription.Texture2DArrayResource
{
MipSlice = 0,
FirstArraySlice = 0,
ArraySize = Description.ArraySize
};
}
if (Description.SampleDescription.Count > 1)
depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
// Create the Depth Stencil View
depthStencilView = ToDispose(new SharpDX.Direct3D11.DepthStencilView(GraphicsDevice, Resource, depthStencilViewDescription) { Tag = this });
// ReadOnly for feature level Direct3D11
if (GraphicsDevice.Features.Level >= FeatureLevel.Level_11_0)
{
// Create a Depth stencil view on this texture2D
depthStencilViewDescription.Flags = DepthStencilViewFlags.ReadOnlyDepth;
if (HasStencil)
depthStencilViewDescription.Flags |= DepthStencilViewFlags.ReadOnlyStencil;
readOnlyView = ToDispose(new SharpDX.Direct3D11.DepthStencilView(GraphicsDevice, Resource, depthStencilViewDescription) { Tag = this });
hasReadOnlyView = true;
}
return hasReadOnlyView;
}
protected override Format GetDefaultViewFormat()
{
return DefaultViewFormat;
}
/// <summary>
/// DepthStencilView casting operator.
/// </summary>
/// <param name="buffer">Source for the.</param>
public static implicit operator DepthStencilView(DepthStencilBuffer buffer)
{
return buffer == null ? null : buffer.depthStencilView;
}
internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipIndex)
{
throw new NotSupportedException();
}
public override Texture Clone()
{
return new DepthStencilBuffer(GraphicsDevice, this.Description, DepthFormat);
}
/// <summary>
/// Creates a new <see cref="DepthStencilBuffer"/> from a <see cref="Texture2DDescription"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description">The description.</param>
/// <returns>
/// A new instance of <see cref="DepthStencilBuffer"/> class.
/// </returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static DepthStencilBuffer New(GraphicsDevice device, Texture2DDescription description)
{
return new DepthStencilBuffer(device, description, ComputeViewFormat(description.Format));
}
/// <summary>
/// Creates a new <see cref="DepthStencilBuffer"/> from a <see cref="Direct3D11.Texture2D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="texture">The native texture <see cref="Direct3D11.Texture2D"/>.</param>
/// <returns>
/// A new instance of <see cref="DepthStencilBuffer"/> class.
/// </returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static DepthStencilBuffer New(GraphicsDevice device, Direct3D11.Texture2D texture)
{
return new DepthStencilBuffer(device, texture, ComputeViewFormat(texture.Description.Format));
}
/// <summary>
/// Creates a new <see cref="DepthStencilBuffer" />.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <param name="shaderResource">if set to <c>true</c> this depth stencil buffer can be set as an input to a shader (default: false).</param>
/// <returns>A new instance of <see cref="DepthStencilBuffer" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static DepthStencilBuffer New(GraphicsDevice device, int width, int height, DepthFormat format, bool shaderResource = false, int arraySize = 1)
{
return new DepthStencilBuffer(device, NewDepthStencilBufferDescription(device.MainDevice, width, height, format, MSAALevel.None, arraySize, shaderResource), format);
}
/// <summary>
/// Creates a new <see cref="DepthStencilBuffer" /> using multisampling.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice" />.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="multiSampleCount">The multisample count.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <param name="shaderResource">if set to <c>true</c> this depth stencil buffer can be set as an input to a shader (default: false).</param>
/// <returns>A new instance of <see cref="DepthStencilBuffer" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
public static DepthStencilBuffer New(GraphicsDevice device, int width, int height, MSAALevel multiSampleCount, DepthFormat format, bool shaderResource = false, int arraySize = 1)
{
return new DepthStencilBuffer(device, NewDepthStencilBufferDescription(device.MainDevice, width, height, format, multiSampleCount, arraySize, shaderResource), format);
}
protected static Texture2DDescription NewDepthStencilBufferDescription(GraphicsDevice device, int width, int height, DepthFormat format, MSAALevel multiSampleCount, int arraySize, bool shaderResource)
{
var desc = Texture2DBase.NewDescription(width, height, DXGI.Format.Unknown, TextureFlags.None, 1, arraySize, ResourceUsage.Default);
desc.BindFlags |= BindFlags.DepthStencil;
if (shaderResource)
{
desc.BindFlags |= BindFlags.ShaderResource;
}
// Sets the MSAALevel
int maximumMSAA = (int)device.Features[(DXGI.Format)format].MSAALevelMax;
desc.SampleDescription.Count = Math.Max(1, Math.Min((int)multiSampleCount, maximumMSAA));
var typelessDepthFormat = (SharpDX.DXGI.Format)format;
// If shader resource view are not required, don't use a TypeLess format
if (shaderResource)
{
// Determine TypeLess Format and ShaderResourceView Format
switch (format)
{
case DepthFormat.Depth16:
typelessDepthFormat = SharpDX.DXGI.Format.R16_Typeless;
break;
case DepthFormat.Depth32:
typelessDepthFormat = SharpDX.DXGI.Format.R32_Typeless;
break;
case DepthFormat.Depth24Stencil8:
typelessDepthFormat = SharpDX.DXGI.Format.R24G8_Typeless;
break;
case DepthFormat.Depth32Stencil8X24:
typelessDepthFormat = SharpDX.DXGI.Format.R32G8X24_Typeless;
break;
default:
throw new InvalidOperationException(string.Format("Unsupported DepthFormat [{0}] for depth buffer", format));
}
}
desc.Format = typelessDepthFormat;
return desc;
}
private static DXGI.Format ComputeViewFormat(DepthFormat format, out bool hasStencil)
{
DXGI.Format viewFormat;
hasStencil = false;
// Determine TypeLess Format and ShaderResourceView Format
switch (format)
{
case DepthFormat.Depth16:
viewFormat = SharpDX.DXGI.Format.R16_Float;
break;
case DepthFormat.Depth32:
viewFormat = SharpDX.DXGI.Format.R32_Float;
break;
case DepthFormat.Depth24Stencil8:
viewFormat = SharpDX.DXGI.Format.R24_UNorm_X8_Typeless;
hasStencil = true;
break;
case DepthFormat.Depth32Stencil8X24:
viewFormat = SharpDX.DXGI.Format.R32_Float_X8X24_Typeless;
hasStencil = true;
break;
default:
viewFormat = DXGI.Format.Unknown;
break;
}
return viewFormat;
}
private static DepthFormat ComputeViewFormat(DXGI.Format format)
{
switch (format)
{
case SharpDX.DXGI.Format.D16_UNorm:
case DXGI.Format.R16_Float:
case DXGI.Format.R16_Typeless:
return DepthFormat.Depth16;
case SharpDX.DXGI.Format.D32_Float:
case DXGI.Format.R32_Float:
case DXGI.Format.R32_Typeless:
return DepthFormat.Depth32;
case SharpDX.DXGI.Format.D24_UNorm_S8_UInt:
case SharpDX.DXGI.Format.R24_UNorm_X8_Typeless:
return DepthFormat.Depth24Stencil8;
case SharpDX.DXGI.Format.D32_Float_S8X24_UInt:
case SharpDX.DXGI.Format.R32_Float_X8X24_Typeless:
return DepthFormat.Depth32Stencil8X24;
}
throw new InvalidOperationException(string.Format("Unsupported DXGI.FORMAT [{0}] for depth buffer", format));
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Describes the storage that is available to a PVS site for caching purposes
/// First published in XenServer 7.1.
/// </summary>
public partial class PVS_cache_storage : XenObject<PVS_cache_storage>
{
#region Constructors
public PVS_cache_storage()
{
}
public PVS_cache_storage(string uuid,
XenRef<Host> host,
XenRef<SR> SR,
XenRef<PVS_site> site,
long size,
XenRef<VDI> VDI)
{
this.uuid = uuid;
this.host = host;
this.SR = SR;
this.site = site;
this.size = size;
this.VDI = VDI;
}
/// <summary>
/// Creates a new PVS_cache_storage from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public PVS_cache_storage(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new PVS_cache_storage from a Proxy_PVS_cache_storage.
/// </summary>
/// <param name="proxy"></param>
public PVS_cache_storage(Proxy_PVS_cache_storage proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given PVS_cache_storage.
/// </summary>
public override void UpdateFrom(PVS_cache_storage update)
{
uuid = update.uuid;
host = update.host;
SR = update.SR;
site = update.site;
size = update.size;
VDI = update.VDI;
}
internal void UpdateFrom(Proxy_PVS_cache_storage proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
SR = proxy.SR == null ? null : XenRef<SR>.Create(proxy.SR);
site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site);
size = proxy.size == null ? 0 : long.Parse(proxy.size);
VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI);
}
public Proxy_PVS_cache_storage ToProxy()
{
Proxy_PVS_cache_storage result_ = new Proxy_PVS_cache_storage();
result_.uuid = uuid ?? "";
result_.host = host ?? "";
result_.SR = SR ?? "";
result_.site = site ?? "";
result_.size = size.ToString();
result_.VDI = VDI ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this PVS_cache_storage
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("SR"))
SR = Marshalling.ParseRef<SR>(table, "SR");
if (table.ContainsKey("site"))
site = Marshalling.ParseRef<PVS_site>(table, "site");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("VDI"))
VDI = Marshalling.ParseRef<VDI>(table, "VDI");
}
public bool DeepEquals(PVS_cache_storage other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._SR, other._SR) &&
Helper.AreEqual2(this._site, other._site) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._VDI, other._VDI);
}
internal static List<PVS_cache_storage> ProxyArrayToObjectList(Proxy_PVS_cache_storage[] input)
{
var result = new List<PVS_cache_storage>();
foreach (var item in input)
result.Add(new PVS_cache_storage(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, PVS_cache_storage server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static PVS_cache_storage get_record(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_record(session.opaque_ref, _pvs_cache_storage);
else
return new PVS_cache_storage(session.XmlRpcProxy.pvs_cache_storage_get_record(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get a reference to the PVS_cache_storage instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PVS_cache_storage> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<PVS_cache_storage>.Create(session.XmlRpcProxy.pvs_cache_storage_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new PVS_cache_storage instance, and return its handle.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<PVS_cache_storage> create(Session session, PVS_cache_storage _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_create(session.opaque_ref, _record);
else
return XenRef<PVS_cache_storage>.Create(session.XmlRpcProxy.pvs_cache_storage_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new PVS_cache_storage instance, and return its handle.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, PVS_cache_storage _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_cache_storage_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pvs_cache_storage_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified PVS_cache_storage instance.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static void destroy(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage);
else
session.XmlRpcProxy.pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage ?? "").parse();
}
/// <summary>
/// Destroy the specified PVS_cache_storage instance.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<Task> async_destroy(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pvs_cache_storage_destroy(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static string get_uuid(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_uuid(session.opaque_ref, _pvs_cache_storage);
else
return session.XmlRpcProxy.pvs_cache_storage_get_uuid(session.opaque_ref, _pvs_cache_storage ?? "").parse();
}
/// <summary>
/// Get the host field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<Host> get_host(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_host(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<Host>.Create(session.XmlRpcProxy.pvs_cache_storage_get_host(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the SR field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<SR> get_SR(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_sr(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<SR>.Create(session.XmlRpcProxy.pvs_cache_storage_get_sr(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the site field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<PVS_site> get_site(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_site(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<PVS_site>.Create(session.XmlRpcProxy.pvs_cache_storage_get_site(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the size field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static long get_size(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_size(session.opaque_ref, _pvs_cache_storage);
else
return long.Parse(session.XmlRpcProxy.pvs_cache_storage_get_size(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Get the VDI field of the given PVS_cache_storage.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<VDI> get_VDI(Session session, string _pvs_cache_storage)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_vdi(session.opaque_ref, _pvs_cache_storage);
else
return XenRef<VDI>.Create(session.XmlRpcProxy.pvs_cache_storage_get_vdi(session.opaque_ref, _pvs_cache_storage ?? "").parse());
}
/// <summary>
/// Return a list of all the PVS_cache_storages known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PVS_cache_storage>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_all(session.opaque_ref);
else
return XenRef<PVS_cache_storage>.Create(session.XmlRpcProxy.pvs_cache_storage_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the PVS_cache_storage Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PVS_cache_storage>, PVS_cache_storage> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_cache_storage_get_all_records(session.opaque_ref);
else
return XenRef<PVS_cache_storage>.Create<Proxy_PVS_cache_storage>(session.XmlRpcProxy.pvs_cache_storage_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// The host on which this object defines PVS cache storage
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL");
/// <summary>
/// SR providing storage for the PVS cache
/// </summary>
[JsonConverter(typeof(XenRefConverter<SR>))]
public virtual XenRef<SR> SR
{
get { return _SR; }
set
{
if (!Helper.AreEqual(value, _SR))
{
_SR = value;
NotifyPropertyChanged("SR");
}
}
}
private XenRef<SR> _SR = new XenRef<SR>("OpaqueRef:NULL");
/// <summary>
/// The PVS_site for which this object defines the storage
/// </summary>
[JsonConverter(typeof(XenRefConverter<PVS_site>))]
public virtual XenRef<PVS_site> site
{
get { return _site; }
set
{
if (!Helper.AreEqual(value, _site))
{
_site = value;
NotifyPropertyChanged("site");
}
}
}
private XenRef<PVS_site> _site = new XenRef<PVS_site>("OpaqueRef:NULL");
/// <summary>
/// The size of the cache VDI (in bytes)
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
NotifyPropertyChanged("size");
}
}
}
private long _size = 21474836480;
/// <summary>
/// The VDI used for caching
/// </summary>
[JsonConverter(typeof(XenRefConverter<VDI>))]
public virtual XenRef<VDI> VDI
{
get { return _VDI; }
set
{
if (!Helper.AreEqual(value, _VDI))
{
_VDI = value;
NotifyPropertyChanged("VDI");
}
}
}
private XenRef<VDI> _VDI = new XenRef<VDI>("OpaqueRef:NULL");
}
}
| |
// 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 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Azure.Management.DataLake.Analytics;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The common Data Lake Analytics job information properties.
/// </summary>
public partial class JobInformation
{
/// <summary>
/// Initializes a new instance of the JobInformation class.
/// </summary>
public JobInformation()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the JobInformation class.
/// </summary>
/// <param name="name">the friendly name of the job.</param>
/// <param name="type">the job type of the current job (Hive or USql).
/// Possible values include: 'USql', 'Hive'</param>
/// <param name="properties">the job specific properties.</param>
/// <param name="jobId">the job's unique identifier (a GUID).</param>
/// <param name="submitter">the user or account that submitted the
/// job.</param>
/// <param name="errorMessage">the error message details for the job,
/// if the job failed.</param>
/// <param name="degreeOfParallelism">the degree of parallelism used
/// for this job. This must be greater than 0, if set to less than 0 it
/// will default to 1.</param>
/// <param name="priority">the priority value for the current job.
/// Lower numbers have a higher priority. By default, a job has a
/// priority of 1000. This must be greater than 0.</param>
/// <param name="submitTime">the time the job was submitted to the
/// service.</param>
/// <param name="startTime">the start time of the job.</param>
/// <param name="endTime">the completion time of the job.</param>
/// <param name="state">the job state. When the job is in the Ended
/// state, refer to Result and ErrorMessage for details. Possible
/// values include: 'Accepted', 'Compiling', 'Ended', 'New', 'Queued',
/// 'Running', 'Scheduling', 'Starting', 'Paused',
/// 'WaitingForCapacity'</param>
/// <param name="result">the result of job execution or the current
/// result of the running job. Possible values include: 'None',
/// 'Succeeded', 'Cancelled', 'Failed'</param>
/// <param name="logFolder">the log folder path to use in the following
/// format:
/// adl://<accountName>.azuredatalakestore.net/system/jobservice/jobs/Usql/2016/03/13/17/18/5fe51957-93bc-4de0-8ddc-c5a4753b068b/logs/.</param>
/// <param name="logFilePatterns">the list of log file name patterns to
/// find in the logFolder. '*' is the only matching character allowed.
/// Example format: jobExecution*.log or *mylog*.txt</param>
/// <param name="stateAuditRecords">the job state audit records,
/// indicating when various operations have been performed on this
/// job.</param>
public JobInformation(string name, JobType type, JobProperties properties, System.Guid? jobId = default(System.Guid?), string submitter = default(string), IList<JobErrorDetails> errorMessage = default(IList<JobErrorDetails>), int? degreeOfParallelism = default(int?), int? priority = default(int?), System.DateTimeOffset? submitTime = default(System.DateTimeOffset?), System.DateTimeOffset? startTime = default(System.DateTimeOffset?), System.DateTimeOffset? endTime = default(System.DateTimeOffset?), JobState? state = default(JobState?), JobResult? result = default(JobResult?), string logFolder = default(string), IList<string> logFilePatterns = default(IList<string>), IList<JobStateAuditRecord> stateAuditRecords = default(IList<JobStateAuditRecord>))
{
JobId = jobId;
Name = name;
Type = type;
Submitter = submitter;
ErrorMessage = errorMessage;
DegreeOfParallelism = degreeOfParallelism;
Priority = priority;
SubmitTime = submitTime;
StartTime = startTime;
EndTime = endTime;
State = state;
Result = result;
LogFolder = logFolder;
LogFilePatterns = logFilePatterns;
StateAuditRecords = stateAuditRecords;
Properties = properties;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the job's unique identifier (a GUID).
/// </summary>
[JsonProperty(PropertyName = "jobId")]
public System.Guid? JobId { get; private set; }
/// <summary>
/// Gets or sets the friendly name of the job.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the job type of the current job (Hive or USql).
/// Possible values include: 'USql', 'Hive'
/// </summary>
[JsonProperty(PropertyName = "type")]
public JobType Type { get; set; }
/// <summary>
/// Gets the user or account that submitted the job.
/// </summary>
[JsonProperty(PropertyName = "submitter")]
public string Submitter { get; private set; }
/// <summary>
/// Gets the error message details for the job, if the job failed.
/// </summary>
[JsonProperty(PropertyName = "errorMessage")]
public IList<JobErrorDetails> ErrorMessage { get; private set; }
/// <summary>
/// Gets or sets the degree of parallelism used for this job. This must
/// be greater than 0, if set to less than 0 it will default to 1.
/// </summary>
[JsonProperty(PropertyName = "degreeOfParallelism")]
public int? DegreeOfParallelism { get; set; }
/// <summary>
/// Gets or sets the priority value for the current job. Lower numbers
/// have a higher priority. By default, a job has a priority of 1000.
/// This must be greater than 0.
/// </summary>
[JsonProperty(PropertyName = "priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets the time the job was submitted to the service.
/// </summary>
[JsonProperty(PropertyName = "submitTime")]
public System.DateTimeOffset? SubmitTime { get; private set; }
/// <summary>
/// Gets the start time of the job.
/// </summary>
[JsonProperty(PropertyName = "startTime")]
public System.DateTimeOffset? StartTime { get; private set; }
/// <summary>
/// Gets the completion time of the job.
/// </summary>
[JsonProperty(PropertyName = "endTime")]
public System.DateTimeOffset? EndTime { get; private set; }
/// <summary>
/// Gets the job state. When the job is in the Ended state, refer to
/// Result and ErrorMessage for details. Possible values include:
/// 'Accepted', 'Compiling', 'Ended', 'New', 'Queued', 'Running',
/// 'Scheduling', 'Starting', 'Paused', 'WaitingForCapacity'
/// </summary>
[JsonProperty(PropertyName = "state")]
public JobState? State { get; private set; }
/// <summary>
/// Gets the result of job execution or the current result of the
/// running job. Possible values include: 'None', 'Succeeded',
/// 'Cancelled', 'Failed'
/// </summary>
[JsonProperty(PropertyName = "result")]
public JobResult? Result { get; private set; }
/// <summary>
/// Gets the log folder path to use in the following format:
/// adl://&lt;accountName&gt;.azuredatalakestore.net/system/jobservice/jobs/Usql/2016/03/13/17/18/5fe51957-93bc-4de0-8ddc-c5a4753b068b/logs/.
/// </summary>
[JsonProperty(PropertyName = "logFolder")]
public string LogFolder { get; private set; }
/// <summary>
/// Gets or sets the list of log file name patterns to find in the
/// logFolder. '*' is the only matching character allowed. Example
/// format: jobExecution*.log or *mylog*.txt
/// </summary>
[JsonProperty(PropertyName = "logFilePatterns")]
public IList<string> LogFilePatterns { get; set; }
/// <summary>
/// Gets the job state audit records, indicating when various
/// operations have been performed on this job.
/// </summary>
[JsonProperty(PropertyName = "stateAuditRecords")]
public IList<JobStateAuditRecord> StateAuditRecords { get; private set; }
/// <summary>
/// Gets or sets the job specific properties.
/// </summary>
[JsonProperty(PropertyName = "properties")]
public JobProperties Properties { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Name");
}
if (Properties == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Properties");
}
if (Properties != null)
{
Properties.Validate();
}
}
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// classes dda_line_interpolator, dda2_line_interpolator
//
//----------------------------------------------------------------------------
using System;
namespace MatterHackers.Agg
{
//===================================================dda_line_interpolator
public sealed class dda_line_interpolator
{
private int m_y;
private int m_inc;
private int m_dy;
//int m_YShift;
private int m_FractionShift;
//--------------------------------------------------------------------
public dda_line_interpolator(int FractionShift)
{
m_FractionShift = FractionShift;
}
//--------------------------------------------------------------------
public dda_line_interpolator(int y1, int y2, int count, int FractionShift)
{
m_FractionShift = FractionShift;
m_y = (y1);
m_inc = (((y2 - y1) << m_FractionShift) / (int)(count));
m_dy = (0);
}
//--------------------------------------------------------------------
//public void operator ++ ()
public void Next()
{
m_dy += m_inc;
}
//--------------------------------------------------------------------
//public void operator -- ()
public void Prev()
{
m_dy -= m_inc;
}
//--------------------------------------------------------------------
//public void operator += (int n)
public void Next(int n)
{
m_dy += m_inc * (int)n;
}
//--------------------------------------------------------------------
//public void operator -= (int n)
public void Prev(int n)
{
m_dy -= m_inc * (int)n;
}
//--------------------------------------------------------------------
public int y()
{
return m_y + (m_dy >> (m_FractionShift));
} // - m_YShift)); }
public int dy()
{
return m_dy;
}
}
//=================================================dda2_line_interpolator
public sealed class dda2_line_interpolator
{
private enum save_size_e { save_size = 2 };
//--------------------------------------------------------------------
public dda2_line_interpolator()
{
}
//-------------------------------------------- Forward-adjusted line
public dda2_line_interpolator(int y1, int y2, int count)
{
m_cnt = (count <= 0 ? 1 : count);
m_lft = ((y2 - y1) / m_cnt);
m_rem = ((y2 - y1) % m_cnt);
m_mod = (m_rem);
m_y = (y1);
if (m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
m_mod -= count;
}
//-------------------------------------------- Backward-adjusted line
public dda2_line_interpolator(int y1, int y2, int count, int unused)
{
m_cnt = (count <= 0 ? 1 : count);
m_lft = ((y2 - y1) / m_cnt);
m_rem = ((y2 - y1) % m_cnt);
m_mod = (m_rem);
m_y = (y1);
if (m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
}
//-------------------------------------------- Backward-adjusted line
public dda2_line_interpolator(int y, int count)
{
m_cnt = (count <= 0 ? 1 : count);
m_lft = ((y) / m_cnt);
m_rem = ((y) % m_cnt);
m_mod = (m_rem);
m_y = (0);
if (m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
}
/*
//--------------------------------------------------------------------
public void save(save_data_type* data)
{
data[0] = m_mod;
data[1] = m_y;
}
//--------------------------------------------------------------------
public void load(save_data_type* data)
{
m_mod = data[0];
m_y = data[1];
}
*/
//--------------------------------------------------------------------
//public void operator++()
public void Next()
{
m_mod += m_rem;
m_y += m_lft;
if (m_mod > 0)
{
m_mod -= m_cnt;
m_y++;
}
}
//--------------------------------------------------------------------
//public void operator--()
public void Prev()
{
if (m_mod <= m_rem)
{
m_mod += m_cnt;
m_y--;
}
m_mod -= m_rem;
m_y -= m_lft;
}
//--------------------------------------------------------------------
public void adjust_forward()
{
m_mod -= m_cnt;
}
//--------------------------------------------------------------------
public void adjust_backward()
{
m_mod += m_cnt;
}
//--------------------------------------------------------------------
public int mod()
{
return m_mod;
}
public int rem()
{
return m_rem;
}
public int lft()
{
return m_lft;
}
//--------------------------------------------------------------------
public int y()
{
return m_y;
}
private int m_cnt;
private int m_lft;
private int m_rem;
private int m_mod;
private int m_y;
}
//---------------------------------------------line_bresenham_interpolator
public sealed class line_bresenham_interpolator
{
private int m_x1_lr;
private int m_y1_lr;
private int m_x2_lr;
private int m_y2_lr;
private bool m_ver;
private int m_len;
private int m_inc;
private dda2_line_interpolator m_interpolator;
public enum subpixel_scale_e
{
subpixel_shift = 8,
subpixel_scale = 1 << subpixel_shift,
subpixel_mask = subpixel_scale - 1
}
//--------------------------------------------------------------------
public static int line_lr(int v)
{
return v >> (int)subpixel_scale_e.subpixel_shift;
}
//--------------------------------------------------------------------
public line_bresenham_interpolator(int x1, int y1, int x2, int y2)
{
m_x1_lr = (line_lr(x1));
m_y1_lr = (line_lr(y1));
m_x2_lr = (line_lr(x2));
m_y2_lr = (line_lr(y2));
m_ver = (Math.Abs(m_x2_lr - m_x1_lr) < Math.Abs(m_y2_lr - m_y1_lr));
if (m_ver)
{
m_len = (int)Math.Abs(m_y2_lr - m_y1_lr);
}
else
{
m_len = (int)Math.Abs(m_x2_lr - m_x1_lr);
}
m_inc = (m_ver ? ((y2 > y1) ? 1 : -1) : ((x2 > x1) ? 1 : -1));
m_interpolator = new dda2_line_interpolator(m_ver ? x1 : y1,
m_ver ? x2 : y2,
(int)m_len);
}
//--------------------------------------------------------------------
public bool is_ver()
{
return m_ver;
}
public int len()
{
return m_len;
}
public int inc()
{
return m_inc;
}
//--------------------------------------------------------------------
public void hstep()
{
m_interpolator.Next();
m_x1_lr += m_inc;
}
//--------------------------------------------------------------------
public void vstep()
{
m_interpolator.Next();
m_y1_lr += m_inc;
}
//--------------------------------------------------------------------
public int x1()
{
return m_x1_lr;
}
public int y1()
{
return m_y1_lr;
}
public int x2()
{
return line_lr(m_interpolator.y());
}
public int y2()
{
return line_lr(m_interpolator.y());
}
public int x2_hr()
{
return m_interpolator.y();
}
public int y2_hr()
{
return m_interpolator.y();
}
}
}
| |
/*===-----------------------------* C# *---------------------------------===//
//
// THIS FILE IS GENERATED BY INVAR. DO NOT EDIT !!!
//
//===----------------------------------------------------------------------===*/
namespace Test.Xyz {
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
using Test.Abc;
/// .
public sealed class ConfigRoot
: Invar.BinaryDecode
, Invar.BinaryEncode
, Invar.JSONEncode
, Invar.XMLEncode
{
public const uint CRC32 = 0x6D03BB9B;
private String revision = "1.0.0";
private TestList list = new TestList();
private TestDict dict = new TestDict();
private TestNest nest = new TestNest();
private Info info = new Info();
private InfoX infox = new InfoX();
private Dictionary<String,String> hotfix = null; // [AutoAdd] Hotfix.
/// .
[Invar.InvarRule("string", "f0")]
public String GetRevision() { return this.revision; }
/// .
[Invar.InvarRule("Test.Xyz.TestList", "f1")]
public TestList GetList() { return this.list; }
/// .
[Invar.InvarRule("Test.Xyz.TestDict", "f2")]
public TestDict GetDict() { return this.dict; }
/// .
[Invar.InvarRule("Test.Xyz.TestNest", "f3")]
public TestNest GetNest() { return this.nest; }
/// .
[Invar.InvarRule("Test.Abc.Info", "f4")]
public Info GetInfo() { return this.info; }
/// .
[Invar.InvarRule("Test.Xyz.InfoX", "f5")]
public InfoX GetInfox() { return this.infox; }
/// [AutoAdd] Hotfix.
[Invar.InvarRule("map<string,string>", "f6")]
public Dictionary<String,String> GetHotfix() { return this.hotfix; }
/// .
[Invar.InvarRule("string", "f0")]
public ConfigRoot SetRevision(String value) { this.revision = value; return this; }
/// .
[Invar.InvarRule("Test.Xyz.TestList", "f1")]
public ConfigRoot SetList(TestList value) { this.list = value; return this; }
/// .
[Invar.InvarRule("Test.Xyz.TestDict", "f2")]
public ConfigRoot SetDict(TestDict value) { this.dict = value; return this; }
/// .
[Invar.InvarRule("Test.Xyz.TestNest", "f3")]
public ConfigRoot SetNest(TestNest value) { this.nest = value; return this; }
/// .
[Invar.InvarRule("Test.Abc.Info", "f4")]
public ConfigRoot SetInfo(Info value) { this.info = value; return this; }
/// .
[Invar.InvarRule("Test.Xyz.InfoX", "f5")]
public ConfigRoot SetInfox(InfoX value) { this.infox = value; return this; }
/// [AutoAdd] Hotfix.
[Invar.InvarRule("map<string,string>", "f6")]
public ConfigRoot SetHotfix(Dictionary<String,String> value) { this.hotfix = value; return this; }
public ConfigRoot Reuse()
{
this.revision = "1.0.0";
this.list.Reuse();
this.dict.Reuse();
this.nest.Reuse();
this.info.Reuse();
this.infox.Reuse();
if (this.hotfix != null) { this.hotfix.Clear(); }
return this;
} //ConfigRoot::Reuse()
public ConfigRoot Copy(ConfigRoot from_)
{
if (null == from_ || this == from_) {
return this;
}
this.revision = from_.revision;
this.list.Copy(from_.list);
this.dict.Copy(from_.dict);
this.nest.Copy(from_.nest);
this.info.Copy(from_.info);
this.infox.Copy(from_.infox);
if (null == from_.hotfix) {
this.hotfix = null;
} else {
if (null == this.hotfix) { this.hotfix = new Dictionary<String,String>(); }
else { this.hotfix.Clear(); }
foreach (var hotfixIter in from_.hotfix) {
this.hotfix.Add(hotfixIter.Key, hotfixIter.Value);
}
}
return this;
} //ConfigRoot::Copy(...)
public void Read(BinaryReader r)
{
this.revision = Encoding.UTF8.GetString(r.ReadBytes(r.ReadInt32()));
this.list.Read(r);
this.dict.Read(r);
this.nest.Read(r);
this.info.Read(r);
this.infox.Read(r);
sbyte hotfixExists = r.ReadSByte();
if ((sbyte)0x01 == hotfixExists) {
if (this.hotfix == null) { this.hotfix = new Dictionary<String,String>(); }
UInt32 lenHotfix = r.ReadUInt32();
for (UInt32 iHotfix = 0; iHotfix < lenHotfix; iHotfix++) {
String k1 = Encoding.UTF8.GetString(r.ReadBytes(r.ReadInt32()));
String v1 = Encoding.UTF8.GetString(r.ReadBytes(r.ReadInt32()));
if (!this.hotfix.ContainsKey(k1)) {
this.hotfix.Add(k1, v1);
} else {
this.hotfix[k1] = v1;
}
}
}
else if ((sbyte)0x00 == hotfixExists) { this.hotfix = null; }
else { throw new IOException("Protoc read error: The value of 'hotfixExists' is invalid.", 498); }
} //ConfigRoot::Read(...)
public void Write(BinaryWriter w)
{
byte[] revisionBytes = Encoding.UTF8.GetBytes(this.revision);
w.Write(revisionBytes.Length);
w.Write(revisionBytes);
this.list.Write(w);
this.dict.Write(w);
this.nest.Write(w);
this.info.Write(w);
this.infox.Write(w);
if (this.hotfix != null) {
w.Write((sbyte)0x01);
w.Write(this.hotfix.Count);
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) {
String k1 = hotfixIter.Key;
byte[] k1Bytes = Encoding.UTF8.GetBytes(k1);
w.Write(k1Bytes.Length);
w.Write(k1Bytes);
String v1 = hotfixIter.Value;
byte[] v1Bytes = Encoding.UTF8.GetBytes(v1);
w.Write(v1Bytes.Length);
w.Write(v1Bytes);
}
} else {
w.Write((sbyte)0x00);
}
} //ConfigRoot::Write(...)
public override String ToString()
{
StringBuilder result = new StringBuilder();
result.Append('{').Append(' ');
result.Append(GetType().ToString());
result.Append(',').Append(' ').Append("revision").Append(':');
result.Append("\"" + this.revision + "\"");
result.Append(',').Append(' ').Append("list").Append(':');
result.Append("<TestList>");
result.Append(',').Append(' ').Append("dict").Append(':');
result.Append("<TestDict>");
result.Append(',').Append(' ').Append("nest").Append(':');
result.Append("<TestNest>");
result.Append(',').Append(' ').Append("info").Append(':');
result.Append("<Info>");
result.Append(',').Append(' ').Append("infox").Append(':');
result.Append("<InfoX>");
result.Append(',').Append(' ').Append("hotfix").Append(':');
if (this.hotfix != null) { result.Append("[" + this.hotfix.Count + "]"); }
else { result.Append("null"); }
result.Append(' ').Append('}');
return result.ToString();
} //ConfigRoot::ToString()
public StringBuilder ToStringJSON()
{
StringBuilder code = new StringBuilder();
this.WriteJSON(code);
return code;
}
public void WriteJSON(StringBuilder s)
{
s.Append('\n').Append('{');
string comma = null;
bool revisionExists = !String.IsNullOrEmpty(this.revision);
if (revisionExists) {
s.Append('"').Append("revision").Append('"').Append(':'); comma = ","; s.Append('"').Append(this.revision.ToString()).Append('"');
}
bool listExists = (null != this.list);
if (!String.IsNullOrEmpty(comma) && listExists) { s.Append(comma); comma = null; }
if (listExists) {
s.Append('"').Append("list").Append('"').Append(':'); comma = ","; this.list.WriteJSON(s);
}
bool dictExists = (null != this.dict);
if (!String.IsNullOrEmpty(comma) && dictExists) { s.Append(comma); comma = null; }
if (dictExists) {
s.Append('"').Append("dict").Append('"').Append(':'); comma = ","; this.dict.WriteJSON(s);
}
bool nestExists = (null != this.nest);
if (!String.IsNullOrEmpty(comma) && nestExists) { s.Append(comma); comma = null; }
if (nestExists) {
s.Append('"').Append("nest").Append('"').Append(':'); comma = ","; this.nest.WriteJSON(s);
}
bool infoExists = (null != this.info);
if (!String.IsNullOrEmpty(comma) && infoExists) { s.Append(comma); comma = null; }
if (infoExists) {
s.Append('"').Append("info").Append('"').Append(':'); comma = ","; this.info.WriteJSON(s);
}
bool infoxExists = (null != this.infox);
if (!String.IsNullOrEmpty(comma) && infoxExists) { s.Append(comma); comma = null; }
if (infoxExists) {
s.Append('"').Append("infox").Append('"').Append(':'); comma = ","; this.infox.WriteJSON(s);
}
bool hotfixExists = (null != this.hotfix && this.hotfix.Count > 0);
if (!String.IsNullOrEmpty(comma) && hotfixExists) { s.Append(comma); comma = null; }
if (hotfixExists) {
int hotfixSize = (null == this.hotfix ? 0 : this.hotfix.Count);
if (hotfixSize > 0) {
s.Append('\n').Append('{');
int hotfixIdx = 0;
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) { /* map.for: this.hotfix */
++hotfixIdx;
String k1 = hotfixIter.Key; /* nest.k */
s.Append('"'); s.Append('"').Append(k1.ToString()).Append('"'); s.Append('"').Append(':');
String v1 = hotfixIter.Value; /* nest.v */
s.Append('"').Append(v1.ToString()).Append('"');
if (hotfixIdx != hotfixSize) { s.Append(','); }
}
s.Append('}');
} comma = ",";
}
s.Append('}').Append('\n');
} //ConfigRoot::WriteJSON(...)
public StringBuilder ToStringLua()
{
StringBuilder code = new StringBuilder();
code.Append("-- ConfigRoot.CRC32: 0x");
code.Append(CRC32.ToString("X2")).Append(" --").Append('\n');
code.Append("local table=");
this.WriteLua(code); code.Append(';');
return code;
}
public void WriteLua(StringBuilder s)
{
s.Append('\n').Append('{');
string comma = null;
bool revisionExists = !String.IsNullOrEmpty(this.revision);
if (revisionExists) {
s.Append("revision").Append('='); comma = ","; s.Append('"').Append(this.revision.ToString()).Append('"');
}
bool listExists = (null != this.list);
if (!String.IsNullOrEmpty(comma) && listExists) { s.Append(comma); comma = null; }
if (listExists) {
s.Append("list").Append('='); comma = ","; this.list.WriteLua(s);
}
bool dictExists = (null != this.dict);
if (!String.IsNullOrEmpty(comma) && dictExists) { s.Append(comma); comma = null; }
if (dictExists) {
s.Append("dict").Append('='); comma = ","; this.dict.WriteLua(s);
}
bool nestExists = (null != this.nest);
if (!String.IsNullOrEmpty(comma) && nestExists) { s.Append(comma); comma = null; }
if (nestExists) {
s.Append("nest").Append('='); comma = ","; this.nest.WriteLua(s);
}
bool infoExists = (null != this.info);
if (!String.IsNullOrEmpty(comma) && infoExists) { s.Append(comma); comma = null; }
if (infoExists) {
s.Append("info").Append('='); comma = ","; this.info.WriteLua(s);
}
bool infoxExists = (null != this.infox);
if (!String.IsNullOrEmpty(comma) && infoxExists) { s.Append(comma); comma = null; }
if (infoxExists) {
s.Append("infox").Append('='); comma = ","; this.infox.WriteLua(s);
}
bool hotfixExists = (null != this.hotfix && this.hotfix.Count > 0);
if (!String.IsNullOrEmpty(comma) && hotfixExists) { s.Append(comma); comma = null; }
if (hotfixExists) {
int hotfixSize = (null == this.hotfix ? 0 : this.hotfix.Count);
if (hotfixSize > 0) {
s.Append('\n').Append('{');
int hotfixIdx = 0;
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) { /* map.for: this.hotfix */
++hotfixIdx;
String k1 = hotfixIter.Key; /* nest.k */
s.Append('"').Append(k1.ToString()).Append('"'); s.Append('=');
String v1 = hotfixIter.Value; /* nest.v */
s.Append('"').Append(v1.ToString()).Append('"');
if (hotfixIdx != hotfixSize) { s.Append(','); }
s.Append('}');
}
} comma = ",";
}
s.Append('}').Append('\n');
}
public StringBuilder ToStringPHP()
{
StringBuilder code = new StringBuilder();
code.Append("<?php ").Append("/* ConfigRoot.CRC32: 0x");
code.Append(CRC32.ToString("X2")).Append(" */").Append('\n');
code.Append('\n').Append("return ");
this.WritePHP(code); code.Append(';').Append('\n');
return code;
}
public void WritePHP(StringBuilder s)
{
s.Append("array").Append('(').Append('\n');
string comma = null;
bool revisionExists = !String.IsNullOrEmpty(this.revision);
if (revisionExists) {
s.Append('\'').Append("revision").Append('\'').Append("=>"); comma = ","; s.Append('\'').Append(this.revision.ToString()).Append('\'');
}
bool listExists = (null != this.list);
if (!String.IsNullOrEmpty(comma) && listExists) { s.Append(comma).Append('\n'); comma = null; }
if (listExists) {
s.Append('\'').Append("list").Append('\'').Append("=>"); comma = ","; this.list.WritePHP(s);
}
bool dictExists = (null != this.dict);
if (!String.IsNullOrEmpty(comma) && dictExists) { s.Append(comma).Append('\n'); comma = null; }
if (dictExists) {
s.Append('\'').Append("dict").Append('\'').Append("=>"); comma = ","; this.dict.WritePHP(s);
}
bool nestExists = (null != this.nest);
if (!String.IsNullOrEmpty(comma) && nestExists) { s.Append(comma).Append('\n'); comma = null; }
if (nestExists) {
s.Append('\'').Append("nest").Append('\'').Append("=>"); comma = ","; this.nest.WritePHP(s);
}
bool infoExists = (null != this.info);
if (!String.IsNullOrEmpty(comma) && infoExists) { s.Append(comma).Append('\n'); comma = null; }
if (infoExists) {
s.Append('\'').Append("info").Append('\'').Append("=>"); comma = ","; this.info.WritePHP(s);
}
bool infoxExists = (null != this.infox);
if (!String.IsNullOrEmpty(comma) && infoxExists) { s.Append(comma).Append('\n'); comma = null; }
if (infoxExists) {
s.Append('\'').Append("infox").Append('\'').Append("=>"); comma = ","; this.infox.WritePHP(s);
}
bool hotfixExists = (null != this.hotfix && this.hotfix.Count > 0);
if (!String.IsNullOrEmpty(comma) && hotfixExists) { s.Append(comma).Append('\n'); comma = null; }
if (hotfixExists) {
int hotfixSize = (null == this.hotfix ? 0 : this.hotfix.Count);
if (hotfixSize > 0) {
s.Append("array").Append('(').Append('\n');
int hotfixIdx = 0;
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) { /* map.for: this.hotfix */
++hotfixIdx;
String k1 = hotfixIter.Key; /* nest.k */
s.Append('\'').Append(k1.ToString()).Append('\''); s.Append("=>");
String v1 = hotfixIter.Value; /* nest.v */
s.Append('\'').Append(v1.ToString()).Append('\'');
if (hotfixIdx != hotfixSize) { s.Append(','); s.Append('\n'); }
}
s.Append("/* map size: ").Append(this.hotfix.Count).Append(" */").Append(')');
} comma = ",";
}
s.Append("/* ").Append(GetType().ToString()).Append(" */");
s.Append(')');
}
public StringBuilder ToStringXML()
{
StringBuilder code = new StringBuilder();
code.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
code.Append('\n').Append("<!-- ").Append("ConfigRoot").Append(".CRC32: 0x");
code.Append(CRC32.ToString("X2")).Append(" -->");
this.WriteXML(code, "ConfigRoot");
return code;
}
public void WriteXML(StringBuilder s, String name)
{
StringBuilder attrs = new StringBuilder();
StringBuilder nodes = new StringBuilder();
attrs.Append(' ').Append("revision").Append('=').Append('"').Append(this.revision).Append('"');
this.list.WriteXML(nodes, "list");
this.dict.WriteXML(nodes, "dict");
this.nest.WriteXML(nodes, "nest");
this.info.WriteXML(nodes, "info");
this.infox.WriteXML(nodes, "infox");
if (this.hotfix != null && this.hotfix.Count > 0) {
nodes.Append('\n').Append('<').Append("hotfix").Append('>');
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) {
nodes.Append('\n');
String k1 = hotfixIter.Key;
nodes.Append('<').Append("k1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(k1);
nodes.Append('"').Append('/').Append('>');
String v1 = hotfixIter.Value;
nodes.Append('<').Append("v1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(v1);
nodes.Append('"').Append('/').Append('>');
}
nodes.Append('<').Append('/').Append("hotfix").Append('>');
}
s.Append('\n').Append('<').Append(name).Append(attrs);
if (nodes.Length == 0) {
s.Append('/').Append('>');
} else {
s.Append('>').Append(nodes);
s.Append('<').Append('/').Append(name).Append('>');
}
} //ConfigRoot::WriteXML(...)
} /* class: ConfigRoot */
/*
[email protected]/string/test.xyz.TestList/test.xyz.TestDict/test.xyz.TestNest/test.abc.Info/tes
t.xyz.InfoX/map-string-string
[email protected]/int32/int8/int16/int32/int64/uint8/uint16/uint32/uint64/float/double/bool/string/vec
-string/int32/test.abc.Info/test.abc.Conflict/vec-test.xyz.Conflict/vec-double/map-test.abc.Info-i
nt32/map-int32-test.abc.Info/map-int32-double/map-string-string
[email protected]/vec-vec-vec-vec-vec-test.abc.Info/test.xyz.Conflict/test.abc.Conflict/map-int32-tes
t.abc.Conflict/vec-vec-test.abc.Info/vec-vec-vec-test.abc.Info/vec-vec-vec-vec-vec-test.abc.Info/v
ec-map-int16-test.abc.Info/map-vec-int32-test.abc.Info/map-test.abc.Info-vec-int32/map-vec-test.ab
c.Info-vec-int32/vec-map-vec-test.abc.Info-vec-int32/map-string-string
[email protected]/map-int8-int8/map-int16-int16/map-int32-int32/map-int64-int64/map-uint8-uint8/ma
p-uint16-uint16/map-uint32-uint32/map-uint64-uint64/map-float-float/map-double-double/map-bool-boo
l/map-string-string/map-int32-int32/map-test.abc.Custom-test.abc.Custom/map-string-string
[email protected]/vec-int8/vec-int16/vec-int32/vec-int64/vec-uint8/vec-uint16/vec-uint32/vec-uint6
4/vec-float/vec-double/vec-bool/vec-string/vec-int32/vec-test.abc.Custom
[email protected]/vec-map-string-test.abc.Custom/map-vec-string-vec-test.abc.Custom/vec-vec-vec-ve
c-vec-test.abc.Custom
*/
} //namespace: Test.Xyz
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.Extensions.FileProviders.Embedded.Tests
{
public class EmbeddedFileProviderTests
{
private static readonly string Namespace = typeof(EmbeddedFileProviderTests).Namespace;
[Fact]
public void ConstructorWithNullAssemblyThrowsArgumentException()
{
Assert.Throws<ArgumentNullException>(() => new EmbeddedFileProvider(null));
}
[Fact]
public void GetFileInfo_ReturnsNotFoundFileInfo_IfFileDoesNotExist()
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly);
// Act
var fileInfo = provider.GetFileInfo("DoesNotExist.Txt");
// Assert
Assert.NotNull(fileInfo);
Assert.False(fileInfo.Exists);
}
[Theory]
[InlineData("File.txt")]
[InlineData("/File.txt")]
public void GetFileInfo_ReturnsFilesAtRoot(string filePath)
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly);
var expectedFileLength = 8;
// Act
var fileInfo = provider.GetFileInfo(filePath);
// Assert
Assert.NotNull(fileInfo);
Assert.True(fileInfo.Exists);
Assert.NotEqual(default(DateTimeOffset), fileInfo.LastModified);
Assert.Equal(expectedFileLength, fileInfo.Length);
Assert.False(fileInfo.IsDirectory);
Assert.Null(fileInfo.PhysicalPath);
Assert.Equal("File.txt", fileInfo.Name);
}
[Fact]
public void GetFileInfo_ReturnsNotFoundFileInfo_IfFileDoesNotExistUnderSpecifiedNamespace()
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly, Namespace + ".SubNamespace");
// Act
var fileInfo = provider.GetFileInfo("File.txt");
// Assert
Assert.NotNull(fileInfo);
Assert.False(fileInfo.Exists);
}
[Fact]
public void GetFileInfo_ReturnsNotFoundIfPathStartsWithBackSlash()
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly);
// Act
var fileInfo = provider.GetFileInfo("\\File.txt");
// Assert
Assert.NotNull(fileInfo);
Assert.False(fileInfo.Exists);
}
public static TheoryData GetFileInfo_LocatesFilesUnderSpecifiedNamespaceData
{
get
{
var theoryData = new TheoryData<string>
{
"ResourcesInSubdirectory/File3.txt"
};
if (TestPlatformHelper.IsWindows)
{
theoryData.Add("ResourcesInSubdirectory\\File3.txt");
}
return theoryData;
}
}
[Theory]
[MemberData(nameof(GetFileInfo_LocatesFilesUnderSpecifiedNamespaceData))]
public void GetFileInfo_LocatesFilesUnderSpecifiedNamespace(string path)
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly, Namespace + ".Resources");
// Act
var fileInfo = provider.GetFileInfo(path);
// Assert
Assert.NotNull(fileInfo);
Assert.True(fileInfo.Exists);
Assert.NotEqual(default(DateTimeOffset), fileInfo.LastModified);
Assert.True(fileInfo.Length > 0);
Assert.False(fileInfo.IsDirectory);
Assert.Null(fileInfo.PhysicalPath);
Assert.Equal("File3.txt", fileInfo.Name);
}
public static TheoryData GetFileInfo_LocatesFilesUnderSubDirectoriesData
{
get
{
var theoryData = new TheoryData<string>
{
"Resources/File.txt"
};
if (TestPlatformHelper.IsWindows)
{
theoryData.Add("Resources\\File.txt");
}
return theoryData;
}
}
[Theory]
[MemberData(nameof(GetFileInfo_LocatesFilesUnderSubDirectoriesData))]
public void GetFileInfo_LocatesFilesUnderSubDirectories(string path)
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly);
// Act
var fileInfo = provider.GetFileInfo(path);
// Assert
Assert.NotNull(fileInfo);
Assert.True(fileInfo.Exists);
Assert.NotEqual(default(DateTimeOffset), fileInfo.LastModified);
Assert.True(fileInfo.Length > 0);
Assert.False(fileInfo.IsDirectory);
Assert.Null(fileInfo.PhysicalPath);
Assert.Equal("File.txt", fileInfo.Name);
}
[Theory]
[InlineData("")]
[InlineData("/")]
public void GetDirectoryContents_ReturnsAllFilesInFileSystem(string path)
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly, Namespace + ".Resources");
// Act
var files = provider.GetDirectoryContents(path);
// Assert
Assert.Collection(files.OrderBy(f => f.Name, StringComparer.Ordinal),
file => Assert.Equal("File.txt", file.Name),
file => Assert.Equal("ResourcesInSubdirectory.File3.txt", file.Name));
Assert.False(provider.GetDirectoryContents("file").Exists);
Assert.False(provider.GetDirectoryContents("file/").Exists);
Assert.False(provider.GetDirectoryContents("file.txt").Exists);
Assert.False(provider.GetDirectoryContents("file/txt").Exists);
}
[Fact]
public void GetDirectoryContents_ReturnsEmptySequence_IfResourcesDoNotExistUnderNamespace()
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly, "Unknown.Namespace");
// Act
var files = provider.GetDirectoryContents(string.Empty);
// Assert
Assert.NotNull(files);
Assert.True(files.Exists);
Assert.Empty(files);
}
[Theory]
[InlineData("Resources")]
[InlineData("/Resources")]
public void GetDirectoryContents_ReturnsNotFoundDirectoryContents_IfHierarchicalPathIsSpecified(string path)
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly);
// Act
var files = provider.GetDirectoryContents(path);
// Assert
Assert.NotNull(files);
Assert.False(files.Exists);
Assert.Empty(files);
}
[Fact]
public void Watch_ReturnsNoOpTrigger()
{
// Arrange
var provider = new EmbeddedFileProvider(GetType().Assembly);
// Act
var token = provider.Watch("Resources/File.txt");
// Assert
Assert.NotNull(token);
Assert.False(token.ActiveChangeCallbacks);
Assert.False(token.HasChanged);
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace Moq.Tests
{
public class SequenceExtensionsFixture
{
[Fact]
public void PerformSequence()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.Do())
.Returns(2)
.Returns(3)
.Returns(() => 4)
.Throws<InvalidOperationException>();
Assert.Equal(2, mock.Object.Do());
Assert.Equal(3, mock.Object.Do());
Assert.Equal(4, mock.Object.Do());
Assert.Throws<InvalidOperationException>(() => mock.Object.Do());
}
[Fact]
public async Task PerformSequenceAsync()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.DoAsync())
.ReturnsAsync(2)
.ReturnsAsync(3)
.ThrowsAsync(new InvalidOperationException());
Assert.Equal(2, mock.Object.DoAsync().Result);
Assert.Equal(3, mock.Object.DoAsync().Result);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await mock.Object.DoAsync());
}
[Fact]
public async Task PerformSequenceValueTaskAsync()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.DoValueAsync())
.ReturnsAsync(2)
.ReturnsAsync(() => 3)
.ThrowsAsync(new InvalidOperationException());
Assert.Equal(2, mock.Object.DoValueAsync().Result);
Assert.Equal(3, mock.Object.DoValueAsync().Result);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await mock.Object.DoValueAsync());
}
[Fact]
public async Task PerformSequenceVoidAsync()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.DoVoidAsync())
.PassAsync()
.PassAsync()
.ThrowsAsync(new InvalidOperationException());
await mock.Object.DoVoidAsync();
await mock.Object.DoVoidAsync();
await Assert.ThrowsAsync<InvalidOperationException>(async () => await mock.Object.DoVoidAsync());
}
[Fact]
public async Task PerformSequenceValueTaskVoidAsync()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.DoValueVoidAsync())
.PassAsync()
.PassAsync()
.ThrowsAsync(new InvalidOperationException());
await mock.Object.DoValueVoidAsync();
await mock.Object.DoValueVoidAsync();
await Assert.ThrowsAsync<InvalidOperationException>(async () => await mock.Object.DoValueVoidAsync());
}
[Fact]
public async Task PerformSequenceAsync_ReturnsAsync_for_Task_with_value_function()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.DoAsync())
.ReturnsAsync(() => 1)
.ReturnsAsync(() => 2);
Assert.Equal(1, await mock.Object.DoAsync());
Assert.Equal(2, await mock.Object.DoAsync());
}
[Fact]
public async Task PerformSequenceAsync_ReturnsAsync_for_ValueTask_with_value_function()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.DoValueAsync())
.ReturnsAsync(() => 1)
.ReturnsAsync(() => 2);
Assert.Equal(1, await mock.Object.DoValueAsync());
Assert.Equal(2, await mock.Object.DoValueAsync());
}
[Fact]
public void PerformSequenceOnProperty()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.Value)
.Returns("foo")
.Returns("bar")
.Throws<InvalidOperationException>();
string temp;
Assert.Equal("foo", mock.Object.Value);
Assert.Equal("bar", mock.Object.Value);
Assert.Throws<InvalidOperationException>(() => temp = mock.Object.Value);
}
[Fact]
public void PerformSequenceWithThrowsFirst()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(x => x.Do())
.Throws<Exception>()
.Returns(1);
Assert.Throws<Exception>(() => mock.Object.Do());
Assert.Equal(1, mock.Object.Do());
}
[Fact]
public void PerformSequenceWithCallBase()
{
var mock = new Mock<Foo>();
mock.SetupSequence(x => x.Do())
.Returns("Good")
.CallBase()
.Throws<InvalidOperationException>();
Assert.Equal("Good", mock.Object.Do());
Assert.Equal("Ok", mock.Object.Do());
Assert.Throws<InvalidOperationException>(() => mock.Object.Do());
}
[Fact]
public void Setting_up_a_sequence_overrides_any_preexisting_setup()
{
const string valueFromPreviousSetup = "value from previous setup";
// Arrange: set up a sequence as the second setup and consume it
var mock = new Mock<IFoo>();
mock.Setup(m => m.Value).Returns(valueFromPreviousSetup);
mock.SetupSequence(m => m.Value).Returns("1");
var _ = mock.Object.Value;
// Act: ask sequence for value when it is exhausted
var actual = mock.Object.Value;
// Assert: should have got the default value, not the one configured by the overridden setup
Assert.Equal(default(string), actual);
Assert.NotEqual(valueFromPreviousSetup, actual);
}
[Fact]
public void When_sequence_exhausted_and_there_was_no_previous_setup_return_value_is_default()
{
// Arrange: set up a sequence as the only setup and consume it
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.Value)
.Returns("1");
var _ = mock.Object.Value;
// Act: ask sequence for value when it is exhausted
string actual = mock.Object.Value;
// Assert: should have got the default value
Assert.Equal(default(string), actual);
}
[Fact]
public void When_sequence_overexhausted_and_new_responses_are_configured_those_are_used_on_next_invocation()
{
// Arrange: set up a sequence and overexhaust it, then set up more responses
var mock = new Mock<IFoo>();
var sequenceSetup = mock.SetupSequence(m => m.Value).Returns("1"); // configure 1st response
var _ = mock.Object.Value; // 1st invocation
_ = mock.Object.Value; // 2nd invocation
sequenceSetup.Returns("2"); // configure 2nd response
sequenceSetup.Returns("3"); // configure 3nd response
// Act: 3rd invocation. will we get back the 2nd configured response, or the 3rd (since we're on the 3rd invocation)?
string actual = mock.Object.Value;
// Assert: no configured response should be skipped, therefore we should get the 2nd one
Assert.Equal("2", actual);
}
[Fact]
public void Verify_can_verify_invocation_count_for_sequences()
{
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.Do());
mock.Object.Do();
mock.Object.Do();
mock.Verify(m => m.Do(), Times.Exactly(2));
}
[Fact]
public void Func_are_invoked_deferred()
{
var mock = new Mock<IFoo>();
var i = 0;
mock.SetupSequence(m => m.Do())
.Returns(() => i);
i++;
Assert.Equal(i, mock.Object.Do());
}
[Fact]
public async Task Func_are_invoked_deferred_for_Task()
{
var mock = new Mock<IFoo>();
var i = 0;
mock.SetupSequence(m => m.DoAsync())
.ReturnsAsync(() => i);
i++;
Assert.Equal(i, await mock.Object.DoAsync());
}
[Fact]
public async Task Func_are_invoked_deferred_for_ValueTask()
{
var mock = new Mock<IFoo>();
var i = 0;
mock.SetupSequence(m => m.DoValueAsync())
.ReturnsAsync(() => i);
i++;
Assert.Equal(i, await mock.Object.DoValueAsync());
}
[Fact]
public void Func_can_be_treated_as_return_value()
{
var mock = new Mock<IFoo>();
Func<int> func = () => 1;
mock.SetupSequence(m => m.GetFunc())
.Returns(func);
Assert.Equal(func, mock.Object.GetFunc());
}
[Fact]
public void Keep_Func_as_return_value_when_setup_method_returns_implicitly_casted_type()
{
var mock = new Mock<IFoo>();
Func<object> funcObj = () => 1;
Func<Delegate> funcDel = () => new Action(() => { });
Func<MulticastDelegate> funcMulticastDel = () => new Action(() => { });
mock.SetupSequence(m => m.GetObj()).Returns(funcObj);
mock.SetupSequence(m => m.GetDel()).Returns(funcDel);
mock.SetupSequence(m => m.GetMulticastDel()).Returns(funcMulticastDel);
Assert.Equal(funcObj, mock.Object.GetObj());
Assert.Equal(funcDel, mock.Object.GetDel());
Assert.Equal(funcMulticastDel, mock.Object.GetMulticastDel());
}
public interface IFoo
{
string Value { get; set; }
int Do();
Task<int> DoAsync();
ValueTask<int> DoValueAsync();
Task DoVoidAsync();
ValueTask DoValueVoidAsync();
Func<int> GetFunc();
object GetObj();
Delegate GetDel();
MulticastDelegate GetMulticastDel();
}
public class Foo
{
public virtual string Do()
{
return "Ok";
}
public virtual Task<string> DoAsync()
{
var tcs = new TaskCompletionSource<string>();
tcs.SetResult("Ok");
return tcs.Task;
}
}
}
}
| |
// Copyright 2019 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
//
// 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 CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example adds a campaign draft for a campaign. Make sure you specify a
/// campaign that has a budget with explicitly_shared set to false.
/// </summary>
public class AddCampaignDraft : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddCampaignDraft"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the base campaign.
/// </summary>
[Option("baseCampaignId", Required = true, HelpText =
"ID of the base campaign.")]
public long BaseCampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// ID of the base campaign.
options.BaseCampaignId = long.Parse("INSERT_BASE_CAMPAIGN_ID_HERE");
return 0;
});
AddCampaignDraft codeExample = new AddCampaignDraft();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.BaseCampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example adds a campaign draft for a campaign. Make sure you specify a " +
"campaign that has a budget with explicitly_shared set to false.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="baseCampaignId">ID of the base campaign</param>
public void Run(GoogleAdsClient client, long customerId, long baseCampaignId)
{
try
{
string draftResourceName = CreateCampaignDraft(client, customerId, baseCampaignId);
string draftCampaignResourceName = FetchDraftCampaign(client, customerId,
draftResourceName);
AddLanguageCriteria(client, customerId, draftCampaignResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the campaign draft.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="baseCampaignId">The base campaign ID.</param>
/// <returns></returns>
private static string CreateCampaignDraft(GoogleAdsClient client, long customerId,
long baseCampaignId)
{
// Get the CampaignDraftService.
CampaignDraftServiceClient campaignDraftService =
client.GetService(Services.V10.CampaignDraftService);
CampaignDraft campaignDraft = new CampaignDraft()
{
BaseCampaign = ResourceNames.Campaign(customerId, baseCampaignId),
Name = "Campaign Draft #" + ExampleUtilities.GetRandomString(),
};
CampaignDraftOperation operation = new CampaignDraftOperation()
{
Create = campaignDraft
};
MutateCampaignDraftsResponse response = campaignDraftService.MutateCampaignDrafts(
customerId.ToString(), new CampaignDraftOperation[] { operation });
string draftResourceName = response.Results[0].ResourceName;
Console.WriteLine($"Campaign with resource ID = '{draftResourceName}' was added.");
return draftResourceName;
}
/// <summary>
/// Fetches the draft campaign associated with a campaign draft.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="draftResourceName">Resource name of the draft.</param>
/// <returns></returns>
private static string FetchDraftCampaign(GoogleAdsClient client, long customerId,
string draftResourceName)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService =
client.GetService(Services.V10.GoogleAdsService);
// Once the draft is created, you can modify the draft campaign as if it were
// a real campaign. For example, you may add criteria, adjust bids, or even
// include additional ads. Adding a criterion is shown here.
string query = $@"
SELECT
campaign_draft.draft_campaign
FROM
campaign_draft
WHERE
campaign_draft.resource_name = '{draftResourceName}'";
// Get the draft campaign resource name.
string draftCampaignResourceName = googleAdsService.Search(
customerId.ToString(), query).First().CampaignDraft.DraftCampaign;
return draftCampaignResourceName;
}
/// <summary>
/// Adds a language criterion to the draft campaign.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// /// <param name="draftCampaignResourceName">Resource name of the draft campaign.</param>
private static void AddLanguageCriteria(GoogleAdsClient client, long customerId,
string draftCampaignResourceName)
{
// Get the CampaignCriterionService.
CampaignCriterionServiceClient campaignCriterionService =
client.GetService(Services.V10.CampaignCriterionService);
// Add a language criterion.
CampaignCriterionOperation criterionOperation = new CampaignCriterionOperation()
{
Create = new CampaignCriterion()
{
Language = new LanguageInfo()
{
// Spanish
LanguageConstant = ResourceNames.LanguageConstant(1003)
},
Campaign = draftCampaignResourceName
}
};
MutateCampaignCriteriaResponse campaignCriteriaResponse =
campaignCriterionService.MutateCampaignCriteria(
customerId.ToString(),
new CampaignCriterionOperation[] { criterionOperation });
string newCampaignCriterionResource = campaignCriteriaResponse.Results[0].ResourceName;
Console.WriteLine($"Campaign Criterion with resource ID = " +
$"'{newCampaignCriterionResource}' was added to campaign with resource ID = " +
$"'{draftCampaignResourceName}'.");
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.ConnectedAngularAppsV2Web
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using System.Reflection;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimeAndDate.Services.DataTypes.Astro;
using TimeAndDate.Services.DataTypes.Places;
using TimeAndDate.Services.DataTypes.Holidays;
using TimeAndDate.Services.DataTypes.BusinessDays;
using TimeAndDate.Services.DataTypes.OnThisDay;
using TimeAndDate.Services.DataTypes.Tides;
namespace TimeAndDate.Services.Common
{
internal static class StringHelpers
{
internal static string ToNum(this bool boolean)
{
return boolean ? "1" : "0";
}
internal static string ResolveHolidayType(Func<dynamic, bool> expr)
{
var x = new[] {
new { arg = "all", type = HolidayType.All },
new { arg = "default", type = HolidayType.Default },
new { arg = "countrydefault", type = HolidayType.DefaultForCountry },
new { arg = "obs", type = HolidayType.Observances },
new { arg = "federal", type = HolidayType.Federal },
new { arg = "federallocal", type = HolidayType.FederalLocal },
new { arg = "local", type = HolidayType.Local },
new { arg = "flagday", type = HolidayType.FlagDays },
new { arg = "local2", type = HolidayType.LocalObservances },
new { arg = "obs1", type = HolidayType.ImportantObservances },
new { arg = "obs2", type = HolidayType.CommonObservances },
new { arg = "obs3", type = HolidayType.OtherObservances },
new { arg = "weekday", type = HolidayType.Weekdays },
new { arg = "christian", type = HolidayType.Christian },
new { arg = "buddhism", type = HolidayType.Buddhism },
new { arg = "hebrew", type = HolidayType.Hebrew },
new { arg = "hinduism", type = HolidayType.Hinduism },
new { arg = "muslim", type = HolidayType.Muslim },
new { arg = "orthodox", type = HolidayType.Orthodox },
new { arg = "seasons", type = HolidayType.Seasons },
new { arg = "tz", type = HolidayType.TimezoneEvents },
new { arg = "un", type = HolidayType.UnitedNations },
new { arg = "world", type = HolidayType.WorldWideObservances }
}.ToList().SingleOrDefault(expr);
return x.arg as string;
}
internal static string ResolveEventType(Func<dynamic, bool> expr)
{
var x = new[] {
new { arg = "events", type = EventType.Events },
new { arg = "births", type = EventType.Births },
new { arg = "deaths", type = EventType.Deaths }
}.ToList().SingleOrDefault(expr);
return x.arg as string;
}
internal static string ResolveBusinessDaysFilterType(Func<dynamic, bool> expr)
{
var x = new[] {
new { arg = "all", type = BusinessDaysFilterType.All },
new { arg = "mon", type = BusinessDaysFilterType.Monday },
new { arg = "tue", type = BusinessDaysFilterType.Tuesday },
new { arg = "wed", type = BusinessDaysFilterType.Wednesday },
new { arg = "thu", type = BusinessDaysFilterType.Thursday },
new { arg = "fri", type = BusinessDaysFilterType.Friday },
new { arg = "sat", type = BusinessDaysFilterType.Saturday },
new { arg = "sun", type = BusinessDaysFilterType.Sunday },
new { arg = "weekend", type = BusinessDaysFilterType.Weekend },
new { arg = "holidays", type = BusinessDaysFilterType.Holidays },
new { arg = "weekendholidays", type = BusinessDaysFilterType.WeekendHolidays },
new { arg = "none", type = BusinessDaysFilterType.None }
}.ToList().SingleOrDefault(expr);
return x.arg as string;
}
internal static string ResolveAstronomyEventClass(Func<dynamic, bool> expr)
{
var x = new[] {
new { arg = "all", type = AstronomyEventClass.All },
new { arg = "current", type = AstronomyEventClass.Current },
new { arg = "daylength", type = AstronomyEventClass.DayLength },
new { arg = "meridian", type = AstronomyEventClass.Meridian },
new { arg = "phase", type = AstronomyEventClass.Phase },
new { arg = "setrise", type = AstronomyEventClass.SetRise },
new { arg = "twilight", type = AstronomyEventClass.AllTwilights },
new { arg = "twilight6", type = AstronomyEventClass.CivilTwilight },
new { arg = "twilight12", type = AstronomyEventClass.NauticalTwilight },
new { arg = "twilight18", type = AstronomyEventClass.AstronomicalTwilight }
}.ToList().SingleOrDefault(expr);
return x.arg as string;
}
internal static string ResolveAstronomyObjectType(Func<dynamic, bool> expr)
{
var x = new[] {
new { arg = "sun", type = AstronomyObjectType.Sun },
new { arg = "moon", type = AstronomyObjectType.Moon },
new { arg = "mercury", type = AstronomyObjectType.Mercury},
new { arg = "venus", type = AstronomyObjectType.Venus},
new { arg = "mars", type = AstronomyObjectType.Mars},
new { arg = "jupiter", type = AstronomyObjectType.Jupiter},
new { arg = "saturn", type = AstronomyObjectType.Saturn},
new { arg = "uranus", type = AstronomyObjectType.Uranus},
new { arg = "neptune", type = AstronomyObjectType.Neptune},
new { arg = "pluto", type = AstronomyObjectType.Pluto},
}.ToList().SingleOrDefault(expr);
return x.arg as string;
}
internal static AstronomyEventCode ResolveAstronomyEventCode(string eventCode)
{
switch (eventCode)
{
case "twi18_start":
return AstronomyEventCode.AstronomicalTwilightStarts;
case "twi12_start":
return AstronomyEventCode.NauticalTwilightStarts;
case "twi6_start":
return AstronomyEventCode.CivilTwilightStarts;
case "rise":
return AstronomyEventCode.Rise;
case "meridian":
return AstronomyEventCode.Meridian;
case "antimeridian":
return AstronomyEventCode.AntiMeridian;
case "set":
return AstronomyEventCode.Set;
case "twi6_end":
return AstronomyEventCode.CivilTwilightEnds;
case "twi12_end":
return AstronomyEventCode.NauticalTwilightEnds;
case "twi18_end":
return AstronomyEventCode.AstronomicalTwilightEnds;
case "newmoon":
return AstronomyEventCode.NewMoon;
case "firstquarter":
return AstronomyEventCode.FirstQuarter;
case "fullmoon":
return AstronomyEventCode.FullMoon;
case "thirdquarter":
return AstronomyEventCode.ThirdQuarter;
default:
throw new ArgumentException("EventCode does not conform to enum AstronomyEventCode");
}
}
internal static TidalPhase ResolveTidalPhase(string tidalPhase)
{
switch (tidalPhase)
{
case "high":
return TidalPhase.High;
case "low":
return TidalPhase.Low;
case "ebb":
return TidalPhase.Ebb;
case "flood":
return TidalPhase.Flood;
default:
throw new ArgumentException("Input does not conform to enum TidalPhase");
}
}
private static string PlaceIdByCoordinates(decimal latitude, decimal longitude)
{
var coords = new StringBuilder();
if (latitude >= 0)
coords.Append("+");
coords.Append(latitude.ToString(CultureInfo.InvariantCulture));
if (longitude >= 0)
coords.Append("+");
coords.Append(longitude.ToString(CultureInfo.InvariantCulture));
return coords.ToString();
}
internal static string GetIdAsString(this LocationId placeId)
{
var id = string.Empty;
if (placeId.NumericId.HasValue)
id = placeId.NumericId.Value.ToString();
else if (!String.IsNullOrEmpty(placeId.TextualId))
id = placeId.TextualId;
else if (placeId.CoordinatesId != null)
id = StringHelpers.PlaceIdByCoordinates(placeId.CoordinatesId.Latitude, placeId.CoordinatesId.Longitude);
return id;
}
}
}
| |
// (c) Copyright Esri, 2010 - 2013
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using System.Resources;
using ESRI.ArcGIS.Geoprocessing;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("FD63EBC5-4B63-4649-982E-25D55CB89CE6")]
[ComVisible(true)]
public interface IHttpBasicDataType
{
string MaskCharacter { get; set; }
}
[Guid("6594937a-3199-42e9-af63-a20d5cc2b211")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.HttpBasicDataType")]
public class HttpBasicDataType: IHttpBasicDataType, IGPDataType, IClone
{
#region IGPDataType Members
ResourceManager resourceManager = null;
string m_dataTypeDisplayName ="OpenStreetMap login";
IGPDataTypeFactory m_dataTypeFactory = null;
const string m_dataTypeName = "HttpBasicAuthenticationDataType";
string m_maskingCharacter = "*";
public HttpBasicDataType()
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
m_dataTypeFactory = new AuthenticationDataTypeFactory();
m_dataTypeDisplayName = resourceManager.GetString("GPTools_Authentication_HttpBasicDataType_displayname");
}
public UID ControlCLSID
{
get
{
UID authenticationControlCLSID = new UIDClass();
authenticationControlCLSID.Value = "{F483BDB7-DBA1-45CA-A31E-665422FD2460}";
return authenticationControlCLSID;
}
}
public IGPValue CreateValue(string text)
{
IGPValue gpValue = new HttpBasicGPValue();
IGPMessage gpValueMessage = gpValue.SetAsText(text);
if (gpValueMessage.IsInformational())
{
return gpValue;
}
else
{
return null;
}
}
public string DisplayName
{
get
{
return m_dataTypeDisplayName;
}
}
public IName FullName
{
get
{
return m_dataTypeFactory.GetDataTypeName(m_dataTypeName) as IName;
}
}
public int HelpContext
{
get
{
return default(int);
}
}
public string HelpFile
{
get
{
return String.Empty;
}
}
public string MetadataFile
{
get
{
return String.Empty;
}
}
public string Name
{
get
{
return m_dataTypeName;
}
}
public IGPMessage ValidateDataType(IGPDataType Type)
{
IGPMessage validateDataTypeMessage = new GPMessageClass();
IHttpBasicDataType targetType = Type as IHttpBasicDataType;
if (targetType == null)
{
IGPStringType targetTypeString = Type as IGPStringType;
if (targetTypeString != null)
return validateDataTypeMessage;
}
if (targetType == null)
{
validateDataTypeMessage.ErrorCode = 501;
validateDataTypeMessage.Type = esriGPMessageType.esriGPMessageTypeError;
validateDataTypeMessage.Description = resourceManager.GetString("GPTools_Authentication_HttpBasicDataType_typevalidation");
}
return validateDataTypeMessage;
}
public IGPMessage ValidateValue(IGPValue Value, IGPDomain Domain)
{
IGPMessage validateValueMessage = new GPMessageClass();
IGPUtilities3 gpUtilities = new GPUtilitiesClass();
IHttpBasicGPValue targetValue = gpUtilities.UnpackGPValue(Value) as IHttpBasicGPValue;
if ( targetValue == null ) {
IGPString targetValueString = gpUtilities.UnpackGPValue(Value) as IGPString;
if ( targetValueString != null )
return validateValueMessage;
}
if (targetValue == null)
{
validateValueMessage.Type = esriGPMessageType.esriGPMessageTypeError;
validateValueMessage.ErrorCode = 502;
validateValueMessage.Description = resourceManager.GetString("GPTools_Authentication_HttpBasicDataType_valuevalidation");
}
if (Domain != null)
{
validateValueMessage = Domain.MemberOf((IGPValue)targetValue);
}
return validateValueMessage;
}
#endregion
#region IClone Members
public void Assign(IClone src)
{
}
public IClone Clone()
{
IClone clone = new HttpBasicDataType() as IClone;
clone.Assign(this);
return clone;
}
public bool IsEqual(IClone other)
{
bool equalResult = false;
IHttpBasicGPValue httpBasicGPValue = other as IHttpBasicGPValue;
if (httpBasicGPValue == null)
return equalResult;
equalResult = true;
return equalResult;
}
public bool IsIdentical(IClone other)
{
return other.Equals(this);
}
#endregion
#region IHttpBasicDataType Members
public string MaskCharacter
{
get
{
return m_maskingCharacter;
}
set
{
m_maskingCharacter = value;
}
}
#endregion
}
}
| |
//Copyright 2010 Microsoft Corporation
//
//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.
#if ASTORIA_SERVER
namespace System.Data.Services
#else
namespace System.Data.Services.Client
#endif
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
#if ASTORIA_LIGHT
using System.Reflection;
using System.Security;
using System.Security.Permissions;
internal static class ExpressionHelpers
{
private static MethodInfo lambdaFunc;
internal static LambdaExpression CreateLambda(Expression body, params ParameterExpression[] parameters)
{
return CreateLambda(InferDelegateType(body, parameters), body, parameters);
}
internal static LambdaExpression CreateLambda(Type delegateType, Expression body, params ParameterExpression[] parameters)
{
var args = new[] { Expression.Parameter(typeof(Expression), "body"), Expression.Parameter(typeof(ParameterExpression[]), "parameters") };
var lambdaFactory = Expression.Lambda<Func<Expression, ParameterExpression[], LambdaExpression>>(
Expression.Call(GetLambdaFactoryMethod(delegateType), args), args
);
return lambdaFactory.Compile().Invoke(body, parameters);
}
private static Type InferDelegateType(Expression body, params ParameterExpression[] parameters)
{
bool isVoid = body.Type == typeof(void);
int length = (parameters == null) ? 0 : parameters.Length;
var typeArgs = new Type[length + (isVoid ? 0 : 1)];
for (int i = 0; i < length; i++)
{
typeArgs[i] = parameters[i].Type;
}
if (isVoid)
{
return Expression.GetActionType(typeArgs);
}
else
{
typeArgs[length] = body.Type;
return Expression.GetFuncType(typeArgs);
}
}
private static MethodInfo GetLambdaFactoryMethod(Type delegateType)
{
if (lambdaFunc == null)
{
lambdaFunc = new Func<Expression, ParameterExpression[], Expression<Action>>(Expression.Lambda<Action>).Method.GetGenericMethodDefinition();
}
return lambdaFunc.MakeGenericMethod(delegateType);
}
}
#endif
internal abstract class ALinqExpressionVisitor
{
internal virtual Expression Visit(Expression exp)
{
if (exp == null)
{
return exp;
}
switch (exp.NodeType)
{
case ExpressionType.UnaryPlus:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return this.VisitUnary((UnaryExpression)exp);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
#if !ASTORIA_CLIENT
case ExpressionType.Power:
#endif
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return this.VisitBinary((BinaryExpression)exp);
case ExpressionType.TypeIs:
return this.VisitTypeIs((TypeBinaryExpression)exp);
case ExpressionType.Conditional:
return this.VisitConditional((ConditionalExpression)exp);
case ExpressionType.Constant:
return this.VisitConstant((ConstantExpression)exp);
case ExpressionType.Parameter:
return this.VisitParameter((ParameterExpression)exp);
case ExpressionType.MemberAccess:
return this.VisitMemberAccess((MemberExpression)exp);
case ExpressionType.Call:
return this.VisitMethodCall((MethodCallExpression)exp);
case ExpressionType.Lambda:
return this.VisitLambda((LambdaExpression)exp);
case ExpressionType.New:
return this.VisitNew((NewExpression)exp);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return this.VisitNewArray((NewArrayExpression)exp);
case ExpressionType.Invoke:
return this.VisitInvocation((InvocationExpression)exp);
case ExpressionType.MemberInit:
return this.VisitMemberInit((MemberInitExpression)exp);
case ExpressionType.ListInit:
return this.VisitListInit((ListInitExpression)exp);
default:
throw new NotSupportedException(Strings.ALinq_UnsupportedExpression(exp.NodeType.ToString()));
}
}
internal virtual MemberBinding VisitBinding(MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
return this.VisitMemberAssignment((MemberAssignment)binding);
case MemberBindingType.MemberBinding:
return this.VisitMemberMemberBinding((MemberMemberBinding)binding);
case MemberBindingType.ListBinding:
return this.VisitMemberListBinding((MemberListBinding)binding);
default:
throw new NotSupportedException(Strings.ALinq_UnsupportedExpression(binding.BindingType.ToString()));
}
}
internal virtual ElementInit VisitElementInitializer(ElementInit initializer)
{
ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments);
if (arguments != initializer.Arguments)
{
return Expression.ElementInit(initializer.AddMethod, arguments);
}
return initializer;
}
internal virtual Expression VisitUnary(UnaryExpression u)
{
Expression operand = this.Visit(u.Operand);
if (operand != u.Operand)
{
return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method);
}
return u;
}
internal virtual Expression VisitBinary(BinaryExpression b)
{
Expression left = this.Visit(b.Left);
Expression right = this.Visit(b.Right);
Expression conversion = this.Visit(b.Conversion);
if (left != b.Left || right != b.Right || conversion != b.Conversion)
{
if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null)
{
return Expression.Coalesce(left, right, conversion as LambdaExpression);
}
else
{
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
}
return b;
}
internal virtual Expression VisitTypeIs(TypeBinaryExpression b)
{
Expression expr = this.Visit(b.Expression);
if (expr != b.Expression)
{
return Expression.TypeIs(expr, b.TypeOperand);
}
return b;
}
internal virtual Expression VisitConstant(ConstantExpression c)
{
return c;
}
internal virtual Expression VisitConditional(ConditionalExpression c)
{
Expression test = this.Visit(c.Test);
Expression iftrue = this.Visit(c.IfTrue);
Expression iffalse = this.Visit(c.IfFalse);
if (test != c.Test || iftrue != c.IfTrue || iffalse != c.IfFalse)
{
return Expression.Condition(test, iftrue, iffalse);
}
return c;
}
internal virtual Expression VisitParameter(ParameterExpression p)
{
return p;
}
internal virtual Expression VisitMemberAccess(MemberExpression m)
{
Expression exp = this.Visit(m.Expression);
if (exp != m.Expression)
{
return Expression.MakeMemberAccess(exp, m.Member);
}
return m;
}
internal virtual Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = this.Visit(m.Object);
IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments);
if (obj != m.Object || args != m.Arguments)
{
return Expression.Call(obj, m.Method, args);
}
return m;
}
internal virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
{
List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
Expression p = this.Visit(original[i]);
if (list != null)
{
list.Add(p);
}
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(p);
}
}
if (list != null)
{
return new ReadOnlyCollection<Expression>(list);
}
return original;
}
internal virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment)
{
Expression e = this.Visit(assignment.Expression);
if (e != assignment.Expression)
{
return Expression.Bind(assignment.Member, e);
}
return assignment;
}
internal virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{
IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings);
if (bindings != binding.Bindings)
{
return Expression.MemberBind(binding.Member, bindings);
}
return binding;
}
internal virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding)
{
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers);
if (initializers != binding.Initializers)
{
return Expression.ListBind(binding.Member, initializers);
}
return binding;
}
internal virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original)
{
List<MemberBinding> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
MemberBinding b = this.VisitBinding(original[i]);
if (list != null)
{
list.Add(b);
}
else if (b != original[i])
{
list = new List<MemberBinding>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(b);
}
}
if (list != null)
{
return list;
}
return original;
}
internal virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original)
{
List<ElementInit> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
ElementInit init = this.VisitElementInitializer(original[i]);
if (list != null)
{
list.Add(init);
}
else if (init != original[i])
{
list = new List<ElementInit>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(init);
}
}
if (list != null)
{
return list;
}
return original;
}
internal virtual Expression VisitLambda(LambdaExpression lambda)
{
Expression body = this.Visit(lambda.Body);
if (body != lambda.Body)
{
#if !ASTORIA_LIGHT
return Expression.Lambda(lambda.Type, body, lambda.Parameters);
#else
ParameterExpression[] parameters = new ParameterExpression[lambda.Parameters.Count];
lambda.Parameters.CopyTo(parameters, 0);
return ExpressionHelpers.CreateLambda(lambda.Type, body, parameters);
#endif
}
return lambda;
}
internal virtual NewExpression VisitNew(NewExpression nex)
{
IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments);
if (args != nex.Arguments)
{
if (nex.Members != null)
{
return Expression.New(nex.Constructor, args, nex.Members);
}
else
{
return Expression.New(nex.Constructor, args);
}
}
return nex;
}
internal virtual Expression VisitMemberInit(MemberInitExpression init)
{
NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings);
if (n != init.NewExpression || bindings != init.Bindings)
{
return Expression.MemberInit(n, bindings);
}
return init;
}
internal virtual Expression VisitListInit(ListInitExpression init)
{
NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers);
if (n != init.NewExpression || initializers != init.Initializers)
{
return Expression.ListInit(n, initializers);
}
return init;
}
internal virtual Expression VisitNewArray(NewArrayExpression na)
{
IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions);
if (exprs != na.Expressions)
{
if (na.NodeType == ExpressionType.NewArrayInit)
{
return Expression.NewArrayInit(na.Type.GetElementType(), exprs);
}
else
{
return Expression.NewArrayBounds(na.Type.GetElementType(), exprs);
}
}
return na;
}
internal virtual Expression VisitInvocation(InvocationExpression iv)
{
IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments);
Expression expr = this.Visit(iv.Expression);
if (args != iv.Arguments || expr != iv.Expression)
{
return Expression.Invoke(expr, args);
}
return iv;
}
}
}
| |
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Nuke.Common.Git;
using Nuke.Common.Utilities;
using Octokit;
using static Nuke.Common.IO.PathConstruction;
namespace Nuke.Common.Tools.GitHub
{
[PublicAPI]
public static class GitHubTasks
{
public static GitHubClient GitHubClient;
private static GitHubClient Client =>
GitHubClient ??= new GitHubClient(new ProductHeaderValue(nameof(NukeBuild)));
public static async Task<IEnumerable<(string DownloadUrl, string RelativePath)>> GetGitHubDownloadUrls(
this GitRepository repository,
string directory = null,
string branch = null)
{
Assert.True(repository.IsGitHubRepository());
Assert.True(!HasPathRoot(directory) || repository.LocalDirectory != null);
var relativeDirectory = HasPathRoot(directory)
? GetRelativePath(repository.LocalDirectory, directory)
: directory;
relativeDirectory = (relativeDirectory + "/").TrimStart("/");
branch ??= await repository.GetDefaultBranch();
var treeResponse = await Client.Git.Tree.GetRecursive(
repository.GetGitHubOwner(),
repository.GetGitHubName(),
branch);
return treeResponse.Tree
.Where(x => x.Type == TreeType.Blob)
.Where(x => x.Path.StartsWithOrdinalIgnoreCase(relativeDirectory))
.Select(x => (repository.GetGitHubDownloadUrl(x.Path, branch), x.Path.TrimStart(relativeDirectory)));
}
public static async Task<string> GetDefaultBranch(this GitRepository repository)
{
Assert.True(repository.IsGitHubRepository());
var repo = await Client.Repository.Get(repository.GetGitHubOwner(), repository.GetGitHubName());
return repo.DefaultBranch;
}
public static async Task<string> GetLatestRelease(this GitRepository repository, bool includePrerelease = false, bool trimPrefix = false)
{
Assert.True(repository.IsGitHubRepository());
var releases = await Client.Repository.Release.GetAll(repository.GetGitHubOwner(), repository.GetGitHubName());
return releases.First(x => !x.Prerelease || includePrerelease).TagName.TrimStart(trimPrefix ? "v" : string.Empty);
}
[ItemCanBeNull]
public static async Task<Milestone> GetGitHubMilestone(this GitRepository repository, string name)
{
Assert.True(repository.IsGitHubRepository());
var milestones = await Client.Issue.Milestone.GetAllForRepository(
repository.GetGitHubOwner(),
repository.GetGitHubName(),
new MilestoneRequest { State = ItemStateFilter.All });
return milestones.FirstOrDefault(x => x.Title == name);
}
public static async Task TryCreateGitHubMilestone(this GitRepository repository, string title)
{
try
{
await repository.CreateGitHubMilestone(title);
}
catch
{
// ignored
}
}
public static async Task CreateGitHubMilestone(this GitRepository repository, string title)
{
Assert.True(repository.IsGitHubRepository());
await Client.Issue.Milestone.Create(
repository.GetGitHubOwner(),
repository.GetGitHubName(),
new NewMilestone(title));
}
public static async Task CloseGitHubMilestone(this GitRepository repository, string title, bool enableIssueChecks = true)
{
Assert.True(repository.IsGitHubRepository());
var milestone = (await repository.GetGitHubMilestone(title)).NotNull("milestone != null");
if (enableIssueChecks)
{
Assert.True(milestone.OpenIssues == 0);
Assert.True(milestone.ClosedIssues != 0);
}
await Client.Issue.Milestone.Update(
repository.GetGitHubOwner(),
repository.GetGitHubName(),
milestone.Number,
new MilestoneUpdate { State = ItemState.Closed });
}
public static bool IsGitHubRepository(this GitRepository repository)
{
return repository != null && repository.Endpoint.EqualsOrdinalIgnoreCase("github.com");
}
public static string GetGitHubOwner(this GitRepository repository)
{
Assert.True(repository.IsGitHubRepository());
return repository.Identifier.Split('/')[0];
}
public static string GetGitHubName(this GitRepository repository)
{
Assert.True(repository.IsGitHubRepository());
return repository.Identifier.Split('/')[1];
}
public static string GetGitHubCompareCommitsUrl(this GitRepository repository, string startCommitSha, string endCommitSha)
{
Assert.True(repository.IsGitHubRepository());
return $"https://github.com/{repository.Identifier}/compare/{endCommitSha}^...{startCommitSha}";
}
public static string GetGitHubCompareTagToHeadUrl(this GitRepository repository, string tag)
{
Assert.True(repository.IsGitHubRepository());
return $"https://github.com/{repository.Identifier}/compare/{tag}...HEAD";
}
public static string GetGitHubCompareTagsUrl(this GitRepository repository, string startTag, string endTag)
{
Assert.True(repository.IsGitHubRepository());
return $"https://github.com/{repository.Identifier}/compare/{endTag}...{startTag}";
}
public static string GetGitHubCommitUrl(this GitRepository repository, string commitSha)
{
Assert.True(repository.IsGitHubRepository());
return $"https://github.com/{repository.Identifier}/commit/{commitSha}";
}
/// <summary>Url in the form of <c>https://raw.githubusercontent.com/{identifier}/{branch}/{file}</c>.</summary>
public static string GetGitHubDownloadUrl(this GitRepository repository, string file, string branch = null)
{
Assert.True(repository.IsGitHubRepository());
branch ??= repository.Branch.NotNull("repository.Branch != null");
var relativePath = GetRepositoryRelativePath(file, repository);
return $"https://raw.githubusercontent.com/{repository.Identifier}/{branch}/{relativePath}";
}
/// <summary>
/// Url in the form of <c>https://github.com/{identifier}/tree/{branch}/directory</c> or
/// <c>https://github.com/{identifier}/blob/{branch}/file</c> depending on the item type.
/// </summary>
public static string GetGitHubBrowseUrl(
this GitRepository repository,
string path = null,
string branch = null,
GitHubItemType itemType = GitHubItemType.Automatic)
{
Assert.True(repository.IsGitHubRepository());
branch ??= repository.Branch.NotNull();
var relativePath = GetRepositoryRelativePath(path, repository);
var method = GetMethod(relativePath, itemType, repository);
Assert.True(path == null || method != null, "Could not determine item type");
return $"https://github.com/{repository.Identifier}/{method}/{branch}/{relativePath}".TrimEnd("/");
}
[CanBeNull]
private static string GetMethod([CanBeNull] string relativePath, GitHubItemType itemType, GitRepository repository)
{
var absolutePath = repository.LocalDirectory != null && relativePath != null
? NormalizePath(Path.Combine(repository.LocalDirectory, relativePath))
: null;
if (itemType == GitHubItemType.Directory || Directory.Exists(absolutePath) || relativePath == null)
return "tree";
if (itemType == GitHubItemType.File || File.Exists(absolutePath))
return "blob";
return null;
}
[ContractAnnotation("path: null => null; path: notnull => notnull")]
private static string GetRepositoryRelativePath([CanBeNull] string path, GitRepository repository)
{
if (path == null)
return null;
if (!Path.IsPathRooted(path))
return path;
var localDirectory = repository.LocalDirectory.NotNull();
Assert.True(IsDescendantPath(localDirectory, path), $"Path {path.SingleQuote()} must be descendant of {localDirectory.SingleQuote()}");
return GetRelativePath(localDirectory, path).Replace(oldChar: '\\', newChar: '/');
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using ServiceStack.DataAnnotations;
using ServiceStack.DesignPatterns.Model;
namespace ServiceStack.Text.Tests.Support
{
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class UserPublicView
{
/// <summary>
/// I'm naming this 'Id' instead of 'UserId' as this is dto is
/// meant to be cached and we may want to handle all caches generically at some point.
/// </summary>
/// <value>The id.</value>
[DataMember]
public Guid Id { get; set; }
[DataMember]
public UserPublicProfile Profile { get; set; }
[DataMember]
public ArrayOfPost Posts { get; set; }
}
[Serializable]
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class UserPublicProfile
{
public UserPublicProfile()
{
this.FollowerUsers = new List<UserSearchResult>();
this.FollowingUsers = new List<UserSearchResult>();
this.UserFileTypes = new ArrayOfString();
}
[DataMember]
public Guid Id
{
get;
set;
}
[DataMember]
public string UserType
{
get;
set;
}
[DataMember]
public string UserName
{
get;
set;
}
[DataMember]
public string FullName
{
get;
set;
}
[DataMember]
public string Country
{
get;
set;
}
[DataMember]
public string LanguageCode
{
get;
set;
}
[DataMember]
public DateTime? DateOfBirth
{
get;
set;
}
[DataMember]
public DateTime? LastLoginDate
{
get;
set;
}
[DataMember]
public long FlowPostCount
{
get;
set;
}
[DataMember]
public int BuyCount
{
get;
set;
}
[DataMember]
public int ClientTracksCount
{
get;
set;
}
[DataMember]
public int ViewCount
{
get;
set;
}
[DataMember]
public List<UserSearchResult> FollowerUsers
{
get;
set;
}
[DataMember]
public List<UserSearchResult> FollowingUsers
{
get;
set;
}
///ArrayOfString causes translation error
[DataMember]
public ArrayOfString UserFileTypes
{
get;
set;
}
[DataMember]
public string OriginalProfileBase64Hash
{
get;
set;
}
[DataMember]
public string AboutMe
{
get;
set;
}
}
[Serializable]
[CollectionDataContract(Namespace = "http://schemas.ddnglobal.com/types/", ItemName = "String")]
public class ArrayOfString : List<string>
{
public ArrayOfString() { }
public ArrayOfString(IEnumerable<string> collection) : base(collection) { }
//TODO: allow params[] constructor, fails on:
//Profile = user.TranslateTo<UserPrivateProfile>()
public static ArrayOfString New(params string[] ids) { return new ArrayOfString(ids); }
//public ArrayOfString(params string[] ids) : base(ids) { }
}
[Serializable]
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class UserSearchResult
: IHasId<Guid>
{
[DataMember]
public Guid Id { get; set; }
[DataMember(EmitDefaultValue = false)]
public string UserType { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember(EmitDefaultValue = false)]
public string FullName { get; set; }
[DataMember(EmitDefaultValue = false)]
public string FirstName { get; set; }
[DataMember(EmitDefaultValue = false)]
public string LastName { get; set; }
[DataMember(EmitDefaultValue = false)]
public string LanguageCode { get; set; }
[DataMember(EmitDefaultValue = false)]
public int FlowPostCount { get; set; }
[DataMember(EmitDefaultValue = false)]
public int ClientTracksCount { get; set; }
[DataMember(EmitDefaultValue = false)]
public int FollowingCount { get; set; }
[DataMember(EmitDefaultValue = false)]
public int FollowersCount { get; set; }
[DataMember(EmitDefaultValue = false)]
public int ViewCount { get; set; }
[DataMember(EmitDefaultValue = false)]
public DateTime ActivationDate { get; set; }
}
[Serializable]
[CollectionDataContract(Namespace = "http://schemas.ddnglobal.com/types/", ItemName = "Post")]
public class ArrayOfPost : List<Post>
{
public ArrayOfPost() { }
public ArrayOfPost(IEnumerable<Post> collection) : base(collection) { }
public static ArrayOfPost New(params Post[] ids) { return new ArrayOfPost(ids); }
}
[Serializable]
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class Post
: IHasStringId
{
public Post()
{
this.TrackUrns = new ArrayOfStringId();
}
public string Id
{
get { return this.Urn; }
}
[DataMember]
public string Urn
{
get;
set;
}
[DataMember]
public DateTime DateAdded
{
get;
set;
}
[DataMember]
public bool CanPreviewFullLength
{
get;
set;
}
[DataMember]
public Guid OriginUserId
{
get;
set;
}
[DataMember]
public string OriginUserName
{
get;
set;
}
[DataMember]
public Guid SourceUserId
{
get;
set;
}
[DataMember]
public string SourceUserName
{
get;
set;
}
[DataMember]
public string SubjectUrn
{
get;
set;
}
[DataMember]
public string ContentUrn
{
get;
set;
}
[DataMember]
public ArrayOfStringId TrackUrns
{
get;
set;
}
[DataMember]
public string Caption
{
get;
set;
}
[DataMember]
public Guid CaptionUserId
{
get;
set;
}
[DataMember]
public string CaptionUserName
{
get;
set;
}
[DataMember]
public string PostType
{
get;
set;
}
[DataMember]
public Guid? OnBehalfOfUserId
{
get;
set;
}
}
[CollectionDataContract(Namespace = "http://schemas.ddnglobal.com/types/", ItemName = "Id")]
public class ArrayOfStringId : List<string>
{
public ArrayOfStringId() { }
public ArrayOfStringId(IEnumerable<string> collection) : base(collection) { }
//TODO: allow params[] constructor, fails on: o.TranslateTo<ArrayOfStringId>()
public static ArrayOfStringId New(params string[] ids) { return new ArrayOfStringId(ids); }
//public ArrayOfStringId(params string[] ids) : base(ids) { }
}
public enum FlowPostType
{
Content,
Text,
Promo,
}
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class Property
{
public Property()
{
}
public Property(string name, string value)
{
this.Name = name;
this.Value = value;
}
[DataMember]
public string Name
{
get;
set;
}
[DataMember]
public string Value
{
get;
set;
}
public override string ToString()
{
return this.Name + "," + this.Value;
}
}
[CollectionDataContract(Namespace = "http://schemas.ddnglobal.com/types/", ItemName = "Property")]
public class Properties
: List<Property>
{
public Properties()
{
}
public Properties(IEnumerable<Property> collection)
: base(collection)
{
}
public string GetPropertyValue(string name)
{
foreach (var property in this)
{
if (string.CompareOrdinal(property.Name, name) == 0)
{
return property.Value;
}
}
return null;
}
public Dictionary<string, string> ToDictionary()
{
var propertyDict = new Dictionary<string, string>();
foreach (var property in this)
{
propertyDict[property.Name] = property.Value;
}
return propertyDict;
}
}
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class ResponseStatus
{
/// <summary>
/// Initializes a new instance of the <see cref="ResponseStatus"/> class.
///
/// A response status without an errorcode == success
/// </summary>
public ResponseStatus()
{
this.Errors = new List<ResponseError>();
}
[DataMember(EmitDefaultValue = false, IsRequired = false)]
public string ErrorCode { get; set; }
[DataMember(EmitDefaultValue = false, IsRequired = false)]
public string Message { get; set; }
[DataMember(EmitDefaultValue = false, IsRequired = false)]
public string StackTrace { get; set; }
[DataMember(EmitDefaultValue = false, IsRequired = false)]
public List<ResponseError> Errors { get; set; }
public bool IsSuccess
{
get { return this.ErrorCode == null; }
}
}
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class ResponseError
{
[DataMember]
public string ErrorCode { get; set; }
[DataMember]
public string FieldName { get; set; }
[DataMember]
public string Message { get; set; }
}
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class GetContentStatsResponse
: IExtensibleDataObject
{
public GetContentStatsResponse()
{
this.Version = 100;
this.ResponseStatus = new ResponseStatus();
this.TopRecommenders = new List<UserSearchResult>();
this.LatestPosts = new List<Post>();
}
[DataMember]
public DateTime CreatedDate { get; set; }
[DataMember]
public List<UserSearchResult> TopRecommenders { get; set; }
[DataMember]
public List<Post> LatestPosts { get; set; }
#region Standard Response Properties
[DataMember]
public int Version
{
get;
set;
}
[DataMember]
public Properties Properties
{
get;
set;
}
public ExtensionDataObject ExtensionData
{
get;
set;
}
[DataMember]
public ResponseStatus ResponseStatus
{
get;
set;
}
#endregion
}
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class ProUserPublicProfile
{
public ProUserPublicProfile()
{
this.SocialLinks = new List<SocialLinkUrl>();
this.ArtistImages = new List<ImageAsset>();
this.Genres = new List<string>();
this.Posts = new ArrayOfPost();
this.FollowerUsers = new List<UserSearchResult>();
this.FollowingUsers = new List<UserSearchResult>();
}
[DataMember]
public Guid Id { get; set; }
[DataMember]
public string Alias { get; set; }
[DataMember]
public string RefUrn { get; set; }
[DataMember]
public string ProUserType { get; set; }
[DataMember]
public string ProUserSalesType { get; set; }
#region Header
[DataMember]
public TextLink ProUserLink { get; set; }
/// <summary>
/// Same as above but in an [A] HTML link
/// </summary>
[DataMember]
public string ProUserLinkHtml { get; set; }
/// <summary>
/// For the twitter and facebook icons
/// </summary>
[DataMember]
public List<SocialLinkUrl> SocialLinks { get; set; }
#endregion
#region Theme
[DataMember]
public ImageAsset BannerImage { get; set; }
[DataMember]
public string BannerImageBackgroundColor { get; set; }
[DataMember]
public List<string> UserFileTypes { get; set; }
[DataMember]
public string OriginalProfileBase64Hash { get; set; }
#endregion
#region Music
[DataMember]
public List<ImageAsset> ArtistImages { get; set; }
[DataMember]
public List<string> Genres { get; set; }
#endregion
#region Biography
[DataMember]
public string BiographyPageHtml { get; set; }
#endregion
#region Outbox
[DataMember]
public ArrayOfPost Posts { get; set; }
[DataMember]
public List<UserSearchResult> FollowerUsers { get; set; }
[DataMember]
public int FollowerUsersCount { get; set; }
[DataMember]
public List<UserSearchResult> FollowingUsers { get; set; }
[DataMember]
public int FollowingUsersCount { get; set; }
#endregion
}
public enum SocialLink
{
iTunes = 0,
Bebo = 1,
Blogger = 2,
Delicious = 3,
Digg = 4,
Email = 5,
EverNote = 6,
Facebook = 7,
Flickr = 8,
FriendFeed = 9,
GoogleWave = 10,
GroveShark = 11,
iLike = 12,
LastFm = 13,
Mix = 14,
MySpace = 15,
Posterous = 16,
Reddit = 17,
Rss = 18,
StumbleUpon = 19,
Twitter = 20,
Vimeo = 21,
Wikipedia = 22,
WordPress = 23,
Yahoo = 24,
YahooBuzz = 25,
YouTube = 26,
}
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class SocialLinkUrl
{
[References(typeof(SocialLink))]
[DataMember(EmitDefaultValue = false)]
public string Name
{
get;
set;
}
[DataMember]
public string LinkUrl
{
get;
set;
}
}
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
[Serializable]
public class ImageAsset
{
[DataMember(EmitDefaultValue = false)]
public string RelativePath { get; set; }
[DataMember(EmitDefaultValue = false)]
public string AbsoluteUrl { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Hash { get; set; }
[DataMember(EmitDefaultValue = false)]
public long? SizeBytes { get; set; }
[DataMember(EmitDefaultValue = false)]
public int? Width { get; set; }
[DataMember(EmitDefaultValue = false)]
public int? Height { get; set; }
[DataMember(EmitDefaultValue = false)]
public string BackgroundColorHex { get; set; }
}
[DataContract(Namespace = "http://schemas.ddnglobal.com/types/")]
public class TextLink
{
[DataMember(EmitDefaultValue = false)]
public string Label
{
get;
set;
}
[DataMember]
public string LinkUrl
{
get;
set;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.Tracing;
using Xunit;
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using Microsoft.Diagnostics.Tracing.Session;
#endif
using System.Diagnostics;
namespace BasicEventSourceTests
{
internal enum Color { Red, Blue, Green };
internal enum ColorUInt32 : uint { Red, Blue, Green };
internal enum ColorByte : byte { Red, Blue, Green };
internal enum ColorSByte : sbyte { Red, Blue, Green };
internal enum ColorInt16 : short { Red, Blue, Green };
internal enum ColorUInt16 : ushort { Red, Blue, Green };
internal enum ColorInt64 : long { Red, Blue, Green };
internal enum ColorUInt64 : ulong { Red, Blue, Green };
public class TestsWrite
{
[EventData]
private struct PartB_UserInfo
{
public string UserName { get; set; }
}
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the EventListener code path
/// </summary>
[Fact]
public void Test_Write_T_EventListener()
{
using (var listener = new EventListenerListener())
{
Test_Write_T(listener);
}
}
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the EventListener code path using events instead of virtual callbacks.
/// </summary>
[Fact]
public void Test_Write_T_EventListener_UseEvents()
{
Test_Write_T(new EventListenerListener(true));
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/// <summary>
/// Tests the EventSource.Write[T] method (can only use the self-describing mechanism).
/// Tests the ETW code path
/// </summary>
[Fact]
public void Test_Write_T_ETW()
{
using (var listener = new EtwListener())
{
Test_Write_T(listener);
}
}
#endif //USE_ETW
/// <summary>
/// Te
/// </summary>
/// <param name="listener"></param>
private void Test_Write_T(Listener listener)
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var logger = new EventSource("EventSourceName"))
{
var tests = new List<SubTest>();
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/String",
delegate ()
{
logger.Write("Greeting", new { msg = "Hello, world!" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Greeting", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "msg"), "Hello, world!");
}));
/*************************************************************************/
decimal myMoney = 300;
tests.Add(new SubTest("Write/Basic/decimal",
delegate ()
{
logger.Write("Decimal", new { money = myMoney });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Decimal", evt.EventName);
var eventMoney = evt.PayloadValue(0, "money");
// TOD FIX ME - Fix TraceEvent to return decimal instead of double.
//Assert.Equal((decimal)eventMoney, (decimal)300);
}));
/*************************************************************************/
DateTime now = DateTime.Now;
tests.Add(new SubTest("Write/Basic/DateTime",
delegate ()
{
logger.Write("DateTime", new { nowTime = now });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("DateTime", evt.EventName);
var eventNow = evt.PayloadValue(0, "nowTime");
Assert.Equal(eventNow, now);
}));
/*************************************************************************/
byte[] byteArray = { 0, 1, 2, 3 };
tests.Add(new SubTest("Write/Basic/byte[]",
delegate ()
{
logger.Write("Bytes", new { bytes = byteArray });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Bytes", evt.EventName);
var eventArray = evt.PayloadValue(0, "bytes");
Array.Equals(eventArray, byteArray);
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/PartBOnly",
delegate ()
{
// log just a PartB
logger.Write("UserInfo", new EventSourceOptions { Keywords = EventKeywords.None },
new { _1 = new PartB_UserInfo { UserName = "Someone Else" } });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("UserInfo", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Someone Else");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/PartBAndC",
delegate ()
{
// log a PartB and a PartC
logger.Write("Duration", new EventSourceOptions { Keywords = EventKeywords.None },
new { _1 = new PartB_UserInfo { UserName = "Myself" }, msec = 10 });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("Duration", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Myself");
Assert.Equal(evt.PayloadValue(1, "msec"), 10);
}));
/*************************************************************************/
/*************************** ENUM TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
GenerateEnumTest<Color>(ref tests, logger, Color.Green);
GenerateEnumTest<ColorUInt32>(ref tests, logger, ColorUInt32.Green);
GenerateEnumTest<ColorByte>(ref tests, logger, ColorByte.Green);
GenerateEnumTest<ColorSByte>(ref tests, logger, ColorSByte.Green);
GenerateEnumTest<ColorInt16>(ref tests, logger, ColorInt16.Green);
GenerateEnumTest<ColorUInt16>(ref tests, logger, ColorUInt16.Green);
GenerateEnumTest<ColorInt64>(ref tests, logger, ColorInt64.Green);
GenerateEnumTest<ColorUInt64>(ref tests, logger, ColorUInt64.Green);
/*************************************************************************/
/*************************** ARRAY TESTING *******************************/
/*************************************************************************/
/*************************************************************************/
GenerateArrayTest<Boolean>(ref tests, logger, new Boolean[] { false, true, false });
GenerateArrayTest<byte>(ref tests, logger, new byte[] { 1, 10, 100 });
GenerateArrayTest<sbyte>(ref tests, logger, new sbyte[] { 1, 10, 100 });
GenerateArrayTest<Int16>(ref tests, logger, new Int16[] { 1, 10, 100 });
GenerateArrayTest<UInt16>(ref tests, logger, new UInt16[] { 1, 10, 100 });
GenerateArrayTest<Int32>(ref tests, logger, new Int32[] { 1, 10, 100 });
GenerateArrayTest<UInt32>(ref tests, logger, new UInt32[] { 1, 10, 100 });
GenerateArrayTest<Int64>(ref tests, logger, new Int64[] { 1, 10, 100 });
GenerateArrayTest<UInt64>(ref tests, logger, new UInt64[] { 1, 10, 100 });
GenerateArrayTest<Char>(ref tests, logger, new Char[] { 'a', 'c', 'b' });
GenerateArrayTest<Double>(ref tests, logger, new Double[] { 1, 10, 100 });
GenerateArrayTest<Single>(ref tests, logger, new Single[] { 1, 10, 100 });
GenerateArrayTest<IntPtr>(ref tests, logger, new IntPtr[] { (IntPtr)1, (IntPtr)10, (IntPtr)100 });
GenerateArrayTest<UIntPtr>(ref tests, logger, new UIntPtr[] { (UIntPtr)1, (UIntPtr)10, (UIntPtr)100 });
GenerateArrayTest<Guid>(ref tests, logger, new Guid[] { Guid.Empty, new Guid("121a11ee-3bcb-49cc-b425-f4906fb14f72") });
/*************************************************************************/
/*********************** DICTIONARY TESTING ******************************/
/*************************************************************************/
var dict = new Dictionary<string, string>() { { "elem1", "10" }, { "elem2", "20" } };
var dictInt = new Dictionary<string, int>() { { "elem1", 10 }, { "elem2", 20 } };
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithStringDict_C",
delegate()
{
// log a dictionary
logger.Write("EventWithStringDict_C", new {
myDict = dict,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithStringDict_C", evt.EventName);
var keyValues = evt.PayloadValue(0, "myDict");
IDictionary<string, object> vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.Equal(vDict["elem1"], "10");
Assert.Equal(vDict["elem2"], "20");
Assert.Equal(evt.PayloadValue(1, "s"), "end");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithStringDict_BC",
delegate()
{
// log a PartB and a dictionary as a PartC
logger.Write("EventWithStringDict_BC", new {
PartB_UserInfo = new { UserName = "Me", LogTime = "Now" },
PartC_Dict = dict,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithStringDict_BC", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Me");
Assert.Equal(structValueAsDictionary["LogTime"], "Now");
var keyValues = evt.PayloadValue(1, "PartC_Dict");
var vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.NotNull(dict);
Assert.Equal(vDict["elem1"], "10"); // string values.
Assert.Equal(vDict["elem2"], "20");
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
/*************************************************************************/
tests.Add(new SubTest("Write/Dict/EventWithIntDict_BC",
delegate()
{
// log a Dict<string, int> as a PartC
logger.Write("EventWithIntDict_BC", new {
PartB_UserInfo = new { UserName = "Me", LogTime = "Now" },
PartC_Dict = dictInt,
s = "end" });
},
delegate(Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EventWithIntDict_BC", evt.EventName);
var structValue = evt.PayloadValue(0, "PartB_UserInfo");
var structValueAsDictionary = structValue as IDictionary<string, object>;
Assert.NotNull(structValueAsDictionary);
Assert.Equal(structValueAsDictionary["UserName"], "Me");
Assert.Equal(structValueAsDictionary["LogTime"], "Now");
var keyValues = evt.PayloadValue(1, "PartC_Dict");
var vDict = GetDictionaryFromKeyValueArray(keyValues);
Assert.NotNull(vDict);
Assert.Equal(vDict["elem1"], 10); // Notice they are integers, not strings.
Assert.Equal(vDict["elem2"], 20);
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
/*************************************************************************/
/**************************** Empty Event TESTING ************************/
/*************************************************************************/
tests.Add(new SubTest("Write/Basic/Message",
delegate ()
{
logger.Write("EmptyEvent");
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EmptyEvent", evt.EventName);
}));
/*************************************************************************/
/**************************** EventSourceOptions TESTING *****************/
/*************************************************************************/
EventSourceOptions options = new EventSourceOptions();
options.Level = EventLevel.LogAlways;
options.Keywords = EventKeywords.All;
options.Opcode = EventOpcode.Info;
options.Tags = EventTags.None;
tests.Add(new SubTest("Write/Basic/MessageOptions",
delegate ()
{
logger.Write("EmptyEvent", options);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EmptyEvent", evt.EventName);
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios",
delegate ()
{
logger.Write("OptionsEvent", options, new { OptionsEvent = "test options!" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("OptionsEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test options!");
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithRefOptios",
delegate ()
{
var v = new { OptionsEvent = "test ref options!" };
logger.Write("RefOptionsEvent", ref options, ref v);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("RefOptionsEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test ref options!");
}));
tests.Add(new SubTest("Write/Basic/WriteOfTWithNullString",
delegate ()
{
string nullString = null;
logger.Write("NullStringEvent", new { a = (string)null, b = nullString });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("NullStringEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "a"), "");
Assert.Equal(evt.PayloadValue(1, "b"), "");
}));
Guid activityId = new Guid("00000000-0000-0000-0000-000000000001");
Guid relActivityId = new Guid("00000000-0000-0000-0000-000000000002");
tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios",
delegate ()
{
var v = new { ActivityMsg = "test activity!" };
logger.Write("ActivityEvent", ref options, ref activityId, ref relActivityId, ref v);
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("ActivityEvent", evt.EventName);
Assert.Equal(evt.PayloadValue(0, "ActivityMsg"), "test activity!");
}));
// If you only wish to run one or several of the tests you can filter them here by
// Uncommenting the following line.
// tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII"));
// Here is where we actually run tests. First test the ETW path
EventTestHarness.RunTests(tests, listener, logger);
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
/// <summary>
/// This is not a user error but it is something unusual.
/// You can use the Write API in a EventSource that was did not
/// Declare SelfDescribingSerialization. In that case THOSE
/// events MUST use SelfDescribing serialization.
/// </summary>
[Fact]
public void Test_Write_T_In_Manifest_Serialization()
{
using (var eventListener = new EventListenerListener())
{
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using (var etwListener = new EtwListener())
#endif
{
var listenerGenerators = new Func<Listener>[]
{
() => eventListener,
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
() => etwListener
#endif // USE_ETW
};
foreach (Func<Listener> listenerGenerator in listenerGenerators)
{
var events = new List<Event>();
using (var listener = listenerGenerator())
{
Debug.WriteLine("Testing Listener " + listener);
// Create an eventSource with manifest based serialization
using (var logger = new SdtEventSources.EventSourceTest())
{
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceSynchronousEnable(logger);
// Use the Write<T> API. This is OK
logger.Write("MyTestEvent", new { arg1 = 3, arg2 = "hi" });
}
}
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("MyTestEvent", _event.EventName);
Assert.Equal(3, (int)_event.PayloadValue(0, "arg1"));
Assert.Equal("hi", (string)_event.PayloadValue(1, "arg2"));
}
}
}
}
private void GenerateEnumTest<T>(ref List<SubTest> tests, EventSource logger, T enumValue)
{
string subTestName = enumValue.GetType().ToString();
tests.Add(new SubTest("Write/Enum/EnumEvent" + subTestName,
delegate ()
{
T c = enumValue;
// log an array
logger.Write("EnumEvent" + subTestName, new { b = "start", v = c, s = "end" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("EnumEvent" + subTestName, evt.EventName);
Assert.Equal(evt.PayloadValue(0, "b"), "start");
if (evt.IsEtw)
{
var value = evt.PayloadValue(1, "v");
Assert.Equal(2, int.Parse(value.ToString())); // Green has the int value of 2.
}
else
{
Assert.Equal(evt.PayloadValue(1, "v"), enumValue);
}
Assert.Equal(evt.PayloadValue(2, "s"), "end");
}));
}
private void GenerateArrayTest<T>(ref List<SubTest> tests, EventSource logger, T[] array)
{
string typeName = array.GetType().GetElementType().ToString();
tests.Add(new SubTest("Write/Array/" + typeName,
delegate ()
{
// log an array
logger.Write("SomeEvent" + typeName, new { a = array, s = "end" });
},
delegate (Event evt)
{
Assert.Equal(logger.Name, evt.ProviderName);
Assert.Equal("SomeEvent" + typeName, evt.EventName);
var eventArray = evt.PayloadValue(0, "a");
Array.Equals(array, eventArray);
Assert.Equal("end", evt.PayloadValue(1, "s"));
}));
}
/// <summary>
/// Convert an array of key value pairs (as ETW structs) into a dictionary with those values.
/// </summary>
/// <param name="structValue"></param>
/// <returns></returns>
private IDictionary<string, object> GetDictionaryFromKeyValueArray(object structValue)
{
var ret = new Dictionary<string, object>();
var asArray = structValue as object[];
Assert.NotNull(asArray);
foreach (var item in asArray)
{
var keyValue = item as IDictionary<string, object>;
Assert.Equal(keyValue.Count, 2);
ret.Add((string)keyValue["Key"], keyValue["Value"]);
}
return ret;
}
}
}
| |
using Newtonsoft.Json.Linq;
using SharpDX;
using System;
using System.Collections.Generic;
using System.IO;
public class RawImageInfo {
public FileInfo file;
public float gamma;
}
public class RawColorTexture {
public Vector3 value;
public RawImageInfo image;
}
public class RawFloatTexture {
public float value;
public RawImageInfo image;
}
public class MaterialBag {
public const string IrayUberType = "studio/material/uber_iray";
public const string DazBrickType = "studio/material/daz_brick";
private readonly ContentFileLocator fileLocator;
private readonly DsonObjectLocator objectLocator;
private readonly Dictionary<string, DsonTypes.Image> imagesByUrl;
private readonly HashSet<string> extraTypes;
private readonly Dictionary<string, object> values;
public MaterialBag(ContentFileLocator fileLocator, DsonObjectLocator objectLocator, Dictionary<string, DsonTypes.Image> imagesByUrl) : this(
fileLocator, objectLocator, imagesByUrl,
new HashSet<string>(),
new Dictionary<string, object>()) {
}
public MaterialBag(ContentFileLocator fileLocator, DsonObjectLocator objectLocator, Dictionary<string, DsonTypes.Image> imagesByUrl, HashSet<string> extraTypes, Dictionary<string, object> values) {
this.fileLocator = fileLocator;
this.objectLocator = objectLocator;
this.imagesByUrl = imagesByUrl;
this.extraTypes = extraTypes;
this.values = values;
}
public MaterialBag Branch() {
var branchedExtraTypes = new HashSet<string>(extraTypes);
var branchedValues = new Dictionary<string, object>(values);
return new MaterialBag(fileLocator, objectLocator, imagesByUrl, branchedExtraTypes, branchedValues);
}
public void AddExtraType(string type) {
extraTypes.Add(type);
}
public bool HasExtraType(string type) {
return extraTypes.Contains(type);
}
private object GetValue(string channelName, string propertyName) {
string url = Uri.EscapeUriString(channelName) + "/" + propertyName;
values.TryGetValue(url, out object val);
return val;
}
private object GetValue(string propertyName) {
string url = Uri.EscapeUriString(propertyName);
values.TryGetValue(url, out object val);
return val;
}
public void SetValue(string channelName, string propertyName, object val) {
if (val == null) {
return;
}
string url = Uri.EscapeUriString(channelName) + "/" + propertyName;
values[url] = val;
}
public void SetValue(string propertyName, object val) {
if (val == null) {
return;
}
string url = Uri.EscapeUriString(propertyName);
values[url] = val;
}
public void RemoveByUrl(string url) {
values.Remove(url);
}
public void SetByUrl(string url, object val) {
values[url] = val;
}
private object GetNonNullValue(string channelName, string propertyName) {
object value = GetValue(channelName, propertyName);
if (value == null) {
throw new NullReferenceException();
}
return value;
}
public int ExtractInteger(string channelName) {
return Convert.ToInt32(GetNonNullValue(channelName, "value"));
}
public bool ExtractBoolean(string channelName) {
return Convert.ToBoolean(GetNonNullValue(channelName, "value"));
}
public float ExtractFloat(string channelName) {
return Convert.ToSingle(GetNonNullValue(channelName, "value"));
}
private float ExtractScale(string channelName) {
object val = GetValue(channelName, "image_modification/scale");
return val != null ? Convert.ToSingle(val) : 1f;
}
public RawImageInfo ExtractImage(string channelName) {
string imageUrl = (string) GetValue(channelName, "image_file");
if (imageUrl == null) {
return null;
}
if (!imagesByUrl.TryGetValue(imageUrl, out var image)) {
//use a default setting
image = new DsonTypes.Image {
map_gamma = 0
};
}
string texturePath = Uri.UnescapeDataString(imageUrl);
FileInfo textureFile = fileLocator.Locate(texturePath).File;
return new RawImageInfo {
file = textureFile,
gamma = image.map_gamma
};
}
public Vector3 ExtractColor(string channelName) {
Vector3 color = new Vector3();
object val = GetValue(channelName, "value");
switch (val) {
case JArray arrayValue:
float[] values = arrayValue.ToObject<float[]>();
color[0] = values[0];
color[1] = values[1];
color[2] = values[2];
break;
case null:
color = Vector3.Zero;
break;
default:
throw new InvalidOperationException("expected a color:" + channelName);
}
color = ColorUtils.SrgbToLinear(color);
return color;
}
public RawColorTexture ExtractColorTexture(string channelName) {
var texture = new RawColorTexture {
image = ExtractImage(channelName),
value = ExtractColor(channelName) * ExtractScale(channelName)
};
return texture;
}
public RawFloatTexture ExtractFloatTexture(string channelName) {
var texture = new RawFloatTexture {
image = ExtractImage(channelName),
value = ExtractFloat(channelName) * ExtractScale(channelName)
};
return texture;
}
public string ExtractUvSetName(Figure figure) {
object uvUrl = GetValue( "uv_set");
string uvName;
if (uvUrl.Equals(0L)) {
uvName = figure.DefaultUvSet.Name;
} else {
uvName = objectLocator.Locate((string) uvUrl).name;
if (!figure.UvSets.TryGetValue(uvName, out var ignore)) {
if (uvName == "default") {
//hack to handle uv-set for genital graft
uvName = figure.DefaultUvSet.Name;
} else {
throw new InvalidOperationException("unrecognized UV set: " + uvName);
}
}
}
return uvName;
}
}
| |
// 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.Threading;
interface IGen<T>
{
void Target(object p);
T Dummy(T t);
}
class GenInt : IGen<int>
{
public int Dummy(int t) { return t; }
public void Target(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<int> obj = new GenInt();
TimerCallback tcb = new TimerCallback(obj.Target);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
class GenDouble : IGen<double>
{
public double Dummy(double t) { return t; }
public void Target(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<double> obj = new GenDouble();
TimerCallback tcb = new TimerCallback(obj.Target);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
class GenString : IGen<string>
{
public string Dummy(string t) { return t; }
public void Target(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<string> obj = new GenString();
TimerCallback tcb = new TimerCallback(obj.Target);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
class GenObject : IGen<object>
{
public object Dummy(object t) { return t; }
public void Target(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<object> obj = new GenObject();
TimerCallback tcb = new TimerCallback(obj.Target);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
class GenGuid : IGen<Guid>
{
public Guid Dummy(Guid t) { return t; }
public void Target(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<Guid> obj = new GenGuid();
TimerCallback tcb = new TimerCallback(obj.Target);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
public class Test
{
public static int delay = 0;
public static int period = 2;
public static int nThreads = 5;
public static int counter = 0;
public static int Xcounter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
GenInt.ThreadPoolTest();
GenDouble.ThreadPoolTest();
GenString.ThreadPoolTest();
GenObject.ThreadPoolTest();
GenGuid.ThreadPoolTest();
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| |
#nullable disable
// -----------------------------------------------------------------------------
// <copyright file="DemTile.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <createdby>bretm</createdby><creationdate>2006-01-10</creationdate>
// -----------------------------------------------------------------------------
using System;
namespace WWT.Maps
{
/// <summary>
/// Represents a Digital Elevation Map tile.
/// Copy of $\VirtualEarth\Main\Metropolis\Applications\DEMPipeline\DemPipeline\DemTile.cs
/// with deleted functionality that is not needed for FL.
/// </summary>
public class DemTile
{
/// <summary>
/// An elevation value equal to 'NoData' represents a sample of
/// unknown elevation. For "double" type, use double.NaN instead.
/// </summary>
public const int NoData = short.MinValue;
int width; // number of columns
int height; // number of rows
int returned; // 1 == true, and the object is invalid
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Member")]
short[,] altitude; // altitude values in arbitrary linear scale
/// <summary>
/// Create a default 257x257 DEM tile at 1m per unit of altitude,
/// initialized to NoData.
/// </summary>
public DemTile() : this(257, 257)
{
}
/// <summary>
/// Constructs a new DemTile width the passed in size.
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
public DemTile(int width, int height)
{
if (width < 0)
throw new ArgumentOutOfRangeException("width");
if (height < 0)
throw new ArgumentOutOfRangeException("height");
this.width = width;
this.height = height;
altitude = new short[height, width];
for (int row = 0; row < height; row++)
for (int col = 0; col < width; col++)
{
altitude[row, col] = DemTile.NoData;
}
}
/// <summary>
/// Constructs a new DemTile and fills it with the passed in data.
/// </summary>
/// <param name="data"></param>
public DemTile(short[,] data)
{
if (data == null)
throw new ArgumentNullException("data");
this.width = data.GetLength(1);
this.height = data.GetLength(0);
this.altitude = data;
}
/// <summary>
/// If true, the DemTile is safe to use. If false, the DemTile was returned to the Codec and cannot be used.
/// </summary>
public bool IsValid
{
get { return returned == 0; }
set
{
System.Threading.Interlocked.Exchange(ref returned, value ? 1 : 0);
altitude = null;
}
}
/// <summary>
/// Returns true if the tile contains only one elevation value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
public bool IsSingleValued(out short value)
{
if (!IsValid) throw new InvalidOperationException();
value = altitude[0, 0];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (altitude[y, x] != value)
{
return false;
}
}
}
return true;
}
/// <summary>
/// Retrieves the width of the DemTile.
/// </summary>
public int Width
{
get { return width; }
}
/// <summary>
/// Retrieves the height of the DemTile.
/// </summary>
public int Height
{
get { return height; }
}
/// <summary>
/// Make sure the row and column values are valid.
/// </summary>
/// <param name="row"></param>
/// <param name="col"></param>
private void ValidateRowCol(int row, int col)
{
if (row < 0 || row >= height)
throw new ArgumentOutOfRangeException("row");
if (col < 0 || col >= width)
throw new ArgumentOutOfRangeException("col");
}
/// <summary>
/// Look up an individual altitude sample.
/// </summary>
/// <param name="row"></param>
/// <param name="col"></param>
/// <returns>Returns the altitude sample in arbitrary units.
/// Use DemTile.AltitudeInMeters to obtain the value in meters.</returns>
public short this[int row, int col]
{
get
{
if (!IsValid) throw new InvalidOperationException();
ValidateRowCol(row, col);
return altitude[row, col];
}
set
{
if (!IsValid) throw new InvalidOperationException();
altitude[row, col] = value;
}
}
// non-linear altitude scale
static object[] scale = new object[] {
// description, meters, resolution,
"Marianas Trench", -11030.0, 10.0, // 10m per unit
"lowest city", -280.0, 0.1, // 10cm per unit
"sea level", 0.0, 0.01, // 1cm per unit
"highest city", 5099.0, 0.2, // 20cm per unit
"Mount Everest", 8872.0,
};
const short scaleMinIndex = -32767;
const short scaleMaxIndex = short.MaxValue;
private static double[] scaleMeters = CalculateScaleMeters();
private static double[] CalculateScaleMeters()
{
double[] m = new double[scaleMaxIndex - scaleMinIndex + 1];
int i = 0;
short x0 = scaleMinIndex;
while (i < scale.Length - 2)
{
double y0 = (double) scale[i + 1];
double r0 = (double) scale[i + 2];
double y1 = (double) scale[i + 4];
short x1;
if (i + 5 >= scale.Length)
x1 = scaleMaxIndex;
else
{
double r1 = (double) scale[i + 5];
x1 = (short) Math.Round(x0 + 2 * (y1 - y0) / (r0 + r1));
}
int dx = x1 - x0;
double dy = y1 - y0;
double dr = 2 * (dy / dx - r0) / dx;
for (short x = x0; x < x1; x++)
{
m[x - scaleMinIndex] = (double) ((x - x0) * (r0 + dr * (x - x0) / 2.0) + y0);
}
i += 3;
x0 = x1;
}
m[m.Length - 1] = (double) scale[scale.Length - 1];
return m;
}
/// <summary>
/// Converts a short index value into an elevation in meters.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static double IndexToMeters(short index)
{
if (index == DemTile.NoData)
return double.NaN;
return scaleMeters[index - scaleMinIndex];
}
/// <summary>
/// Converts a meter value to an index into the Dem tile elevation index.
/// </summary>
/// <param name="meters"></param>
/// <returns></returns>
public static short MetersToIndex(double meters)
{
if (double.IsNaN(meters))
return DemTile.NoData;
if (meters <= scaleMeters[0])
return scaleMinIndex;
if (meters >= scaleMeters[scaleMaxIndex - scaleMinIndex])
return scaleMaxIndex;
int index = Array.BinarySearch<double>(scaleMeters, (double) meters);
if (index >= 0)
return (short) (index + scaleMinIndex);
double mid = (scaleMeters[~index] + scaleMeters[~index - 1]) / 2;
if (meters < mid)
return (short) (~index - 1 + scaleMinIndex);
else
return (short) (~index + scaleMinIndex);
}
/// <summary>
/// Look up an individual altitude sample.
/// </summary>
/// <returns>Returns the altitude sample in meters above sea level.</returns>
public double AltitudeInMeters(int row, int col)
{
// indexer does validation
return IndexToMeters(this[row, col]);
}
/// <summary>
/// Set an individual altitude sample in meters instead of arbitrary
/// linear units.
/// </summary>
public void SetAltitudeInMeters(int row, int col, double meters)
{
// indexer does validation
this[row, col] = MetersToIndex(meters);
}
/// <summary>
/// Retrieves the elevation from a specific location in the tile.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Member")]
public short[,] AltitudeBuffer
{
get { return altitude; }
set { altitude = value; }
}
}
public class TileTools
{
public static int GetServerID(int tileX, int tileY)
{
int server = (tileX & 1) + ((tileY & 1) << 1);
return (server);
}
public static string GetTileID(int tileLevel, int tileX, int tileY)
{
int netLevel = tileLevel;
int netX = tileX;
int netY = tileY;
string tileId = "";
string tileMap = "0123";
if (!string.IsNullOrEmpty(tileMap))
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = netLevel; i > 0; --i)
{
int mask = 1 << (i - 1);
int val = 0;
if ((netX & mask) != 0)
val = 1;
if ((netY & mask) != 0)
val += 2;
sb.Append(tileMap[val]);
}
tileId = sb.ToString();
return tileId;
}
else
{
tileId = "0";
return tileId;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using EIDSS.Reports.BaseControls.Report;
using bv.common.Core;
using DevExpress.XtraBars;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrinting.Preview;
using DevExpress.XtraReports.UI;
using bv.winclient.Core;
using eidss.model.Core;
using eidss.model.Enums;
using HScrollBar = DevExpress.XtraEditors.HScrollBar;
using VScrollBar = DevExpress.XtraEditors.VScrollBar;
namespace EIDSS.Reports.BaseControls
{
public partial class ReportView : UserControl
{
private const float ZoomLandscape = 0.75f;
private const float ZoomDefault = 1f;
private readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (ReportView));
private bool m_IsBarcode;
private bool m_ReportInitializing;
private XtraReport m_Report;
public event EventHandler OnReportEdit;
public event EventHandler OnReportLoadDefault;
public ReportView()
{
InitializeComponent();
printControlReport.VScrollBar.Visible = false;
printControlReport.HScrollBar.Visible = false;
timerScroll.Start();
}
[DefaultValue(false)]
[Browsable(true)]
public bool IsBarcode
{
get { return m_IsBarcode; }
set
{
m_IsBarcode = value;
AjustToolbar();
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public XtraReport Report
{
get { return m_Report; }
set
{
if (m_Report == value)
return;
try
{
m_ReportInitializing = true;
if (m_Report != null)
m_Report.Dispose();
m_Report = value;
if (m_Report != null)
{
printControlReport.PrintingSystem = m_Report.PrintingSystem;
m_Report.PrintingSystem.ClearContent();
Invalidate();
Update();
var baseReport = m_Report as BaseReport;
if (baseReport != null && baseReport.ChildReport != null)
{
baseReport.CreateDocument();
baseReport.ChildReport.CreateDocument();
baseReport.Pages.AddRange(baseReport.ChildReport.Pages);
baseReport.PrintingSystem.ContinuousPageNumbering = true;
}
else
{
m_Report.CreateDocument(true);
}
m_Report.PrintingSystem.PageSettings.Landscape = m_Report.Landscape;
printControlReport.Zoom = m_Report.Landscape ? ZoomLandscape : ZoomDefault;
printControlReport.ExecCommand(PrintingSystemCommand.ZoomToPageWidth);
if (printControlReport.Zoom > 1)
printControlReport.Zoom = 1;
AjustToolbar();
biLoadDefault.Enabled = true;
biEdit.Enabled = true;
}
}
finally
{
m_ReportInitializing = false;
}
}
}
[Browsable(false)]
internal float Zoom
{
get { return printControlReport.Zoom; }
set { printControlReport.Zoom = value; }
}
private void AjustToolbar()
{
if (WinUtils.IsComponentInDesignMode(this))
return;
BarItemVisibility visibility = (IsBarcode) ? BarItemVisibility.Always : BarItemVisibility.Never;
biEdit.Visibility = visibility;
biLoadDefault.Visibility = visibility;
var itemsToRemove = new List<BarItem>();
itemsToRemove.AddRange(new BarItem[] {biExportHtm, biExportMht});
foreach (BarItem item in printBarManager.Items)
{
if ((item is PrintPreviewBarItem) && (string.IsNullOrEmpty(item.Name)))
itemsToRemove.Add(item);
}
if (IsBarcode)
{
itemsToRemove.AddRange(new BarItem[]
{
biFind, biPageSetup, biScale, biMagnifier,
biMultiplePages,
biMultiplePages, biFillBackground, biExportFile
});
}
if (
!EidssUserContext.User.HasPermission(
PermissionHelper.ExecutePermission(EIDSSPermissionObject.CanImportExportData)))
itemsToRemove.Add(biExportFile);
RemoveFromToolbar(itemsToRemove, printBarManager, previewBar1);
}
private void timerScroll_Tick(object sender, EventArgs e)
{
if (m_ReportInitializing && m_Report.PrintingSystem.Document.IsCreating)
return;
VScrollBar vScrollBar = printControlReport.VScrollBar;
bool verticalVisible = (vScrollBar.Maximum >
vScrollBar.Bounds.Height - vScrollBar.Bounds.Y +
2 * SystemInformation.HorizontalScrollBarHeight);
if (vScrollBar.Visible != verticalVisible)
vScrollBar.Visible = verticalVisible;
HScrollBar hScrollBar = printControlReport.HScrollBar;
bool horisontalVisible = (hScrollBar.Maximum >
hScrollBar.ClientSize.Width + SystemInformation.VerticalScrollBarWidth);
if (hScrollBar.Visible != horisontalVisible)
hScrollBar.Visible = horisontalVisible;
}
public static void RemoveFromToolbar
(ICollection<BarItem> itemsToRemove, PrintBarManager barManager, PreviewBar previewBar)
{
foreach (BarItem item in itemsToRemove)
{
barManager.Items.Remove(item);
}
var linksToRemove = new List<LinkPersistInfo>();
foreach (LinkPersistInfo linksInfo in previewBar.LinksPersistInfo)
{
if (itemsToRemove.Contains(linksInfo.Item))
linksToRemove.Add(linksInfo);
}
foreach (LinkPersistInfo linksInfo in linksToRemove)
{
previewBar.LinksPersistInfo.Remove(linksInfo);
}
}
private void biEdit_ItemClick(object sender, ItemClickEventArgs e)
{
EventHandler handler = OnReportEdit;
if (handler != null)
handler(sender, e);
}
private void biLoadDefault_ItemClick(object sender, ItemClickEventArgs e)
{
EventHandler handler = OnReportLoadDefault;
if (handler != null)
handler(sender, e);
}
internal void ApplyResources()
{
m_Resources.ApplyResources(printControlReport, "printControlReport");
m_Resources.ApplyResources(previewBar1, "previewBar1");
m_Resources.ApplyResources(biFind, "biFind");
m_Resources.ApplyResources(biPrint, "biPrint");
m_Resources.ApplyResources(biPrintDirect, "biPrintDirect");
m_Resources.ApplyResources(biPageSetup, "biPageSetup");
m_Resources.ApplyResources(biScale, "biScale");
m_Resources.ApplyResources(biHandTool, "biHandTool");
m_Resources.ApplyResources(biMagnifier, "biMagnifier");
m_Resources.ApplyResources(biZoomOut, "biZoomOut");
m_Resources.ApplyResources(biZoom, "biZoom");
m_Resources.ApplyResources(ZoomIn, "ZoomIn");
m_Resources.ApplyResources(biShowFirstPage, "biShowFirstPage");
m_Resources.ApplyResources(biShowPrevPage, "biShowPrevPage");
m_Resources.ApplyResources(biShowNextPage, "biShowNextPage");
m_Resources.ApplyResources(biShowLastPage, "biShowLastPage");
m_Resources.ApplyResources(biMultiplePages, "biMultiplePages");
m_Resources.ApplyResources(biExportFile, "biExportFile");
m_Resources.ApplyResources(barStatus, "previewBar2");
m_Resources.ApplyResources(biPage, "printPreviewStaticItem1");
m_Resources.ApplyResources(biProgressBar, "progressBarEditItem1");
m_Resources.ApplyResources(biStatusStatus, "printPreviewBarItem1");
m_Resources.ApplyResources(biStatusZoom, "printPreviewStaticItem2");
m_Resources.ApplyResources(barMainMenu, "previewBar3");
m_Resources.ApplyResources(printPreviewSubItem4, "printPreviewSubItem4");
m_Resources.ApplyResources(printPreviewBarItem27, "printPreviewBarItem27");
m_Resources.ApplyResources(printPreviewBarItem28, "printPreviewBarItem28");
m_Resources.ApplyResources(barToolbarsListItem1, "barToolbarsListItem1");
m_Resources.ApplyResources(biExportPdf, "biExportPdf");
m_Resources.ApplyResources(biExportHtm, "biExportHtm");
m_Resources.ApplyResources(biExportMht, "biExportMht");
m_Resources.ApplyResources(biExportRtf, "biExportRtf");
m_Resources.ApplyResources(biExportXls, "biExportXls");
m_Resources.ApplyResources(biExportCsv, "biExportCsv");
m_Resources.ApplyResources(biExportTxt, "biExportTxt");
m_Resources.ApplyResources(biExportGraphic, "biExportGraphic");
m_Resources.ApplyResources(biFillBackground, "biFillBackground");
m_Resources.ApplyResources(printPreviewBarItem2, "printPreviewBarItem2");
m_Resources.ApplyResources(this, "$this");
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/24/2009 2:36:26 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using DotSpatial.Data;
namespace DotSpatial.Symbology
{
public class DrawingFilter : IDrawingFilter
{
#region Events
/// <summary>
/// Occurs after this filter has built its internal list of items.
/// </summary>
public event EventHandler Initialized;
#endregion
#region Private Variables
private IFeatureCategory _category;
private int _chunk;
private int _chunkSize;
private int _count;
private bool _countIsValid;
private IDictionary<IFeature, IDrawnState> _drawnStates;
private IFeatureList _featureList;
private bool _isInitialized;
private IFeatureScheme _scheme;
private bool _selected;
private bool _useCategory;
private bool _useChunks;
private bool _useSelection;
private bool _useVisibility;
private bool _visible;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of DrawingFilter without using any chunks. The use chunks
/// value will be false, and sub-categories will not be selected based on the chunk.
/// </summary>
public DrawingFilter(IFeatureList features, IFeatureScheme scheme)
{
_useChunks = false;
_chunkSize = -1;
Configure(features, scheme);
}
/// <summary>
/// Creates a new instance of DrawingFilter, sub-dividing the features into chunks.
/// regardless of selection or category, chunks simply subdivide the filter
/// into chunks of equal size.
/// </summary>
public DrawingFilter(IFeatureList features, IFeatureScheme scheme, int chunkSize)
{
_useChunks = true;
_chunkSize = chunkSize;
Configure(features, scheme);
}
private void Configure(IFeatureList features, IFeatureScheme scheme)
{
_featureList = features;
_scheme = scheme;
//features.FeatureAdded += new EventHandler<FeatureEventArgs>(features_FeatureAdded);
//features.FeatureRemoved += new EventHandler<FeatureEventArgs>(features_FeatureRemoved);
}
#endregion
#region Methods
/// <summary>
/// Creates a shallow copy
/// </summary>
/// <returns>Returns a shallow copy of this object.</returns>
public object Clone()
{
return MemberwiseClone();
}
/// <summary>
/// This will use the filter expressions on the categories to change the categories for those members.
/// This means that an item will be classified as the last filter that it qualifies for.
/// </summary>
/// <param name="scheme">The scheme of categories to apply to the drawing states</param>
public void ApplyScheme(IFeatureScheme scheme)
{
_scheme = scheme;
if (_isInitialized == false) DoInitialize();
var fc = _scheme.GetCategories().ToList();
// Short cut the rest of this (and prevent loading features) in the case where we know everything is in the default category
if (fc.Count == 1 && string.IsNullOrEmpty(fc[0].FilterExpression))
{
// Replace SchemeCategory in _drawnStates
foreach (var drawnState in _drawnStates)
{
drawnState.Value.SchemeCategory = fc[0];
}
return;
}
var tables = new List<DataTable>(); // just in case there is more than one Table somehow
var allRows = new Dictionary<DataRow, int>();
var tempList = new List<DataTable>();
var containsFID = fc.Any(category => category.FilterExpression != null && category.FilterExpression.Contains("[FID]"));
var featureIndex = 0;
foreach (var f in _featureList)
{
if (f.DataRow == null)
{
f.ParentFeatureSet.FillAttributes();
}
if (f.DataRow != null)
{
DataTable t = f.DataRow.Table;
if (tables.Contains(t) == false)
{
tables.Add(t);
if (containsFID && t.Columns.Contains("FID") == false)
{
f.ParentFeatureSet.AddFid();
tempList.Add(t);
}
}
allRows.Add(f.DataRow, featureIndex);
}
if (_drawnStates.ContainsKey(f)) _drawnStates[f].SchemeCategory = null;
featureIndex++;
}
foreach (IFeatureCategory cat in fc)
{
foreach (DataTable dt in tables)
{
DataRow[] rows = dt.Select(cat.FilterExpression);
foreach (DataRow dr in rows)
{
int index;
if (allRows.TryGetValue (dr, out index))
{
_drawnStates[_featureList[index]].SchemeCategory = cat;
}
}
}
}
foreach (DataTable table in tempList)
{
table.Columns.Remove("FID");
}
}
/// <summary>
/// If UseChunks is true, this uses the index value combined with the chunk size
/// to calculate the chunk, and also sets the category to the [0] category and the
/// selection state to unselected. This can be overridden in sub-classes to come up
/// with a different default state.
/// </summary>
/// <param name="index">The integer index to get the default state of</param>
/// <returns>An IDrawnState</returns>
public virtual IDrawnState GetDefaultState(int index)
{
if (_useChunks)
{
return new DrawnState(_scheme.GetCategories().First(), false, index / _chunkSize, true);
}
return new DrawnState(_scheme.GetCategories().First(), false, 0, true);
}
/// <summary>
/// Gets an enumator for cycling through exclusively the features that satisfy all the listed criteria,
/// including chunk index, selected state, and scheme category.
/// </summary>
/// <returns>An Enumerator for cycling through the values</returns>
public IEnumerator<IFeature> GetEnumerator()
{
if (_isInitialized == false) DoInitialize();
Func<IDrawnState, bool> alwaysTrue = drawnState => true;
Func<IDrawnState, bool> visConstraint = alwaysTrue; // by default, don't test visibility
Func<IDrawnState, bool> selConstraint = alwaysTrue; // by default, don't test selection
Func<IDrawnState, bool> catConstraint = alwaysTrue; // by default, don't test category
Func<IDrawnState, bool> chunkConstraint = alwaysTrue; // by default, don't test chunk
if (_useVisibility)
{
visConstraint = drawnState => drawnState.IsVisible == _visible;
}
if (_useChunks)
{
chunkConstraint = drawnState => drawnState.Chunk == _chunk;
}
if (_useSelection)
{
selConstraint = drawnState => drawnState.IsSelected == _selected;
}
if (_useCategory)
{
catConstraint = drawnState => drawnState.SchemeCategory == _category;
}
Func<IDrawnState, bool> constraint = drawnState => selConstraint(drawnState)
&& chunkConstraint(drawnState)
&& catConstraint(drawnState)
&& visConstraint(drawnState);
var query =
from kvp in _drawnStates
where
constraint(kvp.Value)
select kvp.Key;
query.Count();
return query.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Invalidates this drawing filter, effectively eliminating all the original
/// categories, selection statuses, and only keeps the basic chunk size.
/// </summary>
public void Invalidate()
{
_isInitialized = false;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the scheme category to use
/// </summary>
public IFeatureCategory Category
{
get { return _category; }
set
{
if (_category != value) _countIsValid = false;
_category = value;
}
}
/// <summary>
/// Gets the integer chunk that the filter should use
/// </summary>
public int Chunk
{
get { return _chunk; }
set
{
if (_chunk != value) _countIsValid = false;
_chunk = value;
}
}
/// <summary>
/// Gets or sets the integer size of each chunk. Setting this to
/// a new value will cycle through and update the chunk on all
/// the features.
/// </summary>
public int ChunkSize
{
get { return _chunkSize; }
set
{
if (_chunkSize != value)
{
_chunkSize = value;
}
}
}
/// <summary>
/// If the drawing state for any features has changed, or else if
/// the state of any members has changed, this will cycle through
/// the filter members and cache a new count. If nothing has
/// changed, then this will simply return the cached value.
/// </summary>
public int Count
{
get
{
if (_countIsValid) return _count;
IEnumerator<IFeature> en = GetEnumerator();
_count = 0;
while (en.MoveNext())
{
_count++;
}
_countIsValid = true;
return _count;
}
}
/// <summary>
/// Gets the default category for the scheme.
/// </summary>
public IFeatureCategory DefaultCategory
{
get { return _scheme.GetCategories().First(); }
}
/// <summary>
/// Gets the dictionary of drawn states that this drawing filter uses.
/// </summary>
public IDictionary<IFeature, IDrawnState> DrawnStates
{
get { return _drawnStates; }
}
/// <summary>
/// Gets the underlying list of features that this drawing filter
/// is ultimately based upon.
/// </summary>
public IFeatureList FeatureList
{
get { return _featureList; }
}
/// <summary>
/// If chunks are being used, then this indicates the total count of chunks.
/// Otherwise, this returns 1 as everything is effectively in one chunk.
/// </summary>
public int NumChunks
{
get
{
if (_useChunks) return Convert.ToInt32(Math.Ceiling(_featureList.Count / (double)_chunkSize));
return 1;
}
}
/// <summary>
/// If UseSelection is true, this will get or set the boolean selection state
/// that will be used to select values.
/// </summary>
public bool Selected
{
get { return _selected; }
set
{
if (_selected != value)
{
_countIsValid = false;
_selected = value;
}
}
}
/// <summary>
/// This uses the feature as the key and attempts to find the specified drawn state
/// that describes selection, chunk and category.
/// </summary>
/// <param name="key">The feature</param>
/// <remarks>The strength is that if someone inserts a new member or re-orders
/// the features in the featureset, we don't forget which ones are selected.
/// The disadvantage is that duplicate features in the same featureset
/// will cause an exception.</remarks>
/// <returns></returns>
public IDrawnState this[IFeature key]
{
get
{
if (_isInitialized == false) DoInitialize();
if (_drawnStates == null) return null;
return _drawnStates[key];
}
set
{
if (_isInitialized == false) DoInitialize();
// this will cause an exception if _drawnStates is null, but that might be what is needed
if (_drawnStates[key] != value) _countIsValid = false;
_drawnStates[key] = value;
}
}
/// <summary>
/// This is less direct as it requires searching two indices rather than one, but
/// allows access to the drawn state based on the feature ID.
/// </summary>
/// <param name="index">The integer index in the underlying featureSet.</param>
/// <returns>The current IDrawnState for the current feature.</returns>
public IDrawnState this[int index]
{
get
{
if (_isInitialized == false) DoInitialize();
return _drawnStates[_featureList[index]];
}
set
{
if (_isInitialized == false) DoInitialize();
if (_drawnStates[_featureList[index]] != value) _countIsValid = false;
_drawnStates[_featureList[index]] = value;
}
}
/// <summary>
/// Gets or sets a boolean that indicates whether the filter should subdivide based on category.
/// </summary>
public bool UseCategory
{
get { return _useCategory; }
set
{
if (_useCategory != value)
{
_countIsValid = false;
}
_useCategory = value;
}
}
/// <summary>
/// Gets or sets a boolean that indicates whether we should use the chunk
/// </summary>
public bool UseChunks
{
get { return _useChunks; }
set
{
if (_useChunks != value) _countIsValid = false;
_useChunks = value;
}
}
/// <summary>
/// Gets or sets a boolean that indicates whether this filter should use the Selected
/// </summary>
public bool UseSelection
{
get { return _useSelection; }
set
{
if (_useSelection != value) _countIsValid = false;
_useSelection = value;
}
}
/// <summary>
/// Gets or sets the boolean indicating whether or not this feature should be drawn.
/// </summary>
public bool UseVisibility
{
get { return _useVisibility; }
set
{
if (_useVisibility != value) _countIsValid = false;
_useVisibility = value;
}
}
/// <summary>
/// Gets or sets a boolean that specifies whether to return visible, or hidden features if UseVisibility is true.
/// </summary>
public bool Visible
{
get { return _visible; }
set
{
if (_visible != value) _countIsValid = false;
_visible = value;
}
}
#endregion
#region Protected Method
/// <summary>
/// Fires the Initialized Event
/// </summary>
protected virtual void OnInitialize()
{
_isInitialized = true;
if (Initialized != null) Initialized(this, EventArgs.Empty);
}
#endregion
#region Event Handlers
//void features_FeatureRemoved(object sender, FeatureEventArgs e)
//{
// _drawnStates.Remove(e.Feature);
//}
//void features_FeatureAdded(object sender, FeatureEventArgs e)
//{
// IDrawnState defaultState = GetDefaultState(_featureList.Count);
// _drawnStates.Add(new KeyValuePair<IFeature, IDrawnState>(e.Feature, defaultState));
//}
#endregion
#region Private Methods
/// <summary>
/// This block of code actually cycles through the source features, and assigns a default
/// drawing state to each feature. I thought duplicate features would be less of a problem
/// then people re-ordering an indexed list at some point, so for now we are using
/// features to index the values.
/// </summary>
private void DoInitialize()
{
_drawnStates = new Dictionary<IFeature, IDrawnState>();
for (int i = 0; i < _featureList.Count; i++)
{
_drawnStates.Add(new KeyValuePair<IFeature, IDrawnState>(_featureList[i], GetDefaultState(i)));
}
OnInitialize();
}
#endregion
}
}
| |
// 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 Fixtures.AcceptanceTestsHttp
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for HttpClientFailure.
/// </summary>
public static partial class HttpClientFailureExtensions
{
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Head400(this IHttpClientFailure operations)
{
return operations.Head400Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Head400Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Head400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Get400(this IHttpClientFailure operations)
{
return operations.Get400Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Get400Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Put400(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Put400Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Put400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Put400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Patch400(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Patch400Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Patch400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Patch400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Post400(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Post400Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Post400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Post400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Delete400(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Delete400Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Delete400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Delete400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 401 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Head401(this IHttpClientFailure operations)
{
return operations.Head401Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 401 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Head401Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Head401WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 402 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Get402(this IHttpClientFailure operations)
{
return operations.Get402Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 402 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Get402Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get402WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 403 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Get403(this IHttpClientFailure operations)
{
return operations.Get403Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 403 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Get403Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get403WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 404 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Put404(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Put404Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 404 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Put404Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Put404WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 405 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Patch405(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Patch405Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 405 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Patch405Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Patch405WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 406 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Post406(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Post406Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 406 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Post406Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Post406WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 407 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Delete407(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Delete407Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 407 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Delete407Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Delete407WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 409 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Put409(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Put409Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 409 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Put409Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Put409WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 410 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Head410(this IHttpClientFailure operations)
{
return operations.Head410Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 410 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Head410Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Head410WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 411 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Get411(this IHttpClientFailure operations)
{
return operations.Get411Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 411 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Get411Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get411WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 412 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Get412(this IHttpClientFailure operations)
{
return operations.Get412Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 412 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Get412Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get412WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 413 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Put413(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Put413Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 413 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Put413Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Put413WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 414 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Patch414(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Patch414Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 414 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Patch414Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Patch414WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 415 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Post415(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Post415Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 415 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Post415Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Post415WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 416 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Get416(this IHttpClientFailure operations)
{
return operations.Get416Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 416 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Get416Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get416WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 417 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Delete417(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return operations.Delete417Async(booleanValue).GetAwaiter().GetResult();
}
/// <summary>
/// Return 417 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Delete417Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Delete417WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 429 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Error Head429(this IHttpClientFailure operations)
{
return operations.Head429Async().GetAwaiter().GetResult();
}
/// <summary>
/// Return 429 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> Head429Async(this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Head429WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace HtmlAgilityPack
{
/// <summary>
/// Represents a complete HTML document.
/// </summary>
public partial class HtmlDocument
{
#region Fields
/// <summary>
/// Defines the max level we would go deep into the html document
/// </summary>
private static int _maxDepthLevel = int.MaxValue;
private int _c;
private Crc32 _crc32;
private HtmlAttribute _currentattribute;
private HtmlNode _currentnode;
private Encoding _declaredencoding;
private HtmlNode _documentnode;
private bool _fullcomment;
private int _index;
internal Dictionary<string, HtmlNode> Lastnodes = new Dictionary<string, HtmlNode>();
private HtmlNode _lastparentnode;
private int _line;
private int _lineposition, _maxlineposition;
internal Dictionary<string, HtmlNode> Nodesid;
private ParseState _oldstate;
private bool _onlyDetectEncoding;
internal Dictionary<int, HtmlNode> Openednodes;
private List<HtmlParseError> _parseerrors = new List<HtmlParseError>();
private string _remainder;
private int _remainderOffset;
private ParseState _state;
private Encoding _streamencoding;
internal string Text;
// public props
/// <summary>
/// Adds Debugging attributes to node. Default is false.
/// </summary>
public bool OptionAddDebuggingAttributes;
/// <summary>
/// Defines if closing for non closed nodes must be done at the end or directly in the document.
/// Setting this to true can actually change how browsers render the page. Default is false.
/// </summary>
public bool OptionAutoCloseOnEnd; // close errors at the end
/// <summary>
/// Defines if non closed nodes will be checked at the end of parsing. Default is true.
/// </summary>
public bool OptionCheckSyntax = true;
/// <summary>
/// Defines if a checksum must be computed for the document while parsing. Default is false.
/// </summary>
public bool OptionComputeChecksum;
/// <summary>
/// Defines the default stream encoding to use. Default is System.Text.Encoding.Default.
/// </summary>
public Encoding OptionDefaultStreamEncoding;
/// <summary>
/// Defines if source text must be extracted while parsing errors.
/// If the document has a lot of errors, or cascading errors, parsing performance can be dramatically affected if set to true.
/// Default is false.
/// </summary>
public bool OptionExtractErrorSourceText;
// turning this on can dramatically slow performance if a lot of errors are detected
/// <summary>
/// Defines the maximum length of source text or parse errors. Default is 100.
/// </summary>
public int OptionExtractErrorSourceTextMaxLength = 100;
/// <summary>
/// Defines if LI, TR, TH, TD tags must be partially fixed when nesting errors are detected. Default is false.
/// </summary>
public bool OptionFixNestedTags; // fix li, tr, th, td tags
/// <summary>
/// Defines if output must conform to XML, instead of HTML.
/// </summary>
public bool OptionOutputAsXml;
/// <summary>
/// Defines if attribute value output must be optimized (not bound with double quotes if it is possible). Default is false.
/// </summary>
public bool OptionOutputOptimizeAttributeValues;
/// <summary>
/// Defines if name must be output with it's original case. Useful for asp.net tags and attributes
/// </summary>
public bool OptionOutputOriginalCase;
/// <summary>
/// Defines if name must be output in uppercase. Default is false.
/// </summary>
public bool OptionOutputUpperCase;
/// <summary>
/// Defines if declared encoding must be read from the document.
/// Declared encoding is determined using the meta http-equiv="content-type" content="text/html;charset=XXXXX" html node.
/// Default is true.
/// </summary>
public bool OptionReadEncoding = true;
/// <summary>
/// Defines the name of a node that will throw the StopperNodeException when found as an end node. Default is null.
/// </summary>
public string OptionStopperNodeName;
/// <summary>
/// Defines if the 'id' attribute must be specifically used. Default is true.
/// </summary>
public bool OptionUseIdAttribute = true;
/// <summary>
/// Defines if empty nodes must be written as closed during output. Default is false.
/// </summary>
public bool OptionWriteEmptyNodes;
#endregion
#region Static Members
internal static readonly string HtmlExceptionRefNotChild = "Reference node must be a child of this node";
internal static readonly string HtmlExceptionUseIdAttributeFalse =
"You need to set UseIdAttribute property to true to enable this feature";
#endregion
#region Constructors
/// <summary>
/// Creates an instance of an HTML document.
/// </summary>
public HtmlDocument()
{
_documentnode = CreateNode(HtmlNodeType.Document, 0);
#if SILVERLIGHT || METRO
OptionDefaultStreamEncoding =Encoding.UTF8;
#else
OptionDefaultStreamEncoding = Encoding.Default;
#endif
}
#endregion
#region Properties
/// <summary>
/// Defines the max level we would go deep into the html document. If this depth level is exceeded, and exception is
/// thrown.
/// </summary>
public static int MaxDepthLevel
{
get { return _maxDepthLevel; }
set { _maxDepthLevel = value; }
}
/// <summary>
/// Gets the document CRC32 checksum if OptionComputeChecksum was set to true before parsing, 0 otherwise.
/// </summary>
public int CheckSum
{
get { return _crc32 == null ? 0 : (int)_crc32.CheckSum; }
}
/// <summary>
/// Gets the document's declared encoding.
/// Declared encoding is determined using the meta http-equiv="content-type" content="text/html;charset=XXXXX" html node.
/// </summary>
public Encoding DeclaredEncoding
{
get { return _declaredencoding; }
}
/// <summary>
/// Gets the root node of the document.
/// </summary>
public HtmlNode DocumentNode
{
get { return _documentnode; }
}
/// <summary>
/// Gets the document's output encoding.
/// </summary>
public Encoding Encoding
{
get { return GetOutEncoding(); }
}
/// <summary>
/// Gets a list of parse errors found in the document.
/// </summary>
public IEnumerable<HtmlParseError> ParseErrors
{
get { return _parseerrors; }
}
/// <summary>
/// Gets the remaining text.
/// Will always be null if OptionStopperNodeName is null.
/// </summary>
public string Remainder
{
get { return _remainder; }
}
/// <summary>
/// Gets the offset of Remainder in the original Html text.
/// If OptionStopperNodeName is null, this will return the length of the original Html text.
/// </summary>
public int RemainderOffset
{
get { return _remainderOffset; }
}
/// <summary>
/// Gets the document's stream encoding.
/// </summary>
public Encoding StreamEncoding
{
get { return _streamencoding; }
}
#endregion
#region Public Methods
/// <summary>
/// Gets a valid XML name.
/// </summary>
/// <param name="name">Any text.</param>
/// <returns>A string that is a valid XML name.</returns>
public static string GetXmlName(string name)
{
string xmlname = string.Empty;
bool nameisok = true;
for (int i = 0; i < name.Length; i++)
{
// names are lcase
// note: we are very limited here, too much?
if (((name[i] >= 'a') && (name[i] <= 'z')) ||
((name[i] >= '0') && (name[i] <= '9')) ||
// (name[i]==':') || (name[i]=='_') || (name[i]=='-') || (name[i]=='.')) // these are bads in fact
(name[i] == '_') || (name[i] == '-') || (name[i] == '.'))
{
xmlname += name[i];
}
else
{
nameisok = false;
byte[] bytes = Encoding.UTF8.GetBytes(new char[] { name[i] });
for (int j = 0; j < bytes.Length; j++)
{
xmlname += bytes[j].ToString("x2");
}
xmlname += "_";
}
}
if (nameisok)
{
return xmlname;
}
return "_" + xmlname;
}
/// <summary>
/// Applies HTML encoding to a specified string.
/// </summary>
/// <param name="html">The input string to encode. May not be null.</param>
/// <returns>The encoded string.</returns>
public static string HtmlEncode(string html)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
// replace & by & but only once!
Regex rx = new Regex("&(?!(amp;)|(lt;)|(gt;)|(quot;))", RegexOptions.IgnoreCase);
return rx.Replace(html, "&").Replace("<", "<").Replace(">", ">").Replace("\"", """);
}
/// <summary>
/// Determines if the specified character is considered as a whitespace character.
/// </summary>
/// <param name="c">The character to check.</param>
/// <returns>true if if the specified character is considered as a whitespace character.</returns>
public static bool IsWhiteSpace(int c)
{
if ((c == 10) || (c == 13) || (c == 32) || (c == 9))
{
return true;
}
return false;
}
/// <summary>
/// Creates an HTML attribute with the specified name.
/// </summary>
/// <param name="name">The name of the attribute. May not be null.</param>
/// <returns>The new HTML attribute.</returns>
public HtmlAttribute CreateAttribute(string name)
{
if (name == null)
throw new ArgumentNullException("name");
HtmlAttribute att = CreateAttribute();
att.Name = name;
return att;
}
/// <summary>
/// Creates an HTML attribute with the specified name.
/// </summary>
/// <param name="name">The name of the attribute. May not be null.</param>
/// <param name="value">The value of the attribute.</param>
/// <returns>The new HTML attribute.</returns>
public HtmlAttribute CreateAttribute(string name, string value)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
HtmlAttribute att = CreateAttribute(name);
att.Value = value;
return att;
}
/// <summary>
/// Creates an HTML comment node.
/// </summary>
/// <returns>The new HTML comment node.</returns>
public HtmlCommentNode CreateComment()
{
return (HtmlCommentNode)CreateNode(HtmlNodeType.Comment);
}
/// <summary>
/// Creates an HTML comment node with the specified comment text.
/// </summary>
/// <param name="comment">The comment text. May not be null.</param>
/// <returns>The new HTML comment node.</returns>
public HtmlCommentNode CreateComment(string comment)
{
if (comment == null)
{
throw new ArgumentNullException("comment");
}
HtmlCommentNode c = CreateComment();
c.Comment = comment;
return c;
}
/// <summary>
/// Creates an HTML element node with the specified name.
/// </summary>
/// <param name="name">The qualified name of the element. May not be null.</param>
/// <returns>The new HTML node.</returns>
public HtmlNode CreateElement(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
HtmlNode node = CreateNode(HtmlNodeType.Element);
node.Name = name;
return node;
}
/// <summary>
/// Creates an HTML text node.
/// </summary>
/// <returns>The new HTML text node.</returns>
public HtmlTextNode CreateTextNode()
{
return (HtmlTextNode)CreateNode(HtmlNodeType.Text);
}
/// <summary>
/// Creates an HTML text node with the specified text.
/// </summary>
/// <param name="text">The text of the node. May not be null.</param>
/// <returns>The new HTML text node.</returns>
public HtmlTextNode CreateTextNode(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
HtmlTextNode t = CreateTextNode();
t.Text = text;
return t;
}
/// <summary>
/// Detects the encoding of an HTML stream.
/// </summary>
/// <param name="stream">The input stream. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncoding(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
return DetectEncoding(new StreamReader(stream));
}
/// <summary>
/// Detects the encoding of an HTML text provided on a TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncoding(TextReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
_onlyDetectEncoding = true;
if (OptionCheckSyntax)
{
Openednodes = new Dictionary<int, HtmlNode>();
}
else
{
Openednodes = null;
}
if (OptionUseIdAttribute)
{
Nodesid = new Dictionary<string, HtmlNode>();
}
else
{
Nodesid = null;
}
StreamReader sr = reader as StreamReader;
if (sr != null)
{
_streamencoding = sr.CurrentEncoding;
}
else
{
_streamencoding = null;
}
_declaredencoding = null;
Text = reader.ReadToEnd();
_documentnode = CreateNode(HtmlNodeType.Document, 0);
// this is almost a hack, but it allows us not to muck with the original parsing code
try
{
Parse();
}
catch (EncodingFoundException ex)
{
return ex.Encoding;
}
return null;
}
/// <summary>
/// Detects the encoding of an HTML text.
/// </summary>
/// <param name="html">The input html text. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncodingHtml(string html)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
using(StringReader sr = new StringReader(html))
{
Encoding encoding = DetectEncoding(sr);
return encoding;
}
}
/// <summary>
/// Gets the HTML node with the specified 'id' attribute value.
/// </summary>
/// <param name="id">The attribute id to match. May not be null.</param>
/// <returns>The HTML node with the matching id or null if not found.</returns>
public HtmlNode GetElementbyId(string id)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (Nodesid == null)
{
throw new Exception(HtmlExceptionUseIdAttributeFalse);
}
return Nodesid.ContainsKey(id.ToLower()) ? Nodesid[id.ToLower()] : null;
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
public void Load(Stream stream)
{
Load(new StreamReader(stream, OptionDefaultStreamEncoding));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public void Load(Stream stream, bool detectEncodingFromByteOrderMarks)
{
Load(new StreamReader(stream, detectEncodingFromByteOrderMarks));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
public void Load(Stream stream, Encoding encoding)
{
Load(new StreamReader(stream, encoding));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, buffersize));
}
/// <summary>
/// Loads the HTML document from the specified TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML data into the document. May not be null.</param>
public void Load(TextReader reader)
{
// all Load methods pass down to this one
if (reader == null)
throw new ArgumentNullException("reader");
_onlyDetectEncoding = false;
if (OptionCheckSyntax)
Openednodes = new Dictionary<int, HtmlNode>();
else
Openednodes = null;
if (OptionUseIdAttribute)
{
Nodesid = new Dictionary<string, HtmlNode>();
}
else
{
Nodesid = null;
}
StreamReader sr = reader as StreamReader;
if (sr != null)
{
try
{
// trigger bom read if needed
sr.Peek();
}
// ReSharper disable EmptyGeneralCatchClause
catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
{
// void on purpose
}
_streamencoding = sr.CurrentEncoding;
}
else
{
_streamencoding = null;
}
_declaredencoding = null;
Text = reader.ReadToEnd();
_documentnode = CreateNode(HtmlNodeType.Document, 0);
Parse();
if (!OptionCheckSyntax || Openednodes == null) return;
foreach (HtmlNode node in Openednodes.Values)
{
if (!node._starttag) // already reported
{
continue;
}
string html;
if (OptionExtractErrorSourceText)
{
html = node.OuterHtml;
if (html.Length > OptionExtractErrorSourceTextMaxLength)
{
html = html.Substring(0, OptionExtractErrorSourceTextMaxLength);
}
}
else
{
html = string.Empty;
}
AddError(
HtmlParseErrorCode.TagNotClosed,
node._line, node._lineposition,
node._streamposition, html,
"End tag </" + node.Name + "> was not found");
}
// we don't need this anymore
Openednodes.Clear();
}
/// <summary>
/// Loads the HTML document from the specified string.
/// </summary>
/// <param name="html">String containing the HTML document to load. May not be null.</param>
public void LoadHtml(string html)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
using (StringReader sr = new StringReader(html))
{
Load(sr);
}
}
/// <summary>
/// Saves the HTML document to the specified stream.
/// </summary>
/// <param name="outStream">The stream to which you want to save.</param>
public void Save(Stream outStream)
{
StreamWriter sw = new StreamWriter(outStream, GetOutEncoding());
Save(sw);
}
/// <summary>
/// Saves the HTML document to the specified stream.
/// </summary>
/// <param name="outStream">The stream to which you want to save. May not be null.</param>
/// <param name="encoding">The character encoding to use. May not be null.</param>
public void Save(Stream outStream, Encoding encoding)
{
if (outStream == null)
{
throw new ArgumentNullException("outStream");
}
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
StreamWriter sw = new StreamWriter(outStream, encoding);
Save(sw);
}
/// <summary>
/// Saves the HTML document to the specified StreamWriter.
/// </summary>
/// <param name="writer">The StreamWriter to which you want to save.</param>
public void Save(StreamWriter writer)
{
Save((TextWriter)writer);
}
/// <summary>
/// Saves the HTML document to the specified TextWriter.
/// </summary>
/// <param name="writer">The TextWriter to which you want to save. May not be null.</param>
public void Save(TextWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
DocumentNode.WriteTo(writer);
writer.Flush();
}
/// <summary>
/// Saves the HTML document to the specified XmlWriter.
/// </summary>
/// <param name="writer">The XmlWriter to which you want to save.</param>
public void Save(XmlWriter writer)
{
DocumentNode.WriteTo(writer);
writer.Flush();
}
#endregion
#region Internal Methods
internal HtmlAttribute CreateAttribute()
{
return new HtmlAttribute(this);
}
internal HtmlNode CreateNode(HtmlNodeType type)
{
return CreateNode(type, -1);
}
internal HtmlNode CreateNode(HtmlNodeType type, int index)
{
switch (type)
{
case HtmlNodeType.Comment:
return new HtmlCommentNode(this, index);
case HtmlNodeType.Text:
return new HtmlTextNode(this, index);
default:
return new HtmlNode(type, this, index);
}
}
internal Encoding GetOutEncoding()
{
// when unspecified, use the stream encoding first
return _declaredencoding ?? (_streamencoding ?? OptionDefaultStreamEncoding);
}
internal HtmlNode GetXmlDeclaration()
{
if (!_documentnode.HasChildNodes)
return null;
foreach (HtmlNode node in _documentnode._childnodes)
if (node.Name == "?xml") // it's ok, names are case sensitive
return node;
return null;
}
internal void SetIdForNode(HtmlNode node, string id)
{
if (!OptionUseIdAttribute)
return;
if ((Nodesid == null) || (id == null))
return;
if (node == null)
Nodesid.Remove(id.ToLower());
else
Nodesid[id.ToLower()] = node;
}
internal void UpdateLastParentNode()
{
do
{
if (_lastparentnode.Closed)
_lastparentnode = _lastparentnode.ParentNode;
} while ((_lastparentnode != null) && (_lastparentnode.Closed));
if (_lastparentnode == null)
_lastparentnode = _documentnode;
}
#endregion
#region Private Methods
private void AddError(HtmlParseErrorCode code, int line, int linePosition, int streamPosition, string sourceText, string reason)
{
HtmlParseError err = new HtmlParseError(code, line, linePosition, streamPosition, sourceText, reason);
_parseerrors.Add(err);
return;
}
private void CloseCurrentNode()
{
if (_currentnode.Closed) // text or document are by def closed
return;
bool error = false;
HtmlNode prev = Utilities.GetDictionaryValueOrNull(Lastnodes, _currentnode.Name);
// find last node of this kind
if (prev == null)
{
if (HtmlNode.IsClosedElement(_currentnode.Name))
{
// </br> will be seen as <br>
_currentnode.CloseNode(_currentnode);
// add to parent node
if (_lastparentnode != null)
{
HtmlNode foundNode = null;
Stack<HtmlNode> futureChild = new Stack<HtmlNode>();
for (HtmlNode node = _lastparentnode.LastChild; node != null; node = node.PreviousSibling)
{
if ((node.Name == _currentnode.Name) && (!node.HasChildNodes))
{
foundNode = node;
break;
}
futureChild.Push(node);
}
if (foundNode != null)
{
while (futureChild.Count != 0)
{
HtmlNode node = futureChild.Pop();
_lastparentnode.RemoveChild(node);
foundNode.AppendChild(node);
}
}
else
{
_lastparentnode.AppendChild(_currentnode);
}
}
}
else
{
// node has no parent
// node is not a closed node
if (HtmlNode.CanOverlapElement(_currentnode.Name))
{
// this is a hack: add it as a text node
HtmlNode closenode = CreateNode(HtmlNodeType.Text, _currentnode._outerstartindex);
closenode._outerlength = _currentnode._outerlength;
((HtmlTextNode)closenode).Text = ((HtmlTextNode)closenode).Text.ToLower();
if (_lastparentnode != null)
{
_lastparentnode.AppendChild(closenode);
}
}
else
{
if (HtmlNode.IsEmptyElement(_currentnode.Name))
{
AddError(
HtmlParseErrorCode.EndTagNotRequired,
_currentnode._line, _currentnode._lineposition,
_currentnode._streamposition, _currentnode.OuterHtml,
"End tag </" + _currentnode.Name + "> is not required");
}
else
{
// node cannot overlap, node is not empty
AddError(
HtmlParseErrorCode.TagNotOpened,
_currentnode._line, _currentnode._lineposition,
_currentnode._streamposition, _currentnode.OuterHtml,
"Start tag <" + _currentnode.Name + "> was not found");
error = true;
}
}
}
}
else
{
if (OptionFixNestedTags)
{
if (FindResetterNodes(prev, GetResetters(_currentnode.Name)))
{
AddError(
HtmlParseErrorCode.EndTagInvalidHere,
_currentnode._line, _currentnode._lineposition,
_currentnode._streamposition, _currentnode.OuterHtml,
"End tag </" + _currentnode.Name + "> invalid here");
error = true;
}
}
if (!error)
{
Lastnodes[_currentnode.Name] = prev._prevwithsamename;
prev.CloseNode(_currentnode);
}
}
// we close this node, get grandparent
if (!error)
{
if ((_lastparentnode != null) &&
((!HtmlNode.IsClosedElement(_currentnode.Name)) ||
(_currentnode._starttag)))
{
UpdateLastParentNode();
}
}
}
private string CurrentNodeName()
{
return Text.Substring(_currentnode._namestartindex, _currentnode._namelength);
}
private void DecrementPosition()
{
_index--;
if (_lineposition == 1)
{
_lineposition = _maxlineposition;
_line--;
}
else
{
_lineposition--;
}
}
private HtmlNode FindResetterNode(HtmlNode node, string name)
{
HtmlNode resetter = Utilities.GetDictionaryValueOrNull(Lastnodes, name);
if (resetter == null)
return null;
if (resetter.Closed)
return null;
if (resetter._streamposition < node._streamposition)
{
return null;
}
return resetter;
}
private bool FindResetterNodes(HtmlNode node, string[] names)
{
if (names == null)
return false;
for (int i = 0; i < names.Length; i++)
{
if (FindResetterNode(node, names[i]) != null)
return true;
}
return false;
}
private void FixNestedTag(string name, string[] resetters)
{
if (resetters == null)
return;
HtmlNode prev = Utilities.GetDictionaryValueOrNull(Lastnodes, _currentnode.Name);
// if we find a previous unclosed same name node, without a resetter node between, we must close it
if (prev == null || (Lastnodes[name].Closed)) return;
// try to find a resetter node, if found, we do nothing
if (FindResetterNodes(prev, resetters))
{
return;
}
// ok we need to close the prev now
// create a fake closer node
HtmlNode close = new HtmlNode(prev.NodeType, this, -1);
close._endnode = close;
prev.CloseNode(close);
}
private void FixNestedTags()
{
// we are only interested by start tags, not closing tags
if (!_currentnode._starttag)
return;
string name = CurrentNodeName();
FixNestedTag(name, GetResetters(name));
}
private string[] GetResetters(string name)
{
switch (name)
{
case "li":
return new string[] { "ul" };
case "tr":
return new string[] { "table" };
case "th":
case "td":
return new string[] { "tr", "table" };
default:
return null;
}
}
private void IncrementPosition()
{
if (_crc32 != null)
{
// REVIEW: should we add some checksum code in DecrementPosition too?
_crc32.AddToCRC32(_c);
}
_index++;
_maxlineposition = _lineposition;
if (_c == 10)
{
_lineposition = 1;
_line++;
}
else
{
_lineposition++;
}
}
private bool NewCheck()
{
if (_c != '<')
{
return false;
}
if (_index < Text.Length)
{
if (Text[_index] == '%')
{
switch (_state)
{
case ParseState.AttributeAfterEquals:
PushAttributeValueStart(_index - 1);
break;
case ParseState.BetweenAttributes:
PushAttributeNameStart(_index - 1);
break;
case ParseState.WhichTag:
PushNodeNameStart(true, _index - 1);
_state = ParseState.Tag;
break;
}
_oldstate = _state;
_state = ParseState.ServerSideCode;
return true;
}
}
if (!PushNodeEnd(_index - 1, true))
{
// stop parsing
_index = Text.Length;
return true;
}
_state = ParseState.WhichTag;
if ((_index - 1) <= (Text.Length - 2))
{
if (Text[_index] == '!')
{
PushNodeStart(HtmlNodeType.Comment, _index - 1);
PushNodeNameStart(true, _index);
PushNodeNameEnd(_index + 1);
_state = ParseState.Comment;
if (_index < (Text.Length - 2))
{
if ((Text[_index + 1] == '-') &&
(Text[_index + 2] == '-'))
{
_fullcomment = true;
}
else
{
_fullcomment = false;
}
}
return true;
}
}
PushNodeStart(HtmlNodeType.Element, _index - 1);
return true;
}
private void Parse()
{
int lastquote = 0;
if (OptionComputeChecksum)
{
_crc32 = new Crc32();
}
Lastnodes = new Dictionary<string, HtmlNode>();
_c = 0;
_fullcomment = false;
_parseerrors = new List<HtmlParseError>();
_line = 1;
_lineposition = 1;
_maxlineposition = 1;
_state = ParseState.Text;
_oldstate = _state;
_documentnode._innerlength = Text.Length;
_documentnode._outerlength = Text.Length;
_remainderOffset = Text.Length;
_lastparentnode = _documentnode;
_currentnode = CreateNode(HtmlNodeType.Text, 0);
_currentattribute = null;
_index = 0;
PushNodeStart(HtmlNodeType.Text, 0);
while (_index < Text.Length)
{
_c = Text[_index];
IncrementPosition();
switch (_state)
{
case ParseState.Text:
if (NewCheck())
continue;
break;
case ParseState.WhichTag:
if (NewCheck())
continue;
if (_c == '/')
{
PushNodeNameStart(false, _index);
}
else
{
PushNodeNameStart(true, _index - 1);
DecrementPosition();
}
_state = ParseState.Tag;
break;
case ParseState.Tag:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
{
PushNodeNameEnd(_index - 1);
if (_state != ParseState.Tag)
continue;
_state = ParseState.BetweenAttributes;
continue;
}
if (_c == '/')
{
PushNodeNameEnd(_index - 1);
if (_state != ParseState.Tag)
continue;
_state = ParseState.EmptyTag;
continue;
}
if (_c == '>')
{
PushNodeNameEnd(_index - 1);
if (_state != ParseState.Tag)
continue;
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.Tag)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index);
}
break;
case ParseState.BetweenAttributes:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
continue;
if ((_c == '/') || (_c == '?'))
{
_state = ParseState.EmptyTag;
continue;
}
if (_c == '>')
{
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.BetweenAttributes)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index);
continue;
}
PushAttributeNameStart(_index - 1);
_state = ParseState.AttributeName;
break;
case ParseState.EmptyTag:
if (NewCheck())
continue;
if (_c == '>')
{
if (!PushNodeEnd(_index, true))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.EmptyTag)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index);
continue;
}
_state = ParseState.BetweenAttributes;
break;
case ParseState.AttributeName:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
{
PushAttributeNameEnd(_index - 1);
_state = ParseState.AttributeBeforeEquals;
continue;
}
if (_c == '=')
{
PushAttributeNameEnd(_index - 1);
_state = ParseState.AttributeAfterEquals;
continue;
}
if (_c == '>')
{
PushAttributeNameEnd(_index - 1);
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.AttributeName)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index);
continue;
}
break;
case ParseState.AttributeBeforeEquals:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
continue;
if (_c == '>')
{
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.AttributeBeforeEquals)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index);
continue;
}
if (_c == '=')
{
_state = ParseState.AttributeAfterEquals;
continue;
}
// no equals, no whitespace, it's a new attrribute starting
_state = ParseState.BetweenAttributes;
DecrementPosition();
break;
case ParseState.AttributeAfterEquals:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
continue;
if ((_c == '\'') || (_c == '"'))
{
_state = ParseState.QuotedAttributeValue;
PushAttributeValueStart(_index, _c);
lastquote = _c;
continue;
}
if (_c == '>')
{
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.AttributeAfterEquals)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index);
continue;
}
PushAttributeValueStart(_index - 1);
_state = ParseState.AttributeValue;
break;
case ParseState.AttributeValue:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
{
PushAttributeValueEnd(_index - 1);
_state = ParseState.BetweenAttributes;
continue;
}
if (_c == '>')
{
PushAttributeValueEnd(_index - 1);
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.AttributeValue)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index);
continue;
}
break;
case ParseState.QuotedAttributeValue:
if (_c == lastquote)
{
PushAttributeValueEnd(_index - 1);
_state = ParseState.BetweenAttributes;
continue;
}
if (_c == '<')
{
if (_index < Text.Length)
{
if (Text[_index] == '%')
{
_oldstate = _state;
_state = ParseState.ServerSideCode;
continue;
}
}
}
break;
case ParseState.Comment:
if (_c == '>')
{
if (_fullcomment)
{
if ((Text[_index - 2] != '-') ||
(Text[_index - 3] != '-'))
{
continue;
}
}
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index);
continue;
}
break;
case ParseState.ServerSideCode:
if (_c == '%')
{
if (_index < Text.Length)
{
if (Text[_index] == '>')
{
switch (_oldstate)
{
case ParseState.AttributeAfterEquals:
_state = ParseState.AttributeValue;
break;
case ParseState.BetweenAttributes:
PushAttributeNameEnd(_index + 1);
_state = ParseState.BetweenAttributes;
break;
default:
_state = _oldstate;
break;
}
IncrementPosition();
}
}
}
break;
case ParseState.PcData:
// look for </tag + 1 char
// check buffer end
if ((_currentnode._namelength + 3) <= (Text.Length - (_index - 1)))
{
if (string.Compare(Text.Substring(_index - 1, _currentnode._namelength + 2),
"</" + _currentnode.Name, StringComparison.OrdinalIgnoreCase) == 0)
{
int c = Text[_index - 1 + 2 + _currentnode.Name.Length];
if ((c == '>') || (IsWhiteSpace(c)))
{
// add the script as a text node
HtmlNode script = CreateNode(HtmlNodeType.Text,
_currentnode._outerstartindex +
_currentnode._outerlength);
script._outerlength = _index - 1 - script._outerstartindex;
_currentnode.AppendChild(script);
PushNodeStart(HtmlNodeType.Element, _index - 1);
PushNodeNameStart(false, _index - 1 + 2);
_state = ParseState.Tag;
IncrementPosition();
}
}
}
break;
}
}
// finish the current work
if (_currentnode._namestartindex > 0)
{
PushNodeNameEnd(_index);
}
PushNodeEnd(_index, false);
// we don't need this anymore
Lastnodes.Clear();
}
private void PushAttributeNameEnd(int index)
{
_currentattribute._namelength = index - _currentattribute._namestartindex;
_currentnode.Attributes.Append(_currentattribute);
}
private void PushAttributeNameStart(int index)
{
_currentattribute = CreateAttribute();
_currentattribute._namestartindex = index;
_currentattribute.Line = _line;
_currentattribute._lineposition = _lineposition;
_currentattribute._streamposition = index;
}
private void PushAttributeValueEnd(int index)
{
_currentattribute._valuelength = index - _currentattribute._valuestartindex;
}
private void PushAttributeValueStart(int index)
{
PushAttributeValueStart(index, 0);
}
private void PushAttributeValueStart(int index, int quote)
{
_currentattribute._valuestartindex = index;
if (quote == '\'')
_currentattribute.QuoteType = AttributeValueQuote.SingleQuote;
}
private bool PushNodeEnd(int index, bool close)
{
_currentnode._outerlength = index - _currentnode._outerstartindex;
if ((_currentnode._nodetype == HtmlNodeType.Text) ||
(_currentnode._nodetype == HtmlNodeType.Comment))
{
// forget about void nodes
if (_currentnode._outerlength > 0)
{
_currentnode._innerlength = _currentnode._outerlength;
_currentnode._innerstartindex = _currentnode._outerstartindex;
if (_lastparentnode != null)
{
_lastparentnode.AppendChild(_currentnode);
}
}
}
else
{
if ((_currentnode._starttag) && (_lastparentnode != _currentnode))
{
// add to parent node
if (_lastparentnode != null)
{
_lastparentnode.AppendChild(_currentnode);
}
ReadDocumentEncoding(_currentnode);
// remember last node of this kind
HtmlNode prev = Utilities.GetDictionaryValueOrNull(Lastnodes, _currentnode.Name);
_currentnode._prevwithsamename = prev;
Lastnodes[_currentnode.Name] = _currentnode;
// change parent?
if ((_currentnode.NodeType == HtmlNodeType.Document) ||
(_currentnode.NodeType == HtmlNodeType.Element))
{
_lastparentnode = _currentnode;
}
if (HtmlNode.IsCDataElement(CurrentNodeName()))
{
_state = ParseState.PcData;
return true;
}
if ((HtmlNode.IsClosedElement(_currentnode.Name)) ||
(HtmlNode.IsEmptyElement(_currentnode.Name)))
{
close = true;
}
}
}
if ((close) || (!_currentnode._starttag))
{
if ((OptionStopperNodeName != null) && (_remainder == null) &&
(string.Compare(_currentnode.Name, OptionStopperNodeName, StringComparison.OrdinalIgnoreCase) == 0))
{
_remainderOffset = index;
_remainder = Text.Substring(_remainderOffset);
CloseCurrentNode();
return false; // stop parsing
}
CloseCurrentNode();
}
return true;
}
private void PushNodeNameEnd(int index)
{
_currentnode._namelength = index - _currentnode._namestartindex;
if (OptionFixNestedTags)
{
FixNestedTags();
}
}
private void PushNodeNameStart(bool starttag, int index)
{
_currentnode._starttag = starttag;
_currentnode._namestartindex = index;
}
private void PushNodeStart(HtmlNodeType type, int index)
{
_currentnode = CreateNode(type, index);
_currentnode._line = _line;
_currentnode._lineposition = _lineposition;
if (type == HtmlNodeType.Element)
{
_currentnode._lineposition--;
}
_currentnode._streamposition = index;
}
private void ReadDocumentEncoding(HtmlNode node)
{
if (!OptionReadEncoding)
return;
// format is
// <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
// when we append a child, we are in node end, so attributes are already populated
if (node._namelength != 4) // quick check, avoids string alloc
return;
if (node.Name != "meta") // all nodes names are lowercase
return;
HtmlAttribute att = node.Attributes["http-equiv"];
if (att == null)
return;
if (string.Compare(att.Value, "content-type", StringComparison.OrdinalIgnoreCase) != 0)
return;
HtmlAttribute content = node.Attributes["content"];
if (content != null)
{
string charset = NameValuePairList.GetNameValuePairsValue(content.Value, "charset");
if (!string.IsNullOrEmpty(charset))
{
// The following check fixes the the bug described at: http://htmlagilitypack.codeplex.com/WorkItem/View.aspx?WorkItemId=25273
if (string.Equals(charset, "utf8", StringComparison.OrdinalIgnoreCase))
charset = "utf-8";
try
{
_declaredencoding = Encoding.GetEncoding(charset);
}
catch (ArgumentException)
{
_declaredencoding = null;
}
if (_onlyDetectEncoding)
{
throw new EncodingFoundException(_declaredencoding);
}
if (_streamencoding != null)
{
#if SILVERLIGHT || PocketPC || METRO
if (_declaredencoding.WebName != _streamencoding.WebName)
#else
if (_declaredencoding != null)
if (_declaredencoding.WindowsCodePage != _streamencoding.WindowsCodePage)
#endif
{
AddError(
HtmlParseErrorCode.CharsetMismatch,
_line, _lineposition,
_index, node.OuterHtml,
"Encoding mismatch between StreamEncoding: " +
_streamencoding.WebName + " and DeclaredEncoding: " +
_declaredencoding.WebName);
}
}
}
}
}
#endregion
#region Nested type: ParseState
private enum ParseState
{
Text,
WhichTag,
Tag,
BetweenAttributes,
EmptyTag,
AttributeName,
AttributeBeforeEquals,
AttributeAfterEquals,
AttributeValue,
Comment,
QuotedAttributeValue,
ServerSideCode,
PcData
}
#endregion
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using IronPython.Runtime.Binding;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
#endif
[assembly: PythonModule("_struct", typeof(IronPython.Modules.PythonStruct))]
namespace IronPython.Modules {
public static class PythonStruct {
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.EnsureModuleException("structerror", dict, "error", "struct");
}
#region Public API
public const string __doc__ = null;
public const string __version__ = "0.2";
public const int _PY_STRUCT_FLOAT_COERCE = 0;
public const int _PY_STRUCT_OVERFLOW_MASKING = 0;
public const int _PY_STRUCT_RANGE_CHECKING = 0;
[PythonType, Documentation("Represents a compiled struct pattern")]
public class Struct : IWeakReferenceable {
private string _formatString; // the last format string passed to __init__
private Format[] _formats; // the various formatting options for the compiled struct
private bool _isStandardized; // true if the format is in standardized mode
private bool _isLittleEndian; // true if the format is in little endian mode
private int _encodingCount = -1; // the number of objects consumed/produced by the format
private int _encodingSize = -1; // the number of bytes read/produced by the format
private WeakRefTracker _tracker; // storage for weak proxy's
private void Initialize(Struct s) {
_formatString = s._formatString;
_formats = s._formats;
_isStandardized = s._isStandardized;
_isLittleEndian = s._isLittleEndian;
_encodingCount = s._encodingCount;
_encodingSize = s._encodingSize;
_tracker = s._tracker;
}
internal Struct(CodeContext/*!*/ context, [NotNull]string/*!*/ fmt) {
__init__(context, fmt);
}
#region Python construction
[Documentation("creates a new uninitialized struct object - all arguments are ignored")]
public Struct(params object[] args) {
}
[Documentation("creates a new uninitialized struct object - all arguments are ignored")]
public Struct([ParamDictionary]IDictionary<object, object> kwArgs, params object[] args) {
}
[Documentation("initializes or re-initializes the compiled struct object with a new format")]
public void __init__(CodeContext/*!*/ context, [NotNull]string/*!*/ fmt) {
ContractUtils.RequiresNotNull(fmt, "fmt");
_formatString = fmt;
Struct s;
bool gotIt;
lock (_cache) {
gotIt = _cache.TryGetValue(_formatString, out s);
}
if (gotIt) {
Initialize(s);
} else {
Compile(context, fmt);
}
}
#endregion
#region Public API
[Documentation("gets the current format string for the compiled Struct")]
public string format {
get {
return _formatString;
}
}
[Documentation("returns a string consisting of the values serialized according to the format of the struct object")]
public string/*!*/ pack(CodeContext/*!*/ context, params object[] values) {
if (values.Length != _encodingCount) {
throw Error(context, String.Format("pack requires exactly {0} arguments", _encodingCount));
}
int curObj = 0;
StringBuilder res = new StringBuilder(_encodingSize);
for (int i = 0; i < _formats.Length; i++) {
Format curFormat = _formats[i];
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
int nativeSize = curFormat.NativeSize;
int alignLength = Align(res.Length, nativeSize);
int padLength = alignLength - res.Length;
for (int j = 0; j < padLength; j++) {
res.Append('\0');
}
}
switch (curFormat.Type) {
case FormatType.PadByte:
res.Append('\0', curFormat.Count);
break;
case FormatType.Bool:
res.Append(GetBoolValue(context, curObj++, values) ? (char)1 : '\0');
break;
case FormatType.Char:
for (int j = 0; j < curFormat.Count; j++) {
res.Append(GetCharValue(context, curObj++, values));
}
break;
case FormatType.SignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res.Append((char)(byte)GetSByteValue(context, curObj++, values));
}
break;
case FormatType.UnsignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res.Append((char)GetByteValue(context, curObj++, values));
}
break;
case FormatType.Short:
for (int j = 0; j < curFormat.Count; j++) {
WriteShort(res, _isLittleEndian, GetShortValue(context, curObj++, values));
}
break;
case FormatType.UnsignedShort:
for (int j = 0; j < curFormat.Count; j++) {
WriteUShort(res, _isLittleEndian, GetUShortValue(context, curObj++, values));
}
break;
case FormatType.Int:
for (int j = 0; j < curFormat.Count; j++) {
WriteInt(res, _isLittleEndian, GetIntValue(context, curObj++, values));
}
break;
case FormatType.UnsignedInt:
for (int j = 0; j < curFormat.Count; j++) {
WriteUInt(res, _isLittleEndian, GetULongValue(context, _isStandardized, curObj++, values, "unsigned int"));
}
break;
case FormatType.UnsignedLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteUInt(res, _isLittleEndian, GetULongValue(context, _isStandardized, curObj++, values, "unsigned long"));
}
break;
case FormatType.Pointer:
for (int j = 0; j < curFormat.Count; j++) {
WritePointer(res, _isLittleEndian, GetPointer(context, curObj++, values));
}
break;
case FormatType.LongLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteLong(res, _isLittleEndian, GetLongValue(context, curObj++, values));
}
break;
case FormatType.UnsignedLongLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteULong(res, _isLittleEndian, GetULongLongValue(context, curObj++, values));
}
break;
case FormatType.Double:
for (int j = 0; j < curFormat.Count; j++) {
WriteDouble(res, _isLittleEndian, GetDoubleValue(context, curObj++, values));
}
break;
case FormatType.Float:
for (int j = 0; j < curFormat.Count; j++) {
WriteFloat(res, _isLittleEndian, (float)GetDoubleValue(context, curObj++, values));
}
break;
case FormatType.CString:
WriteString(res, curFormat.Count, GetStringValue(context, curObj++, values));
break;
case FormatType.PascalString:
WritePascalString(res, curFormat.Count - 1, GetStringValue(context, curObj++, values));
break;
default:
throw Error(context, "bad format string");
}
}
return res.ToString();
}
[Documentation("Stores the deserialized data into the provided array")]
public void pack_into(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer, int offset, params object[] args) {
byte[] existing = buffer.ToByteArray();
if (offset + size > existing.Length) {
throw Error(context, String.Format("pack_into requires a buffer of at least {0} bytes", size));
}
string data = pack(context, args);
for (int i = 0; i < data.Length; i++) {
existing[i + offset] = (byte)data[i];
}
buffer.Clear();
buffer.FromStream(new MemoryStream(existing));
}
[Documentation("deserializes the string using the structs specified format")]
public PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [NotNull]string @string) {
if (@string.Length != size) {
throw Error(context, String.Format("unpack requires a string argument of length {0}", size));
}
string data = @string;
int curIndex = 0;
List<object> res = new List<object>(_encodingCount);
for (int i = 0; i < _formats.Length; i++) {
Format curFormat = _formats[i];
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
int nativeSize = curFormat.NativeSize;
if (nativeSize > 0) {
curIndex = Align(curIndex, nativeSize);
}
}
switch (curFormat.Type) {
case FormatType.PadByte:
curIndex += curFormat.Count;
break;
case FormatType.Bool:
for (int j = 0; j < curFormat.Count; j++) {
res.Add(CreateBoolValue(context, ref curIndex, data));
}
break;
case FormatType.Char:
for (int j = 0; j < curFormat.Count; j++) {
res.Add(CreateCharValue(context, ref curIndex, data).ToString());
}
break;
case FormatType.SignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res.Add((int)(sbyte)CreateCharValue(context, ref curIndex, data));
}
break;
case FormatType.UnsignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res.Add((int)CreateCharValue(context, ref curIndex, data));
}
break;
case FormatType.Short:
for (int j = 0; j < curFormat.Count; j++) {
res.Add((int)CreateShortValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.UnsignedShort:
for (int j = 0; j < curFormat.Count; j++) {
res.Add((int)CreateUShortValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.Int:
for (int j = 0; j < curFormat.Count; j++) {
res.Add(CreateIntValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.UnsignedInt:
case FormatType.UnsignedLong:
for (int j = 0; j < curFormat.Count; j++) {
res.Add(BigIntegerOps.__int__((BigInteger)CreateUIntValue(context, ref curIndex, _isLittleEndian, data)));
}
break;
case FormatType.Pointer:
for (int j = 0; j < curFormat.Count; j++) {
if (IntPtr.Size == 4) {
res.Add(CreateIntValue(context, ref curIndex, _isLittleEndian, data));
} else {
res.Add(BigIntegerOps.__int__((BigInteger)CreateLongValue(context, ref curIndex, _isLittleEndian, data)));
}
}
break;
case FormatType.LongLong:
for (int j = 0; j < curFormat.Count; j++) {
res.Add(BigIntegerOps.__int__((BigInteger)CreateLongValue(context, ref curIndex, _isLittleEndian, data)));
}
break;
case FormatType.UnsignedLongLong:
for (int j = 0; j < curFormat.Count; j++) {
res.Add(BigIntegerOps.__int__((BigInteger)CreateULongValue(context, ref curIndex, _isLittleEndian, data)));
}
break;
case FormatType.Float:
for (int j = 0; j < curFormat.Count; j++) {
res.Add((double)CreateFloatValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.Double:
for (int j = 0; j < curFormat.Count; j++) {
res.Add(CreateDoubleValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.CString:
res.Add(CreateString(context, ref curIndex, curFormat.Count, data));
break;
case FormatType.PascalString:
res.Add(CreatePascalString(context, ref curIndex, curFormat.Count - 1, data));
break;
}
}
return new PythonTuple(res);
}
public PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer) {
return unpack_from(context, buffer, 0);
}
public PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [NotNull]PythonBuffer/*!*/ buffer) {
return unpack_from(context, buffer, 0);
}
[Documentation("reads the current format from the specified array")]
public PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer, [DefaultParameterValue(0)] int offset) {
return unpack_from(context, buffer.ToByteArray().MakeString(), offset);
}
[Documentation("reads the current format from the specified string")]
public PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [NotNull]string/*!*/ buffer, [DefaultParameterValue(0)] int offset) {
int bytesAvail = buffer.Length - offset;
if (bytesAvail < size) {
throw Error(context, String.Format("unpack_from requires a buffer of at least {0} bytes", size));
}
return unpack(context, buffer.Substring(offset, size));
}
[Documentation("reads the current format from the specified buffer object")]
public PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [NotNull]PythonBuffer/*!*/ buffer, [DefaultParameterValue(0)] int offset) {
return unpack_from(context, buffer.ToString(), offset);
}
[Documentation("gets the number of bytes that the serialized string will occupy or are required to deserialize the data")]
public int size {
get {
return _encodingSize;
}
}
#endregion
#region IWeakReferenceable Members
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _tracker;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
return Interlocked.CompareExchange(ref _tracker, value, null) == null;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
_tracker = value;
}
#endregion
#region Implementation Details
private void Compile(CodeContext/*!*/ context, string/*!*/ fmt) {
List<Format> res = new List<Format>();
int count = 1;
bool fLittleEndian = BitConverter.IsLittleEndian;
bool fStandardized = false;
for (int i = 0; i < fmt.Length; i++) {
switch (fmt[i]) {
case 'x': // pad byte
res.Add(new Format(FormatType.PadByte, count));
count = 1;
break;
case '?': // bool
res.Add(new Format(FormatType.Bool, count));
count = 1;
break;
case 'c': // char
res.Add(new Format(FormatType.Char, count));
count = 1;
break;
case 'b': // signed char
res.Add(new Format(FormatType.SignedChar, count));
count = 1;
break;
case 'B': // unsigned char
res.Add(new Format(FormatType.UnsignedChar, count));
count = 1;
break;
case 'h': // short
res.Add(new Format(FormatType.Short, count));
count = 1;
break;
case 'H': // unsigned short
res.Add(new Format(FormatType.UnsignedShort, count));
count = 1;
break;
case 'i': // int
case 'l': // long
res.Add(new Format(FormatType.Int, count));
count = 1;
break;
case 'I': // unsigned int
res.Add(new Format(FormatType.UnsignedInt, count));
count = 1;
break;
case 'L': // unsigned long
res.Add(new Format(FormatType.UnsignedLong, count));
count = 1;
break;
case 'q': // long long
res.Add(new Format(FormatType.LongLong, count));
count = 1;
break;
case 'Q': // unsigned long long
res.Add(new Format(FormatType.UnsignedLongLong, count));
count = 1;
break;
case 'f': // float
res.Add(new Format(FormatType.Float, count));
count = 1;
break;
case 'd': // double
res.Add(new Format(FormatType.Double, count));
count = 1;
break;
case 's': // char[]
res.Add(new Format(FormatType.CString, count));
count = 1;
break;
case 'p': // pascal char[]
res.Add(new Format(FormatType.PascalString, count));
count = 1;
break;
case 'P': // void *
res.Add(new Format(FormatType.Pointer, count));
count = 1;
break;
case ' ': // white space, ignore
case '\t':
break;
case '=': // native
if (i != 0) throw Error(context, "unexpected byte order");
fStandardized = true;
break;
case '@': // native
if (i != 0) throw Error(context, "unexpected byte order");
break;
case '<': // little endian
if (i != 0) throw Error(context, "unexpected byte order");
fLittleEndian = true;
fStandardized = true;
break;
case '>': // big endian
case '!': // big endian
if (i != 0) throw Error(context, "unexpected byte order");
fLittleEndian = false;
fStandardized = true;
break;
default:
if (Char.IsDigit(fmt[i])) {
count = 0;
while (Char.IsDigit(fmt[i])) {
count = count * 10 + (fmt[i] - '0');
i++;
}
if (Char.IsWhiteSpace(fmt[i])) Error(context, "white space not allowed between count and format");
i--;
break;
}
throw Error(context, "bad format string");
}
}
// store the new formats
_formats = res.ToArray();
_isStandardized = fStandardized;
_isLittleEndian = fLittleEndian;
_encodingSize = _encodingCount = 0;
for (int i = 0; i < _formats.Length; i++) {
if (_formats[i].Type != FormatType.PadByte) {
if (_formats[i].Type != FormatType.CString && _formats[i].Type != FormatType.PascalString) {
_encodingCount += _formats[i].Count;
} else {
_encodingCount++;
}
}
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
_encodingSize = Align(_encodingSize, _formats[i].NativeSize);
}
_encodingSize += GetNativeSize(_formats[i].Type) * _formats[i].Count;
}
lock (_cache) {
_cache.Add(fmt, this);
}
}
#endregion
#region Internal helpers
internal static Struct Create(string/*!*/ format) {
Struct res = new Struct();
res.__init__(DefaultContext.Default, format); // default context is only used for errors, this better be an error free format.
return res;
}
#endregion
}
#endregion
#region Compiled Format
/// <summary>
/// Enum which specifies the format type for a compiled struct
/// </summary>
private enum FormatType {
None,
PadByte,
Bool,
Char,
SignedChar,
UnsignedChar,
Short,
UnsignedShort,
Int,
UnsignedInt,
UnsignedLong,
Float,
LongLong,
UnsignedLongLong,
Double,
CString,
PascalString,
Pointer,
}
private static int GetNativeSize(FormatType c) {
switch (c) {
case FormatType.Char:
case FormatType.SignedChar:
case FormatType.UnsignedChar:
case FormatType.PadByte:
case FormatType.Bool:
case FormatType.CString:
case FormatType.PascalString:
return 1;
case FormatType.Short:
case FormatType.UnsignedShort:
return 2;
case FormatType.Int:
case FormatType.UnsignedInt:
case FormatType.UnsignedLong:
case FormatType.Float:
return 4;
case FormatType.LongLong:
case FormatType.UnsignedLongLong:
case FormatType.Double:
return 8;
case FormatType.Pointer:
return IntPtr.Size;
default:
throw new InvalidOperationException(c.ToString());
}
}
/// <summary>
/// Struct used to store the format and the number of times it should be repeated.
/// </summary>
private struct Format {
public FormatType Type;
public int Count;
public Format(FormatType type, int count) {
Type = type;
Count = count;
}
public int NativeSize {
get {
return GetNativeSize(Type);
}
}
}
#endregion
#region Cache of compiled struct patterns
private const int MAX_CACHE_SIZE = 1024;
private static CacheDict<string, Struct> _cache = new CacheDict<string, Struct>(MAX_CACHE_SIZE);
private static Struct GetStructFromCache(CodeContext/*!*/ context, [NotNull] string fmt/*!*/) {
Struct s;
bool gotIt;
lock (_cache) {
gotIt = _cache.TryGetValue(fmt, out s);
}
if (!gotIt) {
s = new Struct(context, fmt);
}
return s;
}
[Documentation("Clear the internal cache.")]
public static void _clearcache() {
_cache = new CacheDict<string, Struct>(MAX_CACHE_SIZE);
}
[Documentation("int(x[, base]) -> integer\n\nConvert a string or number to an integer, if possible. A floating point\nargument will be truncated towards zero (this does not include a string\nrepresentation of a floating point number!) When converting a string, use\nthe optional base. It is an error to supply a base when converting a\nnon-string. If base is zero, the proper base is guessed based on the\nstring content. If the argument is outside the integer range a\nlong object will be returned instead.")]
public static int calcsize(CodeContext/*!*/ context, [NotNull]string fmt) {
return GetStructFromCache(context, fmt).size;
}
[Documentation("Return string containing values v1, v2, ... packed according to fmt.")]
public static string/*!*/ pack(CodeContext/*!*/ context, [BytesConversion][NotNull]string fmt/*!*/, params object[] values)
{
return GetStructFromCache(context, fmt).pack(context, values);
}
[Documentation("Pack the values v1, v2, ... according to fmt.\nWrite the packed bytes into the writable buffer buf starting at offset.")]
public static void pack_into(CodeContext/*!*/ context, [BytesConversion][NotNull]string/*!*/ fmt, [NotNull]ArrayModule.array/*!*/ buffer, int offset, params object[] args)
{
GetStructFromCache(context, fmt).pack_into(context, buffer, offset, args);
}
[Documentation("Unpack the string containing packed C structure data, according to fmt.\nRequires len(string) == calcsize(fmt).")]
public static PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [BytesConversion][NotNull]string/*!*/ fmt, [BytesConversion][NotNull]string/*!*/ @string)
{
return GetStructFromCache(context, fmt).unpack(context, @string);
}
[Documentation("Unpack the string containing packed C structure data, according to fmt.\nRequires len(string) == calcsize(fmt).")]
public static PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [BytesConversion][NotNull]string/*!*/ fmt, [NotNull]ArrayModule.array/*!*/ buffer)
{
return GetStructFromCache(context, fmt).unpack(context, buffer);
}
[Documentation("Unpack the string containing packed C structure data, according to fmt.\nRequires len(string) == calcsize(fmt).")]
public static PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [BytesConversion][NotNull]string fmt/*!*/, [NotNull]PythonBuffer/*!*/ buffer)
{
return GetStructFromCache(context, fmt).unpack(context, buffer);
}
[Documentation("Unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [BytesConversion][NotNull]string fmt/*!*/, [NotNull]ArrayModule.array/*!*/ buffer, [DefaultParameterValue(0)] int offset)
{
return GetStructFromCache(context, fmt).unpack_from(context, buffer, offset);
}
[Documentation("Unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [BytesConversion][NotNull]string fmt/*!*/, [BytesConversion][NotNull]string/*!*/ buffer, [DefaultParameterValue(0)] int offset)
{
return GetStructFromCache(context, fmt).unpack_from(context, buffer, offset);
}
[Documentation("Unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [BytesConversion][NotNull]string fmt/*!*/, [NotNull]PythonBuffer/*!*/ buffer, [DefaultParameterValue(0)] int offset)
{
return GetStructFromCache(context, fmt).unpack_from(context, buffer, offset);
}
#endregion
#region Write Helpers
private static void WriteShort(StringBuilder res, bool fLittleEndian, short val) {
if (fLittleEndian) {
res.Append((char)(val & 0xff));
res.Append((char)((val >> 8) & 0xff));
} else {
res.Append((char)((val >> 8) & 0xff));
res.Append((char)(val & 0xff));
}
}
private static void WriteUShort(StringBuilder res, bool fLittleEndian, ushort val) {
if (fLittleEndian) {
res.Append((char)(val & 0xff));
res.Append((char)((val >> 8) & 0xff));
} else {
res.Append((char)((val >> 8) & 0xff));
res.Append((char)(val & 0xff));
}
}
private static void WriteInt(StringBuilder res, bool fLittleEndian, int val) {
if (fLittleEndian) {
res.Append((char)(val & 0xff));
res.Append((char)((val >> 8) & 0xff));
res.Append((char)((val >> 16) & 0xff));
res.Append((char)((val >> 24) & 0xff));
} else {
res.Append((char)((val >> 24) & 0xff));
res.Append((char)((val >> 16) & 0xff));
res.Append((char)((val >> 8) & 0xff));
res.Append((char)(val & 0xff));
}
}
private static void WriteUInt(StringBuilder res, bool fLittleEndian, uint val) {
if (fLittleEndian) {
res.Append((char)(val & 0xff));
res.Append((char)((val >> 8) & 0xff));
res.Append((char)((val >> 16) & 0xff));
res.Append((char)((val >> 24) & 0xff));
} else {
res.Append((char)((val >> 24) & 0xff));
res.Append((char)((val >> 16) & 0xff));
res.Append((char)((val >> 8) & 0xff));
res.Append((char)(val & 0xff));
}
}
private static void WritePointer(StringBuilder res, bool fLittleEndian, IntPtr val) {
if (IntPtr.Size == 4) {
WriteInt(res, fLittleEndian, val.ToInt32());
} else {
WriteLong(res, fLittleEndian, val.ToInt64());
}
}
private static void WriteFloat(StringBuilder res, bool fLittleEndian, float val) {
byte[] bytes = BitConverter.GetBytes(val);
if (fLittleEndian) {
res.Append((char)bytes[0]);
res.Append((char)bytes[1]);
res.Append((char)bytes[2]);
res.Append((char)bytes[3]);
} else {
res.Append((char)bytes[3]);
res.Append((char)bytes[2]);
res.Append((char)bytes[1]);
res.Append((char)bytes[0]);
}
}
private static void WriteLong(StringBuilder res, bool fLittleEndian, long val) {
if (fLittleEndian) {
res.Append((char)(val & 0xff));
res.Append((char)((val >> 8) & 0xff));
res.Append((char)((val >> 16) & 0xff));
res.Append((char)((val >> 24) & 0xff));
res.Append((char)((val >> 32) & 0xff));
res.Append((char)((val >> 40) & 0xff));
res.Append((char)((val >> 48) & 0xff));
res.Append((char)((val >> 56) & 0xff));
} else {
res.Append((char)((val >> 56) & 0xff));
res.Append((char)((val >> 48) & 0xff));
res.Append((char)((val >> 40) & 0xff));
res.Append((char)((val >> 32) & 0xff));
res.Append((char)((val >> 24) & 0xff));
res.Append((char)((val >> 16) & 0xff));
res.Append((char)((val >> 8) & 0xff));
res.Append((char)(val & 0xff));
}
}
private static void WriteULong(StringBuilder res, bool fLittleEndian, ulong val) {
if (fLittleEndian) {
res.Append((char)(val & 0xff));
res.Append((char)((val >> 8) & 0xff));
res.Append((char)((val >> 16) & 0xff));
res.Append((char)((val >> 24) & 0xff));
res.Append((char)((val >> 32) & 0xff));
res.Append((char)((val >> 40) & 0xff));
res.Append((char)((val >> 48) & 0xff));
res.Append((char)((val >> 56) & 0xff));
} else {
res.Append((char)((val >> 56) & 0xff));
res.Append((char)((val >> 48) & 0xff));
res.Append((char)((val >> 40) & 0xff));
res.Append((char)((val >> 32) & 0xff));
res.Append((char)((val >> 24) & 0xff));
res.Append((char)((val >> 16) & 0xff));
res.Append((char)((val >> 8) & 0xff));
res.Append((char)(val & 0xff));
}
}
private static void WriteDouble(StringBuilder res, bool fLittleEndian, double val) {
byte[] bytes = BitConverter.GetBytes(val);
if (fLittleEndian) {
res.Append((char)bytes[0]);
res.Append((char)bytes[1]);
res.Append((char)bytes[2]);
res.Append((char)bytes[3]);
res.Append((char)bytes[4]);
res.Append((char)bytes[5]);
res.Append((char)bytes[6]);
res.Append((char)bytes[7]);
} else {
res.Append((char)bytes[7]);
res.Append((char)bytes[6]);
res.Append((char)bytes[5]);
res.Append((char)bytes[4]);
res.Append((char)bytes[3]);
res.Append((char)bytes[2]);
res.Append((char)bytes[1]);
res.Append((char)bytes[0]);
}
}
private static void WriteString(StringBuilder res, int len, string val) {
for (int i = 0; i < val.Length && i < len; i++) {
res.Append(val[i]);
}
for (int i = val.Length; i < len; i++) {
res.Append('\0');
}
}
private static void WritePascalString(StringBuilder res, int len, string val) {
int lenByte = Math.Min(255, Math.Min(val.Length, len));
res.Append((char)lenByte);
for (int i = 0; i < val.Length && i < len; i++) {
res.Append(val[i]);
}
for (int i = val.Length; i < len; i++) {
res.Append('\0');
}
}
#endregion
#region Data getter helpers
internal static bool GetBoolValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
object res;
if (Converter.TryConvert(val, typeof(bool), out res)) {
return (bool)res;
}
// Should never happen
throw Error(context, "expected bool value got " + val.ToString());
}
internal static char GetCharValue(CodeContext/*!*/ context, int index, object[] args) {
string val = GetValue(context, index, args) as string;
if (val == null || val.Length != 1) throw Error(context, "char format requires string of length 1");
return val[0];
}
internal static sbyte GetSByteValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
sbyte res;
if (Converter.TryConvertToSByte(val, out res)) {
return res;
}
throw Error(context, "expected sbyte value got " + val.ToString());
}
internal static byte GetByteValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
byte res;
if (Converter.TryConvertToByte(val, out res)) return res;
char cres;
if (Converter.TryConvertToChar(val, out cres)) return (byte)cres;
throw Error(context, "expected byte value got " + val.ToString());
}
internal static short GetShortValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
short res;
if (Converter.TryConvertToInt16(val, out res)) return res;
throw Error(context, "expected short value");
}
internal static ushort GetUShortValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
ushort res;
if (Converter.TryConvertToUInt16(val, out res)) return res;
throw Error(context, "expected ushort value");
}
internal static int GetIntValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
int res;
if (Converter.TryConvertToInt32(val, out res)) return res;
throw Error(context, "expected int value");
}
internal static uint GetUIntValue(CodeContext/*!*/ context, bool isStandardized, int index, object[] args) {
object val = GetValue(context, index, args);
uint res;
if (Converter.TryConvertToUInt32(val, out res)) {
return res;
}
if (isStandardized) {
throw Error(context, "expected unsigned long value");
}
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "'I' format requires 0 <= number <= 4294967295");
return 0;
}
internal static uint GetULongValue(CodeContext/*!*/ context, bool isStandardized, int index, object[] args, string type) {
object val = GetValue(context, index, args);
uint res;
if (val is int) {
res = (uint)(int)val;
WarnRange(context, (int)val, isStandardized, type);
} else if (val is BigInteger) {
res = (uint)(((BigInteger)val) & 0xffffffff);
WarnRange(context, (BigInteger)val, isStandardized, type);
} else if (val is Extensible<int>) {
res = (uint)((Extensible<int>)val).Value;
WarnRange(context, ((Extensible<int>)val).Value, isStandardized, type);
} else if (val is Extensible<BigInteger>) {
res = (uint)(((Extensible<BigInteger>)val).Value & 0xffffffff);
BigInteger bi = ((Extensible<BigInteger>)val).Value;
WarnRange(context, bi, isStandardized, type);
} else {
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "struct integer overflow masking is deprecated");
object maskedValue = PythonContext.GetContext(context).Operation(PythonOperationKind.BitwiseAnd, val, (BigInteger)4294967295);
if (!Converter.TryConvertToUInt32(maskedValue, out res)) {
throw PythonOps.OverflowError("can't convert to " + type);
}
}
return res;
}
private static void WarnRange(CodeContext context, int val, bool isStandardized, string type) {
if (val < 0) {
WarnRange(context, isStandardized, type);
}
}
private static void WarnRange(CodeContext context, BigInteger bi, bool isStandardized, string type) {
if (bi < 0 || bi > 4294967295) {
WarnRange(context, isStandardized, type);
}
}
private static void WarnRange(CodeContext context, bool isStandardized, string type) {
if (isStandardized) {
throw Error(context, "expected " + type + " value");
}
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, (type == "unsigned long" ? "'L'" : "'I'") + " format requires 0 <= number <= 4294967295");
}
internal static IntPtr GetPointer(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (IntPtr.Size == 4) {
uint res;
if (Converter.TryConvertToUInt32(val, out res)) {
return new IntPtr(res);
}
} else {
long res;
if (Converter.TryConvertToInt64(val, out res)) {
return new IntPtr(res);
}
}
throw Error(context, "expected pointer value");
}
internal static long GetLongValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
long res;
if (Converter.TryConvertToInt64(val, out res)) return res;
throw Error(context, "expected long value");
}
internal static ulong GetULongLongValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
ulong res;
if (Converter.TryConvertToUInt64(val, out res)) return res;
throw Error(context, "expected ulong value");
}
internal static double GetDoubleValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
double res;
if (Converter.TryConvertToDouble(val, out res)) return res;
throw Error(context, "expected double value");
}
internal static string GetStringValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
string res;
if (Converter.TryConvertToString(val, out res)) return res;
throw Error(context, "expected string value");
}
internal static object GetValue(CodeContext/*!*/ context, int index, object[] args) {
if (index >= args.Length) throw Error(context, "not enough arguments");
return args[index];
}
#endregion
#region Data creater helpers
internal static bool CreateBoolValue(CodeContext/*!*/ context, ref int index, string data) {
return (int)ReadData(context, ref index, data) != 0;
}
internal static char CreateCharValue(CodeContext/*!*/ context, ref int index, string data) {
return ReadData(context, ref index, data);
}
internal static short CreateShortValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, string data) {
byte b1 = (byte)ReadData(context, ref index, data);
byte b2 = (byte)ReadData(context, ref index, data);
if (fLittleEndian) {
return (short)((b2 << 8) | b1);
} else {
return (short)((b1 << 8) | b2);
}
}
internal static ushort CreateUShortValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, string data) {
byte b1 = (byte)ReadData(context, ref index, data);
byte b2 = (byte)ReadData(context, ref index, data);
if (fLittleEndian) {
return (ushort)((b2 << 8) | b1);
} else {
return (ushort)((b1 << 8) | b2);
}
}
internal static float CreateFloatValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, string data) {
byte[] bytes = new byte[4];
if (fLittleEndian) {
bytes[0] = (byte)ReadData(context, ref index, data);
bytes[1] = (byte)ReadData(context, ref index, data);
bytes[2] = (byte)ReadData(context, ref index, data);
bytes[3] = (byte)ReadData(context, ref index, data);
} else {
bytes[3] = (byte)ReadData(context, ref index, data);
bytes[2] = (byte)ReadData(context, ref index, data);
bytes[1] = (byte)ReadData(context, ref index, data);
bytes[0] = (byte)ReadData(context, ref index, data);
}
float res = BitConverter.ToSingle(bytes, 0);
if (PythonContext.GetContext(context).FloatFormat == FloatFormat.Unknown) {
if (Single.IsNaN(res) || Single.IsInfinity(res)) {
throw PythonOps.ValueError("can't unpack IEEE 754 special value on non-IEEE platform");
}
}
return res;
}
internal static int CreateIntValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, string data) {
byte b1 = (byte)ReadData(context, ref index, data);
byte b2 = (byte)ReadData(context, ref index, data);
byte b3 = (byte)ReadData(context, ref index, data);
byte b4 = (byte)ReadData(context, ref index, data);
if (fLittleEndian)
return (int)((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
else
return (int)((b1 << 24) | (b2 << 16) | (b3 << 8) | b4);
}
internal static uint CreateUIntValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, string data) {
byte b1 = (byte)ReadData(context, ref index, data);
byte b2 = (byte)ReadData(context, ref index, data);
byte b3 = (byte)ReadData(context, ref index, data);
byte b4 = (byte)ReadData(context, ref index, data);
if (fLittleEndian)
return (uint)((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
else
return (uint)((b1 << 24) | (b2 << 16) | (b3 << 8) | b4);
}
internal static long CreateLongValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, string data) {
long b1 = (byte)ReadData(context, ref index, data);
long b2 = (byte)ReadData(context, ref index, data);
long b3 = (byte)ReadData(context, ref index, data);
long b4 = (byte)ReadData(context, ref index, data);
long b5 = (byte)ReadData(context, ref index, data);
long b6 = (byte)ReadData(context, ref index, data);
long b7 = (byte)ReadData(context, ref index, data);
long b8 = (byte)ReadData(context, ref index, data);
if (fLittleEndian)
return (long)((b8 << 56) | (b7 << 48) | (b6 << 40) | (b5 << 32) |
(b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
else
return (long)((b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) |
(b5 << 24) | (b6 << 16) | (b7 << 8) | b8);
}
internal static ulong CreateULongValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, string data) {
ulong b1 = (byte)ReadData(context, ref index, data);
ulong b2 = (byte)ReadData(context, ref index, data);
ulong b3 = (byte)ReadData(context, ref index, data);
ulong b4 = (byte)ReadData(context, ref index, data);
ulong b5 = (byte)ReadData(context, ref index, data);
ulong b6 = (byte)ReadData(context, ref index, data);
ulong b7 = (byte)ReadData(context, ref index, data);
ulong b8 = (byte)ReadData(context, ref index, data);
if (fLittleEndian)
return (ulong)((b8 << 56) | (b7 << 48) | (b6 << 40) | (b5 << 32) |
(b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
else
return (ulong)((b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) |
(b5 << 24) | (b6 << 16) | (b7 << 8) | b8);
}
internal static double CreateDoubleValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, string data) {
byte[] bytes = new byte[8];
if (fLittleEndian) {
bytes[0] = (byte)ReadData(context, ref index, data);
bytes[1] = (byte)ReadData(context, ref index, data);
bytes[2] = (byte)ReadData(context, ref index, data);
bytes[3] = (byte)ReadData(context, ref index, data);
bytes[4] = (byte)ReadData(context, ref index, data);
bytes[5] = (byte)ReadData(context, ref index, data);
bytes[6] = (byte)ReadData(context, ref index, data);
bytes[7] = (byte)ReadData(context, ref index, data);
} else {
bytes[7] = (byte)ReadData(context, ref index, data);
bytes[6] = (byte)ReadData(context, ref index, data);
bytes[5] = (byte)ReadData(context, ref index, data);
bytes[4] = (byte)ReadData(context, ref index, data);
bytes[3] = (byte)ReadData(context, ref index, data);
bytes[2] = (byte)ReadData(context, ref index, data);
bytes[1] = (byte)ReadData(context, ref index, data);
bytes[0] = (byte)ReadData(context, ref index, data);
}
double res = BitConverter.ToDouble(bytes, 0);
if (PythonContext.GetContext(context).DoubleFormat == FloatFormat.Unknown) {
if (Double.IsNaN(res) || Double.IsInfinity(res)) {
throw PythonOps.ValueError("can't unpack IEEE 754 special value on non-IEEE platform");
}
}
return res;
}
internal static string CreateString(CodeContext/*!*/ context, ref int index, int count, string data) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < count; i++) {
res.Append(ReadData(context, ref index, data));
}
return res.ToString();
}
internal static string CreatePascalString(CodeContext/*!*/ context, ref int index, int count, string data) {
int realLen = (int)ReadData(context, ref index, data);
StringBuilder res = new StringBuilder();
for (int i = 0; i < realLen; i++) {
res.Append(ReadData(context, ref index, data));
}
for (int i = realLen; i < count; i++) {
// throw away null bytes
ReadData(context, ref index, data);
}
return res.ToString();
}
private static char ReadData(CodeContext/*!*/ context, ref int index, string data) {
if (index >= data.Length) throw Error(context, "not enough data while reading");
return data[index++];
}
#endregion
#region Misc. Private APIs
internal static int Align(int length, int size) {
return length + (size - 1) & ~(size - 1);
}
private static Exception Error(CodeContext/*!*/ context, string msg) {
return PythonExceptions.CreateThrowable((PythonType)PythonContext.GetContext(context).GetModuleState("structerror"), msg);
}
#endregion
}
}
| |
#region Copyright (c) 2004 Ian Davis and James Carlyle
/*------------------------------------------------------------------------------
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 2004 Ian Davis and James Carlyle
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
namespace SemPlan.Spiral.Utility {
using SemPlan.Spiral.Core;
using System;
using System.IO;
using System.Collections;
using System.Xml;
/// <summary>
/// A simple RDF model implementation
/// </summary>
/// <remarks>
/// $Id: SimpleModel.cs,v 1.2 2005/05/26 14:24:31 ian Exp $
///</remarks>
public class SimpleModel {
private Dereferencer itsDereferencer;
private ArrayList itsStatements;
private ParserFactory itsParserFactory;
private TripleStore itsTripleStore;
public SimpleModel(ParserFactory parserFactory) {
itsParserFactory = parserFactory;
itsStatements = new ArrayList();
itsTripleStore = new MemoryTripleStore();
itsDereferencer = new SimpleDereferencer();
}
public void SetParserFactory(ParserFactory parserFactory) {
itsParserFactory = parserFactory;
}
public void ParseString(string content, string baseUri) {
StringReader reader = new StringReader(content);
Parse( reader, baseUri);
}
/// <summary>
/// Parse the RDF at the given URI
/// </summary>
public void Parse(Uri uri, string baseUri) {
DereferencerResponse response = itsDereferencer.Dereference( uri );
if ( response.HasContent ) {
Parse( response.Stream, uri.ToString() );
}
response.Stream.Close();
}
/// <summary>
/// Parse the RDF using the string paramater as a URI
/// </summary>
public void Parse(string uri, string baseUri) {
DereferencerResponse response = itsDereferencer.Dereference( uri );
if ( response.HasContent ) {
Parse( response.Stream, uri.ToString() );
}
response.Stream.Close();
}
/// <summary>
/// Parse the RDF using supplied TextReader and base URI
/// </summary>
public void Parse(TextReader reader, string baseUri) {
Parser parser = itsParserFactory.MakeParser(new ResourceFactory(), new StatementFactory());
StatementHandler handler = new StatementHandler(Add);
StatementHandler tripleStoreHandler = itsTripleStore.GetStatementHandler();
parser.NewStatement += handler;
parser.NewStatement += tripleStoreHandler;
parser.Parse(reader, baseUri);
parser.NewStatement -= handler;
parser.NewStatement -= tripleStoreHandler;
}
/// <summary>
/// Parse the RDF using supplied stream and base URI
/// </summary>
public void Parse(Stream stream, string baseUri) {
Parser parser = itsParserFactory.MakeParser(new ResourceFactory(), new StatementFactory());
StatementHandler handler = new StatementHandler(Add);
StatementHandler tripleStoreHandler = itsTripleStore.GetStatementHandler();
parser.NewStatement += handler;
parser.NewStatement += tripleStoreHandler;
parser.Parse(stream, baseUri);
parser.NewStatement -= handler;
parser.NewStatement -= tripleStoreHandler;
}
public void Add(Statement statement) {
itsStatements.Add(statement);
}
public int Count {
get {
return itsStatements.Count;
}
}
public IEnumerator GetEnumerator() {
return new NTripleEnumerator(this);
}
public void Write(RdfWriter writer) {
writer.StartOutput();
foreach (Statement statement in itsStatements) {
statement.Write(writer);
}
writer.EndOutput();
}
public override string ToString() {
StringWriter output = new StringWriter();
NTripleWriter writer = new NTripleWriter(output);
Write(writer);
return output.ToString();
}
private class NTripleEnumerator : IEnumerator {
private ArrayList itsNTriples;
private int itsIndex;
public NTripleEnumerator(SimpleModel model) {
itsIndex = -1;
itsNTriples = new ArrayList();
StringWriter received = new StringWriter();
NTripleWriter writer = new NTripleWriter(received);
model.Write(writer);
StringReader receivedReader = new StringReader(received.ToString());
string receivedLine = receivedReader.ReadLine();
while (receivedLine != null) {
string trimmed = receivedLine.Trim();
if (trimmed.Length > 0 && ! trimmed.StartsWith("#") ) {
itsNTriples.Add( trimmed );
}
receivedLine = receivedReader.ReadLine();
}
}
public object Current {
get {
if (itsIndex < itsNTriples.Count) {
return itsNTriples[itsIndex];
}
else {
return null;
}
}
}
public bool MoveNext() {
if ( ++itsIndex < itsNTriples.Count ) {
return true;
}
else {
return false;
}
}
public void Reset() {
itsIndex = -1;
}
}
}
}
| |
/* ====================================================================
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 NPOI.SS.UserModel
{
using System;
using System.Collections;
using System.IO;
using NPOI.SS.Formula.Udf;
using System.Collections.Generic;
public enum SheetState : int
{
/// <summary>
/// Indicates the sheet is visible.
/// </summary>
Visible = 0,
/// <summary>
/// Indicates the book window is hidden, but can be shown by the user via the user interface.
/// </summary>
Hidden = 1,
/// <summary>
/// Indicates the sheet is hidden and cannot be shown in the user interface (UI).
/// </summary>
/// <remarks>
/// In Excel this state is only available programmatically in VBA:
/// ThisWorkbook.Sheets("MySheetName").Visible = xlSheetVeryHidden
///
/// </remarks>
VeryHidden = 2
}
/// <summary>
/// High level interface of a Excel workbook. This is the first object most users
/// will construct whether they are reading or writing a workbook. It is also the
/// top level object for creating new sheets/etc.
/// This interface is shared between the implementation specific to xls and xlsx.
/// This way it is possible to access Excel workbooks stored in both formats.
/// </summary>
public interface IWorkbook: IList<ISheet>
{
/// <summary>
/// get the active sheet. The active sheet is is the sheet
/// which is currently displayed when the workbook is viewed in Excel.
/// </summary>
int ActiveSheetIndex { get; }
/// <summary>
/// Gets the first tab that is displayed in the list of tabs in excel.
/// </summary>
int FirstVisibleTab { get; set; }
/// <summary>
/// Sets the order of appearance for a given sheet.
/// </summary>
/// <param name="sheetname">the name of the sheet to reorder</param>
/// <param name="pos">the position that we want to insert the sheet into (0 based)</param>
void SetSheetOrder(String sheetname, int pos);
/// <summary>
/// Sets the tab whose data is actually seen when the sheet is opened.
/// This may be different from the "selected sheet" since excel seems to
/// allow you to show the data of one sheet when another is seen "selected"
/// in the tabs (at the bottom).
/// </summary>
/// <param name="index">the index of the sheet to select (0 based)</param>
void SetSelectedTab(int index);
/// <summary>
/// set the active sheet. The active sheet is is the sheet
/// which is currently displayed when the workbook is viewed in Excel.
/// </summary>
/// <param name="sheetIndex">index of the active sheet (0-based)</param>
void SetActiveSheet(int sheetIndex);
/// <summary>
/// Set the sheet name
/// </summary>
/// <param name="sheet">sheet number (0 based)</param>
/// <returns>Sheet name</returns>
String GetSheetName(int sheet);
/// <summary>
/// Set the sheet name.
/// </summary>
/// <param name="sheet">sheet number (0 based)</param>
/// <param name="name">sheet name</param>
void SetSheetName(int sheet, String name);
/// <summary>
/// Returns the index of the sheet by its name
/// </summary>
/// <param name="name">the sheet name</param>
/// <returns>index of the sheet (0 based)</returns>
int GetSheetIndex(String name);
/// <summary>
/// Returns the index of the given sheet
/// </summary>
/// <param name="sheet">the sheet to look up</param>
/// <returns>index of the sheet (0 based)</returns>
int GetSheetIndex(ISheet sheet);
/// <summary>
/// Sreate an Sheet for this Workbook, Adds it to the sheets and returns
/// the high level representation. Use this to create new sheets.
/// </summary>
/// <returns></returns>
ISheet CreateSheet();
/// <summary>
/// Create an Sheet for this Workbook, Adds it to the sheets and returns
/// the high level representation. Use this to create new sheets.
/// </summary>
/// <param name="sheetname">sheetname to set for the sheet.</param>
/// <returns>Sheet representing the new sheet.</returns>
ISheet CreateSheet(String sheetname);
/// <summary>
/// Create an Sheet from an existing sheet in the Workbook.
/// </summary>
/// <param name="sheetNum"></param>
/// <returns></returns>
ISheet CloneSheet(int sheetNum);
/// <summary>
/// Get the number of spreadsheets in the workbook
/// </summary>
int NumberOfSheets { get; }
/// <summary>
/// Get the Sheet object at the given index.
/// </summary>
/// <param name="index">index of the sheet number (0-based physical & logical)</param>
/// <returns>Sheet at the provided index</returns>
ISheet GetSheetAt(int index);
/// <summary>
/// Get sheet with the given name
/// </summary>
/// <param name="name">name of the sheet</param>
/// <returns>Sheet with the name provided or null if it does not exist</returns>
ISheet GetSheet(String name);
/// <summary>
/// Support foreach ISheet, e.g.
/// HSSFWorkbook workbook = new HSSFWorkbook();
/// foreach(ISheet sheet in workbook) ...
/// </summary>
/// <returns>Enumeration of all the sheets of this workbook</returns>
// new IEnumerator GetEnumerator();
/// <summary>
/// Removes sheet at the given index
/// </summary>
/// <param name="index"></param>
void RemoveSheetAt(int index);
/**
* To set just repeating columns:
* workbook.SetRepeatingRowsAndColumns(0,0,1,-1-1);
* To set just repeating rows:
* workbook.SetRepeatingRowsAndColumns(0,-1,-1,0,4);
* To remove all repeating rows and columns for a sheet.
* workbook.SetRepeatingRowsAndColumns(0,-1,-1,-1,-1);
*/
/// <summary>
/// Sets the repeating rows and columns for a sheet (as found in
/// File->PageSetup->Sheet). This is function is included in the workbook
/// because it Creates/modifies name records which are stored at the
/// workbook level.
/// </summary>
/// <param name="sheetIndex">0 based index to sheet.</param>
/// <param name="startColumn">0 based start of repeating columns.</param>
/// <param name="endColumn">0 based end of repeating columns.</param>
/// <param name="startRow">0 based start of repeating rows.</param>
/// <param name="endRow">0 based end of repeating rows.</param>
[Obsolete("use Sheet#setRepeatingRows(CellRangeAddress) or Sheet#setRepeatingColumns(CellRangeAddress)")]
void SetRepeatingRowsAndColumns(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow);
/// <summary>
/// Create a new Font and add it to the workbook's font table
/// </summary>
/// <returns></returns>
IFont CreateFont();
/// <summary>
/// Finds a font that matches the one with the supplied attributes
/// </summary>
/// <param name="boldWeight"></param>
/// <param name="color"></param>
/// <param name="fontHeight"></param>
/// <param name="name"></param>
/// <param name="italic"></param>
/// <param name="strikeout"></param>
/// <param name="typeOffset"></param>
/// <param name="underline"></param>
/// <returns>the font with the matched attributes or null</returns>
IFont FindFont(short boldWeight, short color, short fontHeight, String name, bool italic, bool strikeout, FontSuperScript typeOffset, FontUnderlineType underline);
/// <summary>
/// Get the number of fonts in the font table
/// </summary>
short NumberOfFonts { get; }
/// <summary>
/// Get the font at the given index number
/// </summary>
/// <param name="idx">index number (0-based)</param>
/// <returns>font at the index</returns>
IFont GetFontAt(short idx);
/// <summary>
/// Create a new Cell style and add it to the workbook's style table
/// </summary>
/// <returns>the new Cell Style object</returns>
ICellStyle CreateCellStyle();
/// <summary>
/// Get the number of styles the workbook Contains
/// </summary>
short NumCellStyles { get; }
/// <summary>
/// Get the cell style object at the given index
/// </summary>
/// <param name="idx">index within the set of styles (0-based)</param>
/// <returns>CellStyle object at the index</returns>
ICellStyle GetCellStyleAt(short idx);
/// <summary>
/// Write out this workbook to an OutPutstream.
/// </summary>
/// <param name="stream">the stream you wish to write to</param>
void Write(Stream stream);
/// <summary>
/// the total number of defined names in this workbook
/// </summary>
int NumberOfNames { get; }
/// <summary>
/// the defined name with the specified name.
/// </summary>
/// <param name="name">the name of the defined name</param>
/// <returns>the defined name with the specified name. null if not found</returns>
IName GetName(String name);
/// <summary>
/// the defined name at the specified index
/// </summary>
/// <param name="nameIndex">position of the named range (0-based)</param>
/// <returns></returns>
IName GetNameAt(int nameIndex);
/// <summary>
/// Creates a new (unInitialised) defined name in this workbook
/// </summary>
/// <returns>new defined name object</returns>
IName CreateName();
/// <summary>
/// Gets the defined name index by name
/// </summary>
/// <param name="name">the name of the defined name</param>
/// <returns>zero based index of the defined name.</returns>
int GetNameIndex(String name);
/// <summary>
/// Remove the defined name at the specified index
/// </summary>
/// <param name="index">named range index (0 based)</param>
void RemoveName(int index);
/// <summary>
/// Remove a defined name by name
/// </summary>
/// <param name="name">the name of the defined name</param>
void RemoveName(String name);
/// <summary>
/// Sets the printarea for the sheet provided
/// </summary>
/// <param name="sheetIndex">Zero-based sheet index</param>
/// <param name="reference">Valid name Reference for the Print Area</param>
void SetPrintArea(int sheetIndex, String reference);
/// <summary>
/// Sets the printarea for the sheet provided
/// </summary>
/// <param name="sheetIndex">Zero-based sheet index (0 = First Sheet)</param>
/// <param name="startColumn">Column to begin printarea</param>
/// <param name="endColumn">Column to end the printarea</param>
/// <param name="startRow">Row to begin the printarea</param>
/// <param name="endRow">Row to end the printarea</param>
void SetPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow);
/// <summary>
/// Retrieves the reference for the printarea of the specified sheet,
/// the sheet name is Appended to the reference even if it was not specified.
/// </summary>
/// <param name="sheetIndex">Zero-based sheet index</param>
/// <returns>Null if no print area has been defined</returns>
String GetPrintArea(int sheetIndex);
/// <summary>
/// Delete the printarea for the sheet specified
/// </summary>
/// <param name="sheetIndex">Zero-based sheet index (0 = First Sheet)</param>
void RemovePrintArea(int sheetIndex);
/// <summary>
/// Retrieves the current policy on what to do when getting missing or blank cells from a row.
/// </summary>
MissingCellPolicy MissingCellPolicy { get; set; }
/// <summary>
/// Returns the instance of DataFormat for this workbook.
/// </summary>
/// <returns>the DataFormat object</returns>
IDataFormat CreateDataFormat();
/// <summary>
/// Adds a picture to the workbook.
/// </summary>
/// <param name="pictureData">The bytes of the picture</param>
/// <param name="format">The format of the picture.</param>
/// <returns>the index to this picture (1 based).</returns>
int AddPicture(byte[] pictureData, PictureType format);
/// <summary>
/// Gets all pictures from the Workbook.
/// </summary>
/// <returns>the list of pictures (a list of link PictureData objects.)</returns>
IList GetAllPictures();
/// <summary>
/// Return an object that handles instantiating concrete classes of
/// the various instances one needs for HSSF and XSSF.
/// </summary>
/// <returns></returns>
ICreationHelper GetCreationHelper();
/// <summary>
/// if this workbook is not visible in the GUI
/// </summary>
bool IsHidden { get; set; }
/// <summary>
/// Check whether a sheet is hidden.
/// </summary>
/// <param name="sheetIx">number of sheet</param>
/// <returns>true if sheet is hidden</returns>
bool IsSheetHidden(int sheetIx);
/**
* Check whether a sheet is very hidden.
* <p>
* This is different from the normal hidden status
* ({@link #isSheetHidden(int)})
* </p>
* @param sheetIx sheet index to check
* @return <code>true</code> if sheet is very hidden
*/
bool IsSheetVeryHidden(int sheetIx);
/**
* Hide or unhide a sheet
*
* @param sheetIx the sheet index (0-based)
* @param hidden True to mark the sheet as hidden, false otherwise
*/
void SetSheetHidden(int sheetIx, SheetState hidden);
/**
* Hide or unhide a sheet.
* <pre>
* 0 = not hidden
* 1 = hidden
* 2 = very hidden.
* </pre>
* @param sheetIx The sheet number
* @param hidden 0 for not hidden, 1 for hidden, 2 for very hidden
*/
void SetSheetHidden(int sheetIx, int hidden);
/// <summary>
/// Register a new toolpack in this workbook.
/// </summary>
/// <param name="toopack">the toolpack to register</param>
void AddToolPack(UDFFinder toopack);
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Serialization;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[Obsolete("For data migration")]
public enum ObsoleteLitShaderMode
{
Forward,
Deferred
}
[Flags, Obsolete("For data migration")]
enum ObsoleteLightLoopSettingsOverrides
{
FptlForForwardOpaque = 1 << 0,
BigTilePrepass = 1 << 1,
ComputeLightEvaluation = 1 << 2,
ComputeLightVariants = 1 << 3,
ComputeMaterialVariants = 1 << 4,
TileAndCluster = 1 << 5,
//Fptl = 1 << 6, //isFptlEnabled set up by system
}
[Flags, Obsolete("For data migration")]
enum ObsoleteFrameSettingsOverrides
{
//lighting settings
Shadow = 1 << 0,
ContactShadow = 1 << 1,
ShadowMask = 1 << 2,
SSR = 1 << 3,
SSAO = 1 << 4,
SubsurfaceScattering = 1 << 5,
Transmission = 1 << 6,
AtmosphericScaterring = 1 << 7,
Volumetrics = 1 << 8,
ReprojectionForVolumetrics = 1 << 9,
LightLayers = 1 << 10,
MSAA = 1 << 11,
ExposureControl = 1 << 12,
//rendering pass
TransparentPrepass = 1 << 13,
TransparentPostpass = 1 << 14,
MotionVectors = 1 << 15,
ObjectMotionVectors = 1 << 16,
Decals = 1 << 17,
RoughRefraction = 1 << 18,
Distortion = 1 << 19,
Postprocess = 1 << 20,
//rendering settings
ShaderLitMode = 1 << 21,
DepthPrepassWithDeferredRendering = 1 << 22,
OpaqueObjects = 1 << 24,
TransparentObjects = 1 << 25,
RealtimePlanarReflection = 1 << 26,
// Async settings
AsyncCompute = 1 << 23,
LightListAsync = 1 << 27,
SSRAsync = 1 << 28,
SSAOAsync = 1 << 29,
ContactShadowsAsync = 1 << 30,
VolumeVoxelizationsAsync = 1 << 31,
}
[Serializable, Obsolete("For data migration")]
class ObsoleteLightLoopSettings
{
public ObsoleteLightLoopSettingsOverrides overrides;
[FormerlySerializedAs("enableTileAndCluster")]
public bool enableDeferredTileAndCluster;
public bool enableComputeLightEvaluation;
public bool enableComputeLightVariants;
public bool enableComputeMaterialVariants;
public bool enableFptlForForwardOpaque;
public bool enableBigTilePrepass;
public bool isFptlEnabled;
}
// The settings here are per frame settings.
// Each camera must have its own per frame settings
[Serializable]
[System.Diagnostics.DebuggerDisplay("FrameSettings overriding {overrides.ToString(\"X\")}")]
[Obsolete("For data migration")]
class ObsoleteFrameSettings
{
public ObsoleteFrameSettingsOverrides overrides;
public bool enableShadow;
public bool enableContactShadows;
public bool enableShadowMask;
public bool enableSSR;
public bool enableSSAO;
public bool enableSubsurfaceScattering;
public bool enableTransmission;
public bool enableAtmosphericScattering;
public bool enableVolumetrics;
public bool enableReprojectionForVolumetrics;
public bool enableLightLayers;
public bool enableExposureControl = true;
public float diffuseGlobalDimmer;
public float specularGlobalDimmer;
public ObsoleteLitShaderMode shaderLitMode;
public bool enableDepthPrepassWithDeferredRendering;
public bool enableTransparentPrepass;
public bool enableMotionVectors; // Enable/disable whole motion vectors pass (Camera + Object).
public bool enableObjectMotionVectors;
[FormerlySerializedAs("enableDBuffer")]
public bool enableDecals;
public bool enableRoughRefraction; // Depends on DepthPyramid - If not enable, just do a copy of the scene color (?) - how to disable rough refraction ?
public bool enableTransparentPostpass;
public bool enableDistortion;
public bool enablePostprocess;
public bool enableOpaqueObjects;
public bool enableTransparentObjects;
public bool enableRealtimePlanarReflection;
public bool enableMSAA;
public bool enableAsyncCompute;
public bool runLightListAsync;
public bool runSSRAsync;
public bool runSSAOAsync;
public bool runContactShadowsAsync;
public bool runVolumeVoxelizationAsync;
public ObsoleteLightLoopSettings lightLoopSettings;
}
public partial struct FrameSettings
{
#pragma warning disable 618 // Type or member is obsolete
internal static void MigrateFromClassVersion(ref ObsoleteFrameSettings oldFrameSettingsFormat, ref FrameSettings newFrameSettingsFormat, ref FrameSettingsOverrideMask newFrameSettingsOverrideMask)
{
if (oldFrameSettingsFormat == null)
return;
// no need to migrate those computed at frame value
//newFrameSettingsFormat.diffuseGlobalDimmer = oldFrameSettingsFormat.diffuseGlobalDimmer;
//newFrameSettingsFormat.specularGlobalDimmer = oldFrameSettingsFormat.specularGlobalDimmer;
// Data
switch (oldFrameSettingsFormat.shaderLitMode)
{
case ObsoleteLitShaderMode.Forward:
newFrameSettingsFormat.litShaderMode = LitShaderMode.Forward;
break;
case ObsoleteLitShaderMode.Deferred:
newFrameSettingsFormat.litShaderMode = LitShaderMode.Deferred;
break;
default:
throw new ArgumentException("Unknown ObsoleteLitShaderMode");
}
newFrameSettingsFormat.SetEnabled(FrameSettingsField.Shadow, oldFrameSettingsFormat.enableShadow);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ContactShadows, oldFrameSettingsFormat.enableContactShadows);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ShadowMask, oldFrameSettingsFormat.enableShadowMask);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.SSR, oldFrameSettingsFormat.enableSSR);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.SSAO, oldFrameSettingsFormat.enableSSAO);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.SubsurfaceScattering, oldFrameSettingsFormat.enableSubsurfaceScattering);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.Transmission, oldFrameSettingsFormat.enableTransmission);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.AtmosphericScattering, oldFrameSettingsFormat.enableAtmosphericScattering);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.Volumetrics, oldFrameSettingsFormat.enableVolumetrics);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ReprojectionForVolumetrics, oldFrameSettingsFormat.enableReprojectionForVolumetrics);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.LightLayers, oldFrameSettingsFormat.enableLightLayers);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.DepthPrepassWithDeferredRendering, oldFrameSettingsFormat.enableDepthPrepassWithDeferredRendering);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.TransparentPrepass, oldFrameSettingsFormat.enableTransparentPrepass);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.MotionVectors, oldFrameSettingsFormat.enableMotionVectors);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ObjectMotionVectors, oldFrameSettingsFormat.enableObjectMotionVectors);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.Decals, oldFrameSettingsFormat.enableDecals);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.RoughRefraction, oldFrameSettingsFormat.enableRoughRefraction);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.TransparentPostpass, oldFrameSettingsFormat.enableTransparentPostpass);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.Distortion, oldFrameSettingsFormat.enableDistortion);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.Postprocess, oldFrameSettingsFormat.enablePostprocess);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.OpaqueObjects, oldFrameSettingsFormat.enableOpaqueObjects);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.TransparentObjects, oldFrameSettingsFormat.enableTransparentObjects);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.RealtimePlanarReflection, oldFrameSettingsFormat.enableRealtimePlanarReflection);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.MSAA, oldFrameSettingsFormat.enableMSAA);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ExposureControl, oldFrameSettingsFormat.enableExposureControl);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.AsyncCompute, oldFrameSettingsFormat.enableAsyncCompute);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.LightListAsync, oldFrameSettingsFormat.runLightListAsync);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.SSRAsync, oldFrameSettingsFormat.runSSRAsync);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.SSAOAsync, oldFrameSettingsFormat.runSSAOAsync);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ContactShadowsAsync, oldFrameSettingsFormat.runContactShadowsAsync);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.VolumeVoxelizationsAsync, oldFrameSettingsFormat.runVolumeVoxelizationAsync);
if (oldFrameSettingsFormat.lightLoopSettings != null)
{
newFrameSettingsFormat.SetEnabled(FrameSettingsField.DeferredTile, oldFrameSettingsFormat.lightLoopSettings.enableDeferredTileAndCluster);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ComputeLightEvaluation, oldFrameSettingsFormat.lightLoopSettings.enableComputeLightEvaluation);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ComputeLightVariants, oldFrameSettingsFormat.lightLoopSettings.enableComputeLightVariants);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.ComputeMaterialVariants, oldFrameSettingsFormat.lightLoopSettings.enableComputeMaterialVariants);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.FPTLForForwardOpaque, oldFrameSettingsFormat.lightLoopSettings.enableFptlForForwardOpaque);
newFrameSettingsFormat.SetEnabled(FrameSettingsField.BigTilePrepass, oldFrameSettingsFormat.lightLoopSettings.enableBigTilePrepass);
}
// OverrideMask
newFrameSettingsOverrideMask.mask = new BitArray128();
Array values = Enum.GetValues(typeof(ObsoleteFrameSettingsOverrides));
foreach (ObsoleteFrameSettingsOverrides val in values)
{
if ((val & oldFrameSettingsFormat.overrides) > 0)
{
switch(val)
{
case ObsoleteFrameSettingsOverrides.Shadow:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.Shadow] = true;
break;
case ObsoleteFrameSettingsOverrides.ContactShadow:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ContactShadows] = true;
break;
case ObsoleteFrameSettingsOverrides.ShadowMask:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ShadowMask] = true;
break;
case ObsoleteFrameSettingsOverrides.SSR:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.SSR] = true;
break;
case ObsoleteFrameSettingsOverrides.SSAO:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.SSAO] = true;
break;
case ObsoleteFrameSettingsOverrides.SubsurfaceScattering:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.SubsurfaceScattering] = true;
break;
case ObsoleteFrameSettingsOverrides.Transmission:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.Transmission] = true;
break;
case ObsoleteFrameSettingsOverrides.AtmosphericScaterring:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.AtmosphericScattering] = true;
break;
case ObsoleteFrameSettingsOverrides.Volumetrics:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.Volumetrics] = true;
break;
case ObsoleteFrameSettingsOverrides.ReprojectionForVolumetrics:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ReprojectionForVolumetrics] = true;
break;
case ObsoleteFrameSettingsOverrides.LightLayers:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.LightLayers] = true;
break;
case ObsoleteFrameSettingsOverrides.ShaderLitMode:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.LitShaderMode] = true;
break;
case ObsoleteFrameSettingsOverrides.DepthPrepassWithDeferredRendering:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.DepthPrepassWithDeferredRendering] = true;
break;
case ObsoleteFrameSettingsOverrides.TransparentPrepass:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.TransparentPrepass] = true;
break;
case ObsoleteFrameSettingsOverrides.MotionVectors:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.MotionVectors] = true;
break;
case ObsoleteFrameSettingsOverrides.ObjectMotionVectors:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ObjectMotionVectors] = true;
break;
case ObsoleteFrameSettingsOverrides.Decals:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.Decals] = true;
break;
case ObsoleteFrameSettingsOverrides.RoughRefraction:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.RoughRefraction] = true;
break;
case ObsoleteFrameSettingsOverrides.TransparentPostpass:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.TransparentPostpass] = true;
break;
case ObsoleteFrameSettingsOverrides.Distortion:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.Distortion] = true;
break;
case ObsoleteFrameSettingsOverrides.Postprocess:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.Postprocess] = true;
break;
case ObsoleteFrameSettingsOverrides.OpaqueObjects:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.OpaqueObjects] = true;
break;
case ObsoleteFrameSettingsOverrides.TransparentObjects:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.TransparentObjects] = true;
break;
case ObsoleteFrameSettingsOverrides.RealtimePlanarReflection:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.RealtimePlanarReflection] = true;
break;
case ObsoleteFrameSettingsOverrides.MSAA:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.MSAA] = true;
break;
case ObsoleteFrameSettingsOverrides.ExposureControl:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ExposureControl] = true;
break;
case ObsoleteFrameSettingsOverrides.AsyncCompute:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.AsyncCompute] = true;
break;
case ObsoleteFrameSettingsOverrides.LightListAsync:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.LightListAsync] = true;
break;
case ObsoleteFrameSettingsOverrides.SSRAsync:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.SSRAsync] = true;
break;
case ObsoleteFrameSettingsOverrides.SSAOAsync:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.SSAOAsync] = true;
break;
case ObsoleteFrameSettingsOverrides.ContactShadowsAsync:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ContactShadowsAsync] = true;
break;
case ObsoleteFrameSettingsOverrides.VolumeVoxelizationsAsync:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.VolumeVoxelizationsAsync] = true;
break;
default:
throw new ArgumentException("Unknown ObsoleteFrameSettingsOverride, was " + val);
}
}
}
if (oldFrameSettingsFormat.lightLoopSettings != null)
{
values = Enum.GetValues(typeof(ObsoleteLightLoopSettingsOverrides));
foreach (ObsoleteLightLoopSettingsOverrides val in values)
{
if ((val & oldFrameSettingsFormat.lightLoopSettings.overrides) > 0)
{
switch (val)
{
case ObsoleteLightLoopSettingsOverrides.TileAndCluster:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.DeferredTile] = true;
break;
case ObsoleteLightLoopSettingsOverrides.BigTilePrepass:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.BigTilePrepass] = true;
break;
case ObsoleteLightLoopSettingsOverrides.ComputeLightEvaluation:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ComputeLightEvaluation] = true;
break;
case ObsoleteLightLoopSettingsOverrides.ComputeLightVariants:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ComputeLightVariants] = true;
break;
case ObsoleteLightLoopSettingsOverrides.ComputeMaterialVariants:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ComputeMaterialVariants] = true;
break;
case ObsoleteLightLoopSettingsOverrides.FptlForForwardOpaque:
newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.FPTLForForwardOpaque] = true;
break;
default:
throw new ArgumentException("Unknown ObsoleteLightLoopSettingsOverrides");
}
}
}
}
//free space:
oldFrameSettingsFormat = null;
}
#pragma warning restore 618 // Type or member is obsolete
internal static void MigrateToAfterPostprocess(ref FrameSettings cameraFrameSettings)
{
cameraFrameSettings.SetEnabled(FrameSettingsField.AfterPostprocess, true);
}
internal static void MigrateToSpecularLighting(ref FrameSettings cameraFrameSettings)
=> cameraFrameSettings.SetEnabled(FrameSettingsField.SpecularLighting, true);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 BroadcastScalarToVector128UInt64()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128UInt64();
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();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__BroadcastScalarToVector128UInt64
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int RetElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector128<UInt64> _clsVar;
private Vector128<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static SimpleUnaryOpTest__BroadcastScalarToVector128UInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__BroadcastScalarToVector128UInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.BroadcastScalarToVector128<UInt64>(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.BroadcastScalarToVector128<UInt64>(
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.BroadcastScalarToVector128<UInt64>(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128))
.MakeGenericMethod( new Type[] { typeof(UInt64) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128))
.MakeGenericMethod( new Type[] { typeof(UInt64) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128))
.MakeGenericMethod( new Type[] { typeof(UInt64) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.BroadcastScalarToVector128<UInt64>(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr);
var result = Avx2.BroadcastScalarToVector128<UInt64>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.BroadcastScalarToVector128<UInt64>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.BroadcastScalarToVector128<UInt64>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector128UInt64();
var result = Avx2.BroadcastScalarToVector128<UInt64>(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.BroadcastScalarToVector128<UInt64>(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
if (firstOp[0] != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((firstOp[0] != result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector128)}<UInt64>(Vector128<UInt64>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using Android.OS;
using Android.Text;
using Android.Util;
using REKT.Graphics;
using REKT.Graphics.Unsafe;
using REKT.DI;
using SkiaSharp;
using System;
using System.Text;
using D = System.Diagnostics.Debug;
using NativeActivity = Android.App.Activity;
using NativeBitmap = Android.Graphics.Bitmap;
using NativeBitmapFactory = Android.Graphics.BitmapFactory;
using NativeContext = Android.Content.Context;
using NativeRect = Android.Graphics.Rect;
using NativeDialog = Android.Support.V7.App.AlertDialog;
using NativeProgressDialog = Android.App.ProgressDialog;
using NativeColour = Android.Graphics.Color;
using NativeArrayAdapter = Android.Widget.ArrayAdapter;
using NativeView = Android.Views.View;
using System.Collections;
using NativeThread = System.Threading.Thread;
namespace REKT
{
public static class AndroidExtensions
{
/////////////////////////////////////////////////////////////////////
// STRINGS
/////////////////////////////////////////////////////////////////////
public static ISpanned ToSpannedHTML(this string rawHtml)
{
ISpanned html;
if (AndroidPlatform.Version >= BuildVersionCodes.N)
html = Html.FromHtml(rawHtml, FromHtmlOptions.ModeLegacy);
else
{
#pragma warning disable CS0618 //deprecation
html = Html.FromHtml(rawHtml);
#pragma warning restore CS0618
}
return html;
}
/////////////////////////////////////////////////////////////////////
// CONTEXTS
/////////////////////////////////////////////////////////////////////
public static SKColor ThemeColour(this NativeContext context, int themeColourID)
{
if (context == null)
throw new ArgumentNullException("context");
using (var typedValue = new TypedValue())
{
var theme = context.Theme;
theme.ResolveAttribute(themeColourID, typedValue, true);
var data = typedValue.Data;
return new SKColor(
(byte)NativeColour.GetRedComponent(data),
(byte)NativeColour.GetGreenComponent(data),
(byte)NativeColour.GetBlueComponent(data),
(byte)NativeColour.GetAlphaComponent(data));
}
}
public static NativeBitmap BitmapResource(this NativeContext context, int bitmapResourceID)
{
using (var opts = new NativeBitmapFactory.Options())
{
opts.InPreferQualityOverSpeed = true;
return NativeBitmapFactory.DecodeResource(context.Resources, bitmapResourceID, opts);
}
}
public static SKBitmap BitmapResourceSkia(this NativeContext context, int bitmapResourceID)
{
using (var nativeBmp = context.BitmapResource(bitmapResourceID))
return nativeBmp.ToSkia();
}
private static void RunOnUIThreadIfPossible(this NativeContext context, Action action)
{
if (context is NativeActivity activity)
activity.RunOnUiThread(action);
else
action();
}
public static void ShowYesNoDialog(this NativeContext context, string title, string text,
Action yesAction = null, Action noAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
builder.SetTitle((title ?? "").Trim());
builder.SetMessage((text ?? "").Trim());
builder.SetCancelable(false);
builder.SetPositiveButton("Yes", (s, e) => { yesAction?.Invoke(); });
builder.SetNegativeButton("No", (s, e) => { noAction?.Invoke(); });
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowOKDialog(this NativeContext context, string title, string text, Action okAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
builder.SetTitle((title ?? "").Trim());
builder.SetMessage((text ?? "").Trim());
builder.SetCancelable(false);
builder.SetPositiveButton(Android.Resource.String.Ok, (s, e) => { okAction?.Invoke(); });
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowWaitDialog(this NativeContext context, string title, string text, Action asyncTask)
{
if (context == null)
throw new ArgumentNullException("context");
if (asyncTask == null)
throw new ArgumentNullException("asyncTask");
context.RunOnUIThreadIfPossible(() =>
{
var dialog = NativeProgressDialog.Show(context, (title ?? "").Trim(), (text ?? "").Trim(), true, false);
new NativeThread(() =>
{
asyncTask?.Invoke();
dialog.Dismiss();
dialog.Dispose();
}).Start();
});
}
public static void ShowListDialog(this NativeContext context, string title, IList data, Action<int> selectionAction,
Action cancelAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
if (selectionAction == null)
throw new ArgumentNullException("selectionAction");
if (data == null)
throw new ArgumentNullException("data");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
var adapter = new NativeArrayAdapter(context, Android.Resource.Layout.SimpleListItem1, data);
builder.SetTitle((title ?? "").Trim())
.SetAdapter(adapter, (s, e) => { selectionAction.Invoke(e.Which); });
if (cancelAction != null)
builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel, (s, e) => { cancelAction.Invoke(); });
else
builder.SetCancelable(false);
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowCustomDialog(this Activity activity, string title, int viewResID,
Action<NativeView> initAction = null,
Action<NativeView> okAction = null,
Action<NativeView> cancelAction = null)
{
if (activity == null)
throw new ArgumentNullException("context");
activity.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(activity))
{
builder.SetTitle((title ?? "").Trim());
var view = activity.LayoutInflater.Inflate(viewResID, null);
initAction?.Invoke(view);
builder.SetView(view);
builder.SetPositiveButton(Android.Resource.String.Ok,
(s, e) => { okAction?.Invoke(view); });
if (cancelAction != null)
builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel,
(s, e) => { cancelAction.Invoke(view); });
else
builder.SetCancelable(false);
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void Toast(this NativeContext context, string text)
{
Android.Widget.Toast.MakeText(context, text, Android.Widget.ToastLength.Long).Show();
}
public static void LaunchWebsite(this NativeContext context, string uri)
{
using (var _uri = Android.Net.Uri.Parse(uri))
using (var intent = new Android.Content.Intent(Android.Content.Intent.ActionView, _uri))
{
intent.AddFlags(Android.Content.ActivityFlags.NewTask);
intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents);
context.StartActivity(intent);
}
}
public static ISpanned GetSpannedHTML(this NativeContext context, int resid)
{
return context.GetString(resid).ToSpannedHTML();
}
public static void LaunchAppSettings(this NativeContext context)
{
using (var _uri = Android.Net.Uri.Parse("package:" + context.PackageName))
using (var intent = new Android.Content.Intent("android.settings.APPLICATION_DETAILS_SETTINGS", _uri))
{
intent.AddFlags(Android.Content.ActivityFlags.NewTask);
intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents);
context.StartActivity(intent);
}
}
/////////////////////////////////////////////////////////////////////
// ACTIVITIES
/////////////////////////////////////////////////////////////////////
public static float CanvasScaleHint(this NativeActivity activity)
{
using (var displayMetrics = new DisplayMetrics())
{
activity.WindowManager.DefaultDisplay.GetMetrics(displayMetrics);
if (displayMetrics.ScaledDensity.IsZero()) //can this even happen??
return 1.0f;
return (displayMetrics.ScaledDensity / 3.0f).Clamp(0.4f, 1.5f);
}
}
public static void With<T>(this NativeActivity activity, int id, Action<T> viewAction) where T : Android.Views.View
{
using (var view = activity.FindViewById<T>(id))
viewAction(view);
}
/////////////////////////////////////////////////////////////////////
// SKIA
/////////////////////////////////////////////////////////////////////
public static NativeRect ToREKT(this SKRect rect)
{
return new NativeRect((int)rect.Left, (int)rect.Top,
(int)rect.Right, (int)rect.Bottom);
}
public static NativeColour ToNative(this SKColor col)
{
return new NativeColour(col.Red, col.Green, col.Blue, col.Alpha);
}
public static SKColor ToREKT(this NativeColour col)
{
return new SKColor(col.R, col.G, col.B, col.A);
}
/////////////////////////////////////////////////////////////////////
// BITMAPS
/////////////////////////////////////////////////////////////////////
public static SKBitmap ToSkia(this NativeBitmap source)
{
if (source == null)
throw new ArgumentNullException("source");
//init destination bitmap
var output = new SKBitmap(
source.Width,
source.Height,
SKColorType.Rgba8888,
SKAlphaType.Unpremul
);
//get source pixels
//"The returned colors are non-premultiplied ARGB values in the sRGB color space.",
//per https://developer.android.com/reference/android/graphics/Bitmap.html
int[] sourcePixels = new int[source.Width * source.Height];
source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height);
//copy into destination
try
{
output.LockPixels();
var buffer = output.GetPixels();
unsafe
{
int* firstPixelAddr = (int*)buffer.ToPointer();
System.Threading.Tasks.Parallel.For(0, output.Height, (y) =>
{
int p = y * output.Width;
int* pixel = firstPixelAddr + p;
for (int x = 0; x < output.Width; x++, p++, pixel++)
*pixel = sourcePixels[p].SwapBytes02();
});
}
output.UnlockPixels();
}
catch (Exception e)
{
e.WriteToLog();
output.Dispose();
throw;
}
return output;
}
public static Bitmap ToREKT(this NativeBitmap source)
{
if (source == null)
throw new ArgumentNullException("source");
#if DEBUG
StringBuilder sb = new StringBuilder("Bitmap: constructing from Android.Graphics.Bitmap:");
sb.AppendLine();
sb.AppendFormattedLine("Dimensions: {0} x {1}", source.Width, source.Height);
sb.AppendFormattedLine("AllocationByteCount: {0}", source.AllocationByteCount);
sb.AppendFormattedLine("ByteCount: {0}", source.ByteCount);
sb.AppendFormattedLine("RowBytes: {0}", source.RowBytes);
sb.AppendFormattedLine("Density: {0}", source.Density);
sb.AppendFormattedLine("HasAlpha: {0}", source.HasAlpha);
sb.AppendFormattedLine("IsPremultiplied: {0}", source.IsPremultiplied);
D.WriteLine(sb);
#endif
//init destination bitmap
var output = new Bitmap(source.Width, source.Height, SKColorType.Rgba8888);
//get source pixels
//"The returned colors are non-premultiplied ARGB values in the sRGB color space.",
//per https://developer.android.com/reference/android/graphics/Bitmap.html
int[] sourcePixels = new int[source.Width * source.Height];
source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height);
//copy into destination
try
{
output.Lock((buffer) =>
{
unsafe
{
byte* firstPixelAddr = (byte*)buffer.ToPointer();
Thread.Distribute((threadIndex, threadCount) =>
{
for (long y = threadIndex; y < output.Height; y += threadCount)
{
long p = y * output.Width;
for (long x = 0; x < output.Width; x++, p++)
output.SetPixel(firstPixelAddr, x, y, ((uint)sourcePixels[p]));
}
});
}
});
}
catch (Exception e)
{
e.WriteToLog();
output.Dispose();
throw;
}
return output;
}
/////////////////////////////////////////////////////////////////////
// UUIDs
/////////////////////////////////////////////////////////////////////
public static bool Equals(this Java.Util.UUID uuid, string uuidString)
{
if (uuid == null)
throw new ArgumentNullException("uuid");
if (uuidString == null)
throw new ArgumentNullException("uuidString");
return uuid.ToString().ToUpper() == uuidString.ToUpper();
}
}
}
| |
using Bridge.Contract;
using Bridge.Contract.Constants;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using Object.Net.Utilities;
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Bridge.Translator
{
public class MemberReferenceBlock : ConversionBlock
{
public MemberReferenceBlock(IEmitter emitter, MemberReferenceExpression memberReferenceExpression)
: base(emitter, memberReferenceExpression)
{
this.Emitter = emitter;
this.MemberReferenceExpression = memberReferenceExpression;
}
public MemberReferenceExpression MemberReferenceExpression
{
get;
set;
}
protected override Expression GetExpression()
{
return this.MemberReferenceExpression;
}
protected override void EmitConversionExpression()
{
this.VisitMemberReferenceExpression();
}
protected string WriteTarget(ResolveResult resolveResult, bool isInterfaceMember, MemberResolveResult memberTargetrr, ResolveResult targetrr, bool openParentheses)
{
string interfaceTempVar = null;
if (isInterfaceMember)
{
MemberResolveResult member = resolveResult as MemberResolveResult;
bool nativeImplementation = true;
var externalInterface = member != null && this.Emitter.Validator.IsExternalInterface(member.Member.DeclaringTypeDefinition, out nativeImplementation);
bool isField = memberTargetrr != null && memberTargetrr.Member is IField && (memberTargetrr.TargetResult is ThisResolveResult || memberTargetrr.TargetResult is LocalResolveResult);
bool variance = false;
if (member != null)
{
var itypeDef = member.Member.DeclaringTypeDefinition;
variance = MetadataUtils.IsJsGeneric(itypeDef, this.Emitter) &&
itypeDef.TypeParameters != null &&
itypeDef.TypeParameters.Any(typeParameter => typeParameter.Variance != VarianceModifier.Invariant);
}
if ((externalInterface && !nativeImplementation || variance) && !(targetrr is ThisResolveResult || targetrr is TypeResolveResult || targetrr is LocalResolveResult || isField))
{
if (openParentheses)
{
this.WriteOpenParentheses();
}
interfaceTempVar = this.GetTempVarName();
this.Write(interfaceTempVar);
this.Write(" = ");
}
}
this.WriteSimpleTarget(resolveResult);
return interfaceTempVar;
}
protected void WriteSimpleTarget(ResolveResult resolveResult)
{
MemberResolveResult member = resolveResult as MemberResolveResult;
if (member == null || !member.Member.IsStatic)
{
this.MemberReferenceExpression.Target.AcceptVisitor(this.Emitter);
return;
}
var imethod = member.Member as IMethod;
var imember = member.Member;
if ((imethod != null && imethod.IsExtensionMethod) || imember == null)
{
this.MemberReferenceExpression.Target.AcceptVisitor(this.Emitter);
return;
}
var target = BridgeTypes.ToJsName(member.Member.DeclaringType, this.Emitter, ignoreLiteralName: false);
this.NoTarget = string.IsNullOrWhiteSpace(target);
if (member.Member.IsStatic
&& target != CS.NS.BRIDGE
&& !target.StartsWith(CS.Bridge.DOTNAME)
&& this.MemberReferenceExpression.Target.ToString().StartsWith(CS.NS.GLOBAL))
{
this.Write(JS.Types.Bridge.Global.DOTNAME);
}
this.Write(target);
}
public bool NoTarget
{
get; set;
}
private void WriteInterfaceMember(string interfaceTempVar, MemberResolveResult resolveResult, bool isSetter, string prefix = null)
{
var itypeDef = resolveResult.Member.DeclaringTypeDefinition;
var externalInterface = this.Emitter.Validator.IsExternalInterface(itypeDef);
bool variance = MetadataUtils.IsJsGeneric(itypeDef, this.Emitter) &&
itypeDef.TypeParameters != null &&
itypeDef.TypeParameters.Any(typeParameter => typeParameter.Variance != VarianceModifier.Invariant);
if (interfaceTempVar != null && externalInterface == null && !variance)
{
this.WriteComma();
this.Write(interfaceTempVar);
}
if (externalInterface != null && externalInterface.IsDualImplementation || variance)
{
if (interfaceTempVar != null)
{
this.WriteCloseParentheses();
}
this.WriteOpenBracket();
this.Write(JS.Funcs.BRIDGE_GET_I);
this.WriteOpenParentheses();
if (interfaceTempVar != null)
{
this.Write(interfaceTempVar);
}
else
{
this.WriteSimpleTarget(resolveResult);
}
this.WriteComma();
var interfaceName = OverloadsCollection.Create(Emitter, resolveResult.Member, isSetter).GetOverloadName(false, prefix);
if (interfaceName.StartsWith("\""))
{
this.Write(interfaceName);
}
else
{
this.WriteScript(interfaceName);
}
if (variance)
{
this.WriteComma();
this.WriteScript(OverloadsCollection.Create(Emitter, resolveResult.Member, isSetter).GetOverloadName(false, prefix, withoutTypeParams: true));
}
/*this.WriteComma();
this.WriteScript(OverloadsCollection.Create(Emitter, resolveResult.Member, isSetter).GetOverloadName(true, prefix));*/
this.Write(")");
this.WriteCloseBracket();
return;
}
this.WriteOpenBracket();
this.Write(OverloadsCollection.Create(Emitter, resolveResult.Member, isSetter).GetOverloadName(externalInterface != null && externalInterface.IsSimpleImplementation, prefix));
this.WriteCloseBracket();
if (interfaceTempVar != null)
{
this.WriteCloseParentheses();
}
}
protected void VisitMemberReferenceExpression()
{
MemberReferenceExpression memberReferenceExpression = this.MemberReferenceExpression;
int pos = this.Emitter.Output.Length;
bool isRefArg = this.Emitter.IsRefArg;
this.Emitter.IsRefArg = false;
ResolveResult resolveResult = null;
ResolveResult expressionResolveResult = null;
string targetVar = null;
string valueVar = null;
bool isStatement = false;
bool isConstTarget = false;
var targetrr = this.Emitter.Resolver.ResolveNode(memberReferenceExpression.Target, this.Emitter);
if (targetrr is ConstantResolveResult)
{
isConstTarget = true;
}
var memberTargetrr = targetrr as MemberResolveResult;
if (memberTargetrr != null && memberTargetrr.Type.Kind == TypeKind.Enum && memberTargetrr.Member is DefaultResolvedField && Helpers.EnumEmitMode(memberTargetrr.Type) == 2)
{
isConstTarget = true;
}
if (memberReferenceExpression.Target is ParenthesizedExpression ||
(targetrr is ConstantResolveResult && targetrr.Type.IsKnownType(KnownTypeCode.Int64)) ||
(targetrr is ConstantResolveResult && targetrr.Type.IsKnownType(KnownTypeCode.UInt64)) ||
(targetrr is ConstantResolveResult && targetrr.Type.IsKnownType(KnownTypeCode.Decimal)))
{
isConstTarget = false;
}
var isInvoke = memberReferenceExpression.Parent is InvocationExpression && (((InvocationExpression)(memberReferenceExpression.Parent)).Target == memberReferenceExpression);
if (isInvoke)
{
resolveResult = this.Emitter.Resolver.ResolveNode(memberReferenceExpression.Parent, this.Emitter);
expressionResolveResult = this.Emitter.Resolver.ResolveNode(memberReferenceExpression, this.Emitter);
if (expressionResolveResult is InvocationResolveResult)
{
resolveResult = expressionResolveResult;
}
else if (expressionResolveResult is MemberResolveResult)
{
if (((MemberResolveResult)expressionResolveResult).Member is IProperty)
{
resolveResult = expressionResolveResult;
}
}
}
else
{
resolveResult = this.Emitter.Resolver.ResolveNode(memberReferenceExpression, this.Emitter);
}
bool oldIsAssignment = this.Emitter.IsAssignment;
bool oldUnary = this.Emitter.IsUnaryAccessor;
if (resolveResult == null)
{
this.Emitter.IsAssignment = false;
this.Emitter.IsUnaryAccessor = false;
if (isConstTarget)
{
this.Write("(");
}
memberReferenceExpression.Target.AcceptVisitor(this.Emitter);
if (isConstTarget)
{
this.Write(")");
}
this.Emitter.IsAssignment = oldIsAssignment;
this.Emitter.IsUnaryAccessor = oldUnary;
this.WriteDot();
string name = memberReferenceExpression.MemberName;
this.Write(name.ToLowerCamelCase());
return;
}
bool isDynamic = false;
if (resolveResult is DynamicInvocationResolveResult)
{
var dynamicResolveResult = (DynamicInvocationResolveResult)resolveResult;
var group = dynamicResolveResult.Target as MethodGroupResolveResult;
if (group != null && group.Methods.Count() > 1)
{
var method = group.Methods.FirstOrDefault(m =>
{
if (dynamicResolveResult.Arguments.Count != m.Parameters.Count)
{
return false;
}
for (int i = 0; i < m.Parameters.Count; i++)
{
var argType = dynamicResolveResult.Arguments[i].Type;
if (argType.Kind == TypeKind.Dynamic)
{
argType = this.Emitter.Resolver.Compilation.FindType(TypeCode.Object);
}
if (!m.Parameters[i].Type.Equals(argType))
{
return false;
}
}
return true;
}) ?? group.Methods.Last();
isDynamic = true;
resolveResult = new MemberResolveResult(new TypeResolveResult(method.DeclaringType), method);
resolveResult = new InvocationResolveResult(resolveResult, method, dynamicResolveResult.Arguments);
}
}
if (resolveResult is MethodGroupResolveResult)
{
var oldResult = (MethodGroupResolveResult)resolveResult;
resolveResult = this.Emitter.Resolver.ResolveNode(memberReferenceExpression.Parent, this.Emitter);
if (resolveResult is DynamicInvocationResolveResult)
{
var method = oldResult.Methods.Last();
resolveResult = new MemberResolveResult(new TypeResolveResult(method.DeclaringType), method);
}
}
MemberResolveResult member = resolveResult as MemberResolveResult;
var globalTarget = member != null ? this.Emitter.IsGlobalTarget(member.Member) : null;
if (member != null &&
member.Member.Attributes.Any(a => a.AttributeType.FullName == "Bridge.NonScriptableAttribute"))
{
throw new EmitterException(this.MemberReferenceExpression, "Member " + member.ToString() + " is marked as not usable from script");
}
if (!(resolveResult is InvocationResolveResult) && member != null && member.Member is IMethod)
{
var interceptor = this.Emitter.Plugins.OnReference(this, this.MemberReferenceExpression, member);
if (interceptor.Cancel)
{
return;
}
if (!string.IsNullOrEmpty(interceptor.Replacement))
{
this.Write(interceptor.Replacement);
return;
}
}
if (globalTarget != null && globalTarget.Item1)
{
var target = globalTarget.Item2;
if (!string.IsNullOrWhiteSpace(target))
{
bool assign = false;
var memberExpression = member.Member is IMethod ? memberReferenceExpression.Parent.Parent : memberReferenceExpression.Parent;
var targetExpression = member.Member is IMethod ? memberReferenceExpression.Parent : memberReferenceExpression;
var assignment = memberExpression as AssignmentExpression;
if (assignment != null && assignment.Right == targetExpression)
{
assign = true;
}
else
{
var varInit = memberExpression as VariableInitializer;
if (varInit != null && varInit.Initializer == targetExpression)
{
assign = true;
}
else if (memberExpression is InvocationExpression)
{
var targetInvocation = (InvocationExpression)memberExpression;
if (targetInvocation.Arguments.Any(a => a == targetExpression))
{
assign = true;
}
}
}
if (assign)
{
if (resolveResult is InvocationResolveResult)
{
this.PushWriter(target);
}
else
{
this.Write(target);
}
return;
}
}
if (resolveResult is InvocationResolveResult)
{
this.PushWriter("");
}
return;
}
Tuple<bool, bool, string> inlineInfo = member != null ? (isDynamic ? ((Emitter)this.Emitter).GetInlineCodeFromMember(member.Member, null) : this.Emitter.GetInlineCode(memberReferenceExpression)) : null;
//string inline = member != null ? this.Emitter.GetInline(member.Member) : null;
string inline = inlineInfo != null ? inlineInfo.Item3 : null;
if (string.IsNullOrEmpty(inline) && member != null &&
member.Member is IMethod &&
!(member is InvocationResolveResult) &&
!(
memberReferenceExpression.Parent is InvocationExpression &&
memberReferenceExpression.NextSibling != null &&
memberReferenceExpression.NextSibling.Role is TokenRole &&
((TokenRole)memberReferenceExpression.NextSibling.Role).Token == "("
)
)
{
var parentInvocation = memberReferenceExpression.Parent as InvocationExpression;
if (parentInvocation == null || parentInvocation.Target != memberReferenceExpression)
{
var method = (IMethod)member.Member;
if (method.TypeArguments.Count > 0 || method.IsExtensionMethod)
{
inline = MemberReferenceBlock.GenerateInlineForMethodReference(method, this.Emitter);
}
}
}
if (member != null && member.Member is IMethod && isInvoke)
{
var i_rr = this.Emitter.Resolver.ResolveNode(memberReferenceExpression.Parent, this.Emitter) as CSharpInvocationResolveResult;
if (i_rr != null && !i_rr.IsExpandedForm)
{
var tpl = this.Emitter.GetAttribute(member.Member.Attributes, JS.NS.BRIDGE + ".TemplateAttribute");
if (tpl != null && tpl.PositionalArguments.Count == 2)
{
inline = tpl.PositionalArguments[1].ConstantValue.ToString();
}
}
}
bool hasInline = !string.IsNullOrEmpty(inline);
bool hasThis = hasInline && Helpers.HasThis(inline);
inline = hasInline ? Helpers.ConvertTokens(this.Emitter, inline, member.Member) : inline;
bool isInterfaceMember = false;
if (hasInline && inline.StartsWith("<self>"))
{
hasThis = true;
inline = inline.Substring(6);
}
bool nativeImplementation = true;
bool isInterface = inline == null && member != null && member.Member.DeclaringTypeDefinition != null && member.Member.DeclaringTypeDefinition.Kind == TypeKind.Interface;
var hasTypeParemeter = isInterface && Helpers.IsTypeParameterType(member.Member.DeclaringType);
if (isInterface)
{
var itypeDef = member.Member.DeclaringTypeDefinition;
var variance = MetadataUtils.IsJsGeneric(itypeDef, this.Emitter) &&
itypeDef.TypeParameters != null &&
itypeDef.TypeParameters.Any(typeParameter => typeParameter.Variance != VarianceModifier.Invariant);
if (variance)
{
isInterfaceMember = true;
}
else
{
var ei = this.Emitter.Validator.IsExternalInterface(itypeDef);
if (ei != null)
{
nativeImplementation = ei.IsNativeImplementation;
}
else
{
nativeImplementation = member.Member.DeclaringTypeDefinition.ParentAssembly.AssemblyName == CS.NS.BRIDGE ||
!this.Emitter.Validator.IsExternalType(member.Member.DeclaringTypeDefinition);
}
if (ei != null && ei.IsSimpleImplementation)
{
nativeImplementation = false;
isInterfaceMember = false;
}
else if (ei != null || hasTypeParemeter)
{
if (hasTypeParemeter || !nativeImplementation)
{
isInterfaceMember = true;
}
}
}
}
string interfaceTempVar = null;
if (hasThis)
{
this.Write("");
var oldBuilder = this.Emitter.Output;
var oldInline = inline;
string thisArg = null;
bool isSimple = true;
if (this.MemberReferenceExpression.Target is BaseReferenceExpression)
{
thisArg = "this";
}
else
{
this.Emitter.Output = new StringBuilder();
this.Emitter.IsAssignment = false;
this.Emitter.IsUnaryAccessor = false;
if (isConstTarget)
{
this.Write("(");
}
this.WriteSimpleTarget(resolveResult);
if (isConstTarget)
{
this.Write(")");
}
thisArg = this.Emitter.Output.ToString();
if (Regex.Matches(inline, @"\{(\*?)this\}").Count > 1)
{
var mrr = resolveResult as MemberResolveResult;
bool isField = mrr != null && mrr.Member is IField &&
(mrr.TargetResult is ThisResolveResult ||
mrr.TargetResult is LocalResolveResult || mrr.TargetResult is MemberResolveResult && ((MemberResolveResult)mrr.TargetResult).Member is IField);
isSimple = (mrr != null && (mrr.TargetResult is ThisResolveResult || mrr.TargetResult is ConstantResolveResult || mrr.TargetResult is LocalResolveResult)) || isField;
}
}
int thisIndex;
inline = member != null ? Helpers.ConvertTokens(this.Emitter, inline, member.Member) : inline;
if (!isSimple)
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
var tempVar = this.GetTempVarName();
inline = inline.Replace("{this}", tempVar);
thisIndex = tempVar.Length + 2;
sb.Append(tempVar);
sb.Append(" = ");
sb.Append(thisArg);
sb.Append(", ");
sb.Append(inline);
sb.Append(")");
inline = sb.ToString();
}
else
{
thisIndex = inline.IndexOf("{this}", StringComparison.Ordinal);
inline = inline.Replace("{this}", thisArg);
}
if (member != null && member.Member is IProperty)
{
this.Emitter.Output = new StringBuilder();
inline = inline.Replace("{0}", "[[0]]");
new InlineArgumentsBlock(this.Emitter, new ArgumentsInfo(this.Emitter, memberReferenceExpression, resolveResult), inline).Emit();
inline = this.Emitter.Output.ToString();
inline = inline.Replace("[[0]]", "{0}");
}
else if (member != null && member.Member is IEvent)
{
this.Emitter.Output = new StringBuilder();
inline = inline.Replace("{0}", "[[0]]");
new InlineArgumentsBlock(this.Emitter, new ArgumentsInfo(this.Emitter, memberReferenceExpression, resolveResult), inline).Emit();
inline = this.Emitter.Output.ToString();
inline = inline.Replace("[[0]]", "{0}");
}
this.Emitter.Output = new StringBuilder(inline);
Helpers.CheckValueTypeClone(resolveResult, this.MemberReferenceExpression, this, pos);
inline = this.Emitter.Output.ToString();
this.Emitter.IsAssignment = oldIsAssignment;
this.Emitter.IsUnaryAccessor = oldUnary;
this.Emitter.Output = oldBuilder;
int[] range = null;
if (thisIndex > -1)
{
range = new[] { thisIndex, thisIndex + thisArg.Length };
}
if (resolveResult is InvocationResolveResult)
{
this.PushWriter(inline, null, thisArg, range);
}
else
{
if (member != null && member.Member is IMethod)
{
new InlineArgumentsBlock(this.Emitter, new ArgumentsInfo(this.Emitter, memberReferenceExpression, resolveResult), oldInline, (IMethod)member.Member, targetrr).EmitFunctionReference();
}
else if (member != null && member.Member is IField && inline.Contains("{0}"))
{
this.PushWriter(inline, null, thisArg, range);
}
else if (InlineArgumentsBlock.FormatArgRegex.IsMatch(inline))
{
this.PushWriter(inline, null, thisArg, range);
}
else
{
this.Write(inline);
}
}
return;
}
if (member != null && member.Member.SymbolKind == SymbolKind.Field && this.Emitter.IsMemberConst(member.Member) && this.Emitter.IsInlineConst(member.Member))
{
var parentExpression = memberReferenceExpression.Parent as MemberReferenceExpression;
bool wrap = false;
if (parentExpression != null)
{
var ii = this.Emitter.GetInlineCode(parentExpression);
if (string.IsNullOrEmpty(ii.Item3))
{
wrap = true;
this.WriteOpenParentheses();
}
}
this.WriteScript(Bridge.Translator.Emitter.ConvertConstant(member.ConstantValue, memberReferenceExpression, this.Emitter));
if (wrap)
{
this.WriteCloseParentheses();
}
}
else if (hasInline && member.Member.IsStatic)
{
if (resolveResult is InvocationResolveResult)
{
this.PushWriter(inline);
}
else
{
if (member != null && member.Member is IMethod)
{
new InlineArgumentsBlock(this.Emitter, new ArgumentsInfo(this.Emitter, memberReferenceExpression, resolveResult), inline, (IMethod)member.Member, targetrr).EmitFunctionReference();
}
else
{
new InlineArgumentsBlock(this.Emitter, new ArgumentsInfo(this.Emitter, memberReferenceExpression, resolveResult), inline).Emit();
}
}
}
else
{
if (member != null && member.IsCompileTimeConstant && member.Member.DeclaringType.Kind == TypeKind.Enum)
{
var typeDef = member.Member.DeclaringType as ITypeDefinition;
if (typeDef != null)
{
var enumMode = Helpers.EnumEmitMode(typeDef);
if ((this.Emitter.Validator.IsExternalType(typeDef) && enumMode == -1) || enumMode == 2)
{
this.WriteScript(member.ConstantValue);
return;
}
if (enumMode >= 3 && enumMode < 7)
{
string enumStringName = this.Emitter.GetEntityName(member.Member);
this.WriteScript(enumStringName);
return;
}
}
}
if (resolveResult is TypeResolveResult)
{
TypeResolveResult typeResolveResult = (TypeResolveResult)resolveResult;
this.Write(BridgeTypes.ToJsName(typeResolveResult.Type, this.Emitter));
return;
}
else
{
if (member != null &&
member.Member is IMethod &&
!(member is InvocationResolveResult) &&
!(
memberReferenceExpression.Parent is InvocationExpression &&
memberReferenceExpression.NextSibling != null &&
memberReferenceExpression.NextSibling.Role is TokenRole &&
((TokenRole)memberReferenceExpression.NextSibling.Role).Token == "("
)
)
{
var parentInvocation = memberReferenceExpression.Parent as InvocationExpression;
if (parentInvocation == null || parentInvocation.Target != memberReferenceExpression)
{
if (!string.IsNullOrEmpty(inline))
{
if (!(resolveResult is InvocationResolveResult) && member != null && member.Member is IMethod)
{
new InlineArgumentsBlock(this.Emitter,
new ArgumentsInfo(this.Emitter, memberReferenceExpression, resolveResult), inline,
(IMethod)member.Member, targetrr).EmitFunctionReference();
}
else if (resolveResult is InvocationResolveResult ||
(member.Member.SymbolKind == SymbolKind.Property && this.Emitter.IsAssignment))
{
this.PushWriter(inline);
}
else
{
this.Write(inline);
}
}
else
{
var resolvedMethod = (IMethod)member.Member;
bool isStatic = resolvedMethod != null && resolvedMethod.IsStatic;
var isExtensionMethod = resolvedMethod.IsExtensionMethod;
this.Emitter.IsAssignment = false;
this.Emitter.IsUnaryAccessor = false;
if (!isStatic)
{
this.Write(isExtensionMethod ? JS.Funcs.BRIDGE_BIND_SCOPE : JS.Funcs.BRIDGE_CACHE_BIND);
this.WriteOpenParentheses();
if (memberReferenceExpression.Target is BaseReferenceExpression)
{
this.WriteThis();
}
else
{
interfaceTempVar = this.WriteTarget(resolveResult, isInterfaceMember, memberTargetrr, targetrr, false);
}
this.Write(", ");
}
this.Emitter.IsAssignment = oldIsAssignment;
this.Emitter.IsUnaryAccessor = oldUnary;
if (isExtensionMethod)
{
this.Write(BridgeTypes.ToJsName(resolvedMethod.DeclaringType, this.Emitter));
}
else
{
this.Emitter.IsAssignment = false;
this.Emitter.IsUnaryAccessor = false;
if (isConstTarget)
{
this.Write("(");
}
if (interfaceTempVar != null)
{
this.Write(interfaceTempVar);
}
else
{
this.WriteSimpleTarget(resolveResult);
}
if (isConstTarget)
{
this.Write(")");
}
this.Emitter.IsAssignment = oldIsAssignment;
this.Emitter.IsUnaryAccessor = oldUnary;
}
if (isInterfaceMember)
{
this.WriteInterfaceMember(interfaceTempVar, member, false);
}
else
{
this.WriteDot();
this.Write(OverloadsCollection.Create(this.Emitter, member.Member).GetOverloadName(!nativeImplementation));
}
if (!isStatic)
{
this.Write(")");
}
}
return;
}
}
bool isProperty = false;
if (member != null && member.Member.SymbolKind == SymbolKind.Property && (member.Member.DeclaringTypeDefinition == null || !this.Emitter.Validator.IsObjectLiteral(member.Member.DeclaringTypeDefinition)))
{
isProperty = true;
bool writeTargetVar = false;
if (this.Emitter.IsAssignment && this.Emitter.AssignmentType != AssignmentOperatorType.Assign)
{
writeTargetVar = true;
}
else if (this.Emitter.IsUnaryAccessor)
{
writeTargetVar = true;
isStatement = memberReferenceExpression.Parent is UnaryOperatorExpression && memberReferenceExpression.Parent.Parent is ExpressionStatement;
if (NullableType.IsNullable(member.Type))
{
isStatement = false;
}
if (!isStatement)
{
this.WriteOpenParentheses();
}
}
if (writeTargetVar)
{
bool isField = memberTargetrr != null && memberTargetrr.Member is IField && (memberTargetrr.TargetResult is ThisResolveResult || memberTargetrr.TargetResult is LocalResolveResult);
if (!(targetrr is ThisResolveResult || targetrr is TypeResolveResult || targetrr is LocalResolveResult || isField))
{
targetVar = this.GetTempVarName();
this.Write(targetVar);
this.Write(" = ");
}
}
}
if (isProperty && this.Emitter.IsUnaryAccessor && !isStatement && targetVar == null)
{
valueVar = this.GetTempVarName();
this.Write(valueVar);
this.Write(" = ");
}
this.Emitter.IsAssignment = false;
this.Emitter.IsUnaryAccessor = false;
if (isConstTarget)
{
this.Write("(");
}
if (targetVar == null && isInterfaceMember)
{
interfaceTempVar = this.WriteTarget(resolveResult, isInterfaceMember, memberTargetrr, targetrr, true);
}
else
{
this.WriteSimpleTarget(resolveResult);
}
if (member != null && targetrr != null && targetrr.Type.Kind == TypeKind.Delegate && (member.Member.Name == "Invoke"))
{
var method = member.Member as IMethod;
if (!(method != null && method.IsExtensionMethod))
{
return;
}
}
if (isConstTarget)
{
this.Write(")");
}
this.Emitter.IsAssignment = oldIsAssignment;
this.Emitter.IsUnaryAccessor = oldUnary;
if (targetVar != null)
{
if (this.Emitter.IsUnaryAccessor && !isStatement)
{
this.WriteComma(false);
valueVar = this.GetTempVarName();
this.Write(valueVar);
this.Write(" = ");
this.Write(targetVar);
}
else
{
this.WriteSemiColon();
this.WriteNewLine();
this.Write(targetVar);
}
}
}
var targetResolveResult = targetrr as MemberResolveResult;
if (targetResolveResult == null || this.Emitter.IsGlobalTarget(targetResolveResult.Member) == null)
{
if (isRefArg)
{
this.WriteComma();
}
else if (!isInterfaceMember && !this.NoTarget)
{
this.WriteDot();
}
}
if (member == null)
{
if (targetrr != null && targetrr.Type.Kind == TypeKind.Dynamic)
{
this.Write(memberReferenceExpression.MemberName);
}
else
{
this.Write(memberReferenceExpression.MemberName.ToLowerCamelCase());
}
}
else if (!string.IsNullOrEmpty(inline))
{
if (!(resolveResult is InvocationResolveResult) && member != null && member.Member is IMethod)
{
new InlineArgumentsBlock(this.Emitter, new ArgumentsInfo(this.Emitter, memberReferenceExpression, resolveResult), inline, (IMethod)member.Member, targetrr).EmitFunctionReference();
}
else if (resolveResult is InvocationResolveResult ||
(member.Member.SymbolKind == SymbolKind.Property && this.Emitter.IsAssignment) ||
(member.Member != null && member.Member is IEvent))
{
this.PushWriter(inline);
}
else
{
this.Write(inline);
}
}
else if (member.Member.SymbolKind == SymbolKind.Property && (member.Member.DeclaringTypeDefinition == null || (!this.Emitter.Validator.IsObjectLiteral(member.Member.DeclaringTypeDefinition) || member.Member.IsStatic)))
{
if (member.Member is IProperty && targetrr != null && targetrr.Type.GetDefinition() != null && this.Emitter.Validator.IsObjectLiteral(targetrr.Type.GetDefinition()) && !this.Emitter.Validator.IsObjectLiteral(member.Member.DeclaringTypeDefinition))
{
this.Write(this.Emitter.GetLiteralEntityName(member.Member));
}
else
{
if (isInterfaceMember)
{
this.WriteInterfaceMember(interfaceTempVar ?? targetVar, member, false);
}
else
{
var name = OverloadsCollection.Create(this.Emitter, member.Member).GetOverloadName(!nativeImplementation);
var property = (IProperty)member.Member;
var proto = member.IsVirtualCall || property.IsVirtual || property.IsOverride;
if (this.MemberReferenceExpression.Target is BaseReferenceExpression && !property.IsIndexer && proto)
{
var alias = BridgeTypes.ToJsName(member.Member.DeclaringType, this.Emitter,
isAlias: true);
if (alias.StartsWith("\""))
{
alias = alias.Insert(1, "$");
name = alias + "+\"$" + name + "\"";
this.WriteIdentifier(name, false);
}
else
{
name = "$" + alias + "$" + name;
this.WriteIdentifier(name);
}
}
else
{
this.WriteIdentifier(name);
}
}
}
}
else if (member.Member.SymbolKind == SymbolKind.Field)
{
bool isConst = this.Emitter.IsMemberConst(member.Member);
if (isConst && this.Emitter.IsInlineConst(member.Member))
{
this.WriteScript(Bridge.Translator.Emitter.ConvertConstant(member.ConstantValue, memberReferenceExpression, this.Emitter));
}
else
{
if (isInterfaceMember)
{
this.WriteInterfaceMember(interfaceTempVar ?? targetVar, member, false);
}
else
{
var fieldName = OverloadsCollection.Create(this.Emitter, member.Member).GetOverloadName(!nativeImplementation);
if (isRefArg)
{
this.WriteScript(fieldName);
}
else
{
this.WriteIdentifier(fieldName);
}
}
}
}
else if (resolveResult is InvocationResolveResult)
{
InvocationResolveResult invocationResult = (InvocationResolveResult)resolveResult;
CSharpInvocationResolveResult cInvocationResult = resolveResult as CSharpInvocationResolveResult;
var expresssionMember = expressionResolveResult as MemberResolveResult;
if (isInterfaceMember)
{
this.WriteInterfaceMember(interfaceTempVar ?? targetVar, member, false);
}
else if (expresssionMember != null &&
cInvocationResult != null &&
cInvocationResult.IsDelegateInvocation &&
invocationResult.Member != expresssionMember.Member)
{
this.Write(OverloadsCollection.Create(this.Emitter, expresssionMember.Member).GetOverloadName(!nativeImplementation));
}
else
{
this.Write(OverloadsCollection.Create(this.Emitter, invocationResult.Member).GetOverloadName(!nativeImplementation));
}
}
else if (member.Member is IEvent)
{
if (this.Emitter.IsAssignment &&
(this.Emitter.AssignmentType == AssignmentOperatorType.Add ||
this.Emitter.AssignmentType == AssignmentOperatorType.Subtract))
{
if (isInterfaceMember)
{
this.WriteInterfaceMember(interfaceTempVar ?? targetVar, member, this.Emitter.AssignmentType == AssignmentOperatorType.Subtract, Helpers.GetAddOrRemove(this.Emitter.AssignmentType == AssignmentOperatorType.Add));
}
else
{
this.Write(Helpers.GetEventRef(member.Member, this.Emitter, this.Emitter.AssignmentType != AssignmentOperatorType.Add, ignoreInterface: !nativeImplementation));
}
this.WriteOpenParentheses();
}
else
{
if (isInterfaceMember)
{
this.WriteInterfaceMember(interfaceTempVar ?? targetVar, member, false);
}
else
{
this.Write(this.Emitter.GetEntityName(member.Member));
}
}
}
else
{
if (isInterfaceMember)
{
this.WriteInterfaceMember(interfaceTempVar ?? targetVar, member, false);
}
else
{
var memberName = this.Emitter.GetEntityName(member.Member);
if (isRefArg)
{
this.WriteScript(memberName);
}
else
{
this.WriteIdentifier(memberName);
}
}
}
Helpers.CheckValueTypeClone(resolveResult, memberReferenceExpression, this, pos);
}
}
public static string GenerateInlineForMethodReference(IMethod method, IEmitter emitter)
{
StringBuilder sb = new StringBuilder();
var parameters = method.Parameters;
if (!method.IsStatic)
{
sb.Append("{this}");
}
else
{
sb.Append(BridgeTypes.ToJsName(method.DeclaringType, emitter));
}
sb.Append(".");
sb.Append(OverloadsCollection.Create(emitter, method).GetOverloadName());
sb.Append("(");
bool needComma = false;
if (!Helpers.IsIgnoreGeneric(method, emitter))
{
foreach (var typeArgument in method.TypeArguments)
{
if (needComma)
{
sb.Append(", ");
}
needComma = true;
if (typeArgument.Kind == TypeKind.TypeParameter)
{
sb.Append("{");
sb.Append(typeArgument.Name);
sb.Append("}");
}
else
{
sb.Append(BridgeTypes.ToJsName(typeArgument, emitter));
}
}
}
foreach (var parameter in parameters)
{
if (needComma)
{
sb.Append(", ");
}
needComma = true;
sb.Append("{");
sb.Append(parameter.Name);
sb.Append("}");
}
sb.Append(")");
return sb.ToString();
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace MiniCRMAppWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel
{
internal partial class CSharpCodeModelService
{
protected override AbstractNodeLocator CreateNodeLocator()
{
return new NodeLocator(this);
}
private class NodeLocator : AbstractNodeLocator
{
public NodeLocator(CSharpCodeModelService codeModelService)
: base(codeModelService)
{
}
protected override EnvDTE.vsCMPart DefaultPart
{
get { return EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; }
}
protected override VirtualTreePoint? GetStartPoint(SourceText text, SyntaxNode node, EnvDTE.vsCMPart part)
{
switch (node.Kind())
{
case SyntaxKind.ArrowExpressionClause:
return GetStartPoint(text, (ArrowExpressionClauseSyntax)node, part);
case SyntaxKind.Attribute:
return GetStartPoint(text, (AttributeSyntax)node, part);
case SyntaxKind.AttributeArgument:
return GetStartPoint(text, (AttributeArgumentSyntax)node, part);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
return GetStartPoint(text, (BaseTypeDeclarationSyntax)node, part);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return GetStartPoint(text, (BaseMethodDeclarationSyntax)node, part);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.EventDeclaration:
return GetStartPoint(text, (BasePropertyDeclarationSyntax)node, part);
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return GetStartPoint(text, (AccessorDeclarationSyntax)node, part);
case SyntaxKind.DelegateDeclaration:
return GetStartPoint(text, (DelegateDeclarationSyntax)node, part);
case SyntaxKind.NamespaceDeclaration:
return GetStartPoint(text, (NamespaceDeclarationSyntax)node, part);
case SyntaxKind.UsingDirective:
return GetStartPoint(text, (UsingDirectiveSyntax)node, part);
case SyntaxKind.EnumMemberDeclaration:
return GetStartPoint(text, (EnumMemberDeclarationSyntax)node, part);
case SyntaxKind.VariableDeclarator:
return GetStartPoint(text, (VariableDeclaratorSyntax)node, part);
case SyntaxKind.Parameter:
return GetStartPoint(text, (ParameterSyntax)node, part);
default:
Debug.Fail("Unsupported node kind: " + node.Kind());
throw new NotSupportedException();
}
}
protected override VirtualTreePoint? GetEndPoint(SourceText text, SyntaxNode node, EnvDTE.vsCMPart part)
{
switch (node.Kind())
{
case SyntaxKind.ArrowExpressionClause:
return GetEndPoint(text, (ArrowExpressionClauseSyntax)node, part);
case SyntaxKind.Attribute:
return GetEndPoint(text, (AttributeSyntax)node, part);
case SyntaxKind.AttributeArgument:
return GetEndPoint(text, (AttributeArgumentSyntax)node, part);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
return GetEndPoint(text, (BaseTypeDeclarationSyntax)node, part);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return GetEndPoint(text, (BaseMethodDeclarationSyntax)node, part);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.EventDeclaration:
return GetEndPoint(text, (BasePropertyDeclarationSyntax)node, part);
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return GetEndPoint(text, (AccessorDeclarationSyntax)node, part);
case SyntaxKind.DelegateDeclaration:
return GetEndPoint(text, (DelegateDeclarationSyntax)node, part);
case SyntaxKind.NamespaceDeclaration:
return GetEndPoint(text, (NamespaceDeclarationSyntax)node, part);
case SyntaxKind.UsingDirective:
return GetEndPoint(text, (UsingDirectiveSyntax)node, part);
case SyntaxKind.EnumMemberDeclaration:
return GetEndPoint(text, (EnumMemberDeclarationSyntax)node, part);
case SyntaxKind.VariableDeclarator:
return GetEndPoint(text, (VariableDeclaratorSyntax)node, part);
case SyntaxKind.Parameter:
return GetEndPoint(text, (ParameterSyntax)node, part);
default:
Debug.Fail("Unsupported node kind: " + node.Kind());
throw new NotSupportedException();
}
}
private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace)
{
Debug.Assert(!openBrace.IsMissing);
var openBraceLine = text.Lines.GetLineFromPosition(openBrace.Span.End);
var textAfterBrace = text.ToString(TextSpan.FromBounds(openBrace.Span.End, openBraceLine.End));
return string.IsNullOrWhiteSpace(textAfterBrace)
? new VirtualTreePoint(openBrace.SyntaxTree, text, text.Lines[openBraceLine.LineNumber + 1].Start)
: new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End);
}
private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace, SyntaxToken closeBrace, int memberStartColumn)
{
Debug.Assert(!openBrace.IsMissing);
Debug.Assert(!closeBrace.IsMissing);
Debug.Assert(memberStartColumn >= 0);
var openBraceLine = text.Lines.GetLineFromPosition(openBrace.SpanStart);
var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart);
var tokenAfterOpenBrace = openBrace.GetNextToken();
var nextPosition = tokenAfterOpenBrace.SpanStart;
// We need to check if there is any significant trivia trailing this token or leading
// to the next token. This accounts for the fact that comments were included in the token
// stream in Dev10.
var significantTrivia = openBrace.GetAllTrailingTrivia()
.Where(t => !t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia))
.FirstOrDefault();
if (significantTrivia.Kind() != SyntaxKind.None)
{
nextPosition = significantTrivia.SpanStart;
}
// If the opening and closing curlies are at least two lines apart then place the cursor
// on the next line provided that there isn't any token on the line with the open curly.
if (openBraceLine.LineNumber + 1 < closeBraceLine.LineNumber &&
openBraceLine.LineNumber < text.Lines.IndexOf(tokenAfterOpenBrace.SpanStart))
{
var lineAfterOpenBrace = text.Lines[openBraceLine.LineNumber + 1];
var firstNonWhitespaceOffset = lineAfterOpenBrace.GetFirstNonWhitespaceOffset() ?? -1;
// If the line contains any text, we return the start of the first non-whitespace character.
if (firstNonWhitespaceOffset >= 0)
{
return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.Start + firstNonWhitespaceOffset);
}
// If the line is all whitespace then place the caret at the first indent after the start
// of the member.
var indentSize = GetTabSize(text);
var lineText = lineAfterOpenBrace.ToString();
var lineEndColumn = lineText.GetColumnFromLineOffset(lineText.Length, indentSize);
int indentColumn = memberStartColumn + indentSize;
var virtualSpaces = indentColumn - lineEndColumn;
return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.End, virtualSpaces);
}
else
{
// If the body is empty then place it after the open brace; otherwise, place
// at the start of the first token after the open curly.
if (closeBrace.SpanStart == nextPosition)
{
return new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End);
}
else
{
return new VirtualTreePoint(openBrace.SyntaxTree, text, nextPosition);
}
}
}
private VirtualTreePoint GetBodyEndPoint(SourceText text, SyntaxToken closeBrace)
{
var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart);
var textBeforeBrace = text.ToString(TextSpan.FromBounds(closeBraceLine.Start, closeBrace.SpanStart));
return string.IsNullOrWhiteSpace(textBeforeBrace)
? new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBraceLine.Start)
: new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBrace.SpanStart);
}
private VirtualTreePoint GetStartPoint(SourceText text, ArrowExpressionClauseSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartWhole:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
startPosition = node.Expression.SpanStart;
break;
default:
throw Exceptions.ThrowENotImpl();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Name.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
case EnvDTE.vsCMPart.vsCMPartNavigate:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartHeader:
startPosition = node.GetFirstTokenAfterAttributes().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyStartPoint(text, node.OpenBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartHeader:
startPosition = node.GetFirstTokenAfterAttributes().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
if (node.Body != null && !node.Body.OpenBraceToken.IsMissing)
{
var line = text.Lines.GetLineFromPosition(node.SpanStart);
var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));
return GetBodyStartPoint(text, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation);
}
else
{
switch (node.Kind())
{
case SyntaxKind.MethodDeclaration:
startPosition = ((MethodDeclarationSyntax)node).Identifier.SpanStart;
break;
case SyntaxKind.ConstructorDeclaration:
startPosition = ((ConstructorDeclarationSyntax)node).Identifier.SpanStart;
break;
case SyntaxKind.DestructorDeclaration:
startPosition = ((DestructorDeclarationSyntax)node).Identifier.SpanStart;
break;
case SyntaxKind.ConversionOperatorDeclaration:
startPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.SpanStart;
break;
case SyntaxKind.OperatorDeclaration:
startPosition = ((OperatorDeclarationSyntax)node).OperatorToken.SpanStart;
break;
default:
startPosition = node.GetFirstTokenAfterAttributes().SpanStart;
break;
}
}
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyStartPoint(text, node.Body.OpenBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private AccessorDeclarationSyntax FindFirstAccessorNode(BasePropertyDeclarationSyntax node)
{
if (node.AccessorList == null)
{
return null;
}
return node.AccessorList.Accessors.FirstOrDefault();
}
private VirtualTreePoint GetStartPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
var firstAccessorNode = FindFirstAccessorNode(node);
if (firstAccessorNode != null)
{
var line = text.Lines.GetLineFromPosition(firstAccessorNode.SpanStart);
var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));
if (firstAccessorNode.Body != null)
{
return GetBodyStartPoint(text, firstAccessorNode.Body.OpenBraceToken, firstAccessorNode.Body.CloseBraceToken, indentation);
}
else if (!firstAccessorNode.SemicolonToken.IsMissing)
{
// This is total weirdness from the old C# code model with auto props.
// If there isn't a body, the semi-colon is used
return GetBodyStartPoint(text, firstAccessorNode.SemicolonToken, firstAccessorNode.SemicolonToken, indentation);
}
}
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.AccessorList != null && !node.AccessorList.OpenBraceToken.IsMissing)
{
var line = text.Lines.GetLineFromPosition(node.SpanStart);
var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));
return GetBodyStartPoint(text, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentation);
}
throw Exceptions.ThrowEFail();
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
if (node.Body != null && !node.Body.OpenBraceToken.IsMissing)
{
var line = text.Lines.GetLineFromPosition(node.SpanStart);
var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(text));
return GetBodyStartPoint(text, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation);
}
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.Body == null ||
node.Body.OpenBraceToken.IsMissing ||
node.Body.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyStartPoint(text, node.Body.OpenBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, NamespaceDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Name.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyStartPoint(text, node.OpenBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.GetFirstToken().SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Name.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part)
{
var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>();
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (field.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = field.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetStartPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part)
{
int startPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
startPosition = node.SpanStart;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
startPosition = node.Identifier.SpanStart;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, startPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, ArrowExpressionClauseSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBody:
endPosition = node.Span.End;
break;
default:
throw Exceptions.ThrowENotImpl();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Name.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
case EnvDTE.vsCMPart.vsCMPartNavigate:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
return GetBodyEndPoint(text, node.CloseBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
if (node.Body != null && !node.Body.CloseBraceToken.IsMissing)
{
return GetBodyEndPoint(text, node.Body.CloseBraceToken);
}
else
{
switch (node.Kind())
{
case SyntaxKind.MethodDeclaration:
endPosition = ((MethodDeclarationSyntax)node).Identifier.Span.End;
break;
case SyntaxKind.ConstructorDeclaration:
endPosition = ((ConstructorDeclarationSyntax)node).Identifier.Span.End;
break;
case SyntaxKind.DestructorDeclaration:
endPosition = ((DestructorDeclarationSyntax)node).Identifier.Span.End;
break;
case SyntaxKind.ConversionOperatorDeclaration:
endPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.Span.End;
break;
case SyntaxKind.OperatorDeclaration:
endPosition = ((OperatorDeclarationSyntax)node).OperatorToken.Span.End;
break;
default:
endPosition = node.GetFirstTokenAfterAttributes().Span.End;
break;
}
}
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyEndPoint(text, node.Body.CloseBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
var firstAccessorNode = FindFirstAccessorNode(node);
if (firstAccessorNode != null)
{
if (firstAccessorNode.Body != null)
{
return GetBodyEndPoint(text, firstAccessorNode.Body.CloseBraceToken);
}
else
{
// This is total weirdness from the old C# code model with auto props.
// If there isn't a body, the semi-colon is used
return GetBodyEndPoint(text, firstAccessorNode.SemicolonToken);
}
}
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.AccessorList != null && !node.AccessorList.CloseBraceToken.IsMissing)
{
return GetBodyEndPoint(text, node.AccessorList.CloseBraceToken);
}
throw Exceptions.ThrowEFail();
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
case EnvDTE.vsCMPart.vsCMPartNavigate:
if (node.Body == null ||
node.Body.OpenBraceToken.IsMissing ||
node.Body.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyEndPoint(text, node.Body.CloseBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, NamespaceDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Name.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing)
{
throw Exceptions.ThrowEFail();
}
return GetBodyEndPoint(text, node.CloseBraceToken);
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Name.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part)
{
var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>();
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (field.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = field.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = field.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
private VirtualTreePoint GetEndPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part)
{
int endPosition;
switch (part)
{
case EnvDTE.vsCMPart.vsCMPartName:
case EnvDTE.vsCMPart.vsCMPartAttributes:
case EnvDTE.vsCMPart.vsCMPartHeader:
case EnvDTE.vsCMPart.vsCMPartWhole:
case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter:
case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes:
throw Exceptions.ThrowENotImpl();
case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter:
if (node.AttributeLists.Count == 0)
{
throw Exceptions.ThrowEFail();
}
endPosition = node.AttributeLists.Last().GetLastToken().Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes:
endPosition = node.Span.End;
break;
case EnvDTE.vsCMPart.vsCMPartBody:
throw Exceptions.ThrowEFail();
case EnvDTE.vsCMPart.vsCMPartNavigate:
endPosition = node.Identifier.Span.End;
break;
default:
throw Exceptions.ThrowEInvalidArg();
}
return new VirtualTreePoint(node.SyntaxTree, text, endPosition);
}
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\PlayerState.h:64
namespace UnrealEngine
{
public partial class APlayerState : AInfo
{
public APlayerState(IntPtr adress)
: base(adress)
{
}
public APlayerState(UObject Parent = null, string Name = "PlayerState")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_APlayerState(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_APlayerState_bFromPreviousLevel_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_bFromPreviousLevel_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_APlayerState_bHasBeenWelcomed_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_bHasBeenWelcomed_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_APlayerState_bIsABot_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_bIsABot_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_APlayerState_bIsInactive_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_bIsInactive_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_APlayerState_bIsSpectator_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_bIsSpectator_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_APlayerState_bOnlySpectator_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_bOnlySpectator_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_APlayerState_bUseCustomPlayerNames_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_bUseCustomPlayerNames_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_APlayerState_ExactPing_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_ExactPing_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_APlayerState_ExactPingV2_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_ExactPingV2_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_PROP_APlayerState_OldName_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_OldName_SET(IntPtr Ptr, string Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_APlayerState_Ping_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_Ping_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_APlayerState_PlayerId_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_PlayerId_SET(IntPtr Ptr, int Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_PROP_APlayerState_PlayerName_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_PlayerName_SET(IntPtr Ptr, string Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_PROP_APlayerState_SavedNetworkAddress_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_SavedNetworkAddress_SET(IntPtr Ptr, string Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_APlayerState_Score_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_Score_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_PROP_APlayerState_SessionName_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_SessionName_SET(IntPtr Ptr, string Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_APlayerState_StartTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_APlayerState_StartTime_SET(IntPtr Ptr, int Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_APlayerState(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_ClientInitialize(IntPtr self, IntPtr c);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_CopyProperties(IntPtr self, IntPtr playerState);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_DispatchCopyProperties(IntPtr self, IntPtr playerState);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_DispatchOverrideWith(IntPtr self, IntPtr playerState);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_APlayerState_Duplicate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_APlayerState_GetOldPlayerName(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_APlayerState_GetPawn(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_APlayerState_GetPlayerName(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_APlayerState_GetPlayerNameCustom(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_HandleWelcomeMessage(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_APlayerState_IsPrimaryPlayer(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_OnDeactivated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_OnReactivated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_OnRep_bIsInactive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_OnRep_PlayerId(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_OnRep_PlayerName(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_OnRep_Score(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_OnRep_UniqueId(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_OverrideWith(IntPtr self, IntPtr playerState);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_RecalculateAvgPing(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_ReceiveCopyProperties(IntPtr self, IntPtr newPlayerState);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_ReceiveOverrideWith(IntPtr self, IntPtr oldPlayerState);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_RegisterPlayerWithSession(IntPtr self, bool bWasFromInvite);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_SeamlessTravelTo(IntPtr self, IntPtr newPlayerState);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_SetOldPlayerName(IntPtr self, string s);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_SetPlayerName(IntPtr self, string s);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_SetPlayerNameInternal(IntPtr self, string s);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_SetShouldUpdateReplicatedPing(IntPtr self, bool bInShouldUpdateReplicatedPing);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_APlayerState_ShouldBroadCastWelcomeMessage(IntPtr self, bool bExiting);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_UnregisterPlayerWithSession(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_APlayerState_UpdatePing(IntPtr self, float inPing);
#endregion
#region Property
public byte bFromPreviousLevel
{
get => E_PROP_APlayerState_bFromPreviousLevel_GET(NativePointer);
set => E_PROP_APlayerState_bFromPreviousLevel_SET(NativePointer, value);
}
/// <summary>
/// client side flag - whether this player has been welcomed or not (player entered message)
/// </summary>
public byte bHasBeenWelcomed
{
get => E_PROP_APlayerState_bHasBeenWelcomed_GET(NativePointer);
set => E_PROP_APlayerState_bHasBeenWelcomed_SET(NativePointer, value);
}
/// <summary>
/// True if this PlayerState is associated with an AIController
/// </summary>
public byte bIsABot
{
get => E_PROP_APlayerState_bIsABot_GET(NativePointer);
set => E_PROP_APlayerState_bIsABot_SET(NativePointer, value);
}
/// <summary>
/// Means this PlayerState came from the GameMode's InactivePlayerArray
/// </summary>
public byte bIsInactive
{
get => E_PROP_APlayerState_bIsInactive_GET(NativePointer);
set => E_PROP_APlayerState_bIsInactive_SET(NativePointer, value);
}
/// <summary>
/// Whether this player is currently a spectator
/// </summary>
public byte bIsSpectator
{
get => E_PROP_APlayerState_bIsSpectator_GET(NativePointer);
set => E_PROP_APlayerState_bIsSpectator_SET(NativePointer, value);
}
public byte bOnlySpectator
{
get => E_PROP_APlayerState_bOnlySpectator_GET(NativePointer);
set => E_PROP_APlayerState_bOnlySpectator_SET(NativePointer, value);
}
/// <summary>
/// if set, GetPlayerName() will call virtual GetPlayerNameCustom() to allow custom access
/// </summary>
public byte bUseCustomPlayerNames
{
get => E_PROP_APlayerState_bUseCustomPlayerNames_GET(NativePointer);
set => E_PROP_APlayerState_bUseCustomPlayerNames_SET(NativePointer, value);
}
/// <summary>
/// Exact ping as float (rounded and compressed in replicated Ping)
/// </summary>
public float ExactPing
{
get => E_PROP_APlayerState_ExactPing_GET(NativePointer);
set => E_PROP_APlayerState_ExactPing_SET(NativePointer, value);
}
public float ExactPingV2
{
get => E_PROP_APlayerState_ExactPingV2_GET(NativePointer);
set => E_PROP_APlayerState_ExactPingV2_SET(NativePointer, value);
}
/// <summary>
/// Previous player name. Saved on client-side to detect player name changes.
/// </summary>
public string OldName
{
get => E_PROP_APlayerState_OldName_GET(NativePointer);
set => E_PROP_APlayerState_OldName_SET(NativePointer, value);
}
/// <summary>
/// Replicated compressed ping for this player (holds ping in msec divided by 4)
/// </summary>
public byte Ping
{
get => E_PROP_APlayerState_Ping_GET(NativePointer);
set => E_PROP_APlayerState_Ping_SET(NativePointer, value);
}
/// <summary>
/// Unique net id number. Actual value varies based on current online subsystem, use it only as a guaranteed unique number per player.
/// </summary>
public int PlayerId
{
get => E_PROP_APlayerState_PlayerId_GET(NativePointer);
set => E_PROP_APlayerState_PlayerId_SET(NativePointer, value);
}
/// <summary>
/// Player name, or blank if none.
/// </summary>
public string PlayerName
{
get => E_PROP_APlayerState_PlayerName_GET(NativePointer);
set => E_PROP_APlayerState_PlayerName_SET(NativePointer, value);
}
public string SavedNetworkAddress
{
get => E_PROP_APlayerState_SavedNetworkAddress_GET(NativePointer);
set => E_PROP_APlayerState_SavedNetworkAddress_SET(NativePointer, value);
}
/// <summary>
/// Player's current score.
/// </summary>
public float Score
{
get => E_PROP_APlayerState_Score_GET(NativePointer);
set => E_PROP_APlayerState_Score_SET(NativePointer, value);
}
/// <summary>
/// The session that the player needs to join/remove from as it is created/leaves
/// </summary>
public string SessionName
{
get => E_PROP_APlayerState_SessionName_GET(NativePointer);
set => E_PROP_APlayerState_SessionName_SET(NativePointer, value);
}
public int StartTime
{
get => E_PROP_APlayerState_StartTime_GET(NativePointer);
set => E_PROP_APlayerState_StartTime_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// Called by Controller when its PlayerState is initially replicated.
/// </summary>
public virtual void ClientInitialize(AController c)
=> E_APlayerState_ClientInitialize(this, c);
/// <summary>
/// Copy properties which need to be saved in inactive PlayerState
/// </summary>
protected virtual void CopyProperties(APlayerState playerState)
=> E_APlayerState_CopyProperties(this, playerState);
public void DispatchCopyProperties(APlayerState playerState)
=> E_APlayerState_DispatchCopyProperties(this, playerState);
/// <summary>
/// calls OverrideWith and triggers OnOverrideWith for BP extension
/// </summary>
public void DispatchOverrideWith(APlayerState playerState)
=> E_APlayerState_DispatchOverrideWith(this, playerState);
/// <summary>
/// Create duplicate PlayerState (for saving Inactive PlayerState)
/// </summary>
public virtual APlayerState Duplicate()
=> E_APlayerState_Duplicate(this);
/// <summary>
/// returns previous player name
/// </summary>
public virtual string GetOldPlayerName()
=> E_APlayerState_GetOldPlayerName(this);
/// <summary>
/// Return the pawn controlled by this Player State.
/// </summary>
public APawn GetPawn()
=> E_APlayerState_GetPawn(this);
/// <summary>
/// returns current player name
/// </summary>
public string GetPlayerName()
=> E_APlayerState_GetPlayerName(this);
/// <summary>
/// custom access to player name, called only when bUseCustomPlayerNames is set
/// </summary>
public virtual string GetPlayerNameCustom()
=> E_APlayerState_GetPlayerNameCustom(this);
/// <summary>
/// called after receiving player name
/// </summary>
protected virtual void HandleWelcomeMessage()
=> E_APlayerState_HandleWelcomeMessage(this);
/// <summary>
/// return true if PlayerState is primary (ie. non-splitscreen) player
/// </summary>
public virtual bool IsPrimaryPlayer()
=> E_APlayerState_IsPrimaryPlayer(this);
/// <summary>
/// Called on the server when the owning player has disconnected, by default this method destroys this player state
/// </summary>
public virtual void OnDeactivated()
=> E_APlayerState_OnDeactivated(this);
/// <summary>
/// Called on the server when the owning player has reconnected and this player state is added to the active players array
/// </summary>
public virtual void OnReactivated()
=> E_APlayerState_OnReactivated(this);
public virtual void OnRep_bIsInactive()
=> E_APlayerState_OnRep_bIsInactive(this);
public virtual void OnRep_PlayerId()
=> E_APlayerState_OnRep_PlayerId(this);
public virtual void OnRep_PlayerName()
=> E_APlayerState_OnRep_PlayerName(this);
public virtual void OnRep_Score()
=> E_APlayerState_OnRep_Score(this);
public virtual void OnRep_UniqueId()
=> E_APlayerState_OnRep_UniqueId(this);
protected virtual void OverrideWith(APlayerState playerState)
=> E_APlayerState_OverrideWith(this, playerState);
/// <summary>
/// Recalculates the replicated Ping value once per second (both clientside and serverside), based upon collected ping data
/// </summary>
public virtual void RecalculateAvgPing()
=> E_APlayerState_RecalculateAvgPing(this);
protected void ReceiveCopyProperties(APlayerState newPlayerState)
=> E_APlayerState_ReceiveCopyProperties(this, newPlayerState);
protected void ReceiveOverrideWith(APlayerState oldPlayerState)
=> E_APlayerState_ReceiveOverrideWith(this, oldPlayerState);
/// <summary>
/// Register a player with the online subsystem
/// </summary>
/// <param name="bWasFromInvite">was this player invited directly</param>
public virtual void RegisterPlayerWithSession(bool bWasFromInvite)
=> E_APlayerState_RegisterPlayerWithSession(this, bWasFromInvite);
/// <summary>
/// called by seamless travel when initializing a player on the other side - copy properties to the new PlayerState that should persist
/// </summary>
public virtual void SeamlessTravelTo(APlayerState newPlayerState)
=> E_APlayerState_SeamlessTravelTo(this, newPlayerState);
/// <summary>
/// set the player name to S
/// </summary>
public virtual void SetOldPlayerName(string s)
=> E_APlayerState_SetOldPlayerName(this, s);
/// <summary>
/// set the player name to S
/// </summary>
public virtual void SetPlayerName(string s)
=> E_APlayerState_SetPlayerName(this, s);
/// <summary>
/// set the player name to S locally, does not trigger net updates
/// </summary>
public virtual void SetPlayerNameInternal(string s)
=> E_APlayerState_SetPlayerNameInternal(this, s);
/// <summary>
/// Sets whether or not the replicated ping value is updated automatically.
/// </summary>
protected void SetShouldUpdateReplicatedPing(bool bInShouldUpdateReplicatedPing)
=> E_APlayerState_SetShouldUpdateReplicatedPing(this, bInShouldUpdateReplicatedPing);
/// <summary>
/// Returns true if should broadcast player welcome/left messages.
/// <para>Current conditions: must be a human player a network game </para>
/// </summary>
public virtual bool ShouldBroadCastWelcomeMessage(bool bExiting)
=> E_APlayerState_ShouldBroadCastWelcomeMessage(this, bExiting);
/// <summary>
/// Unregister a player with the online subsystem
/// </summary>
public virtual void UnregisterPlayerWithSession()
=> E_APlayerState_UnregisterPlayerWithSession(this);
/// <summary>
/// Receives ping updates for the client (both clientside and serverside), from the net driver
/// <para>NOTE: This updates much more frequently clientside, thus the clientside ping will often be different to what the server displays </para>
/// </summary>
public virtual void UpdatePing(float inPing)
=> E_APlayerState_UpdatePing(this, inPing);
#endregion
public static implicit operator IntPtr(APlayerState self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator APlayerState(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<APlayerState>(PtrDesc);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
using System.Windows.Markup;
namespace System.Xaml.Schema
{
public class XamlTypeInvoker
{
private static XamlTypeInvoker s_Unknown;
private static object[] s_emptyObjectArray = Array.Empty<object>();
private Dictionary<XamlType, MethodInfo> _addMethods;
internal MethodInfo EnumeratorMethod { get; set; }
private XamlType _xamlType;
private Action<object> _constructorDelegate;
private ThreeValuedBool _isPublic;
// vvvvv---- Unused members. Servicing policy is to retain these anyway. -----vvvvv
private ThreeValuedBool _isInSystemXaml;
// ^^^^^----- End of unused members. -----^^^^^
protected XamlTypeInvoker()
{
}
public XamlTypeInvoker(XamlType type)
{
_xamlType = type ?? throw new ArgumentNullException(nameof(type));
}
public static XamlTypeInvoker UnknownInvoker
{
get
{
if (s_Unknown == null)
{
s_Unknown = new XamlTypeInvoker();
}
return s_Unknown;
}
}
public EventHandler<XamlSetMarkupExtensionEventArgs> SetMarkupExtensionHandler
{
get { return _xamlType != null ? _xamlType.SetMarkupExtensionHandler : null; }
}
public EventHandler<XamlSetTypeConverterEventArgs> SetTypeConverterHandler
{
get { return _xamlType != null ? _xamlType.SetTypeConverterHandler : null; }
}
public virtual void AddToCollection(object instance, object item)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
IList list = instance as IList;
if (list != null)
{
list.Add(item);
return;
}
ThrowIfUnknown();
if (!_xamlType.IsCollection)
{
throw new NotSupportedException(SR.Get(SRID.OnlySupportedOnCollections));
}
XamlType itemType;
if (item != null)
{
itemType = _xamlType.SchemaContext.GetXamlType(item.GetType());
}
else
{
itemType = _xamlType.ItemType;
}
MethodInfo addMethod = GetAddMethod(itemType);
if (addMethod == null)
{
throw new XamlSchemaException(SR.Get(SRID.NoAddMethodFound, _xamlType, itemType));
}
SafeReflectionInvoker.InvokeMethod(addMethod, instance, new object[] { item });
}
public virtual void AddToDictionary(object instance, object key, object item)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
IDictionary dictionary = instance as IDictionary;
if (dictionary != null)
{
dictionary.Add(key, item);
return;
}
ThrowIfUnknown();
if (!_xamlType.IsDictionary)
{
throw new NotSupportedException(SR.Get(SRID.OnlySupportedOnDictionaries));
}
XamlType itemType;
if (item != null)
{
itemType = _xamlType.SchemaContext.GetXamlType(item.GetType());
}
else
{
itemType = _xamlType.ItemType;
}
MethodInfo addMethod = GetAddMethod(itemType);
if (addMethod == null)
{
throw new XamlSchemaException(SR.Get(SRID.NoAddMethodFound, _xamlType, itemType));
}
SafeReflectionInvoker.InvokeMethod(addMethod, instance, new object[] { key, item });
}
public virtual object CreateInstance(object[] arguments)
{
ThrowIfUnknown();
if (!_xamlType.UnderlyingType.IsValueType && (arguments == null || arguments.Length == 0))
{
object result = DefaultCtorXamlActivator.CreateInstance(this);
if (result != null)
{
return result;
}
}
return CreateInstanceWithActivator(_xamlType.UnderlyingType, arguments);
}
public virtual MethodInfo GetAddMethod(XamlType contentType)
{
if (contentType == null)
{
throw new ArgumentNullException(nameof(contentType));
}
if (IsUnknown || _xamlType.ItemType == null)
{
return null;
}
// Common case is that we match the item type. Short-circuit any additional lookup.
if (contentType == _xamlType.ItemType ||
(_xamlType.AllowedContentTypes.Count == 1 && contentType.CanAssignTo(_xamlType.ItemType)))
{
return _xamlType.AddMethod;
}
// Only collections can have additional content types
if (!_xamlType.IsCollection)
{
return null;
}
// Populate the dictionary of all available Add methods
MethodInfo addMethod;
if (_addMethods == null)
{
Dictionary<XamlType, MethodInfo> addMethods = new Dictionary<XamlType, MethodInfo>();
addMethods.Add(_xamlType.ItemType, _xamlType.AddMethod);
foreach (XamlType type in _xamlType.AllowedContentTypes)
{
addMethod = CollectionReflector.GetAddMethod(
_xamlType.UnderlyingType, type.UnderlyingType);
if (addMethod != null)
{
addMethods.Add(type, addMethod);
}
}
_addMethods = addMethods;
}
// First try the fast path. Look for an exact match.
if (_addMethods.TryGetValue(contentType, out addMethod))
{
return addMethod;
}
// Next the slow path. Check each one for is assignable from.
foreach (KeyValuePair<XamlType, MethodInfo> pair in _addMethods)
{
if (contentType.CanAssignTo(pair.Key))
{
return pair.Value;
}
}
return null;
}
public virtual MethodInfo GetEnumeratorMethod()
{
return _xamlType.GetEnumeratorMethod;
}
public virtual IEnumerator GetItems(object instance)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
IEnumerable enumerable = instance as IEnumerable;
if (enumerable != null)
{
return enumerable.GetEnumerator();
}
ThrowIfUnknown();
if (!_xamlType.IsCollection && !_xamlType.IsDictionary)
{
throw new NotSupportedException(SR.Get(SRID.OnlySupportedOnCollectionsAndDictionaries));
}
MethodInfo getEnumMethod = GetEnumeratorMethod();
return (IEnumerator)SafeReflectionInvoker.InvokeMethod(getEnumMethod, instance, s_emptyObjectArray);
}
// vvvvv---- Unused members. Servicing policy is to retain these anyway. -----vvvvv
private bool IsInSystemXaml
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Retained per servicing policy.")]
get
{
if (_isInSystemXaml == ThreeValuedBool.NotSet)
{
Type type = _xamlType.UnderlyingType.UnderlyingSystemType;
bool result = SafeReflectionInvoker.IsInSystemXaml(type);
_isInSystemXaml = result ? ThreeValuedBool.True : ThreeValuedBool.False;
}
return _isInSystemXaml == ThreeValuedBool.True;
}
}
// ^^^^^----- End of unused members. -----^^^^^
private bool IsPublic
{
get
{
if (_isPublic == ThreeValuedBool.NotSet)
{
Type type = _xamlType.UnderlyingType.UnderlyingSystemType;
_isPublic = type.IsVisible ? ThreeValuedBool.True : ThreeValuedBool.False;
}
return _isPublic == ThreeValuedBool.True;
}
}
private bool IsUnknown
{
get { return _xamlType == null || _xamlType.UnderlyingType == null; }
}
private object CreateInstanceWithActivator(Type type, object[] arguments)
{
return SafeReflectionInvoker.CreateInstance(type, arguments);
}
private void ThrowIfUnknown()
{
if (IsUnknown)
{
throw new NotSupportedException(SR.Get(SRID.NotSupportedOnUnknownType));
}
}
private static class DefaultCtorXamlActivator
{
private static ThreeValuedBool s_securityFailureWithCtorDelegate;
private static ConstructorInfo s_actionCtor =
typeof(Action<object>).GetConstructor(new Type[] { typeof(Object), typeof(IntPtr) });
public static object CreateInstance(XamlTypeInvoker type)
{
if (!EnsureConstructorDelegate(type))
{
return null;
}
object inst = CallCtorDelegate(type);
return inst;
}
#if TARGETTING35SP1
#else
#endif
private static object CallCtorDelegate(XamlTypeInvoker type)
{
object inst = FormatterServices.GetUninitializedObject(type._xamlType.UnderlyingType);
InvokeDelegate(type._constructorDelegate, inst);
return inst;
}
private static void InvokeDelegate(Action<object> action, object argument)
{
action.Invoke(argument);
}
#if TARGETTING35SP1
#else
#endif
// returns true if a delegate is available, false if not
private static bool EnsureConstructorDelegate(XamlTypeInvoker type)
{
if (type._constructorDelegate != null)
{
return true;
}
if (!type.IsPublic)
{
return false;
}
if (s_securityFailureWithCtorDelegate == ThreeValuedBool.NotSet)
{
s_securityFailureWithCtorDelegate =
ThreeValuedBool.False;
}
if (s_securityFailureWithCtorDelegate == ThreeValuedBool.True)
{
return false;
}
Type underlyingType = type._xamlType.UnderlyingType.UnderlyingSystemType;
// Look up public ctors only, for equivalence with Activator.CreateInstance
ConstructorInfo tConstInfo = underlyingType.GetConstructor(Type.EmptyTypes);
if (tConstInfo == null)
{
// Throwing MissingMethodException for equivalence with Activator.CreateInstance
throw new MissingMethodException(SR.Get(SRID.NoDefaultConstructor, underlyingType.FullName));
}
if ((tConstInfo.IsSecurityCritical && !tConstInfo.IsSecuritySafeCritical) ||
(tConstInfo.Attributes & MethodAttributes.HasSecurity) == MethodAttributes.HasSecurity ||
(underlyingType.Attributes & TypeAttributes.HasSecurity) == TypeAttributes.HasSecurity)
{
// We don't want to bypass security checks for a critical or demanding ctor,
// so just treat it as if it were non-public
type._isPublic = ThreeValuedBool.False;
return false;
}
IntPtr constPtr = tConstInfo.MethodHandle.GetFunctionPointer();
// This requires Reflection Permission
Action<object> ctorDelegate = ctorDelegate =
(Action<object>)s_actionCtor.Invoke(new object[] { null, constPtr });
type._constructorDelegate = ctorDelegate;
return true;
}
}
private class UnknownTypeInvoker : XamlTypeInvoker
{
public override void AddToCollection(object instance, object item)
{
throw new NotSupportedException(SR.Get(SRID.NotSupportedOnUnknownType));
}
public override void AddToDictionary(object instance, object key, object item)
{
throw new NotSupportedException(SR.Get(SRID.NotSupportedOnUnknownType));
}
public override object CreateInstance(object[] arguments)
{
throw new NotSupportedException(SR.Get(SRID.NotSupportedOnUnknownType));
}
public override IEnumerator GetItems(object instance)
{
throw new NotSupportedException(SR.Get(SRID.NotSupportedOnUnknownType));
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure.Management.Authorization;
using Microsoft.Azure.Management.Authorization.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Authorization
{
/// <summary>
/// TBD (see http://TBD for more information)
/// </summary>
internal partial class RoleDefinitionOperations : IServiceOperations<AuthorizationManagementClient>, IRoleDefinitionOperations
{
/// <summary>
/// Initializes a new instance of the RoleDefinitionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RoleDefinitionOperations(AuthorizationManagementClient client)
{
this._client = client;
}
private AuthorizationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Authorization.AuthorizationManagementClient.
/// </summary>
public AuthorizationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates a role definition.
/// </summary>
/// <param name='roleDefinitionId'>
/// Required. Role definition id.
/// </param>
/// <param name='parameters'>
/// Required. Role definition.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Role definition create or update operation result.
/// </returns>
public async Task<RoleDefinitionCreateOrUpdateResult> CreateOrUpdateAsync(Guid roleDefinitionId, RoleDefinitionCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("roleDefinitionId", roleDefinitionId);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Authorization/roleDefinitions/";
url = url + Uri.EscapeDataString(roleDefinitionId.ToString());
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject propertiesValue = new JObject();
requestDoc = propertiesValue;
if (parameters.RoleDefinition != null)
{
if (parameters.RoleDefinition.Id != null)
{
propertiesValue["id"] = parameters.RoleDefinition.Id;
}
propertiesValue["name"] = parameters.RoleDefinition.Name.ToString();
if (parameters.RoleDefinition.Type != null)
{
propertiesValue["type"] = parameters.RoleDefinition.Type;
}
if (parameters.RoleDefinition.Properties != null)
{
JObject propertiesValue2 = new JObject();
propertiesValue["properties"] = propertiesValue2;
if (parameters.RoleDefinition.Properties.RoleName != null)
{
propertiesValue2["roleName"] = parameters.RoleDefinition.Properties.RoleName;
}
if (parameters.RoleDefinition.Properties.Description != null)
{
propertiesValue2["description"] = parameters.RoleDefinition.Properties.Description;
}
if (parameters.RoleDefinition.Properties.Type != null)
{
propertiesValue2["type"] = parameters.RoleDefinition.Properties.Type;
}
if (parameters.RoleDefinition.Properties.Permissions != null)
{
if (parameters.RoleDefinition.Properties.Permissions is ILazyCollection == false || ((ILazyCollection)parameters.RoleDefinition.Properties.Permissions).IsInitialized)
{
JArray permissionsArray = new JArray();
foreach (Permission permissionsItem in parameters.RoleDefinition.Properties.Permissions)
{
JObject permissionValue = new JObject();
permissionsArray.Add(permissionValue);
if (permissionsItem.Actions != null)
{
if (permissionsItem.Actions is ILazyCollection == false || ((ILazyCollection)permissionsItem.Actions).IsInitialized)
{
JArray actionsArray = new JArray();
foreach (string actionsItem in permissionsItem.Actions)
{
actionsArray.Add(actionsItem);
}
permissionValue["actions"] = actionsArray;
}
}
if (permissionsItem.NotActions != null)
{
if (permissionsItem.NotActions is ILazyCollection == false || ((ILazyCollection)permissionsItem.NotActions).IsInitialized)
{
JArray notActionsArray = new JArray();
foreach (string notActionsItem in permissionsItem.NotActions)
{
notActionsArray.Add(notActionsItem);
}
permissionValue["notActions"] = notActionsArray;
}
}
}
propertiesValue2["permissions"] = permissionsArray;
}
}
if (parameters.RoleDefinition.Properties.AssignableScopes != null)
{
if (parameters.RoleDefinition.Properties.AssignableScopes is ILazyCollection == false || ((ILazyCollection)parameters.RoleDefinition.Properties.AssignableScopes).IsInitialized)
{
JArray assignableScopesArray = new JArray();
foreach (string assignableScopesItem in parameters.RoleDefinition.Properties.AssignableScopes)
{
assignableScopesArray.Add(assignableScopesItem);
}
propertiesValue2["assignableScopes"] = assignableScopesArray;
}
}
}
}
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.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
RoleDefinitionCreateOrUpdateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RoleDefinitionCreateOrUpdateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
RoleDefinition roleDefinitionInstance = new RoleDefinition();
result.RoleDefinition = roleDefinitionInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
roleDefinitionInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
Guid nameInstance = Guid.Parse(((string)nameValue));
roleDefinitionInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
roleDefinitionInstance.Type = typeInstance;
}
JToken propertiesValue3 = responseDoc["properties"];
if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
{
RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties();
roleDefinitionInstance.Properties = propertiesInstance;
JToken roleNameValue = propertiesValue3["roleName"];
if (roleNameValue != null && roleNameValue.Type != JTokenType.Null)
{
string roleNameInstance = ((string)roleNameValue);
propertiesInstance.RoleName = roleNameInstance;
}
JToken descriptionValue = propertiesValue3["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken typeValue2 = propertiesValue3["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
propertiesInstance.Type = typeInstance2;
}
JToken permissionsArray2 = propertiesValue3["permissions"];
if (permissionsArray2 != null && permissionsArray2.Type != JTokenType.Null)
{
foreach (JToken permissionsValue in ((JArray)permissionsArray2))
{
Permission permissionInstance = new Permission();
propertiesInstance.Permissions.Add(permissionInstance);
JToken actionsArray2 = permissionsValue["actions"];
if (actionsArray2 != null && actionsArray2.Type != JTokenType.Null)
{
foreach (JToken actionsValue in ((JArray)actionsArray2))
{
permissionInstance.Actions.Add(((string)actionsValue));
}
}
JToken notActionsArray2 = permissionsValue["notActions"];
if (notActionsArray2 != null && notActionsArray2.Type != JTokenType.Null)
{
foreach (JToken notActionsValue in ((JArray)notActionsArray2))
{
permissionInstance.NotActions.Add(((string)notActionsValue));
}
}
}
}
JToken assignableScopesArray2 = propertiesValue3["assignableScopes"];
if (assignableScopesArray2 != null && assignableScopesArray2.Type != JTokenType.Null)
{
foreach (JToken assignableScopesValue in ((JArray)assignableScopesArray2))
{
propertiesInstance.AssignableScopes.Add(((string)assignableScopesValue));
}
}
}
}
}
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>
/// Deletes the role definition.
/// </summary>
/// <param name='roleDefinitionId'>
/// Required. Role definition id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Role definition delete operation result.
/// </returns>
public async Task<RoleDefinitionDeleteResult> DeleteAsync(string roleDefinitionId, CancellationToken cancellationToken)
{
// Validate
if (roleDefinitionId == null)
{
throw new ArgumentNullException("roleDefinitionId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("roleDefinitionId", roleDefinitionId);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + roleDefinitionId;
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-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
httpRequest.Headers.Add("x-ms-version", "2015-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RoleDefinitionDeleteResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RoleDefinitionDeleteResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
RoleDefinition roleDefinitionInstance = new RoleDefinition();
result.RoleDefinition = roleDefinitionInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
roleDefinitionInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
Guid nameInstance = Guid.Parse(((string)nameValue));
roleDefinitionInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
roleDefinitionInstance.Type = typeInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties();
roleDefinitionInstance.Properties = propertiesInstance;
JToken roleNameValue = propertiesValue["roleName"];
if (roleNameValue != null && roleNameValue.Type != JTokenType.Null)
{
string roleNameInstance = ((string)roleNameValue);
propertiesInstance.RoleName = roleNameInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken typeValue2 = propertiesValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
propertiesInstance.Type = typeInstance2;
}
JToken permissionsArray = propertiesValue["permissions"];
if (permissionsArray != null && permissionsArray.Type != JTokenType.Null)
{
foreach (JToken permissionsValue in ((JArray)permissionsArray))
{
Permission permissionInstance = new Permission();
propertiesInstance.Permissions.Add(permissionInstance);
JToken actionsArray = permissionsValue["actions"];
if (actionsArray != null && actionsArray.Type != JTokenType.Null)
{
foreach (JToken actionsValue in ((JArray)actionsArray))
{
permissionInstance.Actions.Add(((string)actionsValue));
}
}
JToken notActionsArray = permissionsValue["notActions"];
if (notActionsArray != null && notActionsArray.Type != JTokenType.Null)
{
foreach (JToken notActionsValue in ((JArray)notActionsArray))
{
permissionInstance.NotActions.Add(((string)notActionsValue));
}
}
}
}
JToken assignableScopesArray = propertiesValue["assignableScopes"];
if (assignableScopesArray != null && assignableScopesArray.Type != JTokenType.Null)
{
foreach (JToken assignableScopesValue in ((JArray)assignableScopesArray))
{
propertiesInstance.AssignableScopes.Add(((string)assignableScopesValue));
}
}
}
}
}
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 role definition by name (GUID).
/// </summary>
/// <param name='roleDefinitionName'>
/// Required. Role definition name (GUID).
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Role definition get operation result.
/// </returns>
public async Task<RoleDefinitionGetResult> GetAsync(Guid roleDefinitionName, 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("roleDefinitionName", roleDefinitionName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Authorization/roleDefinitions/";
url = url + Uri.EscapeDataString(roleDefinitionName.ToString());
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RoleDefinitionGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RoleDefinitionGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
RoleDefinition roleDefinitionInstance = new RoleDefinition();
result.RoleDefinition = roleDefinitionInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
roleDefinitionInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
Guid nameInstance = Guid.Parse(((string)nameValue));
roleDefinitionInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
roleDefinitionInstance.Type = typeInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties();
roleDefinitionInstance.Properties = propertiesInstance;
JToken roleNameValue = propertiesValue["roleName"];
if (roleNameValue != null && roleNameValue.Type != JTokenType.Null)
{
string roleNameInstance = ((string)roleNameValue);
propertiesInstance.RoleName = roleNameInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken typeValue2 = propertiesValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
propertiesInstance.Type = typeInstance2;
}
JToken permissionsArray = propertiesValue["permissions"];
if (permissionsArray != null && permissionsArray.Type != JTokenType.Null)
{
foreach (JToken permissionsValue in ((JArray)permissionsArray))
{
Permission permissionInstance = new Permission();
propertiesInstance.Permissions.Add(permissionInstance);
JToken actionsArray = permissionsValue["actions"];
if (actionsArray != null && actionsArray.Type != JTokenType.Null)
{
foreach (JToken actionsValue in ((JArray)actionsArray))
{
permissionInstance.Actions.Add(((string)actionsValue));
}
}
JToken notActionsArray = permissionsValue["notActions"];
if (notActionsArray != null && notActionsArray.Type != JTokenType.Null)
{
foreach (JToken notActionsValue in ((JArray)notActionsArray))
{
permissionInstance.NotActions.Add(((string)notActionsValue));
}
}
}
}
JToken assignableScopesArray = propertiesValue["assignableScopes"];
if (assignableScopesArray != null && assignableScopesArray.Type != JTokenType.Null)
{
foreach (JToken assignableScopesValue in ((JArray)assignableScopesArray))
{
propertiesInstance.AssignableScopes.Add(((string)assignableScopesValue));
}
}
}
}
}
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 role definition by name (GUID).
/// </summary>
/// <param name='roleDefinitionId'>
/// Required. Role definition Id
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Role definition get operation result.
/// </returns>
public async Task<RoleDefinitionGetResult> GetByIdAsync(string roleDefinitionId, CancellationToken cancellationToken)
{
// Validate
if (roleDefinitionId == null)
{
throw new ArgumentNullException("roleDefinitionId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("roleDefinitionId", roleDefinitionId);
TracingAdapter.Enter(invocationId, this, "GetByIdAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + roleDefinitionId;
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RoleDefinitionGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RoleDefinitionGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
RoleDefinition roleDefinitionInstance = new RoleDefinition();
result.RoleDefinition = roleDefinitionInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
roleDefinitionInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
Guid nameInstance = Guid.Parse(((string)nameValue));
roleDefinitionInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
roleDefinitionInstance.Type = typeInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties();
roleDefinitionInstance.Properties = propertiesInstance;
JToken roleNameValue = propertiesValue["roleName"];
if (roleNameValue != null && roleNameValue.Type != JTokenType.Null)
{
string roleNameInstance = ((string)roleNameValue);
propertiesInstance.RoleName = roleNameInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken typeValue2 = propertiesValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
propertiesInstance.Type = typeInstance2;
}
JToken permissionsArray = propertiesValue["permissions"];
if (permissionsArray != null && permissionsArray.Type != JTokenType.Null)
{
foreach (JToken permissionsValue in ((JArray)permissionsArray))
{
Permission permissionInstance = new Permission();
propertiesInstance.Permissions.Add(permissionInstance);
JToken actionsArray = permissionsValue["actions"];
if (actionsArray != null && actionsArray.Type != JTokenType.Null)
{
foreach (JToken actionsValue in ((JArray)actionsArray))
{
permissionInstance.Actions.Add(((string)actionsValue));
}
}
JToken notActionsArray = permissionsValue["notActions"];
if (notActionsArray != null && notActionsArray.Type != JTokenType.Null)
{
foreach (JToken notActionsValue in ((JArray)notActionsArray))
{
permissionInstance.NotActions.Add(((string)notActionsValue));
}
}
}
}
JToken assignableScopesArray = propertiesValue["assignableScopes"];
if (assignableScopesArray != null && assignableScopesArray.Type != JTokenType.Null)
{
foreach (JToken assignableScopesValue in ((JArray)assignableScopesArray))
{
propertiesInstance.AssignableScopes.Add(((string)assignableScopesValue));
}
}
}
}
}
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 all role definitions.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Role definition list operation result.
/// </returns>
public async Task<RoleDefinitionListResult> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Authorization/roleDefinitions";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RoleDefinitionListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RoleDefinitionListResult();
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))
{
RoleDefinition roleDefinitionInstance = new RoleDefinition();
result.RoleDefinitions.Add(roleDefinitionInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
roleDefinitionInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
Guid nameInstance = Guid.Parse(((string)nameValue));
roleDefinitionInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
roleDefinitionInstance.Type = typeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties();
roleDefinitionInstance.Properties = propertiesInstance;
JToken roleNameValue = propertiesValue["roleName"];
if (roleNameValue != null && roleNameValue.Type != JTokenType.Null)
{
string roleNameInstance = ((string)roleNameValue);
propertiesInstance.RoleName = roleNameInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken typeValue2 = propertiesValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
propertiesInstance.Type = typeInstance2;
}
JToken permissionsArray = propertiesValue["permissions"];
if (permissionsArray != null && permissionsArray.Type != JTokenType.Null)
{
foreach (JToken permissionsValue in ((JArray)permissionsArray))
{
Permission permissionInstance = new Permission();
propertiesInstance.Permissions.Add(permissionInstance);
JToken actionsArray = permissionsValue["actions"];
if (actionsArray != null && actionsArray.Type != JTokenType.Null)
{
foreach (JToken actionsValue in ((JArray)actionsArray))
{
permissionInstance.Actions.Add(((string)actionsValue));
}
}
JToken notActionsArray = permissionsValue["notActions"];
if (notActionsArray != null && notActionsArray.Type != JTokenType.Null)
{
foreach (JToken notActionsValue in ((JArray)notActionsArray))
{
permissionInstance.NotActions.Add(((string)notActionsValue));
}
}
}
}
JToken assignableScopesArray = propertiesValue["assignableScopes"];
if (assignableScopesArray != null && assignableScopesArray.Type != JTokenType.Null)
{
foreach (JToken assignableScopesValue in ((JArray)assignableScopesArray))
{
propertiesInstance.AssignableScopes.Add(((string)assignableScopesValue));
}
}
}
}
}
}
}
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 role definitions.
/// </summary>
/// <param name='parameters'>
/// Required. List role definitions filters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Role definition list operation result.
/// </returns>
public async Task<RoleDefinitionListResult> ListWithFiltersAsync(ListDefinitionFilterParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// 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, "ListWithFiltersAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Authorization/roleDefinitions";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters.RoleName != null)
{
odataFilter.Add("roleName eq '" + Uri.EscapeDataString(parameters.RoleName) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
queryParameters.Add("api-version=2015-07-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RoleDefinitionListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RoleDefinitionListResult();
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))
{
RoleDefinition roleDefinitionInstance = new RoleDefinition();
result.RoleDefinitions.Add(roleDefinitionInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
roleDefinitionInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
Guid nameInstance = Guid.Parse(((string)nameValue));
roleDefinitionInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
roleDefinitionInstance.Type = typeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties();
roleDefinitionInstance.Properties = propertiesInstance;
JToken roleNameValue = propertiesValue["roleName"];
if (roleNameValue != null && roleNameValue.Type != JTokenType.Null)
{
string roleNameInstance = ((string)roleNameValue);
propertiesInstance.RoleName = roleNameInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken typeValue2 = propertiesValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
propertiesInstance.Type = typeInstance2;
}
JToken permissionsArray = propertiesValue["permissions"];
if (permissionsArray != null && permissionsArray.Type != JTokenType.Null)
{
foreach (JToken permissionsValue in ((JArray)permissionsArray))
{
Permission permissionInstance = new Permission();
propertiesInstance.Permissions.Add(permissionInstance);
JToken actionsArray = permissionsValue["actions"];
if (actionsArray != null && actionsArray.Type != JTokenType.Null)
{
foreach (JToken actionsValue in ((JArray)actionsArray))
{
permissionInstance.Actions.Add(((string)actionsValue));
}
}
JToken notActionsArray = permissionsValue["notActions"];
if (notActionsArray != null && notActionsArray.Type != JTokenType.Null)
{
foreach (JToken notActionsValue in ((JArray)notActionsArray))
{
permissionInstance.NotActions.Add(((string)notActionsValue));
}
}
}
}
JToken assignableScopesArray = propertiesValue["assignableScopes"];
if (assignableScopesArray != null && assignableScopesArray.Type != JTokenType.Null)
{
foreach (JToken assignableScopesValue in ((JArray)assignableScopesArray))
{
propertiesInstance.AssignableScopes.Add(((string)assignableScopesValue));
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text;
using System.Collections.Generic;
namespace Microsoft.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// KeywordParser
//
////////////////////////////////////////////////////////////////
public class KeywordParser
{
//Enum
protected enum PARSE
{
Initial,
Keyword,
Equal,
Value,
SingleBegin,
SingleEnd,
DoubleBegin,
DoubleEnd,
End
}
//Accessors
//Note: You can override these if you want to leverage our parser (inherit), and change
//some of the behavior (without reimplementing it).
private static Tokens s_DefaultTokens = new Tokens();
public class Tokens
{
public string Equal = "=";
public string Seperator = ";";
public string SingleQuote = "'";
public string DoubleQuote = "\"";
}
//Methods
static public Dictionary<string, string> ParseKeywords(string str)
{
return ParseKeywords(str, s_DefaultTokens);
}
static public Dictionary<string, string> ParseKeywords(string str, Tokens tokens)
{
PARSE state = PARSE.Initial;
int index = 0;
int keyStart = 0;
InsensitiveDictionary keywords = new InsensitiveDictionary(5);
string key = null;
if (str != null)
{
StringBuilder builder = new StringBuilder(str.Length);
for (; index < str.Length; index++)
{
char ch = str[index];
switch (state)
{
case PARSE.Initial:
if (Char.IsLetterOrDigit(ch))
{
keyStart = index;
state = PARSE.Keyword;
}
break;
case PARSE.Keyword:
if (tokens.Seperator.IndexOf(ch) >= 0)
{
state = PARSE.Initial;
}
else if (tokens.Equal.IndexOf(ch) >= 0)
{
//Note: We have a case-insentive hashtable so we don't have to lowercase
key = str.Substring(keyStart, index - keyStart).Trim();
state = PARSE.Equal;
}
break;
case PARSE.Equal:
if (Char.IsWhiteSpace(ch))
break;
builder.Length = 0;
//Note: Since we allow you to alter the tokens, these are not
//constant values, so we cannot use a switch statement...
if (tokens.SingleQuote.IndexOf(ch) >= 0)
{
state = PARSE.SingleBegin;
}
else if (tokens.DoubleQuote.IndexOf(ch) >= 0)
{
state = PARSE.DoubleBegin;
}
else if (tokens.Seperator.IndexOf(ch) >= 0)
{
keywords.Update(key, String.Empty);
state = PARSE.Initial;
}
else
{
state = PARSE.Value;
builder.Append(ch);
}
break;
case PARSE.Value:
if (tokens.Seperator.IndexOf(ch) >= 0)
{
keywords.Update(key, (builder.ToString()).Trim());
state = PARSE.Initial;
}
else
{
builder.Append(ch);
}
break;
case PARSE.SingleBegin:
if (tokens.SingleQuote.IndexOf(ch) >= 0)
state = PARSE.SingleEnd;
else
builder.Append(ch);
break;
case PARSE.DoubleBegin:
if (tokens.DoubleQuote.IndexOf(ch) >= 0)
state = PARSE.DoubleEnd;
else
builder.Append(ch);
break;
case PARSE.SingleEnd:
if (tokens.SingleQuote.IndexOf(ch) >= 0)
{
state = PARSE.SingleBegin;
builder.Append(ch);
}
else
{
keywords.Update(key, builder.ToString());
state = PARSE.End;
goto case PARSE.End;
}
break;
case PARSE.DoubleEnd:
if (tokens.DoubleQuote.IndexOf(ch) >= 0)
{
state = PARSE.DoubleBegin;
builder.Append(ch);
}
else
{
keywords.Update(key, builder.ToString());
state = PARSE.End;
goto case PARSE.End;
}
break;
case PARSE.End:
if (tokens.Seperator.IndexOf(ch) >= 0)
{
state = PARSE.Initial;
}
break;
default:
throw new TestFailedException("Unhandled State: " + StringEx.ToString(state));
}
}
switch (state)
{
case PARSE.Initial:
case PARSE.Keyword:
case PARSE.End:
break;
case PARSE.Equal:
keywords.Update(key, String.Empty);
break;
case PARSE.Value:
keywords.Update(key, (builder.ToString()).Trim());
break;
case PARSE.SingleBegin:
case PARSE.DoubleBegin:
case PARSE.SingleEnd:
case PARSE.DoubleEnd:
keywords.Update(key, builder.ToString());
break;
default:
throw new TestFailedException("Unhandled State: " + StringEx.ToString(state));
}
}
return keywords;
}
}
}
| |
// File generated from our OpenAPI spec
namespace Stripe.Issuing
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
/// <summary>
/// You can <a href="https://stripe.com/docs/issuing/cards">create physical or virtual
/// cards</a> that are issued to cardholders.
/// </summary>
public class Card : StripeEntity<Card>, IHasId, IHasMetadata, IHasObject
{
/// <summary>
/// Unique identifier for the object.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object's type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
/// <summary>
/// The brand of the card.
/// </summary>
[JsonProperty("brand")]
public string Brand { get; set; }
/// <summary>
/// The reason why the card was canceled.
/// One of: <c>lost</c>, or <c>stolen</c>.
/// </summary>
[JsonProperty("cancellation_reason")]
public string CancellationReason { get; set; }
/// <summary>
/// An Issuing <c>Cardholder</c> object represents an individual or business entity who is
/// <a href="https://stripe.com/docs/issuing">issued</a> cards.
///
/// Related guide: <a href="https://stripe.com/docs/issuing/cards#create-cardholder">How to
/// create a Cardholder</a>.
/// </summary>
[JsonProperty("cardholder")]
public Cardholder Cardholder { get; set; }
/// <summary>
/// Time at which the object was created. Measured in seconds since the Unix epoch.
/// </summary>
[JsonProperty("created")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Created { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch;
/// <summary>
/// Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency
/// code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported
/// currency</a>.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
/// <summary>
/// The card's CVC. For security reasons, this is only available for virtual cards, and will
/// be omitted unless you explicitly request it with <a
/// href="https://stripe.com/docs/api/expanding_objects">the <c>expand</c> parameter</a>.
/// Additionally, it's only available via the <a
/// href="https://stripe.com/docs/api/issuing/cards/retrieve">"Retrieve a card"
/// endpoint</a>, not via "List all cards" or any other endpoint.
/// </summary>
[JsonProperty("cvc")]
public string Cvc { get; set; }
/// <summary>
/// The expiration month of the card.
/// </summary>
[JsonProperty("exp_month")]
public long ExpMonth { get; set; }
/// <summary>
/// The expiration year of the card.
/// </summary>
[JsonProperty("exp_year")]
public long ExpYear { get; set; }
/// <summary>
/// The last 4 digits of the card number.
/// </summary>
[JsonProperty("last4")]
public string Last4 { get; set; }
/// <summary>
/// Has the value <c>true</c> if the object exists in live mode or the value <c>false</c> if
/// the object exists in test mode.
/// </summary>
[JsonProperty("livemode")]
public bool Livemode { get; set; }
/// <summary>
/// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can
/// attach to an object. This can be useful for storing additional information about the
/// object in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// The full unredacted card number. For security reasons, this is only available for
/// virtual cards, and will be omitted unless you explicitly request it with <a
/// href="https://stripe.com/docs/api/expanding_objects">the <c>expand</c> parameter</a>.
/// Additionally, it's only available via the <a
/// href="https://stripe.com/docs/api/issuing/cards/retrieve">"Retrieve a card"
/// endpoint</a>, not via "List all cards" or any other endpoint.
/// </summary>
[JsonProperty("number")]
public string Number { get; set; }
#region Expandable ReplacedBy
/// <summary>
/// (ID of the Card)
/// The latest card that replaces this card, if any.
/// </summary>
[JsonIgnore]
public string ReplacedById
{
get => this.InternalReplacedBy?.Id;
set => this.InternalReplacedBy = SetExpandableFieldId(value, this.InternalReplacedBy);
}
/// <summary>
/// (Expanded)
/// The latest card that replaces this card, if any.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public Card ReplacedBy
{
get => this.InternalReplacedBy?.ExpandedObject;
set => this.InternalReplacedBy = SetExpandableFieldObject(value, this.InternalReplacedBy);
}
[JsonProperty("replaced_by")]
[JsonConverter(typeof(ExpandableFieldConverter<Card>))]
internal ExpandableField<Card> InternalReplacedBy { get; set; }
#endregion
#region Expandable ReplacementFor
/// <summary>
/// (ID of the Card)
/// The card this card replaces, if any.
/// </summary>
[JsonIgnore]
public string ReplacementForId
{
get => this.InternalReplacementFor?.Id;
set => this.InternalReplacementFor = SetExpandableFieldId(value, this.InternalReplacementFor);
}
/// <summary>
/// (Expanded)
/// The card this card replaces, if any.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public Card ReplacementFor
{
get => this.InternalReplacementFor?.ExpandedObject;
set => this.InternalReplacementFor = SetExpandableFieldObject(value, this.InternalReplacementFor);
}
[JsonProperty("replacement_for")]
[JsonConverter(typeof(ExpandableFieldConverter<Card>))]
internal ExpandableField<Card> InternalReplacementFor { get; set; }
#endregion
/// <summary>
/// The reason why the previous card needed to be replaced.
/// One of: <c>damaged</c>, <c>expired</c>, <c>lost</c>, or <c>stolen</c>.
/// </summary>
[JsonProperty("replacement_reason")]
public string ReplacementReason { get; set; }
/// <summary>
/// Where and how the card will be shipped.
/// </summary>
[JsonProperty("shipping")]
public CardShipping Shipping { get; set; }
[JsonProperty("spending_controls")]
public CardSpendingControls SpendingControls { get; set; }
/// <summary>
/// Whether authorizations can be approved on this card.
/// One of: <c>active</c>, <c>canceled</c>, or <c>inactive</c>.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// The type of the card.
/// One of: <c>physical</c>, or <c>virtual</c>.
/// </summary>
[JsonProperty("type")]
public string Type { get; set; }
/// <summary>
/// Information relating to digital wallets (like Apple Pay and Google Pay).
/// </summary>
[JsonProperty("wallets")]
public CardWallets Wallets { get; set; }
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.Transformations
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
//
// This class computes, for each program point, the set of identity assignments that reach it.
//
public class GlobalCopyPropagation : IDisposable
{
internal class SubstitutionScoreBoard
{
//
// State
//
internal readonly Operator m_op;
internal readonly int m_idxDst;
internal readonly Expression m_exSrc;
//
// Constructor Methods
//
internal SubstitutionScoreBoard( Operator op ,
int idxDst ,
Expression exSrc )
{
m_op = op;
m_idxDst = idxDst;
m_exSrc = exSrc;
}
}
//
// State
//
private readonly ControlFlowGraphStateForCodeTransformation m_cfg;
private readonly IDisposable m_cfgLock;
private readonly BasicBlock[] m_basicBlocks; // All the basic blocks, in spanning tree order.
private readonly Operator[] m_operators; // All the operators, in spanning tree order.
private readonly VariableExpression[] m_variables; // All the variables, in spanning tree order.
private readonly VariableExpression[][] m_variablesByStorage; // Lookup for multi-mapped variables.
private readonly VariableExpression.Property[] m_varProps;
private readonly int m_bbNum;
private readonly int m_opsNum;
private readonly int m_varNum;
private readonly BitVector[] m_variableUses; // For each variable (spanning tree index), which operators use it.
private readonly BitVector[] m_variableDefinitions; // For each variable (spanning tree index), which operators define it.
private BitVector[] m_operatorKillPre; // For each operator (spanning tree index), which variable assignments it kills BEFORE its execution.
private BitVector[] m_operatorKillPost; // For each operator (spanning tree index), which variable assignments it kills AFTER its execution.
private BitVector[] m_operatorCopy; // For each operator (spanning tree index), which variable assignments are available.
private BitVector[] m_CPin;
private BitVector[] m_CPout;
private BitVector[] m_KILL; // For each basic block (spanning tree index), which variable assignments it kills.
private BitVector[] m_COPY; // For each basic block (spanning tree index), which variable assignments are available at the exit.
//
// Constructor Methods
//
private GlobalCopyPropagation( ControlFlowGraphStateForCodeTransformation cfg )
{
m_cfg = cfg;
m_cfgLock = cfg.GroupLock( cfg.LockSpanningTree () ,
cfg.LockPropertiesOfVariables() ,
cfg.LockUseDefinitionChains () );
m_basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks;
m_operators = cfg.DataFlow_SpanningTree_Operators;
m_variables = cfg.DataFlow_SpanningTree_Variables;
m_variablesByStorage = cfg.DataFlow_SpanningTree_VariablesByStorage;
m_varProps = cfg.DataFlow_PropertiesOfVariables;
m_bbNum = m_basicBlocks.Length;
m_opsNum = m_operators.Length;
m_varNum = m_variables.Length;
m_variableUses = cfg.DataFlow_BitVectorsForUseChains;
m_variableDefinitions = cfg.DataFlow_BitVectorsForDefinitionChains;
//--//
ComputeEquationParameters();
SolveEquations();
PropagateSolutions();
}
//
// Helper Methods
//
public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg )
{
cfg.TraceToFile( "GlobalCopyPropagation" );
using(new PerformanceCounters.ContextualTiming( cfg, "GlobalCopyPropagation" ))
{
using(GlobalCopyPropagation gcp = new GlobalCopyPropagation( cfg ))
{
return gcp.Apply();
}
}
}
public void Dispose()
{
m_cfgLock.Dispose();
}
private bool Apply()
{
TypeSystemForCodeTransformation ts = m_cfg.TypeSystem;
Abstractions.Platform pa = ts.PlatformAbstraction;
Operator[] operators = m_operators;
BitVector[] availableCopies = m_operatorCopy;
BitVector unavailableOperators = new BitVector( operators.Length );
List< SubstitutionScoreBoard > workList = null;
int opsNum = operators.Length;
for(int opIdx = 0; opIdx < opsNum; opIdx++)
{
Operator op = operators[opIdx];
foreach(int opSrcIdx in availableCopies[opIdx])
{
//
// Ignore operators that have been modified in this round.
//
if(unavailableOperators[opSrcIdx])
{
continue;
}
SingleAssignmentOperator opSrc = operators[opSrcIdx] as SingleAssignmentOperator;
Expression exSrc = opSrc.FirstArgument;
TypeRepresentation tdSrc = exSrc.Type;
bool fSkip = false;
foreach(Annotation an in opSrc.Annotations)
{
if(an is NotNullAnnotation)
{
if(exSrc is ConstantExpression)
{
//
// A constant is never null, so it's OK to ignore the annotation.
//
continue;
}
}
//
// Don't propagate copies if they carry annotations, they would be lost.
//
fSkip = true;
break;
}
if(fSkip)
{
continue;
}
//--//
for(int rhsIndex = 0; rhsIndex < op.Arguments.Length; rhsIndex++)
{
Expression exDst = op.Arguments[rhsIndex];
if(exDst == opSrc.FirstResult &&
exDst != exSrc &&
op.CanPropagateCopy( exDst, exSrc ) &&
pa.CanPropagateCopy( opSrc, op, rhsIndex, m_variables, m_variableUses, m_variableDefinitions, operators ) )
{
bool fCopy = false;
if(ts.GetLevel( exSrc ) == Operator.OperatorLevel.StackLocations)
{
// Don't propagate from stack locations to anywhere else, it's inefficient.
}
else if(ts.GetLevel( exDst ) <= Operator.OperatorLevel.ScalarValues &&
ts.GetLevel( exSrc ) <= Operator.OperatorLevel.ScalarValues )
{
fCopy = true;
}
else
{
TypeRepresentation tdDst = exDst.Type;
if(ShouldSubstitute( tdDst, tdSrc ))
{
//
// Rhs and Candidate copy are compatible.
//
fCopy = true;
}
else if(exSrc is ConstantExpression)
{
if(tdDst is ReferenceTypeRepresentation ||
tdDst is PointerTypeRepresentation ||
tdDst.StackEquivalentType == StackEquivalentType.NativeInt )
{
//
// We can always assign a constant to a reference, a pointer type, or a native int.
//
fCopy = true;
}
else if(tdSrc is ScalarTypeRepresentation &&
tdDst is ScalarTypeRepresentation )
{
//
// Convert constant to the target type.
//
var exConst = (ConstantExpression)exSrc;
ulong rawValue;
if(exConst.GetAsRawUlong( out rawValue ))
{
var obj = ConstantExpression.ConvertToType( tdDst, rawValue );
exSrc = m_cfg.TypeSystem.CreateConstant( tdDst, obj );
fCopy = true;
}
}
}
if(fCopy == false)
{
if(op is SingleAssignmentOperator)
{
VariableExpression lhs = op.FirstResult;
if(ShouldSubstitute( lhs.Type, tdSrc ))
{
//
// Lhs and Candidate copy are compatible, through assignment operator.
//
fCopy = true;
}
}
}
}
if(fCopy)
{
foreach(var an in op.FilterAnnotations< BlockCopyPropagationAnnotation >())
{
if(an.IsResult == false && an.Index == rhsIndex)
{
fCopy = false;
break;
}
}
}
if(fCopy)
{
if(workList == null)
{
workList = new List< SubstitutionScoreBoard >();
}
workList.Add( new SubstitutionScoreBoard( op, rhsIndex, exSrc ) );
unavailableOperators.Set( opIdx );
}
}
}
}
}
if(workList == null)
{
return false;
}
foreach(SubstitutionScoreBoard sb in workList)
{
sb.m_op.SubstituteUsage( sb.m_idxDst, sb.m_exSrc );
}
return true;
}
private void ComputeEquationParameters()
{
//
// Compute the KILL and COPY values for each operator.
//
m_operatorKillPre = BitVector.AllocateBitVectors( m_opsNum, m_opsNum );
m_operatorKillPost = BitVector.AllocateBitVectors( m_opsNum, m_opsNum );
m_operatorCopy = BitVector.AllocateBitVectors( m_opsNum, m_opsNum );
for(int opIdx = 0; opIdx < m_opsNum; opIdx++)
{
Operator op = m_operators [opIdx];
BitVector opKillPre = m_operatorKillPre [opIdx];
BitVector opKillPost = m_operatorKillPost[opIdx];
BitVector opCopy = m_operatorCopy [opIdx];
foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >())
{
KillAllReferences( opKillPre, an.Target );
}
if(op is ReturnControlOperator)
{
//
// We don't want to change the expression associated with the return control operator,
// because it's associated with the m_returnValue field on the ControlFlowGraphState object,
// and m_returnValue is associated with registers or stack locations during Phase.ExpandAggregateTypes.
//
foreach(var ex in op.Arguments)
{
var ex2 = ex as VariableExpression;
if(ex2 != null)
{
KillAllReferences( opKillPre, ex2 );
}
}
}
if(op.MayWriteThroughPointerOperands)
{
for(int varIdx = 0; varIdx < m_varNum; varIdx++)
{
if((m_varProps[varIdx] & VariableExpression.Property.AddressTaken) != 0)
{
KillAllReferences( opKillPost, m_variables[varIdx] );
}
}
}
foreach(var lhs in op.Results)
{
KillAllReferences( opKillPost, lhs );
}
foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >())
{
KillAllReferences( opKillPost, an.Target );
}
if(op is SingleAssignmentOperator)
{
bool fCopy = true;
if(op.FirstResult.AliasedVariable is LowLevelVariableExpression &&
op.FirstArgument is ConstantExpression )
{
//
// Don't propagate constant if the target is a low-level variable.
//
fCopy = false;
}
if(fCopy)
{
if(op.FirstResult.Type.IsFloatingPoint != op.FirstArgument.Type.IsFloatingPoint)
{
//
// Don't mix floating-point and integer numbers.
//
fCopy = false;
}
}
if(fCopy)
{
foreach(var an in op.FilterAnnotations< BlockCopyPropagationAnnotation >())
{
if(an.IsResult && an.Index == 0)
{
fCopy = false;
break;
}
}
}
if(fCopy)
{
opCopy.Set( op.SpanningTreeIndex );
}
}
}
//
// Compute the KILL and COPY values for each basic block.
//
m_KILL = BitVector.AllocateBitVectors( m_bbNum, m_opsNum );
m_COPY = BitVector.AllocateBitVectors( m_bbNum, m_opsNum );
for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++)
{
BasicBlock bb = m_basicBlocks[bbIdx];
BitVector bbKill = m_KILL [bbIdx];
BitVector bbCopy = m_COPY [bbIdx];
int pos = bb.Operators[0].SpanningTreeIndex;
int len = bb.Operators.Length;
while(--len >= 0)
{
bbKill.OrInPlace ( m_operatorKillPre[pos] );
bbCopy.DifferenceInPlace( m_operatorKillPre[pos] );
bbKill.OrInPlace ( m_operatorKillPost[pos] );
bbCopy.DifferenceInPlace( m_operatorKillPost[pos] );
bbCopy.OrInPlace ( m_operatorCopy[pos] );
bbKill.DifferenceInPlace( m_operatorCopy[pos] );
pos++;
}
}
}
private void SolveEquations()
{
//
// Prepare initial state for Data Flow computation.
//
m_CPin = BitVector.AllocateBitVectors( m_bbNum, m_opsNum );
m_CPout = BitVector.AllocateBitVectors( m_bbNum, m_opsNum );
BitVector CopyTotal = new BitVector( m_opsNum );
for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++)
{
CopyTotal.OrInPlace( m_COPY[bbIdx] );
}
for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++)
{
if(m_basicBlocks[bbIdx] is EntryBasicBlock)
{
}
else
{
m_CPin[bbIdx].Assign( CopyTotal );
}
}
//
// Solve the Data Flow equations.
//
BitVector tmp = new BitVector( m_opsNum );
while(true)
{
bool fDone = true;
//
// CPout = (CPin - Kill) Or Copy
//
for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++)
{
tmp.Difference( m_CPin[bbIdx], m_KILL[bbIdx] );
tmp.OrInPlace( m_COPY[bbIdx] );
if(m_CPout[bbIdx] != tmp)
{
m_CPout[bbIdx].Assign( tmp );
fDone = false;
}
}
if(fDone)
{
break;
}
//
// CPin = And { CPout(<predecessors>) }
//
for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++)
{
BitVector b = m_CPin[bbIdx];
bool fFirst = true;
foreach(BasicBlockEdge edge in m_basicBlocks[bbIdx].Predecessors)
{
BitVector CPpred = m_CPout[ edge.Predecessor.SpanningTreeIndex ];
if(fFirst)
{
fFirst = false;
b.Assign( CPpred );
}
else
{
b.AndInPlace( CPpred );
}
}
if(fFirst)
{
b.ClearAll();
}
}
}
}
private void PropagateSolutions()
{
//
// Apply the solution to all the operators.
//
BitVector tmp = new BitVector( m_opsNum );
BitVector tmp2 = new BitVector( m_opsNum );
for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++)
{
tmp.Assign( m_CPin[bbIdx] );
BasicBlock bb = m_basicBlocks[bbIdx];
int pos = bb.Operators[0].SpanningTreeIndex;
int len = bb.Operators.Length;
while(--len >= 0)
{
tmp2.Assign( m_operatorCopy[pos] );
tmp.DifferenceInPlace( m_operatorKillPre[pos] );
m_operatorCopy[pos].Assign( tmp );
tmp.DifferenceInPlace( m_operatorKillPost[pos] );
tmp.OrInPlace ( tmp2 );
pos++;
}
}
}
//--//
private void KillAllReferences( BitVector opKill ,
VariableExpression var )
{
int varIdx = var.SpanningTreeIndex;
//
// We actually use multiple instances of physical registers and stack locations, each one with a different type.
// But whenever we encounter one, we need to kill all of them.
//
foreach(VariableExpression var2 in m_variablesByStorage[varIdx])
{
int varIdx2 = var2.SpanningTreeIndex;
opKill.OrInPlace( m_variableDefinitions[varIdx2] );
opKill.OrInPlace( m_variableUses [varIdx2] );
}
}
private bool ShouldSubstitute( TypeRepresentation tdDst ,
TypeRepresentation tdSrc )
{
if(tdDst.CanBeAssignedFrom( tdSrc, null ))
{
if(tdDst is PointerTypeRepresentation)
{
tdDst = tdDst.UnderlyingType;
if(tdDst == m_cfg.TypeSystem.WellKnownTypes.System_Void)
{
//
// It's always OK to substitute a 'void*' with something more specific.
//
return true;
}
if(tdSrc is PointerTypeRepresentation)
{
tdSrc = tdSrc.UnderlyingType;
//
// Only substitute the pointer if the source is more specific.
//
return ShouldSubstitute( tdDst, tdSrc );
}
else
{
//
// If the source is not a pointer, don't make the substitution.
//
return false;
}
}
return true;
}
return false;
}
//
// Access Methods
//
public BasicBlock[] BasicBlocks
{
get
{
return m_basicBlocks;
}
}
public Operator[] Operators
{
get
{
return m_operators;
}
}
public VariableExpression[] Variables
{
get
{
return m_variables;
}
}
public BitVector[] VariableUses
{
get
{
return m_variableUses;
}
}
public BitVector[] VariableDefinitions
{
get
{
return m_variableDefinitions;
}
}
public BitVector[] AvailableCopyAssignments
{
get
{
return m_operatorCopy;
}
}
}
}
| |
/*
* Unity VSCode Support
*
* Seamless support for Microsoft Visual Studio Code in Unity
*
* Version:
* 2.2
*
* Authors:
* Matthew Davey <[email protected]>
*/
// REQUIRES: VSCode 0.8.0 - Settings directory moved to .vscode
// TODO: Currently VSCode will not debug mono on Windows -- need a solution.
namespace dotBunny.Unity
{
using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
public static class VSCode
{
/// <summary>
/// Current Version Number
/// </summary
public const float Version = 2.2f;
/// <summary>
/// Current Version Code
/// </summary
public const string VersionCode = "-RELEASE";
#region Properties
/// <summary>
/// Should debug information be displayed in the Unity terminal?
/// </summary>
public static bool Debug
{
get
{
return EditorPrefs.GetBool("VSCode_Debug", false);
}
set
{
EditorPrefs.SetBool("VSCode_Debug", value);
}
}
/// <summary>
/// Is the Visual Studio Code Integration Enabled?
/// </summary>
/// <remarks>
/// We do not want to automatically turn it on, for in larger projects not everyone is using VSCode
/// </remarks>
public static bool Enabled
{
get
{
return EditorPrefs.GetBool("VSCode_Enabled", false);
}
set
{
EditorPrefs.SetBool("VSCode_Enabled", value);
}
}
/// <summary>
/// Should the launch.json file be written?
/// </summary>
/// <remarks>
/// Useful to disable if someone has their own custom one rigged up
/// </remarks>
public static bool WriteLaunchFile
{
get
{
return EditorPrefs.GetBool("VSCode_WriteLaunchFile", true);
}
set
{
EditorPrefs.SetBool("VSCode_WriteLaunchFile", value);
}
}
/// <summary>
/// Should the plugin automatically update itself.
/// </summary>
static bool AutomaticUpdates
{
get
{
return EditorPrefs.GetBool("VSCode_AutomaticUpdates", false);
}
set
{
EditorPrefs.SetBool("VSCode_AutomaticUpdates", value);
}
}
static float GitHubVersion
{
get
{
return EditorPrefs.GetFloat("VSCode_GitHubVersion", Version);
}
set
{
EditorPrefs.SetFloat("VSCode_GitHubVersion", value);
}
}
/// <summary>
/// When was the last time that the plugin was updated?
/// </summary>
static DateTime LastUpdate
{
get
{
// Feature creation date.
DateTime lastTime = new DateTime(2015, 10, 8);
if (EditorPrefs.HasKey("VSCode_LastUpdate"))
{
DateTime.TryParse(EditorPrefs.GetString("VSCode_LastUpdate"), out lastTime);
}
return lastTime;
}
set
{
EditorPrefs.SetString("VSCode_LastUpdate", value.ToString());
}
}
/// <summary>
/// Quick reference to the VSCode launch settings file
/// </summary>
static string LaunchPath
{
get
{
return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "launch.json";
}
}
/// <summary>
/// The full path to the project
/// </summary>
static string ProjectPath
{
get
{
return System.IO.Path.GetDirectoryName(UnityEngine.Application.dataPath);
}
}
/// <summary>
/// Quick reference to the VSCode settings folder
/// </summary>
static string SettingsFolder
{
get
{
return ProjectPath + System.IO.Path.DirectorySeparatorChar + ".vscode";
}
}
static string SettingsPath
{
get
{
return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "settings.json";
}
}
static int UpdateTime
{
get
{
return EditorPrefs.GetInt("VSCode_UpdateTime", 7);
}
set
{
EditorPrefs.SetInt("VSCode_UpdateTime", value);
}
}
#endregion
/// <summary>
/// Integration Constructor
/// </summary>
static VSCode()
{
if (Enabled)
{
UpdateUnityPreferences(true);
// Add Update Check
DateTime targetDate = LastUpdate.AddDays(UpdateTime);
if (DateTime.Now >= targetDate)
{
CheckForUpdate();
}
}
//System.AppDomain.CurrentDomain.DomainUnload += System_AppDomain_CurrentDomain_DomainUnload;
}
// static void System_AppDomain_CurrentDomain_DomainUnload (object sender, System.EventArgs e)
// {
// if (Enabled) {
// UpdateUnityPreferences (false);
// }
// }
#region Public Members
/// <summary>
/// Force Unity To Write Project File
/// </summary>
/// <remarks>
/// Reflection!
/// </remarks>
public static void SyncSolution()
{
System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SyncSolution.Invoke(null, null);
}
/// <summary>
/// Update the solution files so that they work with VS Code
/// </summary>
public static void UpdateSolution()
{
// No need to process if we are not enabled
if (!VSCode.Enabled)
{
return;
}
if (VSCode.Debug)
{
UnityEngine.Debug.Log("[VSCode] Updating Solution & Project Files");
}
var currentDirectory = Directory.GetCurrentDirectory();
var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln");
var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj");
foreach (var filePath in solutionFiles)
{
string content = File.ReadAllText(filePath);
content = ScrubSolutionContent(content);
File.WriteAllText(filePath, content);
ScrubFile(filePath);
}
foreach (var filePath in projectFiles)
{
string content = File.ReadAllText(filePath);
content = ScrubProjectContent(content);
File.WriteAllText(filePath, content);
ScrubFile(filePath);
}
}
#endregion
#region Private Members
/// <summary>
/// Call VSCode with arguements
/// </summary>
static void CallVSCode(string args)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
#if UNITY_EDITOR_OSX
proc.StartInfo.FileName = "open";
proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCode\" --args " + args;
proc.StartInfo.UseShellExecute = false;
#elif UNITY_EDITOR_WIN
proc.StartInfo.FileName = "code";
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
#else
//TODO: Allow for manual path to code?
proc.StartInfo.FileName = "code";
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
#endif
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
}
/// <summary>
/// Check for Updates with GitHub
/// </summary>
static void CheckForUpdate()
{
var fileContent = string.Empty;
EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f);
// Because were not a runtime framework, lets just use the simplest way of doing this
try
{
using (var webClient = new System.Net.WebClient())
{
fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs");
}
}
catch (Exception e)
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] " + e.Message);
}
}
finally
{
EditorUtility.ClearProgressBar();
}
// Set the last update time
LastUpdate = DateTime.Now;
string[] fileExploded = fileContent.Split('\n');
if (fileExploded.Length > 7)
{
float github = Version;
if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github))
{
GitHubVersion = github;
}
if (github > Version)
{
var GUIDs = AssetDatabase.FindAssets("t:Script VSCode");
var path = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar +
AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar);
if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No"))
{
File.WriteAllText(path, fileContent);
}
}
}
}
/// <summary>
/// Force Unity Preferences Window To Read From Settings
/// </summary>
static void FixUnityPreferences()
{
// I want that window, please and thank you
System.Type T = System.Type.GetType("UnityEditor.PreferencesWindow,UnityEditor");
if (EditorWindow.focusedWindow == null)
return;
// Only run this when the editor window is visible (cause its what screwed us up)
if (EditorWindow.focusedWindow.GetType() == T)
{
var window = EditorWindow.GetWindow(T, true, "Unity Preferences");
if (window == null)
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] No Preferences Window Found (really?)");
}
return;
}
var invokerType = window.GetType();
var invokerMethod = invokerType.GetMethod("ReadPreferences",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (invokerMethod != null)
{
invokerMethod.Invoke(window, null);
}
else if (Debug)
{
UnityEngine.Debug.Log("[VSCode] No Reflection Method Found For Preferences");
}
}
// // Get internal integration class
// System.Type iT = System.Type.GetType("UnityEditor.VisualStudioIntegration.UnityVSSupport,UnityEditor.VisualStudioIntegration");
// var iinvokerMethod = iT.GetMethod("ScriptEditorChanged", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
// var temp = EditorPrefs.GetString("kScriptsDefaultApp");
// iinvokerMethod.Invoke(null,new object[] { temp } );
}
/// <summary>
/// Determine what port Unity is listening for on Windows
/// </summary>
static int GetDebugPort()
{
#if UNITY_EDITOR_WIN
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "netstat";
process.StartInfo.Arguments = "-a -n -o -p TCP";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string[] lines = output.Split('\n');
process.WaitForExit();
foreach (string line in lines)
{
string[] tokens = Regex.Split(line, "\\s+");
if (tokens.Length > 4)
{
int test = -1;
int.TryParse(tokens[5], out test);
if (test > 1023)
{
try
{
var p = System.Diagnostics.Process.GetProcessById(test);
if (p.ProcessName == "Unity")
{
return test;
}
}
catch
{
}
}
}
}
#else
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "lsof";
process.StartInfo.Arguments = "-c /^Unity$/ -i 4tcp -a";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
// Not thread safe (yet!)
string output = process.StandardOutput.ReadToEnd();
string[] lines = output.Split('\n');
process.WaitForExit();
foreach (string line in lines)
{
int port = -1;
if (line.StartsWith("Unity"))
{
string[] portions = line.Split(new string[] { "TCP *:" }, System.StringSplitOptions.None);
if (portions.Length >= 2)
{
Regex digitsOnly = new Regex(@"[^\d]");
string cleanPort = digitsOnly.Replace(portions[1], "");
if (int.TryParse(cleanPort, out port))
{
if (port > -1)
{
return port;
}
}
}
}
}
#endif
return -1;
}
// HACK: This is in until Unity can figure out why MD keeps opening even though a different program is selected.
[MenuItem("Assets/Open C# Project In Code", false, 1000)]
static void MenuOpenProject()
{
// Force the project files to be sync
SyncSolution();
// Load Project
CallVSCode("\"" + ProjectPath + "\" -r");
}
[MenuItem("Assets/Open C# Project In Code", true, 1000)]
static bool ValidateMenuOpenProject()
{
return Enabled;
}
/// <summary>
/// VS Code Integration Preferences Item
/// </summary>
/// <remarks>
/// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off
/// </remarks>
[PreferenceItem("VSCode")]
static void VSCodePreferencesItem()
{
EditorGUILayout.BeginVertical();
EditorGUILayout.HelpBox("Support development of this plugin, follow @reapazor and @dotbunny on Twitter.", MessageType.Info);
EditorGUI.BeginChangeCheck();
Enabled = EditorGUILayout.Toggle(new GUIContent("Enable Integration", "Should the integration work its magic for you?"), Enabled);
EditorGUILayout.Space();
EditorGUI.BeginDisabledGroup(!Enabled);
Debug = EditorGUILayout.Toggle(new GUIContent("Output Messages To Console", "Should informational messages be sent to Unity's Console?"), Debug);
WriteLaunchFile = EditorGUILayout.Toggle(new GUIContent("Always Write Launch File", "Always write the launch.json settings when entering play mode?"), WriteLaunchFile);
EditorGUILayout.Space();
AutomaticUpdates = EditorGUILayout.Toggle(new GUIContent("Automatic Updates", "Should the plugin automatically update itself?"), AutomaticUpdates);
EditorGUI.BeginDisabledGroup(!AutomaticUpdates);
UpdateTime = EditorGUILayout.IntSlider(new GUIContent("Update Timer (Days)", "After how many days should updates be checked for?"), UpdateTime, 1, 31);
EditorGUI.EndDisabledGroup();
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
EditorGUILayout.Space();
if (EditorGUI.EndChangeCheck())
{
UpdateUnityPreferences(Enabled);
//UnityEditor.PreferencesWindow.Read
// TODO: Force Unity To Reload Preferences
// This seems to be a hick up / issue
if (VSCode.Debug)
{
if (Enabled)
{
UnityEngine.Debug.Log("[VSCode] Integration Enabled");
}
else
{
UnityEngine.Debug.Log("[VSCode] Integration Disabled");
}
}
}
if (GUILayout.Button(new GUIContent("Force Update", "Check for updates to the plugin, right NOW!")))
{
CheckForUpdate();
EditorGUILayout.EndVertical();
return;
}
if (GUILayout.Button(new GUIContent("Write Workspace Settings", "Output a default set of workspace settings for VSCode to use, ignoring many different types of files.")))
{
WriteWorkspaceSettings();
EditorGUILayout.EndVertical();
return;
}
GUILayout.FlexibleSpace();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(
new GUIContent(
string.Format("{0:0.00}", Version) + VersionCode,
"GitHub's Version @ " + string.Format("{0:0.00}", GitHubVersion)));
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
/// <summary>
/// Asset Open Callback (from Unity)
/// </summary>
/// <remarks>
/// Called when Unity is about to open an asset.
/// </remarks>
[UnityEditor.Callbacks.OnOpenAssetAttribute()]
static bool OnOpenedAsset(int instanceID, int line)
{
// bail out if we are not on a Mac or if we don't want to use VSCode
if (!Enabled)
{
return false;
}
// current path without the asset folder
string appPath = ProjectPath;
// determine asset that has been double clicked in the project view
UnityEngine.Object selected = EditorUtility.InstanceIDToObject(instanceID);
if (selected.GetType().ToString() == "UnityEditor.MonoScript")
{
string completeFilepath = appPath + Path.DirectorySeparatorChar + AssetDatabase.GetAssetPath(selected);
string args = null;
if (line == -1)
{
args = "\"" + ProjectPath + "\" \"" + completeFilepath + "\" -r";
}
else
{
args = "\"" + ProjectPath + "\" -g \"" + completeFilepath + ":" + line.ToString() + "\" -r";
}
// call 'open'
CallVSCode(args);
return true;
}
// Didnt find a code file? let Unity figure it out
return false;
}
/// <summary>
/// Executed when the Editor's playmode changes allowing for capture of required data
/// </summary>
static void OnPlaymodeStateChanged()
{
if (VSCode.Enabled && VSCode.WriteLaunchFile && UnityEngine.Application.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
{
int port = GetDebugPort();
if (port > -1)
{
if (!Directory.Exists(VSCode.SettingsFolder))
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
UpdateLaunchFile(port);
if (VSCode.Debug)
{
UnityEngine.Debug.Log("[VSCode] Debug Port Found (" + port + ")");
}
}
else
{
if (VSCode.Debug)
{
UnityEngine.Debug.LogWarning("[VSCode] Unable to determine debug port.");
}
}
}
}
/// <summary>
/// Detect when scripts are reloaded and relink playmode detection
/// </summary>
[UnityEditor.Callbacks.DidReloadScripts()]
static void OnScriptReload()
{
EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged;
EditorApplication.playmodeStateChanged += OnPlaymodeStateChanged;
}
/// <summary>
/// Remove extra/erroneous lines from a file.
static void ScrubFile(string path)
{
string[] lines = File.ReadAllLines(path);
System.Collections.Generic.List<string> newLines = new System.Collections.Generic.List<string>();
for (int i = 0; i < lines.Length; i++)
{
// Check Empty
if (string.IsNullOrEmpty(lines[i].Trim()) || lines[i].Trim() == "\t" || lines[i].Trim() == "\t\t")
{
}
else
{
newLines.Add(lines[i]);
}
}
File.WriteAllLines(path, newLines.ToArray());
}
/// <summary>
/// Remove extra/erroneous data from project file (content).
/// </summary>
static string ScrubProjectContent(string content)
{
if (content.Length == 0)
return "";
// Make sure our reference framework is 2.0, still the base for Unity
if (content.IndexOf("<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>") != -1)
{
content = Regex.Replace(content, "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>");
}
string targetPath = "";// "<TargetPath>Temp" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "</TargetPath>"; //OutputPath
string langVersion = "<LangVersion>default</LangVersion>";
bool found = true;
int location = 0;
string addedOptions = "";
int startLocation = -1;
int endLocation = -1;
int endLength = 0;
while (found)
{
startLocation = -1;
endLocation = -1;
endLength = 0;
addedOptions = "";
startLocation = content.IndexOf("<PropertyGroup", location);
if (startLocation != -1)
{
endLocation = content.IndexOf("</PropertyGroup>", startLocation);
endLength = (endLocation - startLocation);
if (endLocation == -1)
{
found = false;
continue;
}
else
{
found = true;
location = endLocation;
}
if (content.Substring(startLocation, endLength).IndexOf("<TargetPath>") == -1)
{
addedOptions += "\n\r\t" + targetPath + "\n\r";
}
if (content.Substring(startLocation, endLength).IndexOf("<LangVersion>") == -1)
{
addedOptions += "\n\r\t" + langVersion + "\n\r";
}
if (!string.IsNullOrEmpty(addedOptions))
{
content = content.Substring(0, endLocation) + addedOptions + content.Substring(endLocation);
}
}
else
{
found = false;
}
}
return content;
}
/// <summary>
/// Remove extra/erroneous data from solution file (content).
/// </summary>
static string ScrubSolutionContent(string content)
{
// Replace Solution Version
content = content.Replace(
"Microsoft Visual Studio Solution File, Format Version 11.00\r\n# Visual Studio 2008\r\n",
"\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 2012");
// Remove Solution Properties (Unity Junk)
int startIndex = content.IndexOf("GlobalSection(SolutionProperties) = preSolution");
if (startIndex != -1)
{
int endIndex = content.IndexOf("EndGlobalSection", startIndex);
content = content.Substring(0, startIndex) + content.Substring(endIndex + 16);
}
return content;
}
/// <summary>
/// Update Visual Studio Code Launch file
/// </summary>
static void UpdateLaunchFile(int port)
{
// Write out proper formatted JSON (hence no more SimpleJSON here)
string fileContent = "{\n\t\"version\":\"0.1.0\",\n\t\"configurations\":[ \n\t\t{\n\t\t\t\"name\":\"Unity\",\n\t\t\t\"type\":\"mono\",\n\t\t\t\"address\":\"localhost\",\n\t\t\t\"port\":" + port + "\n\t\t}\n\t]\n}";
File.WriteAllText(VSCode.LaunchPath, fileContent);
}
/// <summary>
/// Update Unity Editor Preferences
static void UpdateUnityPreferences(bool enabled)
{
if (enabled)
{
#if UNITY_EDITOR_OSX
var newPath = "/Applications/Visual Studio Code.app";
#elif UNITY_EDITOR_WIN
var newPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + "Code" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code.cmd";
#else
var newPath = "/usr/local/bin/code";
#endif
// App
if (EditorPrefs.GetString("kScriptsDefaultApp") != newPath)
{
EditorPrefs.SetString("VSCode_PreviousApp", EditorPrefs.GetString("kScriptsDefaultApp"));
}
EditorPrefs.SetString("kScriptsDefaultApp", newPath);
// Arguments
if (EditorPrefs.GetString("kScriptEditorArgs") != "-r -g \"$(File):$(Line)\"")
{
EditorPrefs.SetString("VSCode_PreviousArgs", EditorPrefs.GetString("kScriptEditorArgs"));
}
EditorPrefs.SetString("kScriptEditorArgs", "-r -g \"$(File):$(Line)\"");
EditorPrefs.SetString("kScriptEditorArgs" + newPath, "-r -g \"$(File):$(Line)\"");
// MonoDevelop Solution
if (EditorPrefs.GetBool("kMonoDevelopSolutionProperties", false))
{
EditorPrefs.SetBool("VSCode_PreviousMD", true);
}
EditorPrefs.SetBool("kMonoDevelopSolutionProperties", false);
// Support Unity Proj (JS)
if (EditorPrefs.GetBool("kExternalEditorSupportsUnityProj", false))
{
EditorPrefs.SetBool("VSCode_PreviousUnityProj", true);
}
EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", false);
// Attach to Editor
if (!EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", false))
{
EditorPrefs.SetBool("VSCode_PreviousAttach", false);
}
EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true);
}
else
{
// Restore previous app
if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousApp")))
{
EditorPrefs.SetString("kScriptsDefaultApp", EditorPrefs.GetString("VSCode_PreviousApp"));
}
// Restore previous args
if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousArgs")))
{
EditorPrefs.SetString("kScriptEditorArgs", EditorPrefs.GetString("VSCode_PreviousArgs"));
}
// Restore MD setting
if (EditorPrefs.GetBool("VSCode_PreviousMD", false))
{
EditorPrefs.SetBool("kMonoDevelopSolutionProperties", true);
}
// Restore MD setting
if (EditorPrefs.GetBool("VSCode_PreviousUnityProj", false))
{
EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", true);
}
// Restore previous attach
if (!EditorPrefs.GetBool("VSCode_PreviousAttach", true))
{
EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", false);
}
}
FixUnityPreferences();
}
/// <summary>
/// Write Default Workspace Settings
/// </summary>
static void WriteWorkspaceSettings()
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] Workspace Settings Written");
}
if (!Directory.Exists(VSCode.SettingsFolder))
{
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
}
string exclusions =
"{\n" +
"\t\"files.exclude\":\n" +
"\t{\n" +
// Hidden Files
"\t\t\"**/.DS_Store\":true,\n" +
"\t\t\"**/.git\":true,\n" +
"\t\t\"**/.gitignore\":true,\n" +
"\t\t\"**/.gitmodules\":true,\n" +
// Project Files
"\t\t\"**/*.booproj\":true,\n" +
"\t\t\"**/*.pidb\":true,\n" +
"\t\t\"**/*.suo\":true,\n" +
"\t\t\"**/*.user\":true,\n" +
"\t\t\"**/*.userprefs\":true,\n" +
"\t\t\"**/*.unityproj\":true,\n" +
"\t\t\"**/*.dll\":true,\n" +
"\t\t\"**/*.exe\":true,\n" +
// Media Files
"\t\t\"**/*.pdf\":true,\n" +
// Audio
"\t\t\"**/*.mid\":true,\n" +
"\t\t\"**/*.midi\":true,\n" +
"\t\t\"**/*.wav\":true,\n" +
// Textures
"\t\t\"**/*.gif\":true,\n" +
"\t\t\"**/*.ico\":true,\n" +
"\t\t\"**/*.jpg\":true,\n" +
"\t\t\"**/*.jpeg\":true,\n" +
"\t\t\"**/*.png\":true,\n" +
"\t\t\"**/*.psd\":true,\n" +
"\t\t\"**/*.tga\":true,\n" +
"\t\t\"**/*.tif\":true,\n" +
"\t\t\"**/*.tiff\":true,\n" +
// Models
"\t\t\"**/*.3ds\":true,\n" +
"\t\t\"**/*.3DS\":true,\n" +
"\t\t\"**/*.fbx\":true,\n" +
"\t\t\"**/*.FBX\":true,\n" +
"\t\t\"**/*.lxo\":true,\n" +
"\t\t\"**/*.LXO\":true,\n" +
"\t\t\"**/*.ma\":true,\n" +
"\t\t\"**/*.MA\":true,\n" +
"\t\t\"**/*.obj\":true,\n" +
"\t\t\"**/*.OBJ\":true,\n" +
// Unity File Types
"\t\t\"**/*.asset\":true,\n" +
"\t\t\"**/*.cubemap\":true,\n" +
"\t\t\"**/*.flare\":true,\n" +
"\t\t\"**/*.mat\":true,\n" +
"\t\t\"**/*.meta\":true,\n" +
"\t\t\"**/*.prefab\":true,\n" +
"\t\t\"**/*.unity\":true,\n" +
// Folders
"\t\t\"build/\":true,\n" +
"\t\t\"Build/\":true,\n" +
"\t\t\"Library/\":true,\n" +
"\t\t\"library/\":true,\n" +
"\t\t\"obj/\":true,\n" +
"\t\t\"Obj/\":true,\n" +
"\t\t\"ProjectSettings/\":true,\r" +
"\t\t\"temp/\":true,\n" +
"\t\t\"Temp/\":true\n" +
"\t}\n" +
"}";
// Dont like the replace but it fixes the issue with the JSON
File.WriteAllText(VSCode.SettingsPath, exclusions);
}
#endregion
}
/// <summary>
/// VSCode Asset AssetPostprocessor
/// <para>This will ensure any time that the project files are generated the VSCode versions will be made</para>
/// </summary>
/// <remarks>Undocumented Event</remarks>
public class VSCodeAssetPostprocessor : AssetPostprocessor
{
/// <summary>
/// On documented, project generation event callback
/// </summary>
private static void OnGeneratedCSProjectFiles()
{
// Force execution of VSCode update
VSCode.UpdateSolution();
}
}
}
| |
// 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 CompareEqualSingle()
{
var test = new SimpleBinaryOpTest__CompareEqualSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqualSingle
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single> _dataTable;
static SimpleBinaryOpTest__CompareEqualSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareEqualSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.CompareEqual(
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()
{
var result = Sse.CompareEqual(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.CompareEqual(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqual), 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()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareEqualSingle();
var result = Sse.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] == right[0]) ? -1 : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != ((left[i] == right[i]) ? -1 : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareEqual)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class ConstantTests
{
private static TypeBuilder GetTypeBuilder()
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
return module.DefineType("Type");
}
private static MethodInfo GlobalMethod(params Type[] parameterTypes)
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module");
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(void), parameterTypes);
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
module.CreateGlobalFunctions();
return module.GetMethod(globalMethod.Name);
}
private class PrivateGenericClass<T>
{
}
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolConstantTest(bool useInterpreter)
{
foreach (bool value in new bool[] { true, false })
{
VerifyBoolConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteConstantTest(bool useInterpreter)
{
foreach (byte value in new byte[] { 0, 1, byte.MaxValue })
{
VerifyByteConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCustomConstantTest(bool useInterpreter)
{
foreach (C value in new C[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyCustomConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCharConstantTest(bool useInterpreter)
{
foreach (char value in new char[] { '\0', '\b', 'A', '\uffff' })
{
VerifyCharConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCustom2ConstantTest(bool useInterpreter)
{
foreach (D value in new D[] { null, new D(), new D(0), new D(5) })
{
VerifyCustom2Constant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalConstantTest(bool useInterpreter)
{
foreach (decimal value in new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, int.MinValue, int.MaxValue, int.MinValue - 1L, int.MaxValue + 1L, long.MinValue, long.MaxValue, long.MaxValue + 1m, ulong.MaxValue, ulong.MaxValue + 1m })
{
VerifyDecimalConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDelegateConstantTest(bool useInterpreter)
{
foreach (Delegate value in new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } })
{
VerifyDelegateConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleConstantTest(bool useInterpreter)
{
foreach (double value in new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN })
{
VerifyDoubleConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckEnumConstantTest(bool useInterpreter)
{
foreach (E value in new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue })
{
VerifyEnumConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckEnumLongConstantTest(bool useInterpreter)
{
foreach (El value in new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue })
{
VerifyEnumLongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatConstantTest(bool useInterpreter)
{
foreach (float value in new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN })
{
VerifyFloatConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFuncOfObjectConstantTest(bool useInterpreter)
{
foreach (Func<object> value in new Func<object>[] { null, (Func<object>)delegate () { return null; } })
{
VerifyFuncOfObjectConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckInterfaceConstantTest(bool useInterpreter)
{
foreach (I value in new I[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyInterfaceConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableOfCustomConstantTest(bool useInterpreter)
{
foreach (IEquatable<C> value in new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyIEquatableOfCustomConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableOfCustom2ConstantTest(bool useInterpreter)
{
foreach (IEquatable<D> value in new IEquatable<D>[] { null, new D(), new D(0), new D(5) })
{
VerifyIEquatableOfCustom2Constant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntConstantTest(bool useInterpreter)
{
foreach (int value in new int[] { 0, 1, -1, int.MinValue, int.MaxValue })
{
VerifyIntConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongConstantTest(bool useInterpreter)
{
foreach (long value in new long[] { 0, 1, -1, long.MinValue, long.MaxValue })
{
VerifyLongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckObjectConstantTest(bool useInterpreter)
{
foreach (object value in new object[] { null, new object(), new C(), new D(3) })
{
VerifyObjectConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructConstantTest(bool useInterpreter)
{
foreach (S value in new S[] { default(S), new S() })
{
VerifyStructConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteConstantTest(bool useInterpreter)
{
foreach (sbyte value in new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue })
{
VerifySByteConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringConstantTest(bool useInterpreter)
{
foreach (Sc value in new Sc[] { default(Sc), new Sc(), new Sc(null) })
{
VerifyStructWithStringConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringAndFieldConstantTest(bool useInterpreter)
{
foreach (Scs value in new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) })
{
VerifyStructWithStringAndFieldConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortConstantTest(bool useInterpreter)
{
foreach (short value in new short[] { 0, 1, -1, short.MinValue, short.MaxValue })
{
VerifyShortConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithTwoValuesConstantTest(bool useInterpreter)
{
foreach (Sp value in new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) })
{
VerifyStructWithTwoValuesConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithValueConstantTest(bool useInterpreter)
{
foreach (Ss value in new Ss[] { default(Ss), new Ss(), new Ss(new S()) })
{
VerifyStructWithValueConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStringConstantTest(bool useInterpreter)
{
foreach (string value in new string[] { null, "", "a", "foo" })
{
VerifyStringConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntConstantTest(bool useInterpreter)
{
foreach (uint value in new uint[] { 0, 1, uint.MaxValue })
{
VerifyUIntConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongConstantTest(bool useInterpreter)
{
foreach (ulong value in new ulong[] { 0, 1, ulong.MaxValue })
{
VerifyULongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortConstantTest(bool useInterpreter)
{
foreach (ushort value in new ushort[] { 0, 1, ushort.MaxValue })
{
VerifyUShortConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTypeConstantTest(bool useInterpreter)
{
foreach (Type value in new[]
{
null,
typeof(int),
typeof(Func<string>),
typeof(List<>).GetGenericArguments()[0],
GetTypeBuilder(),
typeof(PrivateGenericClass<>).GetGenericArguments()[0],
typeof(PrivateGenericClass<>),
typeof(PrivateGenericClass<int>)
})
{
VerifyTypeConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckMethodInfoConstantTest(bool useInterpreter)
{
foreach (MethodInfo value in new MethodInfo[]
{
null,
typeof(SomePublicMethodsForLdToken).GetMethod(nameof(SomePublicMethodsForLdToken.Bar), BindingFlags.Public | BindingFlags.Static),
typeof(SomePublicMethodsForLdToken).GetMethod(nameof(SomePublicMethodsForLdToken.Qux), BindingFlags.Public | BindingFlags.Static),
typeof(SomePublicMethodsForLdToken).GetMethod(nameof(SomePublicMethodsForLdToken.Qux), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(typeof(int)),
typeof(List<>).GetMethod(nameof(List<int>.Add)),
typeof(List<int>).GetMethod(nameof(List<int>.Add)),
GlobalMethod(Type.EmptyTypes),
GlobalMethod(typeof(PrivateGenericClass<int>)),
GlobalMethod(typeof(PrivateGenericClass<>))
})
{
VerifyMethodInfoConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckConstructorInfoConstantTest(bool useInterpreter)
{
foreach (
ConstructorInfo value in
typeof(SomePublicMethodsForLdToken).GetConstructors()
.Concat(typeof(string).GetConstructors())
.Concat(typeof(List<>).GetConstructors())
.Append(null))
{
VerifyConstructorInfoConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithEnumConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithStructConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithStructWithStringAndValueConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithCustomTest(bool useInterpreter)
{
CheckGenericHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithEnumTest(bool useInterpreter)
{
CheckGenericHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithObjectTest(bool useInterpreter)
{
CheckGenericHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructTest(bool useInterpreter)
{
CheckGenericHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructWithStringAndValueTest(bool useInterpreter)
{
CheckGenericHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassRestrictionWithCustomTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassRestrictionWithObjectTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassAndNewRestrictionWithCustomTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassAndNewRestrictionWithObjectTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithSubClassRestrictionTest(bool useInterpreter)
{
CheckGenericWithSubClassRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithSubClassAndNewRestrictionTest(bool useInterpreter)
{
CheckGenericWithSubClassAndNewRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void BoundConstantCaching1(bool useInterpreter)
{
ConstantExpression c = Expression.Constant(new Bar());
BinaryExpression e =
Expression.Add(
Expression.Field(c, "Foo"),
Expression.Subtract(
Expression.Field(c, "Baz"),
Expression.Field(c, "Qux")
)
);
Assert.Equal(42, Expression.Lambda<Func<int>>(e).Compile(useInterpreter)());
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void BoundConstantCaching2(bool useInterpreter)
{
var b = new Bar();
ConstantExpression c1 = Expression.Constant(b);
ConstantExpression c2 = Expression.Constant(b);
ConstantExpression c3 = Expression.Constant(b);
BinaryExpression e =
Expression.Add(
Expression.Field(c1, "Foo"),
Expression.Subtract(
Expression.Field(c2, "Baz"),
Expression.Field(c3, "Qux")
)
);
Assert.Equal(42, Expression.Lambda<Func<int>>(e).Compile(useInterpreter)());
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void BoundConstantCaching3(bool useInterpreter)
{
var b = new Bar() { Foo = 1 };
for (var i = 1; i <= 10; i++)
{
var e = (Expression)Expression.Constant(0);
for (var j = 1; j <= i; j++)
{
e = Expression.Add(e, Expression.Field(Expression.Constant(b), "Foo"));
}
Assert.Equal(i, Expression.Lambda<Func<int>>(e).Compile(useInterpreter)());
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void BoundConstantCaching4(bool useInterpreter)
{
Bar[] bs = new[]
{
new Bar() { Foo = 1 },
new Bar() { Foo = 1 },
};
for (var i = 1; i <= 10; i++)
{
var e = (Expression)Expression.Constant(0);
for (var j = 1; j <= i; j++)
{
e = Expression.Add(e, Expression.Field(Expression.Constant(bs[j % 2]), "Foo"));
}
Assert.Equal(i, Expression.Lambda<Func<int>>(e).Compile(useInterpreter)());
}
}
#endregion
#region Generic helpers
public static void CheckGenericWithStructRestrictionConstantHelper<Ts>(bool useInterpreter) where Ts : struct
{
foreach (Ts value in new Ts[] { default(Ts), new Ts() })
{
VerifyGenericWithStructRestriction<Ts>(value, useInterpreter);
}
}
public static void CheckGenericHelper<T>(bool useInterpreter)
{
foreach (T value in new T[] { default(T) })
{
VerifyGeneric<T>(value, useInterpreter);
}
}
public static void CheckGenericWithClassRestrictionHelper<Tc>(bool useInterpreter) where Tc : class
{
foreach (Tc value in new Tc[] { null, default(Tc) })
{
VerifyGenericWithClassRestriction<Tc>(value, useInterpreter);
}
}
public static void CheckGenericWithClassAndNewRestrictionHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
foreach (Tcn value in new Tcn[] { null, default(Tcn), new Tcn() })
{
VerifyGenericWithClassAndNewRestriction<Tcn>(value, useInterpreter);
}
}
public static void CheckGenericWithSubClassRestrictionHelper<TC>(bool useInterpreter) where TC : C
{
foreach (TC value in new TC[] { null, default(TC), (TC)new C() })
{
VerifyGenericWithSubClassRestriction<TC>(value, useInterpreter);
}
}
public static void CheckGenericWithSubClassAndNewRestrictionHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
foreach (TCn value in new TCn[] { null, default(TCn), new TCn(), (TCn)new C() })
{
VerifyGenericWithSubClassAndNewRestriction<TCn>(value, useInterpreter);
}
}
#endregion
#region Test verifiers
private static void VerifyBoolConstant(bool value, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Constant(value, typeof(bool)),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyByteConstant(byte value, bool useInterpreter)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
Expression.Constant(value, typeof(byte)),
Enumerable.Empty<ParameterExpression>());
Func<byte> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCustomConstant(C value, bool useInterpreter)
{
Expression<Func<C>> e =
Expression.Lambda<Func<C>>(
Expression.Constant(value, typeof(C)),
Enumerable.Empty<ParameterExpression>());
Func<C> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCharConstant(char value, bool useInterpreter)
{
Expression<Func<char>> e =
Expression.Lambda<Func<char>>(
Expression.Constant(value, typeof(char)),
Enumerable.Empty<ParameterExpression>());
Func<char> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCustom2Constant(D value, bool useInterpreter)
{
Expression<Func<D>> e =
Expression.Lambda<Func<D>>(
Expression.Constant(value, typeof(D)),
Enumerable.Empty<ParameterExpression>());
Func<D> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDecimalConstant(decimal value, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Constant(value, typeof(decimal)),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDelegateConstant(Delegate value, bool useInterpreter)
{
Expression<Func<Delegate>> e =
Expression.Lambda<Func<Delegate>>(
Expression.Constant(value, typeof(Delegate)),
Enumerable.Empty<ParameterExpression>());
Func<Delegate> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDoubleConstant(double value, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Constant(value, typeof(double)),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyEnumConstant(E value, bool useInterpreter)
{
Expression<Func<E>> e =
Expression.Lambda<Func<E>>(
Expression.Constant(value, typeof(E)),
Enumerable.Empty<ParameterExpression>());
Func<E> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyEnumLongConstant(El value, bool useInterpreter)
{
Expression<Func<El>> e =
Expression.Lambda<Func<El>>(
Expression.Constant(value, typeof(El)),
Enumerable.Empty<ParameterExpression>());
Func<El> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyFloatConstant(float value, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Constant(value, typeof(float)),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyFuncOfObjectConstant(Func<object> value, bool useInterpreter)
{
Expression<Func<Func<object>>> e =
Expression.Lambda<Func<Func<object>>>(
Expression.Constant(value, typeof(Func<object>)),
Enumerable.Empty<ParameterExpression>());
Func<Func<object>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyInterfaceConstant(I value, bool useInterpreter)
{
Expression<Func<I>> e =
Expression.Lambda<Func<I>>(
Expression.Constant(value, typeof(I)),
Enumerable.Empty<ParameterExpression>());
Func<I> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIEquatableOfCustomConstant(IEquatable<C> value, bool useInterpreter)
{
Expression<Func<IEquatable<C>>> e =
Expression.Lambda<Func<IEquatable<C>>>(
Expression.Constant(value, typeof(IEquatable<C>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<C>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIEquatableOfCustom2Constant(IEquatable<D> value, bool useInterpreter)
{
Expression<Func<IEquatable<D>>> e =
Expression.Lambda<Func<IEquatable<D>>>(
Expression.Constant(value, typeof(IEquatable<D>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<D>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIntConstant(int value, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Constant(value, typeof(int)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyLongConstant(long value, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Constant(value, typeof(long)),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyObjectConstant(object value, bool useInterpreter)
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Constant(value, typeof(object)),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructConstant(S value, bool useInterpreter)
{
Expression<Func<S>> e =
Expression.Lambda<Func<S>>(
Expression.Constant(value, typeof(S)),
Enumerable.Empty<ParameterExpression>());
Func<S> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifySByteConstant(sbyte value, bool useInterpreter)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
Expression.Constant(value, typeof(sbyte)),
Enumerable.Empty<ParameterExpression>());
Func<sbyte> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithStringConstant(Sc value, bool useInterpreter)
{
Expression<Func<Sc>> e =
Expression.Lambda<Func<Sc>>(
Expression.Constant(value, typeof(Sc)),
Enumerable.Empty<ParameterExpression>());
Func<Sc> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithStringAndFieldConstant(Scs value, bool useInterpreter)
{
Expression<Func<Scs>> e =
Expression.Lambda<Func<Scs>>(
Expression.Constant(value, typeof(Scs)),
Enumerable.Empty<ParameterExpression>());
Func<Scs> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyShortConstant(short value, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Constant(value, typeof(short)),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithTwoValuesConstant(Sp value, bool useInterpreter)
{
Expression<Func<Sp>> e =
Expression.Lambda<Func<Sp>>(
Expression.Constant(value, typeof(Sp)),
Enumerable.Empty<ParameterExpression>());
Func<Sp> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithValueConstant(Ss value, bool useInterpreter)
{
Expression<Func<Ss>> e =
Expression.Lambda<Func<Ss>>(
Expression.Constant(value, typeof(Ss)),
Enumerable.Empty<ParameterExpression>());
Func<Ss> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStringConstant(string value, bool useInterpreter)
{
Expression<Func<string>> e =
Expression.Lambda<Func<string>>(
Expression.Constant(value, typeof(string)),
Enumerable.Empty<ParameterExpression>());
Func<string> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyUIntConstant(uint value, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Constant(value, typeof(uint)),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyULongConstant(ulong value, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Constant(value, typeof(ulong)),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyUShortConstant(ushort value, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Constant(value, typeof(ushort)),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyTypeConstant(Type value, bool useInterpreter)
{
Expression<Func<Type>> e =
Expression.Lambda<Func<Type>>(
Expression.Constant(value, typeof(Type)),
Enumerable.Empty<ParameterExpression>());
Func<Type> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyMethodInfoConstant(MethodInfo value, bool useInterpreter)
{
Expression<Func<MethodInfo>> e =
Expression.Lambda<Func<MethodInfo>>(
Expression.Constant(value, typeof(MethodInfo)),
Enumerable.Empty<ParameterExpression>());
Func<MethodInfo> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyConstructorInfoConstant(ConstructorInfo value, bool useInterpreter)
{
Expression<Func<ConstructorInfo>> e =
Expression.Lambda<Func<ConstructorInfo>>(Expression.Constant(value, typeof(ConstructorInfo)));
Func<ConstructorInfo> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithStructRestriction<Ts>(Ts value, bool useInterpreter) where Ts : struct
{
Expression<Func<Ts>> e =
Expression.Lambda<Func<Ts>>(
Expression.Constant(value, typeof(Ts)),
Enumerable.Empty<ParameterExpression>());
Func<Ts> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGeneric<T>(T value, bool useInterpreter)
{
Expression<Func<T>> e =
Expression.Lambda<Func<T>>(
Expression.Constant(value, typeof(T)),
Enumerable.Empty<ParameterExpression>());
Func<T> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithClassRestriction<Tc>(Tc value, bool useInterpreter) where Tc : class
{
Expression<Func<Tc>> e =
Expression.Lambda<Func<Tc>>(
Expression.Constant(value, typeof(Tc)),
Enumerable.Empty<ParameterExpression>());
Func<Tc> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithClassAndNewRestriction<Tcn>(Tcn value, bool useInterpreter) where Tcn : class, new()
{
Expression<Func<Tcn>> e =
Expression.Lambda<Func<Tcn>>(
Expression.Constant(value, typeof(Tcn)),
Enumerable.Empty<ParameterExpression>());
Func<Tcn> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithSubClassRestriction<TC>(TC value, bool useInterpreter) where TC : C
{
Expression<Func<TC>> e =
Expression.Lambda<Func<TC>>(
Expression.Constant(value, typeof(TC)),
Enumerable.Empty<ParameterExpression>());
Func<TC> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithSubClassAndNewRestriction<TCn>(TCn value, bool useInterpreter) where TCn : C, new()
{
Expression<Func<TCn>> e =
Expression.Lambda<Func<TCn>>(
Expression.Constant(value, typeof(TCn)),
Enumerable.Empty<ParameterExpression>());
Func<TCn> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
#endregion
[Fact]
public static void InvalidTypeValueType()
{
// implicit cast, but not reference assignable.
Assert.Throws<ArgumentException>(null, () => Expression.Constant(0, typeof(long)));
}
[Fact]
public static void InvalidTypeReferenceType()
{
Assert.Throws<ArgumentException>(null, () => Expression.Constant("hello", typeof(Expression)));
}
[Fact]
public static void NullType()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.Constant("foo", null));
}
[Fact]
public static void ByRefType()
{
Assert.Throws<ArgumentException>(() => Expression.Constant(null, typeof(string).MakeByRefType()));
}
[Fact]
public static void PointerType()
{
Assert.Throws<ArgumentException>("type", () => Expression.Constant(null, typeof(string).MakePointerType()));
}
[Fact]
public static void GenericType()
{
Assert.Throws<ArgumentException>(() => Expression.Constant(null, typeof(List<>)));
}
[Fact]
public static void TypeContainsGenericParameters()
{
Assert.Throws<ArgumentException>(() => Expression.Constant(null, typeof(List<>.Enumerator)));
Assert.Throws<ArgumentException>(() => Expression.Constant(null, typeof(List<>).MakeGenericType(typeof(List<>))));
}
[Fact]
public static void ToStringTest()
{
ConstantExpression e1 = Expression.Constant(1);
Assert.Equal("1", e1.ToString());
ConstantExpression e2 = Expression.Constant("bar");
Assert.Equal("\"bar\"", e2.ToString());
ConstantExpression e3 = Expression.Constant(null, typeof(object));
Assert.Equal("null", e3.ToString());
var b = new Bar();
ConstantExpression e4 = Expression.Constant(b);
Assert.Equal($"value({b.ToString()})", e4.ToString());
var f = new Foo();
ConstantExpression e5 = Expression.Constant(f);
Assert.Equal(f.ToString(), e5.ToString());
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void DecimalConstantRetainsScaleAnd(bool useInterpreter)
{
var lambda = Expression.Lambda<Func<decimal>>(Expression.Constant(-0.000m));
var func = lambda.Compile(useInterpreter);
var bits = decimal.GetBits(func());
Assert.Equal(unchecked((int)0x80030000), bits[3]);
}
class Bar
{
public int Foo = 41;
public int Qux = 43;
public int Baz = 44;
}
class Foo
{
public override string ToString()
{
return "Bar";
}
}
}
// NB: Should be public in order for ILGen to emit ldtoken
public class SomePublicMethodsForLdToken
{
public static void Bar() { }
public static void Qux<T>() { }
}
}
| |
using System;
using System.Collections;
using BigMath;
using Raksha.Asn1;
using Raksha.Asn1.X509;
using Raksha.Crypto;
using Raksha.Math;
using Raksha.Security;
using Raksha.Security.Certificates;
using Raksha.Utilities;
using Raksha.X509.Store;
namespace Raksha.X509
{
/// <remarks>
/// The Holder object.
/// <pre>
/// Holder ::= SEQUENCE {
/// baseCertificateID [0] IssuerSerial OPTIONAL,
/// -- the issuer and serial number of
/// -- the holder's Public Key Certificate
/// entityName [1] GeneralNames OPTIONAL,
/// -- the name of the claimant or role
/// objectDigestInfo [2] ObjectDigestInfo OPTIONAL
/// -- used to directly authenticate the holder,
/// -- for example, an executable
/// }
/// </pre>
/// </remarks>
public class AttributeCertificateHolder
//: CertSelector, Selector
: IX509Selector
{
internal readonly Holder holder;
internal AttributeCertificateHolder(
Asn1Sequence seq)
{
holder = Holder.GetInstance(seq);
}
public AttributeCertificateHolder(
X509Name issuerName,
BigInteger serialNumber)
{
holder = new Holder(
new IssuerSerial(
GenerateGeneralNames(issuerName),
new DerInteger(serialNumber)));
}
public AttributeCertificateHolder(
X509Certificate cert)
{
X509Name name;
try
{
name = PrincipalUtilities.GetIssuerX509Principal(cert);
}
catch (Exception e)
{
throw new CertificateParsingException(e.Message);
}
holder = new Holder(new IssuerSerial(GenerateGeneralNames(name), new DerInteger(cert.SerialNumber)));
}
public AttributeCertificateHolder(
X509Name principal)
{
holder = new Holder(GenerateGeneralNames(principal));
}
/**
* Constructs a holder for v2 attribute certificates with a hash value for
* some type of object.
* <p>
* <code>digestedObjectType</code> can be one of the following:
* <ul>
* <li>0 - publicKey - A hash of the public key of the holder must be
* passed.</li>
* <li>1 - publicKeyCert - A hash of the public key certificate of the
* holder must be passed.</li>
* <li>2 - otherObjectDigest - A hash of some other object type must be
* passed. <code>otherObjectTypeID</code> must not be empty.</li>
* </ul>
* </p>
* <p>This cannot be used if a v1 attribute certificate is used.</p>
*
* @param digestedObjectType The digest object type.
* @param digestAlgorithm The algorithm identifier for the hash.
* @param otherObjectTypeID The object type ID if
* <code>digestedObjectType</code> is
* <code>otherObjectDigest</code>.
* @param objectDigest The hash value.
*/
public AttributeCertificateHolder(
int digestedObjectType,
string digestAlgorithm,
string otherObjectTypeID,
byte[] objectDigest)
{
// TODO Allow 'objectDigest' to be null?
holder = new Holder(new ObjectDigestInfo(digestedObjectType, otherObjectTypeID,
new AlgorithmIdentifier(digestAlgorithm), Arrays.Clone(objectDigest)));
}
/**
* Returns the digest object type if an object digest info is used.
* <p>
* <ul>
* <li>0 - publicKey - A hash of the public key of the holder must be
* passed.</li>
* <li>1 - publicKeyCert - A hash of the public key certificate of the
* holder must be passed.</li>
* <li>2 - otherObjectDigest - A hash of some other object type must be
* passed. <code>otherObjectTypeID</code> must not be empty.</li>
* </ul>
* </p>
*
* @return The digest object type or -1 if no object digest info is set.
*/
public int DigestedObjectType
{
get
{
ObjectDigestInfo odi = holder.ObjectDigestInfo;
return odi == null
? -1
: odi.DigestedObjectType.Value.IntValue;
}
}
/**
* Returns the other object type ID if an object digest info is used.
*
* @return The other object type ID or <code>null</code> if no object
* digest info is set.
*/
public string DigestAlgorithm
{
get
{
ObjectDigestInfo odi = holder.ObjectDigestInfo;
return odi == null
? null
: odi.DigestAlgorithm.ObjectID.Id;
}
}
/**
* Returns the hash if an object digest info is used.
*
* @return The hash or <code>null</code> if no object digest info is set.
*/
public byte[] GetObjectDigest()
{
ObjectDigestInfo odi = holder.ObjectDigestInfo;
return odi == null
? null
: odi.ObjectDigest.GetBytes();
}
/**
* Returns the digest algorithm ID if an object digest info is used.
*
* @return The digest algorithm ID or <code>null</code> if no object
* digest info is set.
*/
public string OtherObjectTypeID
{
get
{
ObjectDigestInfo odi = holder.ObjectDigestInfo;
return odi == null
? null
: odi.OtherObjectTypeID.Id;
}
}
private GeneralNames GenerateGeneralNames(
X509Name principal)
{
// return GeneralNames.GetInstance(new DerSequence(new GeneralName(principal)));
return new GeneralNames(new GeneralName(principal));
}
private bool MatchesDN(
X509Name subject,
GeneralNames targets)
{
GeneralName[] names = targets.GetNames();
for (int i = 0; i != names.Length; i++)
{
GeneralName gn = names[i];
if (gn.TagNo == GeneralName.DirectoryName)
{
try
{
if (X509Name.GetInstance(gn.Name).Equivalent(subject))
{
return true;
}
}
catch (Exception)
{
}
}
}
return false;
}
private object[] GetNames(
GeneralName[] names)
{
int count = 0;
for (int i = 0; i != names.Length; i++)
{
if (names[i].TagNo == GeneralName.DirectoryName)
{
++count;
}
}
object[] result = new object[count];
int pos = 0;
for (int i = 0; i != names.Length; i++)
{
if (names[i].TagNo == GeneralName.DirectoryName)
{
result[pos++] = X509Name.GetInstance(names[i].Name);
}
}
return result;
}
private X509Name[] GetPrincipals(
GeneralNames names)
{
object[] p = this.GetNames(names.GetNames());
int count = 0;
for (int i = 0; i != p.Length; i++)
{
if (p[i] is X509Name)
{
++count;
}
}
X509Name[] result = new X509Name[count];
int pos = 0;
for (int i = 0; i != p.Length; i++)
{
if (p[i] is X509Name)
{
result[pos++] = (X509Name)p[i];
}
}
return result;
}
/**
* Return any principal objects inside the attribute certificate holder entity names field.
*
* @return an array of IPrincipal objects (usually X509Name), null if no entity names field is set.
*/
public X509Name[] GetEntityNames()
{
if (holder.EntityName != null)
{
return GetPrincipals(holder.EntityName);
}
return null;
}
/**
* Return the principals associated with the issuer attached to this holder
*
* @return an array of principals, null if no BaseCertificateID is set.
*/
public X509Name[] GetIssuer()
{
if (holder.BaseCertificateID != null)
{
return GetPrincipals(holder.BaseCertificateID.Issuer);
}
return null;
}
/**
* Return the serial number associated with the issuer attached to this holder.
*
* @return the certificate serial number, null if no BaseCertificateID is set.
*/
public BigInteger SerialNumber
{
get
{
if (holder.BaseCertificateID != null)
{
return holder.BaseCertificateID.Serial.Value;
}
return null;
}
}
public object Clone()
{
return new AttributeCertificateHolder((Asn1Sequence)holder.ToAsn1Object());
}
public bool Match(
// Certificate cert)
X509Certificate x509Cert)
{
// if (!(cert is X509Certificate))
// {
// return false;
// }
//
// X509Certificate x509Cert = (X509Certificate)cert;
try
{
if (holder.BaseCertificateID != null)
{
return holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber)
&& MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer);
}
if (holder.EntityName != null)
{
if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName))
{
return true;
}
}
if (holder.ObjectDigestInfo != null)
{
IDigest md = null;
try
{
md = DigestUtilities.GetDigest(DigestAlgorithm);
}
catch (Exception)
{
return false;
}
switch (DigestedObjectType)
{
case ObjectDigestInfo.PublicKey:
{
// TODO: DSA Dss-parms
//byte[] b = x509Cert.GetPublicKey().getEncoded();
// TODO Is this the right way to encode?
byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
x509Cert.GetPublicKey()).GetEncoded();
md.BlockUpdate(b, 0, b.Length);
break;
}
case ObjectDigestInfo.PublicKeyCert:
{
byte[] b = x509Cert.GetEncoded();
md.BlockUpdate(b, 0, b.Length);
break;
}
// TODO Default handler?
}
// TODO Shouldn't this be the other way around?
if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest()))
{
return false;
}
}
}
catch (CertificateEncodingException)
{
return false;
}
return false;
}
public override bool Equals(
object obj)
{
if (obj == this)
{
return true;
}
if (!(obj is AttributeCertificateHolder))
{
return false;
}
AttributeCertificateHolder other = (AttributeCertificateHolder)obj;
return this.holder.Equals(other.holder);
}
public override int GetHashCode()
{
return this.holder.GetHashCode();
}
public bool Match(
object obj)
{
if (!(obj is X509Certificate))
{
return false;
}
// return Match((Certificate)obj);
return Match((X509Certificate)obj);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.FullyQualify;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.FullyQualify
{
public class FullyQualifyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new CSharpFullyQualifyCodeFixProvider());
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|IDictionary|] Method()
{
Foo();
}
}",
@"class Class
{
System.Collections.IDictionary Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|IDictionary|] Method()
{
Foo();
}
}",
@"class Class
{
System.Collections.Generic.IDictionary Method()
{
Foo();
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithNoArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|List|] Method()
{
Foo();
}
}",
@"class Class
{
System.Collections.Generic.List Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithCorrectArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|List<int>|] Method()
{
Foo();
}
}",
@"class Class
{
System.Collections.Generic.List<int> Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSmartTagDisplayText()
{
await TestSmartTagTextAsync(
@"class Class
{
[|List<int>|] Method()
{
Foo();
}
}",
"System.Collections.Generic.List");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithWrongArgs()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string>|] Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnVar1()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class var { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnVar2()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class Bar { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericInLocalDeclaration()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Foo()
{
[|List<int>|] a = new List<int>();
}
}",
@"class Class
{
void Foo()
{
System.Collections.Generic.List<int> a = new List<int>();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericItemType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
List<[|Int32|]> l;
}",
@"using System.Collections.Generic;
class Class
{
List<System.Int32> l;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateWithExistingUsings()
{
await TestInRegularAndScriptAsync(
@"using System;
class Class
{
[|List<int>|] Method()
{
Foo();
}
}",
@"using System;
class Class
{
System.Collections.Generic.List<int> Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
class Class
{
[|List<int>|] Method()
{
Foo();
}
}
}",
@"namespace N
{
class Class
{
System.Collections.Generic.List<int> Method()
{
Foo();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespaceWithUsings()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
using System;
class Class
{
[|List<int>|] Method()
{
Foo();
}
}
}",
@"namespace N
{
using System;
class Class
{
System.Collections.Generic.List<int> Method()
{
Foo();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExistingUsing()
{
await TestActionCountAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Foo();
}
}",
count: 1);
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Foo();
}
}",
@"using System.Collections.Generic;
class Class
{
System.Collections.IDictionary Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBound()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Class
{
[|String|] Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBoundGeneric()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
[|List<int>|] Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnEnum()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Foo()
{
var a = [|Colors|].Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}",
@"class Class
{
void Foo()
{
var a = A.Colors.Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnClassInheritance()
{
await TestInRegularAndScriptAsync(
@"class Class : [|Class2|]
{
}
namespace A
{
class Class2
{
}
}",
@"class Class : A.Class2
{
}
namespace A
{
class Class2
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnImplementedInterface()
{
await TestInRegularAndScriptAsync(
@"class Class : [|IFoo|]
{
}
namespace A
{
interface IFoo
{
}
}",
@"class Class : A.IFoo
{
}
namespace A
{
interface IFoo
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAllInBaseList()
{
await TestInRegularAndScriptAsync(
@"class Class : [|IFoo|], Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IFoo
{
}
}",
@"class Class : B.IFoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IFoo
{
}
}");
await TestInRegularAndScriptAsync(
@"class Class : B.IFoo, [|Class2|]
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IFoo
{
}
}",
@"class Class : B.IFoo, A.Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IFoo
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeUnexpanded()
{
await TestInRegularAndScriptAsync(
@"[[|Obsolete|]]
class Class
{
}",
@"[System.Obsolete]
class Class
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeExpanded()
{
await TestInRegularAndScriptAsync(
@"[[|ObsoleteAttribute|]]
class Class
{
}",
@"[System.ObsoleteAttribute]
class Class
{
}");
}
[WorkItem(527360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExtensionMethods()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Foo
{
void Bar()
{
var values = new List<int>() { 1, 2, 3 };
values.[|Where|](i => i > 1);
}
}");
}
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterNew()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Foo()
{
List<int> l;
l = new [|List<int>|]();
}
}",
@"class Class
{
void Foo()
{
List<int> l;
l = new System.Collections.Generic.List<int>();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestArgumentsInMethodCall()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test()
{
Console.WriteLine([|DateTime|].Today);
}
}",
@"class Class
{
void Test()
{
Console.WriteLine(System.DateTime.Today);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestCallSiteArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test([|DateTime|] dt)
{
}
}",
@"class Class
{
void Test(System.DateTime dt)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestUsePartialClass()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
public class Class
{
[|PClass|] c;
}
}
namespace B
{
public partial class PClass
{
}
}",
@"namespace A
{
public class Class
{
B.PClass c;
}
}
namespace B
{
public partial class PClass
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericClassInNestedNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
[|GenericClass<int>|] c;
}
}",
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
A.B.GenericClass<int> c;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeStaticMethod()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test()
{
[|Math|].Sqrt();
}",
@"class Class
{
void Test()
{
System.Math.Sqrt();
}");
}
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
class Class
{
[|C|].Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}",
@"namespace A
{
class Class
{
B.C.Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}");
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSimpleNameWithLeadingTrivia()
{
await TestInRegularAndScriptAsync(
@"class Class { void Test() { /*foo*/[|Int32|] i; } }",
@"class Class { void Test() { /*foo*/System.Int32 i; } }",
ignoreTrivia: false);
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericNameWithLeadingTrivia()
{
await TestInRegularAndScriptAsync(
@"class Class { void Test() { /*foo*/[|List<int>|] l; } }",
@"class Class { void Test() { /*foo*/System.Collections.Generic.List<int> l; } }",
ignoreTrivia: false);
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName()
{
await TestInRegularAndScriptAsync(
@"public class Program
{
public class Inner
{
}
}
class Test
{
[|Inner|] i;
}",
@"public class Program
{
public class Inner
{
}
}
class Test
{
Program.Inner i;
}");
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName_NotForGenericType()
{
await TestMissingInRegularAndScriptAsync(
@"class Program<T>
{
public class Inner
{
}
}
class Test
{
[|Inner|] i;
}");
}
[WorkItem(538764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538764")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyThroughAlias()
{
await TestInRegularAndScriptAsync(
@"using Alias = System;
class C
{
[|Int32|] i;
}",
@"using Alias = System;
class C
{
Alias.Int32 i;
}");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces1()
{
await TestInRegularAndScriptAsync(
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
[|C|] c;
}",
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
Outer.C.C c;
}");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces2()
{
await TestInRegularAndScriptAsync(
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
[|C|] c;
}",
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
Outer.C c;
}",
index: 1);
}
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterAlias()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
System::[|Console|] :: WriteLine(""TEST"");
}
}");
}
[WorkItem(540942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540942")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnIncompleteStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.IO;
class C
{
static void Main(string[] args)
{
[|Path|] }
}");
}
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAssemblyAttribute()
{
await TestInRegularAndScriptAsync(
@"[assembly: [|InternalsVisibleTo|](""Project"")]",
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project"")]");
}
[WorkItem(543388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543388")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAliasName()
{
await TestMissingInRegularAndScriptAsync(
@"using [|GIBBERISH|] = Foo.GIBBERISH;
class Program
{
static void Main(string[] args)
{
GIBBERISH x;
}
}
namespace Foo
{
public class GIBBERISH
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAttributeOverloadResolutionError()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Runtime.InteropServices;
class M
{
[[|DllImport|]()]
static extern int? My();
}");
}
[WorkItem(544950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544950")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnAbstractConstructor()
{
await TestMissingInRegularAndScriptAsync(
@"using System.IO;
class Program
{
static void Main(string[] args)
{
var s = new [|Stream|]();
}
}");
}
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttribute()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 1);
await TestInRegularAndScriptAsync(
input,
@"[assembly: System.Runtime.InteropServices.Guid(""9ed54f84-a89d-4fcd-a854-44251e925f09"")]");
}
[WorkItem(546027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGeneratePropertyFromAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
[AttributeUsage(AttributeTargets.Class)]
class MyAttrAttribute : Attribute
{
}
[MyAttr(123, [|Version|] = 1)]
class D
{
}");
}
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task ShouldTriggerOnCS0308()
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestInRegularAndScriptAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<int> f;
}
}");
}
[WorkItem(947579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousTypeFix()
{
await TestInRegularAndScriptAsync(
@"using n1;
using n2;
class B
{
void M1()
{
[|var a = new A();|]
}
}
namespace n1
{
class A
{
}
}
namespace n2
{
class A
{
}
}",
@"using n1;
using n2;
class B
{
void M1()
{
var a = new n1.A();
}
}
namespace n1
{
class A
{
}
}
namespace n2
{
class A
{
}
}");
}
[WorkItem(995857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995857")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task NonPublicNamespaces()
{
await TestInRegularAndScriptAsync(
@"namespace MS.Internal.Xaml
{
private class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
[|Xaml|]
}
}",
@"namespace MS.Internal.Xaml
{
private class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
System.Xaml
}
}");
await TestInRegularAndScriptAsync(
@"namespace MS.Internal.Xaml
{
public class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
[|Xaml|]
}
}",
@"namespace MS.Internal.Xaml
{
public class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
MS.Internal.Xaml
}
}", index: 1);
}
[WorkItem(11071, "https://github.com/dotnet/roslyn/issues/11071")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousFixOrdering()
{
await TestInRegularAndScriptAsync(
@"using n1;
using n2;
[[|Inner|].C]
class B
{
}
namespace n1
{
namespace Inner
{
}
}
namespace n2
{
namespace Inner
{
class CAttribute
{
}
}
}",
@"using n1;
using n2;
[n2.Inner.C]
class B
{
}
namespace n1
{
namespace Inner
{
}
}
namespace n2
{
namespace Inner
{
class CAttribute
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleTest()
{
await TestInRegularAndScriptAsync(
@"class Class
{
([|IDictionary|], string) Method()
{
Foo();
}
}",
@"class Class
{
(System.Collections.IDictionary, string) Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class Class
{
([|IDictionary|] a, string) Method()
{
Foo();
}
}",
@"class Class
{
(System.Collections.IDictionary a, string) Method()
{
Foo();
}
}");
}
[WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestContextualKeyword1()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace N
{
class nameof
{
}
}
class C
{
void M()
{
[|nameof|]
}
}");
}
[WorkItem(18623, "https://github.com/dotnet/roslyn/issues/18623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestDoNotQualifyToTheSameTypeToFixWrongArity()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class Program : [|IReadOnlyCollection|]
{
}");
}
}
}
| |
using DotVVM.Framework.Controls;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using System.Security.Cryptography;
using System.Text;
#if DotNetCore
using Microsoft.Extensions.DependencyModel;
#endif
namespace DotVVM.Framework.Utils
{
public static class ReflectionUtils
{
public static IEnumerable<Assembly> GetAllAssemblies()
{
#if DotNetCore
return DependencyContext.Default.GetDefaultAssemblyNames().Select(Assembly.Load);
#else
return AppDomain.CurrentDomain.GetAssemblies();
#endif
}
public static bool IsFullName(string typeName)
=> typeName.Contains(".");
public static bool IsAssemblyNamespace(string fullName)
=> GetAllNamespaces().Contains(fullName, StringComparer.Ordinal);
public static ISet<string> GetAllNamespaces()
=> new HashSet<string>(GetAllAssemblies()
.SelectMany(a => a.GetLoadableTypes()
.Select(t => t.Namespace))
.Distinct()
.ToList());
/// <summary>
/// Gets the property name from lambda expression, e.g. 'a => a.FirstName'
/// </summary>
public static MemberInfo GetMemberFromExpression(Expression expression)
{
var body = expression as MemberExpression;
if (body == null)
{
var unaryExpressionBody = (UnaryExpression)expression;
body = unaryExpressionBody.Operand as MemberExpression;
}
return body.Member;
}
// http://haacked.com/archive/2012/07/23/get-all-types-in-an-assembly.aspx/
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException("assembly");
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
/// <summary>
/// Gets filesystem path of assembly CodeBase
/// http://stackoverflow.com/questions/52797/how-do-i-get-the-path-of-the-assembly-the-code-is-in
/// </summary>
public static string GetCodeBasePath(this Assembly assembly)
{
string codeBase = assembly.CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
return Uri.UnescapeDataString(uri.Path);
}
/// <summary>
/// Gets the specified property of a given object.
/// </summary>
public static object GetObjectPropertyValue(object item, string propertyName, out PropertyInfo prop)
{
prop = null;
if (item == null) return null;
var type = item.GetType();
prop = type.GetProperty(propertyName);
if (prop == null)
{
throw new Exception(String.Format("The object of type {0} does not have a property named {1}!", type, propertyName)); // TODO: exception handling
}
return prop.GetValue(item);
}
/// <summary>
/// Extracts the value of a specified property and converts it to string. If the property name is empty, returns a string representation of a given object.
/// Null values are converted to empty string.
/// </summary>
public static string ExtractMemberStringValue(object item, string propertyName)
{
if (!string.IsNullOrEmpty(propertyName))
{
PropertyInfo prop;
item = GetObjectPropertyValue(item, propertyName, out prop);
}
return item?.ToString() ?? "";
}
/// <summary>
/// Converts a value to a specified type
/// </summary>
public static object ConvertValue(object value, Type type)
{
var typeinfo = type.GetTypeInfo();
// handle null values
if ((value == null) && (typeinfo.IsValueType))
return Activator.CreateInstance(type);
// handle nullable types
if (typeinfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if ((value is string) && ((string)value == string.Empty))
{
// value is an empty string, return null
return null;
}
else
{
// value is not null
type = Nullable.GetUnderlyingType(type); typeinfo = type.GetTypeInfo();
}
}
// handle exceptions
if ((value is string) && (type == typeof(Guid)))
return new Guid((string)value);
if (type == typeof(object)) return value;
// handle enums
if (typeinfo.IsEnum && value is string)
{
var split = ((string)value).Split(',', '|');
var isFlags = type.GetTypeInfo().IsDefined(typeof(FlagsAttribute));
if (!isFlags && split.Length > 1) throw new Exception($"Enum {type} does allow multiple values. Use [FlagsAttribute] to allow it.");
dynamic result = null;
foreach (var val in split)
{
try
{
if (result == null) result = Enum.Parse(type, val.Trim(), ignoreCase: true); // Enum.TryParse requires type parameter
else
{
result |= (dynamic)Enum.Parse(type, val.Trim(), ignoreCase: true);
}
}
catch (Exception ex)
{
throw new Exception($"The enum {type} does not allow a value '{val}'!", ex); // TODO: exception handling
}
}
return result;
}
// generic to string
if (type == typeof(string))
{
return value.ToString();
}
if (value is string && type.IsArray)
{
var str = value as string;
var objectArray = str.Split(',').Select(s => ConvertValue(s.Trim(), typeinfo.GetElementType()))
.ToArray();
var array = Array.CreateInstance(type.GetElementType(), objectArray.Length);
objectArray.CopyTo(array, 0);
return array;
}
// convert
return Convert.ChangeType(value, type);
}
public static Type FindType(string name, bool ignoreCase = false)
{
var stringComparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
// Type.GetType might sometimes work well
var type = Type.GetType(name, false, ignoreCase);
if (type != null) return type;
var split = name.Split(',');
name = split[0];
var assemblies = ReflectionUtils.GetAllAssemblies();
if (split.Length > 1)
{
var assembly = split[1];
return assemblies.Where(a => a.GetName().Name == assembly).Select(a => a.GetType(name)).FirstOrDefault(t => t != null);
}
type = assemblies.Where(a => name.StartsWith(a.GetName().Name, stringComparison)).Select(a => a.GetType(name, false, ignoreCase)).FirstOrDefault(t => t != null);
if (type != null) return type;
return assemblies.Select(a => a.GetType(name, false, ignoreCase)).FirstOrDefault(t => t != null);
}
public static Type GetEnumerableType(Type collectionType)
{
var result = TypeDescriptorUtils.GetCollectionItemType(new ResolvedTypeDescriptor(collectionType));
if (result == null) return null;
return ResolvedTypeDescriptor.ToSystemType(result);
}
private static readonly HashSet<Type> NumericTypes = new HashSet<Type>()
{
typeof (sbyte),
typeof (byte),
typeof (short),
typeof (ushort),
typeof (int),
typeof (uint),
typeof (long),
typeof (ulong),
typeof (char),
typeof (float),
typeof (double),
typeof (decimal)
};
public static bool IsNumericType(this Type type)
{
return NumericTypes.Contains(type);
}
public static bool IsDynamicOrObject(this Type type)
{
return type.GetInterfaces().Contains(typeof(IDynamicMetaObjectProvider)) ||
type == typeof(object);
}
public static bool IsDelegate(this Type type)
{
return typeof(Delegate).IsAssignableFrom(type);
}
public static bool IsReferenceType(this Type type)
{
return type.IsArray || type.GetTypeInfo().IsClass || type.GetTypeInfo().IsInterface || type.IsDelegate();
}
public static bool IsDerivedFrom(this Type T, Type superClass)
{
return superClass.IsAssignableFrom(T);
}
public static bool Implements(this Type T, Type interfaceType)
{
return T.GetInterfaces().Any(x =>
{
return x.Name == interfaceType.Name;
});
}
public static bool IsDynamic(this Type type)
{
return type.GetInterfaces().Contains(typeof(IDynamicMetaObjectProvider));
}
public static bool IsObject(this Type type)
{
return type == typeof(Object);
}
public static bool IsNullable(this Type type)
{
return Nullable.GetUnderlyingType(type) != null;
}
public static T GetCustomAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit = true) =>
(T)attributeProvider.GetCustomAttributes(typeof(T), inherit).FirstOrDefault();
public static IEnumerable<T> GetCustomAttributes<T>(this ICustomAttributeProvider attributeProvider, bool inherit = true) =>
attributeProvider.GetCustomAttributes(typeof(T), inherit).Cast<T>();
public static string GetTypeHash(this Type type)
{
using (var sha1 = SHA1.Create())
{
var hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(type.AssemblyQualifiedName));
return Convert.ToBase64String(hashBytes);
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Petstore
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public partial class SwaggerPetstoreClient : ServiceClient<SwaggerPetstoreClient>, ISwaggerPetstoreClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SwaggerPetstoreClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SwaggerPetstoreClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SwaggerPetstoreClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SwaggerPetstoreClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SwaggerPetstoreClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerPetstoreClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("http://petstore.swagger.io/v1");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// List all pets
/// </summary>
/// <param name='limit'>
/// How many items to return at one time (max 100)
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<Pet>,ListPetsHeaders>> ListPetsWithHttpMessagesAsync(int? limit = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("limit", limit);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListPets", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString();
List<string> _queryParameters = new List<string>();
if (limit != null)
{
_queryParameters.Add(string.Format("limit={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(limit, SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<Pet>,ListPetsHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<Pet>>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<ListPetsHeaders>(JsonSerializer.Create(DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create a pet
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> CreatePetsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreatePets", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Info for a specific pet
/// </summary>
/// <param name='petId'>
/// The id of the pet to retrieve
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<Pet>>> ShowPetByIdWithHttpMessagesAsync(string petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (petId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "petId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("petId", petId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ShowPetById", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets/{petId}").ToString();
_url = _url.Replace("{petId}", System.Uri.EscapeDataString(petId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<Pet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<Pet>>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.IO
{
// Provides methods for processing file system strings in a cross-platform manner.
// Most of the methods don't do a complete parsing (such as examining a UNC hostname),
// but they will handle most string operations.
public static partial class Path
{
// Platform specific alternate directory separator character.
// There is only one directory separator char on Unix, which is the same
// as the alternate separator on Windows, so same definition is used for both.
public static readonly char AltDirectorySeparatorChar = '/';
// Changes the extension of a file path. The path parameter
// specifies a file path, and the extension parameter
// specifies a file extension (with a leading period, such as
// ".exe" or ".cs").
//
// The function returns a file path with the same root, directory, and base
// name parts as path, but with the file extension changed to
// the specified extension. If path is null, the function
// returns null. If path does not contain a file extension,
// the new file extension is appended to the path. If extension
// is null, any exsiting extension is removed from path.
public static string ChangeExtension(string path, string extension)
{
if (path != null)
{
PathInternal.CheckInvalidPathChars(path);
string s = path;
for (int i = path.Length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == '.')
{
s = path.Substring(0, i);
break;
}
if (IsDirectoryOrVolumeSeparator(ch)) break;
}
if (extension != null && path.Length != 0)
{
s = (extension.Length == 0 || extension[0] != '.') ?
s + "." + extension :
s + extension;
}
return s;
}
return null;
}
// Returns the directory path of a file path. This method effectively
// removes the last element of the given file path, i.e. it returns a
// string consisting of all characters up to but not including the last
// backslash ("\") in the file path. The returned value is null if the file
// path is null or if the file path denotes a root (such as "\", "C:", or
// "\\server\share").
public static string GetDirectoryName(string path)
{
if (path != null)
{
PathInternal.CheckInvalidPathChars(path);
int root = PathInternal.GetRootLength(path);
path = RemoveRelativeSegments(path, root);
int i = path.Length;
if (i > root)
{
i = path.Length;
if (i == root) return null;
while (i > root && !PathInternal.IsDirectorySeparator(path[--i])) ;
return path.Substring(0, i);
}
}
return null;
}
public static char[] GetInvalidPathChars()
{
return (char[])PathInternal.InvalidPathChars.Clone();
}
public static char[] GetInvalidFileNameChars()
{
return (char[])InvalidFileNameChars.Clone();
}
// Returns the extension of the given path. The returned value includes the
// period (".") character of the extension except when you have a terminal period when you get string.Empty, such as ".exe" or
// ".cpp". The returned value is null if the given path is
// null or if the given path does not include an extension.
[Pure]
public static string GetExtension(string path)
{
if (path == null)
return null;
PathInternal.CheckInvalidPathChars(path);
int length = path.Length;
for (int i = length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == '.')
{
if (i != length - 1)
return path.Substring(i, length - i);
else
return string.Empty;
}
if (IsDirectoryOrVolumeSeparator(ch))
break;
}
return string.Empty;
}
// Returns the name and extension parts of the given path. The resulting
// string contains the characters of path that follow the last
// separator in path. The resulting string is null if path is null.
[Pure]
public static string GetFileName(string path)
{
if (path != null)
{
PathInternal.CheckInvalidPathChars(path);
int length = path.Length;
for (int i = length - 1; i >= 0; i--)
{
char ch = path[i];
if (IsDirectoryOrVolumeSeparator(ch))
return path.Substring(i + 1, length - i - 1);
}
}
return path;
}
[Pure]
public static string GetFileNameWithoutExtension(string path)
{
if (path == null)
return null;
path = GetFileName(path);
int i;
return (i = path.LastIndexOf('.')) == -1 ?
path : // No path extension found
path.Substring(0, i);
}
// Returns a cryptographically strong random 8.3 string that can be
// used as either a folder name or a file name.
public static string GetRandomFileName()
{
// 5 bytes == 40 bits == 40/5 == 8 chars in our encoding.
// So 10 bytes provides 16 chars, of which we need 11
// for the 8.3 name.
byte[] key = CreateCryptoRandomByteArray(10);
// rndCharArray is expected to be 16 chars
char[] rndCharArray = ToBase32StringSuitableForDirName(key).ToCharArray();
rndCharArray[8] = '.';
return new string(rndCharArray, 0, 12);
}
// Returns a unique temporary file name, and creates a 0-byte file by that
// name on disk.
[System.Security.SecuritySafeCritical]
public static string GetTempFileName()
{
return InternalGetTempFileName(checkHost: true);
}
// Tests if a path includes a file extension. The result is
// true if the characters that follow the last directory
// separator ('\\' or '/') or volume separator (':') in the path include
// a period (".") other than a terminal period. The result is false otherwise.
[Pure]
public static bool HasExtension(string path)
{
if (path != null)
{
PathInternal.CheckInvalidPathChars(path);
for (int i = path.Length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == '.')
{
return i != path.Length - 1;
}
if (IsDirectoryOrVolumeSeparator(ch)) break;
}
}
return false;
}
public static string Combine(string path1, string path2)
{
if (path1 == null || path2 == null)
throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
Contract.EndContractBlock();
PathInternal.CheckInvalidPathChars(path1);
PathInternal.CheckInvalidPathChars(path2);
return CombineNoChecks(path1, path2);
}
public static string Combine(string path1, string path2, string path3)
{
if (path1 == null || path2 == null || path3 == null)
throw new ArgumentNullException((path1 == null) ? "path1" : (path2 == null) ? "path2" : "path3");
Contract.EndContractBlock();
PathInternal.CheckInvalidPathChars(path1);
PathInternal.CheckInvalidPathChars(path2);
PathInternal.CheckInvalidPathChars(path3);
return CombineNoChecks(path1, path2, path3);
}
public static string Combine(params string[] paths)
{
if (paths == null)
{
throw new ArgumentNullException("paths");
}
Contract.EndContractBlock();
int finalSize = 0;
int firstComponent = 0;
// We have two passes, the first calcuates how large a buffer to allocate and does some precondition
// checks on the paths passed in. The second actually does the combination.
for (int i = 0; i < paths.Length; i++)
{
if (paths[i] == null)
{
throw new ArgumentNullException("paths");
}
if (paths[i].Length == 0)
{
continue;
}
PathInternal.CheckInvalidPathChars(paths[i]);
if (IsPathRooted(paths[i]))
{
firstComponent = i;
finalSize = paths[i].Length;
}
else
{
finalSize += paths[i].Length;
}
char ch = paths[i][paths[i].Length - 1];
if (!IsDirectoryOrVolumeSeparator(ch))
finalSize++;
}
StringBuilder finalPath = StringBuilderCache.Acquire(finalSize);
for (int i = firstComponent; i < paths.Length; i++)
{
if (paths[i].Length == 0)
{
continue;
}
if (finalPath.Length == 0)
{
finalPath.Append(paths[i]);
}
else
{
char ch = finalPath[finalPath.Length - 1];
if (!IsDirectoryOrVolumeSeparator(ch))
{
finalPath.Append(DirectorySeparatorChar);
}
finalPath.Append(paths[i]);
}
}
return StringBuilderCache.GetStringAndRelease(finalPath);
}
private static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
return path1;
if (path1.Length == 0)
return path2;
if (IsPathRooted(path2))
return path2;
char ch = path1[path1.Length - 1];
return IsDirectoryOrVolumeSeparator(ch) ?
path1 + path2 :
path1 + DirectorySeparatorCharAsString + path2;
}
private static string CombineNoChecks(string path1, string path2, string path3)
{
if (path1.Length == 0)
return CombineNoChecks(path2, path3);
if (path2.Length == 0)
return CombineNoChecks(path1, path3);
if (path3.Length == 0)
return CombineNoChecks(path1, path2);
if (IsPathRooted(path3))
return path3;
if (IsPathRooted(path2))
return CombineNoChecks(path2, path3);
bool hasSep1 = IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]);
bool hasSep2 = IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]);
if (hasSep1 && hasSep2)
{
return path1 + path2 + path3;
}
else if (hasSep1)
{
return path1 + path2 + DirectorySeparatorCharAsString + path3;
}
else if (hasSep2)
{
return path1 + DirectorySeparatorCharAsString + path2 + path3;
}
else
{
// string.Concat only has string-based overloads up to four arguments; after that requires allocating
// a params string[]. Instead, try to use a cached StringBuilder.
StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + 2);
sb.Append(path1)
.Append(DirectorySeparatorChar)
.Append(path2)
.Append(DirectorySeparatorChar)
.Append(path3);
return StringBuilderCache.GetStringAndRelease(sb);
}
}
private static readonly char[] s_Base32Char = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5'};
private static string ToBase32StringSuitableForDirName(byte[] buff)
{
// This routine is optimised to be used with buffs of length 20
Debug.Assert(((buff.Length % 5) == 0), "Unexpected hash length");
// For every 5 bytes, 8 characters are appended.
StringBuilder sb = StringBuilderCache.Acquire();
// Create l char for each of the last 5 bits of each byte.
// Consume 3 MSB bits 5 bytes at a time.
int len = buff.Length;
int i = 0;
do
{
byte b0 = (i < len) ? buff[i++] : (byte)0;
byte b1 = (i < len) ? buff[i++] : (byte)0;
byte b2 = (i < len) ? buff[i++] : (byte)0;
byte b3 = (i < len) ? buff[i++] : (byte)0;
byte b4 = (i < len) ? buff[i++] : (byte)0;
// Consume the 5 Least significant bits of each byte
sb.Append(s_Base32Char[b0 & 0x1F]);
sb.Append(s_Base32Char[b1 & 0x1F]);
sb.Append(s_Base32Char[b2 & 0x1F]);
sb.Append(s_Base32Char[b3 & 0x1F]);
sb.Append(s_Base32Char[b4 & 0x1F]);
// Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4
sb.Append(s_Base32Char[(
((b0 & 0xE0) >> 5) |
((b3 & 0x60) >> 2))]);
sb.Append(s_Base32Char[(
((b1 & 0xE0) >> 5) |
((b4 & 0x60) >> 2))]);
// Consume 3 MSB bits of b2, 1 MSB bit of b3, b4
b2 >>= 5;
Debug.Assert(((b2 & 0xF8) == 0), "Unexpected set bits");
if ((b3 & 0x80) != 0)
b2 |= 0x08;
if ((b4 & 0x80) != 0)
b2 |= 0x10;
sb.Append(s_Base32Char[b2]);
} while (i < len);
return StringBuilderCache.GetStringAndRelease(sb);
}
/// <summary>
/// Try and remove relative segments from the given path (without combining with a root).
/// </summary>
/// <param name="skip">Skip the specified number of characters before evaluating.</param>
private static string RemoveRelativeSegments(string path, int skip = 0)
{
bool flippedSeparator = false;
// Remove "//", "/./", and "/../" from the path by copying each character to the output,
// except the ones we're removing, such that the builder contains the normalized path
// at the end.
var sb = StringBuilderCache.Acquire(path.Length);
if (skip > 0)
sb.Append(path, 0, skip);
int componentCharCount = 0;
for (int i = skip; i < path.Length; i++)
{
char c = path[i];
if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length)
{
componentCharCount = 0;
// Skip this character if it's a directory separator and if the next character is, too,
// e.g. "parent//child" => "parent/child"
if (PathInternal.IsDirectorySeparator(path[i + 1]))
{
continue;
}
// Skip this character and the next if it's referring to the current directory,
// e.g. "parent/./child" =? "parent/child"
if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) &&
path[i + 1] == '.')
{
i++;
continue;
}
// Skip this character and the next two if it's referring to the parent directory,
// e.g. "parent/child/../grandchild" => "parent/grandchild"
if (i + 2 < path.Length &&
(i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) &&
path[i + 1] == '.' && path[i + 2] == '.')
{
// Unwind back to the last slash (and if there isn't one, clear out everything).
int s;
for (s = sb.Length - 1; s >= 0; s--)
{
if (PathInternal.IsDirectorySeparator(sb[s]))
{
sb.Length = s;
break;
}
}
if (s < 0)
sb.Length = 0;
i += 2;
continue;
}
}
if (++componentCharCount > MaxComponentLength)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
// Normalize the directory separator if needed
if (c != Path.DirectorySeparatorChar && c == Path.AltDirectorySeparatorChar)
{
c = Path.DirectorySeparatorChar;
flippedSeparator = true;
}
sb.Append(c);
}
if (flippedSeparator || sb.Length != path.Length)
{
return StringBuilderCache.GetStringAndRelease(sb);
}
else
{
// We haven't changed the source path, return the original
StringBuilderCache.Release(sb);
return path;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Data.Tables.Models;
using Azure.Data.Tables.Sas;
using NUnit.Framework;
namespace Azure.Data.Tables.Tests
{
/// <summary>
/// The suite of tests for the <see cref="TableServiceClient"/> class.
/// </summary>
/// <remarks>
/// These tests have a dependency on live Azure services and may incur costs for the associated
/// Azure subscription.
/// </remarks>
public class TableClientLiveTests : TableServiceLiveTestsBase
{
public TableClientLiveTests(bool isAsync, TableEndpointType endpointType) : base(isAsync, endpointType /* To record tests, add this argument, RecordedTestMode.Record */)
{ }
[Test]
public void ValidateSasCredentials()
{
// Create a SharedKeyCredential that we can use to sign the SAS token
var credential = new TableSharedKeyCredential(TestEnvironment.AccountName, TestEnvironment.PrimaryStorageAccountKey);
// Build a shared access signature with only Read permissions.
TableSasBuilder sas = client.GetSasBuilder(TableSasPermissions.Read, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc));
string token = sas.Sign(credential);
// Build a SAS URI
UriBuilder sasUri = new UriBuilder(TestEnvironment.StorageUri)
{
Query = token
};
// Create the TableServiceClient using the SAS URI.
var sasAuthedService = InstrumentClient(new TableServiceClient(sasUri.Uri, Recording.InstrumentClientOptions(new TableClientOptions())));
var sasTableclient = sasAuthedService.GetTableClient(tableName);
// Validate that we are able to query the table from the service.
Assert.That(async () => await sasTableclient.QueryAsync().ToEnumerableAsync().ConfigureAwait(false), Throws.Nothing);
// Validate that we are not able to upsert an entity to the table.
Assert.That(async () => await sasTableclient.UpsertEntityAsync(CreateTableEntities("partition", 1).First(), UpdateMode.Replace).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>().And.Property("Status").EqualTo((int)HttpStatusCode.Forbidden));
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
[TestCase(null)]
[TestCase(5)]
public async Task CreatedEntitiesCanBeQueriedWithAndWithoutPagination(int? pageCount)
{
List<IDictionary<string, object>> entityResults;
List<Dictionary<string, object>> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 20);
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.CreateEntityAsync(entity).ConfigureAwait(false);
}
// Query the entities.
entityResults = await client.QueryAsync(maxPerPage: pageCount).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count), "The entity result count should match the created count");
entityResults.Clear();
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CreatedEntitiesCanBeQueriedWithFilters()
{
List<IDictionary<string, object>> entityResults;
List<Dictionary<string, object>> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 20);
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.CreateEntityAsync(entity).ConfigureAwait(false);
}
// Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'.
entityResults = await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task EntityCanBeUpserted()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string propertyName = "SomeStringProperty";
const string originalValue = "This is the original";
const string updatedValue = "This is new and improved!";
var entity = new Dictionary<string, object>
{
{"PartitionKey", PartitionKeyValue},
{"RowKey", rowKeyValue},
{propertyName, originalValue}
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var entityToUpdate = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
entityToUpdate[propertyName] = updatedValue;
await client.UpsertEntityAsync(entityToUpdate, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the updated entity from the service.
var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task EntityUpdateRespectsEtag()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string propertyName = "SomeStringProperty";
const string originalValue = "This is the original";
const string updatedValue = "This is new and improved!";
const string updatedValue2 = "This changed due to a matching Etag";
var entity = new Dictionary<string, object>
{
{"PartitionKey", PartitionKeyValue},
{"RowKey", rowKeyValue},
{propertyName, originalValue}
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
originalEntity[propertyName] = updatedValue;
// Use a wildcard ETag to update unconditionally.
await client.UpdateEntityAsync(originalEntity, "*", UpdateMode.Replace).ConfigureAwait(false);
// Fetch the updated entity from the service.
var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");
updatedEntity[propertyName] = updatedValue2;
// Use a non-matching ETag.
Assert.That(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity[TableConstants.PropertyNames.Etag] as string, UpdateMode.Replace).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>());
// Use a matching ETag.
await client.UpdateEntityAsync(updatedEntity, updatedEntity[TableConstants.PropertyNames.Etag] as string, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the newly updated entity from the service.
updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task EntityMergeRespectsEtag()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string propertyName = "SomeStringProperty";
const string originalValue = "This is the original";
const string updatedValue = "This is new and improved!";
const string updatedValue2 = "This changed due to a matching Etag";
var entity = new Dictionary<string, object>
{
{"PartitionKey", PartitionKeyValue},
{"RowKey", rowKeyValue},
{propertyName, originalValue}
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
originalEntity[propertyName] = updatedValue;
// Use a wildcard ETag to update unconditionally.
await client.UpdateEntityAsync(originalEntity, "*", UpdateMode.Merge).ConfigureAwait(false);
// Fetch the updated entity from the service.
var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");
updatedEntity[propertyName] = updatedValue2;
// Use a non-matching ETag.
Assert.That(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity[TableConstants.PropertyNames.Etag] as string, UpdateMode.Merge).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>());
// Use a matching ETag.
await client.UpdateEntityAsync(updatedEntity, updatedEntity[TableConstants.PropertyNames.Etag] as string, UpdateMode.Merge).ConfigureAwait(false);
// Fetch the newly updated entity from the service.
updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task EntityMergeDoesPartialPropertyUpdates()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string propertyName = "SomeStringProperty";
const string mergepropertyName = "MergedProperty";
const string originalValue = "This is the original";
const string mergeValue = "This was merged!";
const string mergeUpdatedValue = "merged value was updated!";
var entity = new Dictionary<string, object>
{
{"PartitionKey", PartitionKeyValue},
{"RowKey", rowKeyValue},
{propertyName, originalValue}
};
var partialEntity = new Dictionary<string, object>
{
{"PartitionKey", PartitionKeyValue},
{"RowKey", rowKeyValue},
{mergepropertyName, mergeValue}
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
// Verify that the merge property does not yet exist yet and that the original property does exist.
Assert.That(originalEntity.TryGetValue(mergepropertyName, out var _), Is.False);
Assert.That(originalEntity[propertyName], Is.EqualTo(originalValue));
await client.UpsertEntityAsync(partialEntity, UpdateMode.Merge).ConfigureAwait(false);
// Fetch the updated entity from the service.
var mergedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
// Verify that the merge property does not yet exist yet and that the original property does exist.
Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeValue));
Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue));
// Update just the merged value.
partialEntity[mergepropertyName] = mergeUpdatedValue;
await client.UpsertEntityAsync(partialEntity, UpdateMode.Merge).ConfigureAwait(false);
// Fetch the updated entity from the service.
mergedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
// Verify that the merge property does not yet exist yet and that the original property does exist.
Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeUpdatedValue));
Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue));
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task EntityDeleteRespectsEtag()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string propertyName = "SomeStringProperty";
const string originalValue = "This is the original";
var entity = new Dictionary<string, object>
{
{"PartitionKey", PartitionKeyValue},
{"RowKey", rowKeyValue},
{propertyName, originalValue}
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
var staleEtag = originalEntity[TableConstants.PropertyNames.Etag] as string;
// Use a wildcard ETag to delete unconditionally.
await client.DeleteAsync(PartitionKeyValue, rowKeyValue).ConfigureAwait(false);
// Validate that the entity is deleted.
var emptyresult = await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(emptyresult, Is.Empty, $"The query should have returned no results.");
// Create the new entity again.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
// Use a non-matching ETag.
Assert.That(async () => await client.DeleteAsync(PartitionKeyValue, rowKeyValue, staleEtag).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>());
// Use a matching ETag.
await client.DeleteAsync(PartitionKeyValue, rowKeyValue, originalEntity[TableConstants.PropertyNames.Etag] as string).ConfigureAwait(false);
// Validate that the entity is deleted.
emptyresult = await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(emptyresult, Is.Empty, $"The query should have returned no results.");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CreatedEntitiesAreRoundtrippedWithProperOdataAnnoations()
{
List<IDictionary<string, object>> entityResults;
List<Dictionary<string, object>> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1);
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.CreateEntityAsync(entity).ConfigureAwait(false);
}
// Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'.
entityResults = await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(entityResults.First()[StringTypePropertyName], Is.TypeOf<string>(), "The entity property should be of type string");
Assert.That(entityResults.First()[DateTypePropertyName], Is.TypeOf<DateTime>(), "The entity property should be of type DateTime");
Assert.That(entityResults.First()[GuidTypePropertyName], Is.TypeOf<Guid>(), "The entity property should be of type Guid");
Assert.That(entityResults.First()[BinaryTypePropertyName], Is.TypeOf<byte[]>(), "The entity property should be of type byte[]");
Assert.That(entityResults.First()[Int64TypePropertyName], Is.TypeOf<long>(), "The entity property should be of type int64");
Assert.That(entityResults.First()[DoubleTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double");
Assert.That(entityResults.First()[DoubleDecimalTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double");
Assert.That(entityResults.First()[IntTypePropertyName], Is.TypeOf<int>(), "The entity property should be of type int");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task UpsertedEntitiesAreRoundtrippedWithProperOdataAnnoations()
{
List<IDictionary<string, object>> entityResults;
List<Dictionary<string, object>> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1);
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
}
// Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'.
entityResults = await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(entityResults.First()[StringTypePropertyName], Is.TypeOf<string>(), "The entity property should be of type string");
Assert.That(entityResults.First()[DateTypePropertyName], Is.TypeOf<DateTime>(), "The entity property should be of type DateTime");
Assert.That(entityResults.First()[GuidTypePropertyName], Is.TypeOf<Guid>(), "The entity property should be of type Guid");
Assert.That(entityResults.First()[BinaryTypePropertyName], Is.TypeOf<byte[]>(), "The entity property should be of type byte[]");
Assert.That(entityResults.First()[Int64TypePropertyName], Is.TypeOf<long>(), "The entity property should be of type int64");
Assert.That(entityResults.First()[DoubleTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double");
Assert.That(entityResults.First()[DoubleDecimalTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double");
Assert.That(entityResults.First()[IntTypePropertyName], Is.TypeOf<int>(), "The entity property should be of type int");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CreateEntityReturnsEntitiesWithoutOdataAnnoations()
{
List<Dictionary<string, object>> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1);
// Create an entity.
var createdEntity = (await client.CreateEntityAsync(entitiesToCreate.First()).ConfigureAwait(false)).Value;
Assert.That(createdEntity.Keys.Count(k => k.EndsWith(TableConstants.Odata.OdataTypeString)), Is.Zero, "The entity should not containt any odata data annotation properties");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task QueryReturnsEntitiesWithoutOdataAnnoations()
{
List<IDictionary<string, object>> entityResults;
List<Dictionary<string, object>> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1);
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
}
// Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'.
entityResults = await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(entityResults.First().Keys.Count(k => k.EndsWith(TableConstants.Odata.OdataTypeString)), Is.Zero, "The entity should not containt any odata data annotation properties");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
[TestCase(null)]
[TestCase(5)]
public async Task CreatedCustomEntitiesCanBeQueriedWithAndWithoutPagination(int? pageCount)
{
List<TestEntity> entityResults;
var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 20);
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.CreateEntityAsync(entity).ConfigureAwait(false);
}
// Query the entities.
entityResults = await client.QueryAsync<TestEntity>(maxPerPage: pageCount).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count), "The entity result count should match the created count");
entityResults.Clear();
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CreatedCustomEntitiesCanBeQueriedWithFilters()
{
List<TestEntity> entityResults;
var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 20);
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.CreateEntityAsync(entity).ConfigureAwait(false);
}
// Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'.
entityResults = await client.QueryAsync<TestEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CustomEntityCanBeUpserted()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string propertyName = "SomeStringProperty";
const string originalValue = "This is the original";
const string updatedValue = "This is new and improved!";
var entity = new SimpleTestEntity
{
PartitionKey = PartitionKeyValue,
RowKey = rowKeyValue,
StringTypeProperty = originalValue,
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var entityToUpdate = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
entityToUpdate[propertyName] = updatedValue;
await client.UpsertEntityAsync(entityToUpdate, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the updated entity from the service.
var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CustomEntityUpdateRespectsEtag()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string propertyName = "SomeStringProperty";
const string originalValue = "This is the original";
const string updatedValue = "This is new and improved!";
const string updatedValue2 = "This changed due to a matching Etag";
var entity = new SimpleTestEntity
{
PartitionKey = PartitionKeyValue,
RowKey = rowKeyValue,
StringTypeProperty = originalValue,
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
originalEntity[propertyName] = updatedValue;
// Use a wildcard ETag to update unconditionally.
await client.UpdateEntityAsync(originalEntity, "*", UpdateMode.Replace).ConfigureAwait(false);
// Fetch the updated entity from the service.
var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");
updatedEntity[propertyName] = updatedValue2;
// Use a non-matching ETag.
Assert.That(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity[TableConstants.PropertyNames.Etag] as string, UpdateMode.Replace).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>());
// Use a matching ETag.
await client.UpdateEntityAsync(updatedEntity, updatedEntity[TableConstants.PropertyNames.Etag] as string, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the newly updated entity from the service.
updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CustomEntityMergeRespectsEtag()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string propertyName = "SomeStringProperty";
const string originalValue = "This is the original";
const string updatedValue = "This is new and improved!";
const string updatedValue2 = "This changed due to a matching Etag";
var entity = new SimpleTestEntity
{
PartitionKey = PartitionKeyValue,
RowKey = rowKeyValue,
StringTypeProperty = originalValue,
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
originalEntity[propertyName] = updatedValue;
// Use a wildcard ETag to update unconditionally.
await client.UpdateEntityAsync(originalEntity, "*", UpdateMode.Merge).ConfigureAwait(false);
// Fetch the updated entity from the service.
var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");
updatedEntity[propertyName] = updatedValue2;
// Use a non-matching ETag.
Assert.That(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity[TableConstants.PropertyNames.Etag] as string, UpdateMode.Merge).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>());
// Use a matching ETag.
await client.UpdateEntityAsync(updatedEntity, updatedEntity[TableConstants.PropertyNames.Etag] as string, UpdateMode.Merge).ConfigureAwait(false);
// Fetch the newly updated entity from the service.
updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CustomEntityDeleteRespectsEtag()
{
string tableName = $"testtable{Recording.GenerateId()}";
const string rowKeyValue = "1";
const string originalValue = "This is the original";
var entity = new SimpleTestEntity
{
PartitionKey = PartitionKeyValue,
RowKey = rowKeyValue,
StringTypeProperty = originalValue,
};
// Create the new entity.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
var staleEtag = originalEntity[TableConstants.PropertyNames.Etag] as string;
// Use a wildcard ETag to delete unconditionally.
await client.DeleteAsync(PartitionKeyValue, rowKeyValue).ConfigureAwait(false);
// Validate that the entity is deleted.
var emptyresult = await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(emptyresult, Is.Empty, $"The query should have returned no results.");
// Create the new entity again.
await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);
// Fetch the created entity from the service.
originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
// Use a non-matching ETag.
Assert.That(async () => await client.DeleteAsync(PartitionKeyValue, rowKeyValue, staleEtag).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>());
// Use a matching ETag.
await client.DeleteAsync(PartitionKeyValue, rowKeyValue, originalEntity[TableConstants.PropertyNames.Etag] as string).ConfigureAwait(false);
// Validate that the entity is deleted.
emptyresult = await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false);
Assert.That(emptyresult, Is.Empty, $"The query should have returned no results.");
}
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[Test]
public async Task CreatedCustomEntitiesAreRoundtrippedProprly()
{
List<TestEntity> entityResults;
var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 1);
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.CreateEntityAsync(entity).ConfigureAwait(false);
}
// Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'.
entityResults = await client.QueryAsync<TestEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false);
entityResults.Sort((first, second) => first.IntTypeProperty.CompareTo(second.IntTypeProperty));
for (int i = 0; i < entityResults.Count; i++)
{
Assert.That(entityResults[i].BinaryTypeProperty, Is.EqualTo(entitiesToCreate[i].BinaryTypeProperty), "The entities should be equivalent");
Assert.That(entityResults[i].DatetimeOffsetTypeProperty, Is.EqualTo(entitiesToCreate[i].DatetimeOffsetTypeProperty), "The entities should be equivalent");
Assert.That(entityResults[i].DatetimeTypeProperty, Is.EqualTo(entitiesToCreate[i].DatetimeTypeProperty), "The entities should be equivalent");
Assert.That(entityResults[i].DoubleTypeProperty, Is.EqualTo(entitiesToCreate[i].DoubleTypeProperty), "The entities should be equivalent");
Assert.That(entityResults[i].GuidTypeProperty, Is.EqualTo(entitiesToCreate[i].GuidTypeProperty), "The entities should be equivalent");
Assert.That(entityResults[i].Int64TypeProperty, Is.EqualTo(entitiesToCreate[i].Int64TypeProperty), "The entities should be equivalent");
Assert.That(entityResults[i].IntTypeProperty, Is.EqualTo(entitiesToCreate[i].IntTypeProperty), "The entities should be equivalent");
Assert.That(entityResults[i].PartitionKey, Is.EqualTo(entitiesToCreate[i].PartitionKey), "The entities should be equivalent");
Assert.That(entityResults[i].RowKey, Is.EqualTo(entitiesToCreate[i].RowKey), "The entities should be equivalent");
Assert.That(entityResults[i].StringTypeProperty, Is.EqualTo(entitiesToCreate[i].StringTypeProperty), "The entities should be equivalent");
}
}
/// <summary>
/// Validates the functionality of the TableServiceClient.
/// </summary>
[Test]
public async Task GetAccessPoliciesReturnsPolicies()
{
// Create some policies.
var policyToCreate = new List<SignedIdentifier>
{
new SignedIdentifier("MyPolicy", new AccessPolicy(new DateTime(2020, 1,1,1,1,0,DateTimeKind.Utc), new DateTime(2021, 1,1,1,1,0,DateTimeKind.Utc), "r"))
};
await client.SetAccessPolicyAsync(tableAcl: policyToCreate);
// Get the created policy.
var policies = await client.GetAccessPolicyAsync();
Assert.That(policies.Value[0].Id, Is.EqualTo(policyToCreate[0].Id));
Assert.That(policies.Value[0].AccessPolicy.Expiry, Is.EqualTo(policyToCreate[0].AccessPolicy.Expiry));
Assert.That(policies.Value[0].AccessPolicy.Permission, Is.EqualTo(policyToCreate[0].AccessPolicy.Permission));
Assert.That(policies.Value[0].AccessPolicy.Start, Is.EqualTo(policyToCreate[0].AccessPolicy.Start));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Buffers.Tests
{
public abstract class ArrayBufferWriterTests<T> where T : IEquatable<T>
{
[Fact]
public void ArrayBufferWriter_Ctor()
{
{
var output = new ArrayBufferWriter<T>();
Assert.Equal(0, output.FreeCapacity);
Assert.Equal(0, output.Capacity);
Assert.Equal(0, output.WrittenCount);
Assert.True(ReadOnlySpan<T>.Empty.SequenceEqual(output.WrittenSpan));
Assert.True(ReadOnlyMemory<T>.Empty.Span.SequenceEqual(output.WrittenMemory.Span));
}
{
var output = new ArrayBufferWriter<T>(200);
Assert.True(output.FreeCapacity >= 200);
Assert.True(output.Capacity >= 200);
Assert.Equal(0, output.WrittenCount);
Assert.True(ReadOnlySpan<T>.Empty.SequenceEqual(output.WrittenSpan));
Assert.True(ReadOnlyMemory<T>.Empty.Span.SequenceEqual(output.WrittenMemory.Span));
}
{
ArrayBufferWriter<T> output = default;
Assert.Equal(null, output);
}
}
[Fact]
public void Invalid_Ctor()
{
Assert.Throws<ArgumentException>(() => new ArrayBufferWriter<T>(0));
Assert.Throws<ArgumentException>(() => new ArrayBufferWriter<T>(-1));
Assert.Throws<OutOfMemoryException>(() => new ArrayBufferWriter<T>(int.MaxValue));
}
[Fact]
public void Clear()
{
var output = new ArrayBufferWriter<T>(256);
int previousAvailable = output.FreeCapacity;
WriteData(output, 2);
Assert.True(output.FreeCapacity < previousAvailable);
Assert.True(output.WrittenCount > 0);
Assert.False(ReadOnlySpan<T>.Empty.SequenceEqual(output.WrittenSpan));
Assert.False(ReadOnlyMemory<T>.Empty.Span.SequenceEqual(output.WrittenMemory.Span));
Assert.True(output.WrittenSpan.SequenceEqual(output.WrittenMemory.Span));
output.Clear();
Assert.Equal(0, output.WrittenCount);
Assert.True(ReadOnlySpan<T>.Empty.SequenceEqual(output.WrittenSpan));
Assert.True(ReadOnlyMemory<T>.Empty.Span.SequenceEqual(output.WrittenMemory.Span));
Assert.Equal(previousAvailable, output.FreeCapacity);
}
[Fact]
public void Advance()
{
{
var output = new ArrayBufferWriter<T>();
int capacity = output.Capacity;
Assert.Equal(capacity, output.FreeCapacity);
output.Advance(output.FreeCapacity);
Assert.Equal(capacity, output.WrittenCount);
Assert.Equal(0, output.FreeCapacity);
}
{
var output = new ArrayBufferWriter<T>();
output.Advance(output.Capacity);
Assert.Equal(output.Capacity, output.WrittenCount);
Assert.Equal(0, output.FreeCapacity);
int previousCapacity = output.Capacity;
Span<T> _ = output.GetSpan();
Assert.True(output.Capacity > previousCapacity);
}
{
var output = new ArrayBufferWriter<T>(256);
WriteData(output, 2);
ReadOnlyMemory<T> previousMemory = output.WrittenMemory;
ReadOnlySpan<T> previousSpan = output.WrittenSpan;
Assert.True(previousSpan.SequenceEqual(previousMemory.Span));
output.Advance(10);
Assert.False(previousMemory.Span.SequenceEqual(output.WrittenMemory.Span));
Assert.False(previousSpan.SequenceEqual(output.WrittenSpan));
Assert.True(output.WrittenSpan.SequenceEqual(output.WrittenMemory.Span));
}
{
var output = new ArrayBufferWriter<T>();
_ = output.GetSpan(20);
WriteData(output, 10);
ReadOnlyMemory<T> previousMemory = output.WrittenMemory;
ReadOnlySpan<T> previousSpan = output.WrittenSpan;
Assert.True(previousSpan.SequenceEqual(previousMemory.Span));
Assert.Throws<InvalidOperationException>(() => output.Advance(247));
output.Advance(10);
Assert.False(previousMemory.Span.SequenceEqual(output.WrittenMemory.Span));
Assert.False(previousSpan.SequenceEqual(output.WrittenSpan));
Assert.True(output.WrittenSpan.SequenceEqual(output.WrittenMemory.Span));
}
}
[Fact]
public void AdvanceZero()
{
var output = new ArrayBufferWriter<T>();
WriteData(output, 2);
Assert.Equal(2, output.WrittenCount);
ReadOnlyMemory<T> previousMemory = output.WrittenMemory;
ReadOnlySpan<T> previousSpan = output.WrittenSpan;
Assert.True(previousSpan.SequenceEqual(previousMemory.Span));
output.Advance(0);
Assert.Equal(2, output.WrittenCount);
Assert.True(previousMemory.Span.SequenceEqual(output.WrittenMemory.Span));
Assert.True(previousSpan.SequenceEqual(output.WrittenSpan));
Assert.True(output.WrittenSpan.SequenceEqual(output.WrittenMemory.Span));
}
[Fact]
public void InvalidAdvance()
{
{
var output = new ArrayBufferWriter<T>();
Assert.Throws<ArgumentException>(() => output.Advance(-1));
Assert.Throws<InvalidOperationException>(() => output.Advance(output.Capacity + 1));
}
{
var output = new ArrayBufferWriter<T>();
WriteData(output, 100);
Assert.Throws<InvalidOperationException>(() => output.Advance(output.FreeCapacity + 1));
}
}
[Fact]
public void GetSpan_DefaultCtor()
{
var output = new ArrayBufferWriter<T>();
Span<T> span = output.GetSpan();
Assert.Equal(256, span.Length);
}
[Theory]
[MemberData(nameof(SizeHints))]
public void GetSpan_DefaultCtor(int sizeHint)
{
var output = new ArrayBufferWriter<T>();
Span<T> span = output.GetSpan(sizeHint);
Assert.Equal(sizeHint <= 256 ? 256 : sizeHint, span.Length);
}
[Fact]
public void GetSpan_InitSizeCtor()
{
var output = new ArrayBufferWriter<T>(100);
Span<T> span = output.GetSpan();
Assert.Equal(100, span.Length);
}
[Theory]
[MemberData(nameof(SizeHints))]
public void GetSpan_InitSizeCtor(int sizeHint)
{
{
var output = new ArrayBufferWriter<T>(256);
Span<T> span = output.GetSpan(sizeHint);
Assert.Equal(sizeHint <= 256 ? 256 : sizeHint + 256, span.Length);
}
{
var output = new ArrayBufferWriter<T>(1000);
Span<T> span = output.GetSpan(sizeHint);
Assert.Equal(sizeHint <= 1000 ? 1000 : sizeHint + 1000, span.Length);
}
}
[Fact]
public void GetMemory_DefaultCtor()
{
var output = new ArrayBufferWriter<T>();
Memory<T> memory = output.GetMemory();
Assert.Equal(256, memory.Length);
}
[Theory]
[MemberData(nameof(SizeHints))]
public void GetMemory_DefaultCtor(int sizeHint)
{
var output = new ArrayBufferWriter<T>();
Memory<T> memory = output.GetMemory(sizeHint);
Assert.Equal(sizeHint <= 256 ? 256 : sizeHint, memory.Length);
}
[Fact]
public void GetMemory_InitSizeCtor()
{
var output = new ArrayBufferWriter<T>(100);
Memory<T> memory = output.GetMemory();
Assert.Equal(100, memory.Length);
}
[Theory]
[MemberData(nameof(SizeHints))]
public void GetMemory_InitSizeCtor(int sizeHint)
{
{
var output = new ArrayBufferWriter<T>(256);
Memory<T> memory = output.GetMemory(sizeHint);
Assert.Equal(sizeHint <= 256 ? 256 : sizeHint + 256, memory.Length);
}
{
var output = new ArrayBufferWriter<T>(1000);
Memory<T> memory = output.GetMemory(sizeHint);
Assert.Equal(sizeHint <= 1000 ? 1000 : sizeHint + 1000, memory.Length);
}
}
public static bool IsX64 { get; } = IntPtr.Size == 8;
// NOTE: InvalidAdvance_Large test is constrained to run on Windows and MacOSX because it causes
// problems on Linux due to the way deferred memory allocation works. On Linux, the allocation can
// succeed even if there is not enough memory but then the test may get killed by the OOM killer at the
// time the memory is accessed which triggers the full memory allocation.
[PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)]
[ConditionalFact(nameof(IsX64))]
[OuterLoop]
public void InvalidAdvance_Large()
{
try
{
{
var output = new ArrayBufferWriter<T>(2_000_000_000);
WriteData(output, 1_000);
Assert.Throws<InvalidOperationException>(() => output.Advance(int.MaxValue));
Assert.Throws<InvalidOperationException>(() => output.Advance(2_000_000_000 - 1_000 + 1));
}
}
catch (OutOfMemoryException) { }
}
[Fact]
public void GetMemoryAndSpan()
{
{
var output = new ArrayBufferWriter<T>();
WriteData(output, 2);
Span<T> span = output.GetSpan();
Memory<T> memory = output.GetMemory();
Span<T> memorySpan = memory.Span;
Assert.True(span.Length > 0);
Assert.True(memorySpan.Length > 0);
Assert.Equal(span.Length, memorySpan.Length);
for (int i = 0; i < span.Length; i++)
{
Assert.Equal(default, span[i]);
Assert.Equal(default, memorySpan[i]);
}
}
{
var output = new ArrayBufferWriter<T>();
WriteData(output, 2);
ReadOnlyMemory<T> writtenSoFarMemory = output.WrittenMemory;
ReadOnlySpan<T> writtenSoFar = output.WrittenSpan;
Assert.True(writtenSoFarMemory.Span.SequenceEqual(writtenSoFar));
int previousAvailable = output.FreeCapacity;
Span<T> span = output.GetSpan(500);
Assert.True(span.Length >= 500);
Assert.True(output.FreeCapacity >= 500);
Assert.True(output.FreeCapacity > previousAvailable);
Assert.Equal(writtenSoFar.Length, output.WrittenCount);
Assert.False(writtenSoFar.SequenceEqual(span.Slice(0, output.WrittenCount)));
Memory<T> memory = output.GetMemory();
Span<T> memorySpan = memory.Span;
Assert.True(span.Length >= 500);
Assert.True(memorySpan.Length >= 500);
Assert.Equal(span.Length, memorySpan.Length);
for (int i = 0; i < span.Length; i++)
{
Assert.Equal(default, span[i]);
Assert.Equal(default, memorySpan[i]);
}
memory = output.GetMemory(500);
memorySpan = memory.Span;
Assert.True(memorySpan.Length >= 500);
Assert.Equal(span.Length, memorySpan.Length);
for (int i = 0; i < memorySpan.Length; i++)
{
Assert.Equal(default, memorySpan[i]);
}
}
}
[Fact]
public void GetSpanShouldAtleastDoubleWhenGrowing()
{
var output = new ArrayBufferWriter<T>(256);
WriteData(output, 100);
int previousAvailable = output.FreeCapacity;
_ = output.GetSpan(previousAvailable);
Assert.Equal(previousAvailable, output.FreeCapacity);
_ = output.GetSpan(previousAvailable + 1);
Assert.True(output.FreeCapacity >= previousAvailable * 2);
}
[Fact]
public void GetSpanOnlyGrowsAboveThreshold()
{
{
var output = new ArrayBufferWriter<T>();
_ = output.GetSpan();
int previousAvailable = output.FreeCapacity;
for (int i = 0; i < 10; i++)
{
_ = output.GetSpan();
Assert.Equal(previousAvailable, output.FreeCapacity);
}
}
{
var output = new ArrayBufferWriter<T>();
_ = output.GetSpan(10);
int previousAvailable = output.FreeCapacity;
for (int i = 0; i < 10; i++)
{
_ = output.GetSpan(previousAvailable);
Assert.Equal(previousAvailable, output.FreeCapacity);
}
}
}
[Fact]
public void InvalidGetMemoryAndSpan()
{
var output = new ArrayBufferWriter<T>();
WriteData(output, 2);
Assert.Throws<ArgumentException>(() => output.GetSpan(-1));
Assert.Throws<ArgumentException>(() => output.GetMemory(-1));
}
[Fact]
public void MultipleCallsToGetSpan()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
return;
}
var output = new ArrayBufferWriter<T>(300);
Assert.True(MemoryMarshal.TryGetArray(output.GetMemory(), out ArraySegment<T> array));
GCHandle pinnedArray = GCHandle.Alloc(array.Array, GCHandleType.Pinned);
try
{
int previousAvailable = output.FreeCapacity;
Assert.True(previousAvailable >= 300);
Assert.True(output.Capacity >= 300);
Assert.Equal(previousAvailable, output.Capacity);
Span<T> span = output.GetSpan();
Assert.True(span.Length >= previousAvailable);
Assert.True(span.Length >= 256);
Span<T> newSpan = output.GetSpan();
Assert.Equal(span.Length, newSpan.Length);
unsafe
{
void* pSpan = Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
void* pNewSpan = Unsafe.AsPointer(ref MemoryMarshal.GetReference(newSpan));
Assert.Equal((IntPtr)pSpan, (IntPtr)pNewSpan);
}
Assert.Equal(span.Length, output.GetSpan().Length);
}
finally
{
pinnedArray.Free();
}
}
protected abstract void WriteData(IBufferWriter<T> bufferWriter, int numBytes);
public static IEnumerable<object[]> SizeHints
{
get
{
return new List<object[]>
{
new object[] { 0 },
new object[] { 1 },
new object[] { 2 },
new object[] { 3 },
new object[] { 99 },
new object[] { 100 },
new object[] { 101 },
new object[] { 255 },
new object[] { 256 },
new object[] { 257 },
new object[] { 1000 },
new object[] { 2000 },
};
}
}
}
}
| |
// 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 ShiftRightArithmeticInt3232()
{
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt3232();
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();
// 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();
// 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 ImmUnaryOpTest__ShiftRightArithmeticInt3232
{
private struct TestStruct
{
public Vector128<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticInt3232 testClass)
{
var result = Sse2.ShiftRightArithmetic(_fld, 32);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ImmUnaryOpTest__ShiftRightArithmeticInt3232()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public ImmUnaryOpTest__ShiftRightArithmeticInt3232()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftRightArithmetic(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftRightArithmetic(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftRightArithmetic(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftRightArithmetic(
_clsVar,
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightArithmetic(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt3232();
var result = Sse2.ShiftRightArithmetic(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftRightArithmetic(_fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftRightArithmetic(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
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(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(firstOp[0] >> 31) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(firstOp[i] >> 31) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightArithmetic)}<Int32>(Vector128<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright 2007-2008 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.
namespace MassTransit.Pipeline.Inspectors
{
using System;
using System.Linq;
using System.Text;
using Batch;
using Batch.Pipeline;
using Distributor.Pipeline;
using Saga;
using Saga.Pipeline;
using Sinks;
public class PipelineViewer :
PipelineInspectorBase<PipelineViewer>
{
private readonly StringBuilder _text = new StringBuilder();
private int _depth;
public string Text
{
get { return _text.ToString(); }
}
protected override void IncreaseDepth()
{
_depth++;
}
protected override void DecreaseDepth()
{
_depth--;
}
public bool Inspect(MessagePipeline element)
{
Append("Pipeline");
return true;
}
public bool Inspect<TMessage>(MessageRouter<TMessage> element) where TMessage : class
{
Append(string.Format("Routed ({0})", typeof (TMessage).ToFriendlyName()));
return true;
}
public bool Inspect<TMessage, TBatchId>(BatchMessageRouter<TMessage, TBatchId> element)
where TMessage : class, BatchedBy<TBatchId>
{
Append(string.Format("Batch Routed ({0})", typeof (TMessage).Name));
return true;
}
public bool Inspect<TMessage, TBatchId>(BatchCombiner<TMessage, TBatchId> element)
where TMessage : class, BatchedBy<TBatchId>
{
Append(string.Format("Batch Combiner ({0}) [{1}]", typeof (TMessage).Name, element.BatchId));
return true;
}
public bool Inspect<TMessage>(MessageFilter<TMessage> element) where TMessage : class
{
Append(string.Format("Filtered '{0}' ({1})", element.Description, typeof (TMessage).Name));
return true;
}
public bool Inspect(MessageInterceptor element)
{
Append(string.Format("Interceptor"));
return true;
}
public bool Inspect<TMessage>(InstanceMessageSink<TMessage> sink) where TMessage : class
{
Append(string.Format("Consumed by Instance ({0})", typeof (TMessage).Name));
return true;
}
public bool Inspect<TMessage>(DistributorMessageSink<TMessage> sink) where TMessage : class
{
Append(string.Format("Distributor ({0})", typeof (TMessage).Name));
return true;
}
public bool Inspect<TSaga, TMessage>(SagaWorkerMessageSink<TSaga, TMessage> sink) where TMessage : class
where TSaga : SagaStateMachine<TSaga>, ISaga
{
Append(string.Format("Saga Distributor Worker ({0} - {1})", typeof(TSaga).Name, typeof (TMessage).Name));
return true;
}
public bool Inspect<TMessage>(WorkerMessageSink<TMessage> sink) where TMessage : class
{
Type messageType = typeof (TMessage).GetGenericArguments().First();
Append(string.Format("Distributor Worker ({0})", messageType.Name));
return true;
}
public bool Inspect<TMessage>(EndpointMessageSink<TMessage> sink) where TMessage : class
{
Append(string.Format("Send {0} to Endpoint {1}", typeof (TMessage).Name, sink.Address));
return true;
}
public bool Inspect<TMessage>(IPipelineSink<TMessage> sink) where TMessage : class
{
Append(string.Format("Unknown Message Sink {0} ({1})", sink.GetType(), typeof (TMessage).Name));
return true;
}
public bool Inspect<TMessage, TKey>(CorrelatedMessageRouter<TMessage, TKey> sink)
where TMessage : class, CorrelatedBy<TKey>
{
Append(string.Format("Correlated by {1} ({0})", typeof (TMessage).Name, typeof (TKey).Name));
return true;
}
public bool Inspect<TMessage, TKey>(CorrelatedMessageSinkRouter<TMessage, TKey> sink)
where TMessage : class, CorrelatedBy<TKey>
{
Append(string.Format("Routed for Correlation Id {1} ({0})", typeof (TMessage).Name, sink.CorrelationId));
return true;
}
public bool Inspect<TComponent, TMessage>(ComponentMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : class, Consumes<TMessage>.All
{
Type componentType = typeof (TComponent);
string componentName = componentType.IsGenericType ? componentType.GetGenericTypeDefinition().FullName : componentType.FullName;
Append(string.Format("Consumed by Component {0} ({1})", componentName, typeof (TMessage).Name));
return true;
}
public bool Inspect<TComponent, TMessage>(CorrelatedSagaMessageSink<TComponent, TMessage> sink)
where TMessage : class, CorrelatedBy<Guid>
where TComponent : class, Consumes<TMessage>.All, ISaga
{
Type componentType = typeof (TComponent);
string componentName = componentType.IsGenericType ? componentType.GetGenericTypeDefinition().FullName : componentType.FullName;
string policyDescription = GetPolicy(sink.Policy);
Append(string.Format("{0} Saga {1} ({2})", policyDescription, componentName, typeof (TMessage).Name));
return true;
}
private string GetPolicy<TComponent, TMessage>(ISagaPolicy<TComponent, TMessage> policy)
where TComponent : class, ISaga
{
string description;
Type policyType = policy.GetType().GetGenericTypeDefinition();
if (policyType == typeof (InitiatingSagaPolicy<,>))
description = "Initiates New";
else if (policyType == typeof (ExistingSagaPolicy<,>))
description = "Orchestrates Existing";
else if (policyType == typeof (CreateOrUseExistingSagaPolicy<,>))
description = "Initiates New Or Orchestrates Existing";
else
description = policyType.Name;
return description;
}
public bool Inspect<TComponent, TMessage>(PropertySagaMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : class, Consumes<TMessage>.All, ISaga
{
Type componentType = typeof (TComponent);
string componentName = componentType.IsGenericType ? componentType.GetGenericTypeDefinition().FullName : componentType.FullName;
string policyDescription = GetPolicy(sink.Policy);
string expression = sink.Selector.ToString();
Append(string.Format("{0} Saga {1} ({2}): {3}", policyDescription, componentName, typeof (TMessage).Name, expression));
return true;
}
public bool Inspect<TComponent, TMessage>(PropertySagaStateMachineMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : SagaStateMachine<TComponent>, ISaga
{
Type componentType = typeof (TComponent);
string componentName = componentType.IsGenericType ? componentType.GetGenericTypeDefinition().FullName : componentType.FullName;
string policyDescription = GetPolicy(sink.Policy);
string expression = sink.Selector.ToString();
Append(string.Format("{0} Saga {1} ({2}): {3}", policyDescription, componentName, typeof (TMessage).Name, expression));
return true;
}
public bool Inspect<TComponent, TMessage>(CorrelatedSagaStateMachineMessageSink<TComponent, TMessage> sink)
where TMessage : class, CorrelatedBy<Guid>
where TComponent : SagaStateMachine<TComponent>, ISaga
{
Type componentType = typeof (TComponent);
string componentName = componentType.IsGenericType ? componentType.GetGenericTypeDefinition().FullName : componentType.FullName;
string policyDescription = GetPolicy(sink.Policy);
Append(string.Format("{0} SagaStateMachine {1} ({2})", policyDescription, componentName, typeof (TMessage).Name));
return true;
}
public bool Inspect<TComponent, TMessage>(SelectedComponentMessageSink<TComponent, TMessage> sink)
where TMessage : class
where TComponent : class, Consumes<TMessage>.Selected
{
Append(string.Format("Conditionally Consumed by Component {0} ({1})", typeof (TComponent).FullName, typeof (TMessage).Name));
return true;
}
public bool Inspect<TInput, TOutput>(MessageTranslator<TInput, TOutput> translator) where TInput : class where TOutput : class, TInput
{
Append(string.Format("Translated from {0} to {1}", typeof (TInput).FullName, typeof (TOutput).FullName));
return true;
}
private void Pad()
{
_text.Append(new string('\t', _depth));
}
private void Append(string text)
{
Pad();
_text.AppendFormat(text).AppendLine();
}
public static void Trace(IMessagePipeline pipeline)
{
PipelineViewer viewer = new PipelineViewer();
pipeline.Inspect(viewer);
System.Diagnostics.Trace.WriteLine(viewer.Text);
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Data;
using System.Collections;
namespace fyiReporting.Data
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class XmlCommand : IDbCommand
{
XmlConnection _xc; // connection we're running under
string _cmd; // command to execute
// parsed constituents of the command
string _Url; // url of the xml file
string _RowsXPath; // XPath specifying rows selection
ArrayList _ColumnsXPath; // XPath for each column
string _Type; // type of request
DataParameterCollection _Parameters = new DataParameterCollection();
public XmlCommand(XmlConnection conn)
{
_xc = conn;
}
internal string Url
{
get
{
// Check to see if "Url" or "@Url" is a parameter
IDbDataParameter dp= _Parameters["Url"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Url"] as IDbDataParameter;
// Then check to see if the Url value is a parameter?
if (dp == null)
dp = _Parameters[_Url] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _Url; // don't pass null; pass existing value
return _Url; // the value must be a constant
}
set {_Url = value;}
}
internal string RowsXPath
{
get
{
IDbDataParameter dp= _Parameters["RowsXPath"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@RowsXPath"] as IDbDataParameter;
// Then check to see if the RowsXPath value is a parameter?
if (dp == null)
dp = _Parameters[_RowsXPath] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _RowsXPath; // don't pass null; pass existing value
return _RowsXPath; // the value must be a constant
}
set {_RowsXPath = value;}
}
internal ArrayList ColumnsXPath
{
get {return _ColumnsXPath;}
set {_ColumnsXPath = value;}
}
internal string Type
{
get {return _Type;}
set {_Type = value;}
}
#region IDbCommand Members
public void Cancel()
{
throw new NotImplementedException("Cancel not implemented");
}
public void Prepare()
{
return; // Prepare is a noop
}
public System.Data.CommandType CommandType
{
get
{
throw new NotImplementedException("CommandType not implemented");
}
set
{
throw new NotImplementedException("CommandType not implemented");
}
}
public IDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
if (!(behavior == CommandBehavior.SingleResult ||
behavior == CommandBehavior.SchemaOnly))
throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only.");
return new XmlDataReader(behavior, _xc, this);
}
IDataReader System.Data.IDbCommand.ExecuteReader()
{
return ExecuteReader(System.Data.CommandBehavior.SingleResult);
}
public object ExecuteScalar()
{
throw new NotImplementedException("ExecuteScalar not implemented");
}
public int ExecuteNonQuery()
{
throw new NotImplementedException("ExecuteNonQuery not implemented");
}
public int CommandTimeout
{
get
{
return 0;
}
set
{
throw new NotImplementedException("CommandTimeout not implemented");
}
}
public IDbDataParameter CreateParameter()
{
return new XmlDataParameter();
}
public IDbConnection Connection
{
get
{
return this._xc;
}
set
{
throw new NotImplementedException("Setting Connection not implemented");
}
}
public System.Data.UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
set
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
}
public string CommandText
{
get
{
return this._cmd;
}
set
{
// Parse the command string for keyword value pairs separated by ';'
string[] args = value.Split(';');
string url=null;
string[] colxpaths=null;
string rowsxpath=null;
string type="both"; // assume we want both attributes and elements
foreach(string arg in args)
{
string[] param = arg.Trim().Split('=');
if (param == null || param.Length != 2)
continue;
string key = param[0].Trim().ToLower();
string val = param[1];
switch (key)
{
case "url":
case "file":
url = val;
break;
case "rowsxpath":
rowsxpath = val;
break;
case "type":
{
type = val.Trim().ToLower();
if (!(type == "attributes" || type == "elements" || type == "both"))
throw new ArgumentException(string.Format("type '{0}' is invalid. Must be 'attributes', 'elements' or 'both'", val));
break;
}
case "columnsxpath":
// column list is separated by ','
colxpaths = val.Trim().Split(',');
break;
default:
throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0]));
}
}
// User must specify both the url and the RowsXPath
if (url == null)
throw new ArgumentException("CommandText requires a 'Url=' parameter.");
if (rowsxpath == null)
throw new ArgumentException("CommandText requires a 'RowsXPath=' parameter.");
_cmd = value;
_Url = url;
_Type = type;
_RowsXPath = rowsxpath;
if (colxpaths != null)
_ColumnsXPath = new ArrayList(colxpaths);
}
}
public IDataParameterCollection Parameters
{
get
{
return _Parameters;
}
}
public IDbTransaction Transaction
{
get
{
throw new NotImplementedException("Transaction not implemented");
}
set
{
throw new NotImplementedException("Transaction not implemented");
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose of
}
#endregion
}
}
| |
using NSubstitute;
using NuKeeper.Abstractions.CollaborationPlatform;
using NuKeeper.Abstractions.Configuration;
using NuKeeper.Abstractions.Logging;
using NuKeeper.Abstractions.Output;
using NuKeeper.Collaboration;
using NuKeeper.Commands;
using NuKeeper.GitHub;
using NuKeeper.Inspection.Logging;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NuKeeper.Abstractions.Git;
using NuKeeper.AzureDevOps;
namespace NuKeeper.Tests.Commands
{
[TestFixture]
public class OrganisationCommandTests
{
private static CollaborationFactory GetCollaborationFactory(Func<IGitDiscoveryDriver, IEnvironmentVariablesProvider, ISettingsReader> createSettingsReader)
{
var environmentVariablesProvider = Substitute.For<IEnvironmentVariablesProvider>();
return new CollaborationFactory(
new ISettingsReader[] { createSettingsReader(new MockedGitDiscoveryDriver(), environmentVariablesProvider) },
Substitute.For<INuKeeperLogger>()
);
}
[Test]
public async Task ShouldCallEngineAndNotSucceedWithoutParams()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e));
var command = new OrganisationCommand(engine, logger, fileSettings, collaborationFactory);
var status = await command.OnExecute();
Assert.That(status, Is.EqualTo(-1));
await engine
.DidNotReceive()
.Run(Arg.Any<SettingsContainer>());
}
[Test]
public async Task ShouldCallEngineAndSucceedWithRequiredGithubParams()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e));
var command = new OrganisationCommand(engine, logger, fileSettings, collaborationFactory);
command.PersonalAccessToken = "abc";
command.OrganisationName = "testOrg";
var status = await command.OnExecute();
Assert.That(status, Is.EqualTo(0));
await engine
.Received(1)
.Run(Arg.Any<SettingsContainer>());
}
[Test]
public async Task ShouldCallEngineAndSucceedWithRequiredAzureDevOpsParams()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var collaborationFactory = GetCollaborationFactory((d, e) => new AzureDevOpsSettingsReader(d, e));
var command = new OrganisationCommand(engine, logger, fileSettings, collaborationFactory);
command.PersonalAccessToken = "abc";
command.OrganisationName = "testOrg";
command.ApiEndpoint = "https://dev.azure.com/org";
var status = await command.OnExecute();
Assert.That(status, Is.EqualTo(0));
await engine
.Received(1)
.Run(Arg.Any<SettingsContainer>());
}
[Test]
public async Task ShouldPopulateSettings()
{
var fileSettings = FileSettings.Empty();
var (settings, platformSettings) = await CaptureSettings(fileSettings);
Assert.That(platformSettings, Is.Not.Null);
Assert.That(platformSettings.Token, Is.Not.Null);
Assert.That(platformSettings.Token, Is.EqualTo("testToken"));
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Scope, Is.EqualTo(ServerScope.Organisation));
Assert.That(settings.SourceControlServerSettings.Repository, Is.Null);
Assert.That(settings.SourceControlServerSettings.OrganisationName, Is.EqualTo("testOrg"));
}
[Test]
public async Task EmptyFileResultsInDefaultSettings()
{
var fileSettings = FileSettings.Empty();
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.UserSettings, Is.Not.Null);
Assert.That(settings.BranchSettings, Is.Not.Null);
Assert.That(settings.PackageFilters.MinimumAge, Is.EqualTo(TimeSpan.FromDays(7)));
Assert.That(settings.PackageFilters.Excludes, Is.Null);
Assert.That(settings.PackageFilters.Includes, Is.Null);
Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(3));
Assert.That(settings.UserSettings.AllowedChange, Is.EqualTo(VersionChange.Major));
Assert.That(settings.UserSettings.NuGetSources, Is.Null);
Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.Console));
Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Text));
Assert.That(settings.BranchSettings.BranchNameTemplate, Is.Null);
Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(10));
Assert.That(settings.BranchSettings.DeleteBranchAfterMerge, Is.EqualTo(true));
Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Null);
Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Null);
}
[Test]
public async Task WillReadApiFromFile()
{
var fileSettings = new FileSettings
{
Api = "http://github.contoso.com/"
};
var (_, platformSettings) = await CaptureSettings(fileSettings);
Assert.That(platformSettings, Is.Not.Null);
Assert.That(platformSettings.BaseApiUrl, Is.Not.Null);
Assert.That(platformSettings.BaseApiUrl, Is.EqualTo(new Uri("http://github.contoso.com/")));
}
[Test]
public async Task WillReadLabelFromFile()
{
var fileSettings = new FileSettings
{
Label = new List<string> { "testLabel" }
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Labels, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Labels, Has.Count.EqualTo(1));
Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("testLabel"));
}
[Test]
public async Task WillReadRepoFiltersFromFile()
{
var fileSettings = new FileSettings
{
IncludeRepos = "foo",
ExcludeRepos = "bar"
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.IncludeRepos.ToString(), Is.EqualTo("foo"));
Assert.That(settings.SourceControlServerSettings.ExcludeRepos.ToString(), Is.EqualTo("bar"));
}
[Test]
public async Task WillReadMaxPackageUpdatesFromFile()
{
var fileSettings = new FileSettings
{
MaxPackageUpdates = 42
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(42));
}
[Test]
public async Task WillReadMaxRepoFromFile()
{
var fileSettings = new FileSettings
{
MaxRepo = 42
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(42));
}
[Test]
public async Task WillReadBranchNamePrefixFromFile()
{
var testTemplate = "nukeeper/MyBranch";
var fileSettings = new FileSettings
{
BranchNameTemplate = testTemplate
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.BranchSettings, Is.Not.Null);
Assert.That(settings.BranchSettings.BranchNameTemplate, Is.EqualTo(testTemplate));
}
[Test]
public async Task CommandLineWillOverrideIncludeRepo()
{
var fileSettings = new FileSettings
{
IncludeRepos = "foo",
ExcludeRepos = "bar"
};
var (settings, _) = await CaptureSettings(fileSettings, true);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.IncludeRepos.ToString(), Is.EqualTo("IncludeFromCommand"));
Assert.That(settings.SourceControlServerSettings.ExcludeRepos.ToString(), Is.EqualTo("bar"));
}
[Test]
public async Task CommandLineWillOverrideExcludeRepo()
{
var fileSettings = new FileSettings
{
IncludeRepos = "foo",
ExcludeRepos = "bar"
};
var (settings, _) = await CaptureSettings(fileSettings, false, true);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.IncludeRepos.ToString(), Is.EqualTo("foo"));
Assert.That(settings.SourceControlServerSettings.ExcludeRepos.ToString(), Is.EqualTo("ExcludeFromCommand"));
}
[Test]
public async Task CommandLineWillOverrideForkMode()
{
var (_, platformSettings) = await CaptureSettings(FileSettings.Empty(), false, false, null, ForkMode.PreferSingleRepository);
Assert.That(platformSettings, Is.Not.Null);
Assert.That(platformSettings.ForkMode, Is.Not.Null);
Assert.That(platformSettings.ForkMode, Is.EqualTo(ForkMode.PreferSingleRepository));
}
[Test]
public async Task CommandLineWillOverrideMaxRepo()
{
var fileSettings = new FileSettings
{
MaxRepo = 12,
};
var (settings, _) = await CaptureSettings(fileSettings, false, true, 22);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(22));
}
public static async Task<(SettingsContainer fileSettings, CollaborationPlatformSettings platformSettings)> CaptureSettings(
FileSettings settingsIn,
bool addCommandRepoInclude = false,
bool addCommandRepoExclude = false,
int? maxRepo = null,
ForkMode? forkMode = null)
{
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
SettingsContainer settingsOut = null;
var engine = Substitute.For<ICollaborationEngine>();
await engine.Run(Arg.Do<SettingsContainer>(x => settingsOut = x));
fileSettings.GetSettings().Returns(settingsIn);
var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e));
var command = new OrganisationCommand(engine, logger, fileSettings, collaborationFactory);
command.PersonalAccessToken = "testToken";
command.OrganisationName = "testOrg";
if (addCommandRepoInclude)
{
command.IncludeRepos = "IncludeFromCommand";
}
if (addCommandRepoExclude)
{
command.ExcludeRepos = "ExcludeFromCommand";
}
if (forkMode != null)
{
command.ForkMode = forkMode;
}
command.MaxRepositoriesChanged = maxRepo;
await command.OnExecute();
return (settingsOut, collaborationFactory.Settings);
}
}
}
| |
/*
* 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 java = biz.ritter.javapi;
namespace biz.ritter.javapi.util.logging
{
/**
* A {@code FileHandler} writes logging records into a specified file or a
* rotating set of files.
* <p>
* When a set of files is used and a given amount of data has been written to
* one file, then this file is closed and another file is opened. The name of
* these files are generated by given name pattern, see below for details.
* When the files have all been filled the Handler returns to the first and goes
* through the set again.
* <p>
* By default, the I/O buffering mechanism is enabled, but when each log record
* is complete, it is flushed out.
* <p>
* {@code XMLFormatter} is the default formatter for {@code FileHandler}.
* <p>
* {@code FileHandler} reads the following {@code LogManager} properties for
* initialization; if a property is not defined or has an invalid value, a
* default value is used.
* <ul>
* <li>java.util.logging.FileHandler.append specifies whether this
* {@code FileHandler} should append onto existing files, defaults to
* {@code false}.</li>
* <li>java.util.logging.FileHandler.count specifies how many output files to
* rotate, defaults to 1.</li>
* <li>java.util.logging.FileHandler.filter specifies the {@code Filter} class
* name, defaults to no {@code Filter}.</li>
* <li>java.util.logging.FileHandler.formatter specifies the {@code Formatter}
* class, defaults to {@code java.util.logging.XMLFormatter}.</li>
* <li>java.util.logging.FileHandler.encoding specifies the character set
* encoding name, defaults to the default platform encoding.</li>
* <li>java.util.logging.FileHandler.level specifies the level for this
* {@code Handler}, defaults to {@code Level.ALL}.</li>
* <li>java.util.logging.FileHandler.limit specifies the maximum number of
* bytes to write to any one file, defaults to zero, which means no limit.</li>
* <li>java.util.logging.FileHandler.pattern specifies name pattern for the
* output files. See below for details. Defaults to "%h/java%u.log".</li>
* </ul>
* <p>
* Name pattern is a string that may include some special substrings, which will
* be replaced to generate output files:
* <ul>
* <li>"/" represents the local pathname separator</li>
* <li>"%g" represents the generation number to distinguish rotated logs</li>
* <li>"%h" represents the home directory of the current user, which is
* specified by "user.home" system property</li>
* <li>"%t" represents the system's temporary directory</li>
* <li>"%u" represents a unique number to resolve conflicts</li>
* <li>"%%" represents the percent sign character '%'</li>
* </ul>
* <p>
* Normally, the generation numbers are not larger than the given file count and
* follow the sequence 0, 1, 2.... If the file count is larger than one, but the
* generation field("%g") has not been specified in the pattern, then the
* generation number after a dot will be added to the end of the file name.
* <p>
* The "%u" unique field is used to avoid conflicts and is set to 0 at first. If
* one {@code FileHandler} tries to open the filename which is currently in use
* by another process, it will repeatedly increment the unique number field and
* try again. If the "%u" component has not been included in the file name
* pattern and some contention on a file does occur, then a unique numerical
* value will be added to the end of the filename in question immediately to the
* right of a dot. The generation of unique IDs for avoiding conflicts is only
* guaranteed to work reliably when using a local disk file system.
*/
public class FileHandler : StreamHandler {
private const String LCK_EXT = ".lck"; //$NON-NLS-1$
private const int DEFAULT_COUNT = 1;
private const int DEFAULT_LIMIT = 0;
private const bool DEFAULT_APPEND = false;
private const String DEFAULT_PATTERN = "%h/java%u.log"; //$NON-NLS-1$
// maintain all file locks hold by this process
private static readonly java.util.Hashtable<String, java.nio.channels.FileLock> allLocks = new java.util.Hashtable<String, java.nio.channels.FileLock>();
// the count of files which the output cycle through
private int count;
// the size limitation in byte of log file
private int limit;
// whether the FileHandler should open a existing file for output in append
// mode
private bool append;
// the pattern for output file name
private String pattern;
// maintain a LogManager instance for convenience
private LogManager manager;
// output stream, which can measure the output file length
private MeasureOutputStream output;
// used output file
private java.io.File[] files;
// output file lock
java.nio.channels.FileLock lockJ = null;
// current output file name
String fileName = null;
// current unique ID
int uniqueID = -1;
/**
* Construct a {@code FileHandler} using {@code LogManager} properties or
* their default value.
*
* @throws IOException
* if any I/O error occurs.
* @throws SecurityException
* if a security manager exists and it determines that the
* caller does not have the required permissions to control this
* handler; required permissions include
* {@code LogPermission("control")},
* {@code FilePermission("write")} etc.
*/
public FileHandler(){// throws IOException {
init(null, null, null, null);
}
// init properties
private void init(String p, java.lang.Boolean a, java.lang.Integer l, java.lang.Integer c)
{//throws IOException {
// check access
manager = LogManager.getLogManager();
manager.checkAccess();
initProperties(p, a, l, c);
initOutputFiles();
}
private void initOutputFiles() {//throws FileNotFoundException, IOException {
while (true) {
// try to find a unique file which is not locked by other process
uniqueID++;
// FIXME: improve performance here
for (int generation = 0; generation < count; generation++) {
// cache all file names for rotation use
files[generation] = new java.io.File(parseFileName(generation));
}
fileName = files[0].getAbsolutePath();
lock (allLocks) {
/*
* if current process has held lock for this fileName continue
* to find next file
*/
if (null != allLocks.get(fileName)) {
continue;
}
if (files[0].exists()
&& (!append || files[0].length() >= limit)) {
for (int i = count - 1; i > 0; i--) {
if (files[i].exists()) {
files[i].delete();
}
files[i - 1].renameTo(files[i]);
}
}
java.io.FileOutputStream fileStream = new java.io.FileOutputStream(fileName
+ LCK_EXT);
java.nio.channels.FileChannel channel = fileStream.getChannel();
/*
* if lock is unsupported and IOException thrown, just let the
* IOException throws out and exit otherwise it will go into an
* undead cycle
*/
lockJ = channel.tryLock();
if (null == lockJ) {
try {
fileStream.close();
} catch (Exception e) {
// ignore
}
continue;
}
allLocks.put(fileName, lockJ);
break;
}
}
output = new MeasureOutputStream(new java.io.BufferedOutputStream(
new java.io.FileOutputStream(fileName, append)), files[0].length());
setOutputStream(output);
}
private void initProperties(String p, java.lang.Boolean a, java.lang.Integer l, java.lang.Integer c) {
base.initProperties("ALL", null, "java.util.logging.XMLFormatter",
null);
String className = this.getClass().getName();
pattern = (null == p) ? getStringProperty(className + ".pattern",
DEFAULT_PATTERN) : p;
if (null == pattern || "".equals(pattern)) {
// logging.19=Pattern cannot be empty
throw new java.lang.NullPointerException("Pattern cannot be empty");
}
append = (null == a) ? getBooleanProperty(className + ".append",
DEFAULT_APPEND) : a.booleanValue();
count = (null == c) ? getIntProperty(className + ".count",
DEFAULT_COUNT) : c.intValue();
limit = (null == l) ? getIntProperty(className + ".limit",
DEFAULT_LIMIT) : l.intValue();
count = count < 1 ? DEFAULT_COUNT : count;
limit = limit < 0 ? DEFAULT_LIMIT : limit;
files = new java.io.File[count];
}
void findNextGeneration() {
base.close();
for (int i = count - 1; i > 0; i--) {
if (files[i].exists()) {
files[i].delete();
}
files[i - 1].renameTo(files[i]);
}
try {
output = new MeasureOutputStream(new java.io.BufferedOutputStream(
new java.io.FileOutputStream(files[0])));
} catch (java.io.FileNotFoundException e1) {
// logging.1A=Error happened when open log file.
this.getErrorManager().error("Error happened when open log file.", //$NON-NLS-1$
e1, ErrorManager.OPEN_FAILURE);
}
setOutputStream(output);
}
/**
* Transform the pattern to the valid file name, replacing any patterns, and
* applying generation and uniqueID if present
*
* @param gen
* generation of this file
* @return transformed filename ready for use
*/
private String parseFileName(int gen) {
int cur = 0;
int next = 0;
bool hasUniqueID = false;
bool hasGeneration = false;
// TODO privilege code?
String homePath = java.lang.SystemJ.getProperty("user.home"); //$NON-NLS-1$
if (homePath == null) {
throw new java.lang.NullPointerException();
}
bool homePathHasSepEnd = homePath.endsWith(java.io.File.separator);
String tempPath = java.lang.SystemJ.getProperty("java.io.tmpdir"); //$NON-NLS-1$
tempPath = tempPath == null ? homePath : tempPath;
bool tempPathHasSepEnd = tempPath.endsWith(java.io.File.separator);
java.lang.StringBuilder sb = new java.lang.StringBuilder();
pattern = pattern.replace('/', java.io.File.separatorChar);
char[] value = pattern.toCharArray();
while ((next = pattern.indexOf('%', cur)) >= 0) {
if (++next < pattern.length()) {
switch (value[next]) {
case 'g':
sb.append(value, cur, next - cur - 1).append(gen);
hasGeneration = true;
break;
case 'u':
sb.append(value, cur, next - cur - 1).append(uniqueID);
hasUniqueID = true;
break;
case 't':
/*
* we should probably try to do something cute here like
* lookahead for adjacent '/'
*/
sb.append(value, cur, next - cur - 1).append(tempPath);
if (!tempPathHasSepEnd) {
sb.append(java.io.File.separator);
}
break;
case 'h':
sb.append(value, cur, next - cur - 1).append(homePath);
if (!homePathHasSepEnd) {
sb.append(java.io.File.separator);
}
break;
case '%':
sb.append(value, cur, next - cur - 1).append('%');
break;
default:
sb.append(value, cur, next - cur);
break;
}
cur = ++next;
} else {
// fail silently
}
}
sb.append(value, cur, value.Length - cur);
if (!hasGeneration && count > 1) {
sb.append(".").append(gen); //$NON-NLS-1$
}
if (!hasUniqueID && uniqueID > 0) {
sb.append(".").append(uniqueID); //$NON-NLS-1$
}
return sb.toString();
}
// get bool LogManager property, if invalid value got, using default
// value
private bool getBooleanProperty(String key, bool defaultValue) {
String property = manager.getProperty(key);
if (null == property) {
return defaultValue;
}
bool result = defaultValue;
if ("true".equalsIgnoreCase(property)) { //$NON-NLS-1$
result = true;
} else if ("false".equalsIgnoreCase(property)) { //$NON-NLS-1$
result = false;
}
return result;
}
// get String LogManager property, if invalid value got, using default value
private String getStringProperty(String key, String defaultValue) {
String property = manager.getProperty(key);
return property == null ? defaultValue : property;
}
// get int LogManager property, if invalid value got, using default value
private int getIntProperty(String key, int defaultValue) {
String property = manager.getProperty(key);
int result = defaultValue;
if (null != property) {
try {
result = java.lang.Integer.parseInt(property);
} catch (Exception e) {
// ignore
}
}
return result;
}
/**
* Constructs a new {@code FileHandler}. The given name pattern is used as
* output filename, the file limit is set to zero (no limit), the file count
* is set to one; the remaining configuration is done using
* {@code LogManager} properties or their default values. This handler
* writes to only one file with no size limit.
*
* @param pattern
* the name pattern for the output file.
* @throws IOException
* if any I/O error occurs.
* @throws SecurityException
* if a security manager exists and it determines that the
* caller does not have the required permissions to control this
* handler; required permissions include
* {@code LogPermission("control")},
* {@code FilePermission("write")} etc.
* @throws IllegalArgumentException
* if the pattern is empty.
* @throws NullPointerException
* if the pattern is {@code null}.
*/
public FileHandler(String pattern){// throws IOException {
if (pattern.equals("")) { //$NON-NLS-1$
// logging.19=Pattern cannot be empty
throw new java.lang.IllegalArgumentException("Pattern cannot be empty"); //$NON-NLS-1$
}
init(pattern, null, java.lang.Integer.valueOf(DEFAULT_LIMIT), java.lang.Integer
.valueOf(DEFAULT_COUNT));
}
/**
* Construct a new {@code FileHandler}. The given name pattern is used as
* output filename, the file limit is set to zero (no limit), the file count
* is initialized to one and the value of {@code append} becomes the new
* instance's append mode. The remaining configuration is done using
* {@code LogManager} properties. This handler writes to only one file
* with no size limit.
*
* @param pattern
* the name pattern for the output file.
* @param append
* the append mode.
* @throws IOException
* if any I/O error occurs.
* @throws SecurityException
* if a security manager exists and it determines that the
* caller does not have the required permissions to control this
* handler; required permissions include
* {@code LogPermission("control")},
* {@code FilePermission("write")} etc.
* @throws IllegalArgumentException
* if {@code pattern} is empty.
* @throws NullPointerException
* if {@code pattern} is {@code null}.
*/
public FileHandler(String pattern, bool append) {//throws IOException {
if (pattern.equals("")) { //$NON-NLS-1$
throw new java.lang.IllegalArgumentException("Pattern cannot be empty"); //$NON-NLS-1$
}
init(pattern, java.lang.Boolean.valueOf(append), java.lang.Integer.valueOf(DEFAULT_LIMIT),
java.lang.Integer.valueOf(DEFAULT_COUNT));
}
/**
* Construct a new {@code FileHandler}. The given name pattern is used as
* output filename, the maximum file size is set to {@code limit} and the
* file count is initialized to {@code count}. The remaining configuration
* is done using {@code LogManager} properties. This handler is configured
* to write to a rotating set of count files, when the limit of bytes has
* been written to one output file, another file will be opened instead.
*
* @param pattern
* the name pattern for the output file.
* @param limit
* the data amount limit in bytes of one output file, can not be
* negative.
* @param count
* the maximum number of files to use, can not be less than one.
* @throws IOException
* if any I/O error occurs.
* @throws SecurityException
* if a security manager exists and it determines that the
* caller does not have the required permissions to control this
* handler; required permissions include
* {@code LogPermission("control")},
* {@code FilePermission("write")} etc.
* @throws IllegalArgumentException
* if {@code pattern} is empty, {@code limit < 0} or
* {@code count < 1}.
* @throws NullPointerException
* if {@code pattern} is {@code null}.
*/
public FileHandler(String pattern, int limit, int count){// throws IOException {
if (pattern.equals("")) { //$NON-NLS-1$
throw new java.lang.IllegalArgumentException("Pattern cannot be empty"); //$NON-NLS-1$
}
if (limit < 0 || count < 1) {
// logging.1B=The limit and count property must be larger than 0 and
// 1, respectively
throw new java.lang.IllegalArgumentException("The limit and count property must be larger than 0 and 1, respectively"); //$NON-NLS-1$
}
init(pattern, null, java.lang.Integer.valueOf(limit), java.lang.Integer.valueOf(count));
}
/**
* Construct a new {@code FileHandler}. The given name pattern is used as
* output filename, the maximum file size is set to {@code limit}, the file
* count is initialized to {@code count} and the append mode is set to
* {@code append}. The remaining configuration is done using
* {@code LogManager} properties. This handler is configured to write to a
* rotating set of count files, when the limit of bytes has been written to
* one output file, another file will be opened instead.
*
* @param pattern
* the name pattern for the output file.
* @param limit
* the data amount limit in bytes of one output file, can not be
* negative.
* @param count
* the maximum number of files to use, can not be less than one.
* @param append
* the append mode.
* @throws IOException
* if any I/O error occurs.
* @throws SecurityException
* if a security manager exists and it determines that the
* caller does not have the required permissions to control this
* handler; required permissions include
* {@code LogPermission("control")},
* {@code FilePermission("write")} etc.
* @throws IllegalArgumentException
* if {@code pattern} is empty, {@code limit < 0} or
* {@code count < 1}.
* @throws NullPointerException
* if {@code pattern} is {@code null}.
*/
public FileHandler(String pattern, int limit, int count, bool append)
{// throws IOException {
if (pattern.equals("")) { //$NON-NLS-1$
throw new java.lang.IllegalArgumentException("Pattern cannot be empty"); //$NON-NLS-1$
}
if (limit < 0 || count < 1) {
// logging.1B=The limit and count property must be larger than 0 and
// 1, respectively
throw new java.lang.IllegalArgumentException("The limit and count property must be larger than 0 and 1, respectively"); //$NON-NLS-1$
}
init(pattern, java.lang.Boolean.valueOf(append), java.lang.Integer.valueOf(limit), java.lang.Integer
.valueOf(count));
}
/**
* Flushes and closes all opened files.
*
* @throws SecurityException
* if a security manager exists and it determines that the
* caller does not have the required permissions to control this
* handler; required permissions include
* {@code LogPermission("control")},
* {@code FilePermission("write")} etc.
*/
public override void close() {
// release locks
base.close();
allLocks.remove(fileName);
try {
java.nio.channels.FileChannel channel = lockJ.channel();
lockJ.release();
channel.close();
java.io.File file = new java.io.File(fileName + LCK_EXT);
file.delete();
} catch (java.io.IOException e) {
// ignore
}
}
/**
* Publish a {@code LogRecord}.
*
* @param record
* the log record to publish.
*/
public override void publish(LogRecord record) {
lock (this) {
base.publish(record);
flush();
findNextGeneration();
}}
}
/**
* This output stream uses the decorator pattern to add measurement features
* to OutputStream which can detect the total size(in bytes) of output, the
* initial size can be set.
*/
class MeasureOutputStream : java.io.OutputStream {
java.io.OutputStream wrapped;
long length;
public MeasureOutputStream(java.io.OutputStream stream, long currentLength) {
wrapped = stream;
length = currentLength;
}
public MeasureOutputStream(java.io.OutputStream stream) :
this(stream, 0){
}
public override void write(int oneByte) {//throws IOException {
wrapped.write(oneByte);
length++;
}
public override void write(byte[] bytes) {//throws IOException {
wrapped.write(bytes);
length += bytes.Length;
}
public override void write(byte[] b, int off, int len) {//throws IOException {
wrapped.write(b, off, len);
length += len;
}
public override void close() {//throws IOException {
wrapped.close();
}
public override void flush() {//throws IOException {
wrapped.flush();
}
public long getLength() {
return length;
}
public void setLength(long newLength) {
length = newLength;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Globalization;
namespace System.IO.Packaging
{
/// <summary>
/// The package properties are a subset of the standard OLE property sets
/// SummaryInformation and DocumentSummaryInformation, and include such properties
/// as Title and Subject.
/// </summary>
/// <remarks>
/// <para>Setting a property to null deletes this property. 'null' is never strictly speaking
/// a property value, but an absence indicator.</para>
/// </remarks>
internal class PartBasedPackageProperties : PackageProperties
{
#region Constructors
internal PartBasedPackageProperties(Package package)
{
_package = package;
// Initialize literals as Xml Atomic strings.
_nameTable = PackageXmlStringTable.NameTable;
ReadPropertyValuesFromPackage();
// No matter what happens during initialization, the dirty flag should not be set.
_dirty = false;
}
#endregion Constructors
#region Public Properties
/// <value>
/// The primary creator. The identification is environment-specific and
/// can consist of a name, email address, employee ID, etc. It is
/// recommended that this value be only as verbose as necessary to
/// identify the individual.
/// </value>
public override string Creator
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Creator);
}
set
{
RecordNewBinding(PackageXmlEnum.Creator, value);
}
}
/// <value>
/// The title.
/// </value>
public override string Title
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Title);
}
set
{
RecordNewBinding(PackageXmlEnum.Title, value);
}
}
/// <value>
/// The topic of the contents.
/// </value>
public override string Subject
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Subject);
}
set
{
RecordNewBinding(PackageXmlEnum.Subject, value);
}
}
/// <value>
/// The category. This value is typically used by UI applications to create navigation
/// controls.
/// </value>
public override string Category
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Category);
}
set
{
RecordNewBinding(PackageXmlEnum.Category, value);
}
}
/// <value>
/// A delimited set of keywords to support searching and indexing. This
/// is typically a list of terms that are not available elsewhere in the
/// properties.
/// </value>
public override string Keywords
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Keywords);
}
set
{
RecordNewBinding(PackageXmlEnum.Keywords, value);
}
}
/// <value>
/// The description or abstract of the contents.
/// </value>
public override string Description
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Description);
}
set
{
RecordNewBinding(PackageXmlEnum.Description, value);
}
}
/// <value>
/// The type of content represented, generally defined by a specific
/// use and intended audience. Example values include "Whitepaper",
/// "Security Bulletin", and "Exam". (This property is distinct from
/// MIME content types as defined in RFC 2616.)
/// </value>
public override string ContentType
{
get
{
string contentType = GetPropertyValue(PackageXmlEnum.ContentType) as string;
return contentType;
}
set
{
RecordNewBinding(PackageXmlEnum.ContentType, value);
}
}
/// <value>
/// The status of the content. Example values include "Draft",
/// "Reviewed", and "Final".
/// </value>
public override string ContentStatus
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.ContentStatus);
}
set
{
RecordNewBinding(PackageXmlEnum.ContentStatus, value);
}
}
/// <value>
/// The version number. This value is set by the user or by the application.
/// </value>
public override string Version
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Version);
}
set
{
RecordNewBinding(PackageXmlEnum.Version, value);
}
}
/// <value>
/// The revision number. This value indicates the number of saves or
/// revisions. The application is responsible for updating this value
/// after each revision.
/// </value>
public override string Revision
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Revision);
}
set
{
RecordNewBinding(PackageXmlEnum.Revision, value);
}
}
/// <value>
/// The creation date and time.
/// </value>
public override Nullable<DateTime> Created
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.Created);
}
set
{
RecordNewBinding(PackageXmlEnum.Created, value);
}
}
/// <value>
/// The date and time of the last modification.
/// </value>
public override Nullable<DateTime> Modified
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.Modified);
}
set
{
RecordNewBinding(PackageXmlEnum.Modified, value);
}
}
/// <value>
/// The user who performed the last modification. The identification is
/// environment-specific and can consist of a name, email address,
/// employee ID, etc. It is recommended that this value be only as
/// verbose as necessary to identify the individual.
/// </value>
public override string LastModifiedBy
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.LastModifiedBy);
}
set
{
RecordNewBinding(PackageXmlEnum.LastModifiedBy, value);
}
}
/// <value>
/// The date and time of the last printing.
/// </value>
public override Nullable<DateTime> LastPrinted
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.LastPrinted);
}
set
{
RecordNewBinding(PackageXmlEnum.LastPrinted, value);
}
}
/// <value>
/// A language of the intellectual content of the resource
/// </value>
public override string Language
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Language);
}
set
{
RecordNewBinding(PackageXmlEnum.Language, value);
}
}
/// <value>
/// A unique identifier.
/// </value>
public override string Identifier
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Identifier);
}
set
{
RecordNewBinding(PackageXmlEnum.Identifier, value);
}
}
#endregion Public Properties
#region Internal Methods
// Invoked from Package.Flush.
// The expectation is that whatever is currently dirty will get flushed.
internal void Flush()
{
if (!_dirty)
return;
// Make sure there is a part to write to and that it contains
// the expected start markup.
EnsureXmlWriter();
// Write the property elements and clear _dirty.
SerializeDirtyProperties();
// add closing markup and close the writer.
CloseXmlWriter();
}
// Invoked from Package.Close.
internal void Close()
{
Flush();
}
#endregion Internal Methods
#region Private Methods
// The property store is implemented as a hash table of objects.
// Keys are taken from the set of string constants defined in this
// class and compared by their references rather than their values.
private object GetPropertyValue(PackageXmlEnum propertyName)
{
_package.ThrowIfWriteOnly();
if (!_propertyDictionary.ContainsKey(propertyName))
return null;
return _propertyDictionary[propertyName];
}
// Shim function to adequately cast the result of GetPropertyValue.
private Nullable<DateTime> GetDateTimePropertyValue(PackageXmlEnum propertyName)
{
object valueObject = GetPropertyValue(propertyName);
if (valueObject == null)
return null;
// If an object is there, it will be a DateTime (not a Nullable<DateTime>).
return (Nullable<DateTime>)valueObject;
}
// Set new property value.
// Override that sets the initializing flag to false to reflect the default
// situation: recording a binding to implement a value assignment.
private void RecordNewBinding(PackageXmlEnum propertyenum, object value)
{
RecordNewBinding(propertyenum, value, false /* not invoked at construction */, null);
}
// Set new property value.
// Null value is passed for deleting a property.
// While initializing, we are not assigning new values, and so the dirty flag should
// stay untouched.
private void RecordNewBinding(PackageXmlEnum propertyenum, object value, bool initializing, XmlReader reader)
{
// If we are reading values from the package, reader cannot be null
Debug.Assert(!initializing || reader != null);
if (!initializing)
_package.ThrowIfReadOnly();
// Case of an existing property.
if (_propertyDictionary.ContainsKey(propertyenum))
{
// Parsing should detect redundant entries.
if (initializing)
{
throw new XmlException(SR.Format(SR.DuplicateCorePropertyName, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Nullable<DateTime> values can be checked against null
if (value == null) // a deletion
{
_propertyDictionary.Remove(propertyenum);
}
else // an update
{
_propertyDictionary[propertyenum] = value;
}
// If the binding is an assignment rather than an initialization, set the dirty flag.
_dirty = !initializing;
}
// Case of an initial value being set for a property. If value is null, no need to do anything
else if (value != null)
{
_propertyDictionary.Add(propertyenum, value);
// If the binding is an assignment rather than an initialization, set the dirty flag.
_dirty = !initializing;
}
}
// Initialize object from property values found in package.
// All values will remain null if the package is not enabled for reading.
private void ReadPropertyValuesFromPackage()
{
Debug.Assert(_propertyPart == null); // This gets called exclusively from constructor.
// Don't try to read properties from the package it does not have read access
if (_package.FileOpenAccess == FileAccess.Write)
return;
_propertyPart = GetPropertyPart();
if (_propertyPart == null)
return;
ParseCorePropertyPart(_propertyPart);
}
// Locate core properties part using the package relationship that points to it.
private PackagePart GetPropertyPart()
{
// Find a package-wide relationship of type CoreDocumentPropertiesRelationshipType.
PackageRelationship corePropertiesRelationship = GetCorePropertiesRelationship();
if (corePropertiesRelationship == null)
return null;
// Retrieve the part referenced by its target URI.
if (corePropertiesRelationship.TargetMode != TargetMode.Internal)
throw new FileFormatException(SR.NoExternalTargetForMetadataRelationship);
PackagePart propertiesPart = null;
Uri propertiesPartUri = PackUriHelper.ResolvePartUri(
PackUriHelper.PackageRootUri,
corePropertiesRelationship.TargetUri);
if (!_package.PartExists(propertiesPartUri))
throw new FileFormatException(SR.DanglingMetadataRelationship);
propertiesPart = _package.GetPart(propertiesPartUri);
if (!propertiesPart.ValidatedContentType.AreTypeAndSubTypeEqual(s_coreDocumentPropertiesContentType))
{
throw new FileFormatException(SR.WrongContentTypeForPropertyPart);
}
return propertiesPart;
}
// Find a package-wide relationship of type CoreDocumentPropertiesRelationshipType.
private PackageRelationship GetCorePropertiesRelationship()
{
PackageRelationship propertiesPartRelationship = null;
foreach (PackageRelationship rel
in _package.GetRelationshipsByType(CoreDocumentPropertiesRelationshipType))
{
if (propertiesPartRelationship != null)
{
throw new FileFormatException(SR.MoreThanOneMetadataRelationships);
}
propertiesPartRelationship = rel;
}
return propertiesPartRelationship;
}
// Deserialize properties part.
private void ParseCorePropertyPart(PackagePart part)
{
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.NameTable = _nameTable;
using (Stream stream = part.GetStream(FileMode.Open, FileAccess.Read))
// Create a reader that uses _nameTable so as to use the set of tag literals
// in effect as a set of atomic identifiers.
using (XmlReader reader = XmlReader.Create(stream, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
if (reader.MoveToContent() != XmlNodeType.Element
|| (object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.PackageCorePropertiesNamespace)
|| (object)reader.LocalName != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.CoreProperties))
{
throw new XmlException(SR.CorePropertiesElementExpected,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// The schema is closed and defines no attributes on the root element.
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 0)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Iterate through property elements until EOF. Note the proper closing of all
// open tags is checked by the reader itself.
// This loop deals only with depth-1 start tags. Handling of element content
// is delegated to dedicated functions.
int attributesCount;
while (reader.Read() && reader.MoveToContent() != XmlNodeType.None)
{
// Ignore end-tags. We check element errors on opening tags.
if (reader.NodeType == XmlNodeType.EndElement)
continue;
// Any content markup that is not an element here is unexpected.
if (reader.NodeType != XmlNodeType.Element)
{
throw new XmlException(SR.PropertyStartTagExpected,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Any element below the root should open at level 1 exclusively.
if (reader.Depth != 1)
{
throw new XmlException(SR.NoStructuredContentInsideProperties,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
attributesCount = PackagingUtilities.GetNonXmlnsAttributeCount(reader);
// Property elements can occur in any order (xsd:all).
object localName = reader.LocalName;
PackageXmlEnum xmlStringIndex = PackageXmlStringTable.GetEnumOf(localName);
String valueType = PackageXmlStringTable.GetValueType(xmlStringIndex);
if (Array.IndexOf(s_validProperties, xmlStringIndex) == -1) // An unexpected element is an error.
{
throw new XmlException(
SR.Format(SR.InvalidPropertyNameInCorePropertiesPart, reader.LocalName),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Any element not in the valid core properties namespace is unexpected.
// The following is an object comparison, not a string comparison.
if ((object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlStringTable.GetXmlNamespace(xmlStringIndex)))
{
throw new XmlException(SR.UnknownNamespaceInCorePropertiesPart,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
if (String.CompareOrdinal(valueType, "String") == 0)
{
// The schema is closed and defines no attributes on this type of element.
if (attributesCount != 0)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
RecordNewBinding(xmlStringIndex, GetStringData(reader), true /*initializing*/, reader);
}
else if (String.CompareOrdinal(valueType, "DateTime") == 0)
{
int allowedAttributeCount = (object)reader.NamespaceURI ==
PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace)
? 1 : 0;
// The schema is closed and defines no attributes on this type of element.
if (attributesCount != allowedAttributeCount)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
if (allowedAttributeCount != 0)
{
ValidateXsiType(reader,
PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace),
W3cdtf);
}
RecordNewBinding(xmlStringIndex, GetDateData(reader), true /*initializing*/, reader);
}
else // An unexpected element is an error.
{
Debug.Assert(false, "Unknown value type for properties");
}
}
}
}
// This method validates xsi:type="dcterms:W3CDTF"
// The value of xsi:type is a qualified name. It should have a prefix that matches
// the xml namespace (ns) within the scope and the name that matches name
// The comparisons should be case-sensitive comparisons
internal static void ValidateXsiType(XmlReader reader, Object ns, string name)
{
// Get the value of xsi;type
String typeValue = reader.GetAttribute(PackageXmlStringTable.GetXmlString(PackageXmlEnum.Type),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
// Missing xsi:type
if (typeValue == null)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
int index = typeValue.IndexOf(':');
// The value of xsi:type is not a qualified name
if (index == -1)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Check the following conditions
// The namespace of the prefix (string before ":") matches "ns"
// The name (string after ":") matches "name"
if (!Object.ReferenceEquals(ns, reader.LookupNamespace(typeValue.Substring(0, index)))
|| String.CompareOrdinal(name, typeValue.Substring(index + 1, typeValue.Length - index - 1)) != 0)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
// Expect to find text data and return its value.
private string GetStringData(XmlReader reader)
{
if (reader.IsEmptyElement)
return string.Empty;
reader.Read();
if (reader.MoveToContent() == XmlNodeType.EndElement)
return string.Empty;
// If there is any content in the element, it should be text content and nothing else.
if (reader.NodeType != XmlNodeType.Text)
{
throw new XmlException(SR.NoStructuredContentInsideProperties,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
return reader.Value;
}
// Expect to find text data and return its value as DateTime.
private Nullable<DateTime> GetDateData(XmlReader reader)
{
string data = GetStringData(reader);
DateTime dateTime;
try
{
// Note: No more than 7 second decimals are accepted by the
// list of formats given. There currently is no method that
// would perform XSD-compliant parsing.
dateTime = DateTime.ParseExact(data, s_dateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
catch (FormatException exc)
{
throw new XmlException(SR.XsdDateTimeExpected,
exc, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
return dateTime;
}
// Make sure there is a part to write to and that it contains
// the expected start markup.
private void EnsureXmlWriter()
{
if (_xmlWriter != null)
return;
EnsurePropertyPart(); // Should succeed or throw an exception.
Stream writerStream = new IgnoreFlushAndCloseStream(_propertyPart.GetStream(FileMode.Create, FileAccess.Write));
_xmlWriter = XmlWriter.Create(writerStream, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 });
WriteXmlStartTagsForPackageProperties();
}
// Create a property part if none exists yet.
private void EnsurePropertyPart()
{
if (_propertyPart != null)
return;
// If _propertyPart is null, no property part existed when this object was created,
// and this function is being called for the first time.
// However, when read access is available, we can afford the luxury of checking whether
// a property part and its referring relationship got correctly created in the meantime
// outside of this class.
// In write-only mode, it is impossible to perform this check, and the external creation
// scenario will result in an exception being thrown.
if (_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite)
{
_propertyPart = GetPropertyPart();
if (_propertyPart != null)
return;
}
CreatePropertyPart();
}
// Create a new property relationship pointing to a new property part.
// If only this class is used for manipulating property relationships, there cannot be a
// pre-existing dangling property relationship.
// No check is performed here for other classes getting misused insofar as this function
// has to work in write-only mode.
private void CreatePropertyPart()
{
_propertyPart = _package.CreatePart(GeneratePropertyPartUri(), s_coreDocumentPropertiesContentType.ToString());
_package.CreateRelationship(_propertyPart.Uri, TargetMode.Internal,
CoreDocumentPropertiesRelationshipType);
}
private Uri GeneratePropertyPartUri()
{
string propertyPartName = DefaultPropertyPartNamePrefix
+ Guid.NewGuid().ToString(GuidStorageFormatString)
+ DefaultPropertyPartNameExtension;
return PackUriHelper.CreatePartUri(new Uri(propertyPartName, UriKind.Relative));
}
private void WriteXmlStartTagsForPackageProperties()
{
_xmlWriter.WriteStartDocument();
// <coreProperties
_xmlWriter.WriteStartElement(PackageXmlStringTable.GetXmlString(PackageXmlEnum.CoreProperties), // local name
PackageXmlStringTable.GetXmlString(PackageXmlEnum.PackageCorePropertiesNamespace)); // namespace
// xmlns:dc
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCorePropertiesNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCorePropertiesNamespace));
// xmlns:dcterms
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublincCoreTermsNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCoreTermsNamespace));
// xmlns:xsi
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
}
// Write the property elements and clear _dirty.
private void SerializeDirtyProperties()
{
// Create a property element for each non-null entry.
foreach (KeyValuePair<PackageXmlEnum, Object> entry in _propertyDictionary)
{
Debug.Assert(entry.Value != null);
PackageXmlEnum propertyNamespace = PackageXmlStringTable.GetXmlNamespace(entry.Key);
_xmlWriter.WriteStartElement(PackageXmlStringTable.GetXmlString(entry.Key),
PackageXmlStringTable.GetXmlString(propertyNamespace));
if (entry.Value is Nullable<DateTime>)
{
if (propertyNamespace == PackageXmlEnum.DublinCoreTermsNamespace)
{
// xsi:type=
_xmlWriter.WriteStartAttribute(PackageXmlStringTable.GetXmlString(PackageXmlEnum.Type),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
// "dcterms:W3CDTF"
_xmlWriter.WriteQualifiedName(W3cdtf,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCoreTermsNamespace));
_xmlWriter.WriteEndAttribute();
}
// Use sortable ISO 8601 date/time pattern. Include second fractions down to the 100-nanosecond interval,
// which is the definition of a "tick" for the DateTime type.
_xmlWriter.WriteString(XmlConvert.ToString(((Nullable<DateTime>)entry.Value).Value.ToUniversalTime(), "yyyy-MM-ddTHH:mm:ss.fffffffZ"));
}
else
{
// The following uses the fact that ToString is virtual.
_xmlWriter.WriteString(entry.Value.ToString());
}
_xmlWriter.WriteEndElement();
}
// Mark properties as saved.
_dirty = false;
}
// Add end markup and close the writer.
private void CloseXmlWriter()
{
// Close the root element.
_xmlWriter.WriteEndElement();
// Close the writer itself.
_xmlWriter.Dispose();
// Make sure we know it's closed.
_xmlWriter = null;
}
#endregion Private Methods
#region Private Fields
private Package _package;
private PackagePart _propertyPart;
private XmlWriter _xmlWriter;
// Table of objects from the closed set of literals defined below.
// (Uses object comparison rather than string comparison.)
private const int NumCoreProperties = 16;
private Dictionary<PackageXmlEnum, Object> _propertyDictionary = new Dictionary<PackageXmlEnum, Object>(NumCoreProperties);
private bool _dirty = false;
// This System.Xml.NameTable makes sure that we use the same references to strings
// throughout (including when parsing Xml) and so can perform reference comparisons
// rather than value comparisons.
private NameTable _nameTable;
// Literals.
private static readonly ContentType s_coreDocumentPropertiesContentType
= new ContentType("application/vnd.openxmlformats-package.core-properties+xml");
private const string CoreDocumentPropertiesRelationshipType
= "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
private const string DefaultPropertyPartNamePrefix =
"/package/services/metadata/core-properties/";
private const string W3cdtf = "W3CDTF";
private const string DefaultPropertyPartNameExtension = ".psmdcp";
private const string GuidStorageFormatString = @"N"; // N - simple format without adornments
private static PackageXmlEnum[] s_validProperties = new PackageXmlEnum[] {
PackageXmlEnum.Creator,
PackageXmlEnum.Identifier,
PackageXmlEnum.Title,
PackageXmlEnum.Subject,
PackageXmlEnum.Description,
PackageXmlEnum.Language,
PackageXmlEnum.Created,
PackageXmlEnum.Modified,
PackageXmlEnum.ContentType,
PackageXmlEnum.Keywords,
PackageXmlEnum.Category,
PackageXmlEnum.Version,
PackageXmlEnum.LastModifiedBy,
PackageXmlEnum.ContentStatus,
PackageXmlEnum.Revision,
PackageXmlEnum.LastPrinted
};
// Array of formats to supply to XmlConvert.ToDateTime or DateTime.ParseExact.
// xsd:DateTime requires full date time in sortable (ISO 8601) format.
// It can be expressed in local time, universal time (Z), or relative to universal time (zzz).
// Negative years are accepted.
// IMPORTANT: Second fractions are recognized only down to 1 tenth of a microsecond because this is the resolution
// of the DateTime type. The Xml standard, however, allows any number of decimals; but XmlConvert only offers
// this very awkward API with an explicit pattern enumeration.
private static readonly string[] s_dateTimeFormats = new string[] {
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ssZ",
"yyyy-MM-ddTHH:mm:sszzz",
@"\-yyyy-MM-ddTHH:mm:ss",
@"\-yyyy-MM-ddTHH:mm:ssZ",
@"\-yyyy-MM-ddTHH:mm:sszzz",
"yyyy-MM-ddTHH:mm:ss.ff",
"yyyy-MM-ddTHH:mm:ss.fZ",
"yyyy-MM-ddTHH:mm:ss.fzzz",
@"\-yyyy-MM-ddTHH:mm:ss.f",
@"\-yyyy-MM-ddTHH:mm:ss.fZ",
@"\-yyyy-MM-ddTHH:mm:ss.fzzz",
"yyyy-MM-ddTHH:mm:ss.ff",
"yyyy-MM-ddTHH:mm:ss.ffZ",
"yyyy-MM-ddTHH:mm:ss.ffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ff",
@"\-yyyy-MM-ddTHH:mm:ss.ffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffzzz",
"yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss.fffZ",
"yyyy-MM-ddTHH:mm:ss.fffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fff",
@"\-yyyy-MM-ddTHH:mm:ss.fffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffzzz",
"yyyy-MM-ddTHH:mm:ss.ffff",
"yyyy-MM-ddTHH:mm:ss.ffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ffff",
@"\-yyyy-MM-ddTHH:mm:ss.ffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffffzzz",
"yyyy-MM-ddTHH:mm:ss.fffff",
"yyyy-MM-ddTHH:mm:ss.fffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fffff",
@"\-yyyy-MM-ddTHH:mm:ss.fffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffffzzz",
"yyyy-MM-ddTHH:mm:ss.ffffff",
"yyyy-MM-ddTHH:mm:ss.ffffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ffffff",
@"\-yyyy-MM-ddTHH:mm:ss.ffffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffffffzzz",
"yyyy-MM-ddTHH:mm:ss.fffffff",
"yyyy-MM-ddTHH:mm:ss.fffffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fffffff",
@"\-yyyy-MM-ddTHH:mm:ss.fffffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffffffzzz",
};
#endregion Private Fields
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
using EdgeData = IFunctionalMap<SymbolicValue, FList<SymbolicValue>>;
public class OldAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions, MethodResult>
: AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult>
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
{
public OldAnalysisDriver(
IBasicAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions> basicDriver
) : base(basicDriver)
{
}
public override IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions> MethodDriver(
Method method,
IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult> classDriver,
bool removeInferredPrecondition = false)
{
return new MDriver(method, this, classDriver, removeInferredPrecondition);
}
private class MDriver
: BasicMethodDriverWithInference<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions>
, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions>
, IFactBase<SymbolicValue>
{
private OptimisticHeapAnalyzer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> optimisticHeapAnalysis;
private Converter<ExternalExpression<APC, SymbolicValue>, string> expr2String;
private IFullExpressionDecoder<Type, SymbolicValue, ExternalExpression<APC, SymbolicValue>> expressionDecoder;
private readonly IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult> classDriver;
private readonly AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult> specializedParent;
private readonly bool RemoveInferredPreconditions;
public IDisjunctiveExpressionRefiner<SymbolicValue, BoxedExpression> DisjunctiveExpressionRefiner { get; set; }
public SyntacticInformation<Method, Field, SymbolicValue> AdditionalSyntacticInformation { get; set; }
public ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, SymbolicValue, SymbolicValue, IValueContext<Local, Parameter, Method, Field, Type, SymbolicValue>, EdgeData>
ValueLayer
{ get; private set; }
public ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<APC, SymbolicValue>, SymbolicValue>, EdgeData>
ExpressionLayer
{ get; private set; }
public ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, SymbolicValue, SymbolicValue, IValueContext<Local, Parameter, Method, Field, Type, SymbolicValue>, EdgeData>
HybridLayer
{ get; protected set; }
public IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> MetaDataDecoder
{ get { return this.RawLayer.MetaDataDecoder; } }
public MDriver(
Method method,
OldAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions, MethodResult> parent,
IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult> classDriver,
bool removeInferredPrecondition
)
: base(method, parent)
{
specializedParent = parent;
// Here we build our stack of adapters.
//
// Expr (expressions)
// Heap (symbolic values)
// StackDepth (Temp decoder for APC)
// CFG (Unit decoder for APC, including Assume)
// cciilprovider (Unit decoder for PC)
//
// The base class already built the first 3
// The last two are built on demand
this.classDriver = classDriver;
RemoveInferredPreconditions = removeInferredPrecondition;
}
public IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<APC, SymbolicValue>, SymbolicValue> Context { get { return this.ExpressionLayer.Decoder.AssumeNotNull().Context; } }
public Converter<SymbolicValue, int> KeyNumber { get { return SymbolicValue.GetUniqueKey; } }
public Comparison<SymbolicValue> VariableComparer { get { return SymbolicValue.Compare; } }
public void RunHeapAndExpressionAnalyses()
{
if (optimisticHeapAnalysis != null) return;
optimisticHeapAnalysis = new OptimisticHeapAnalyzer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(this.StackLayer, this.Options.TraceEGraph);
optimisticHeapAnalysis.TurnArgumentExceptionThrowsIntoAssertFalse = this.Options.TurnArgumentExceptionThrowsIntoAssertFalse;
optimisticHeapAnalysis.IgnoreExplicitAssumptions = this.Options.IgnoreExplicitAssumptions;
optimisticHeapAnalysis.TraceAssumptions = this.Options.TraceAssumptions;
var heapsolver = this.StackLayer.CreateForward(optimisticHeapAnalysis,
new DFAOptions { Trace = this.Options.TraceHeapAnalysis });
heapsolver(optimisticHeapAnalysis.InitialValue());
this.ValueLayer = CodeLayerFactory.Create(optimisticHeapAnalysis.GetDecoder(this.StackLayer.Decoder),
this.StackLayer.MetaDataDecoder,
this.StackLayer.ContractDecoder,
delegate (SymbolicValue source) { return source.ToString(); },
delegate (SymbolicValue dest) { return dest.ToString(); },
(v1, v2) => v1.symbol.GlobalId > v2.symbol.GlobalId
);
if (this.PrintIL)
{
Console.WriteLine("-----------------Value based CFG---------------------");
this.ValueLayer.Decoder.Context.MethodContext.CFG.Print(Console.Out, this.ValueLayer.Printer, optimisticHeapAnalysis.GetEdgePrinter(),
(block) => optimisticHeapAnalysis.GetContexts(block),
null);
}
var exprAnalysis = new ExpressionAnalysis<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, SymbolicValue, IValueContext<Local, Parameter, Method, Field, Type, SymbolicValue>, EdgeData>(
this.ValueLayer,
this.Options,
optimisticHeapAnalysis.IsUnreachable
);
var exprsolver = this.ValueLayer.CreateForward(exprAnalysis.CreateExpressionAnalyzer(),
new DFAOptions { Trace = this.Options.TraceExpressionAnalysis });
exprsolver(exprAnalysis.InitialValue(SymbolicValue.GetUniqueKey));
var exprDecoder = exprAnalysis.GetDecoder(this.ValueLayer.Decoder);
expr2String = ExprPrinter.Printer(exprDecoder.Context, this);
this.ExpressionLayer = CodeLayerFactory.Create(
exprDecoder,
this.ValueLayer.MetaDataDecoder,
this.ValueLayer.ContractDecoder,
expr2String,
this.ValueLayer.VariableToString,
(v1, v2) => v1.symbol.GlobalId > v2.symbol.GlobalId
);
if (this.PrintIL)
{
Console.WriteLine("-----------------Expression based CFG---------------------");
this.ExpressionLayer.Decoder.Context.MethodContext.CFG.Print(Console.Out, this.ExpressionLayer.Printer, exprAnalysis.GetBlockPrinter(expr2String),
(block) => exprAnalysis.GetContexts(block),
null);
}
this.HybridLayer = CodeLayerFactory.Create(
this.ValueLayer.Decoder,
this.ValueLayer.MetaDataDecoder,
this.ValueLayer.ContractDecoder,
this.ValueLayer.ExpressionToString,
this.ValueLayer.VariableToString,
this.ExpressionLayer.Printer,
this.ExpressionLayer.NewerThan
);
if (Options.TraceAssumptions)
{
#region Produce trace output to extract implicit assumptions. Please don't remove this code!
Console.WriteLine("<assumptions>");
Console.WriteLine(@"<subroutine id=""{0}"" methodName=""{1}"">", HybridLayer.Decoder.Context.MethodContext.CFG.Subroutine.Id, HybridLayer.Decoder.Context.MethodContext.CFG.Subroutine.Name);
foreach (var b in HybridLayer.Decoder.Context.MethodContext.CFG.Subroutine.Blocks)
{
Console.WriteLine(@"<block index=""{0}"">", b.Index);
foreach (var apc in b.APCs())
{
Console.WriteLine(@"<apc name=""{0}"" index=""{1}"" ilOffset=""{2}"" primarySourceContext=""{3}"" sourceContext=""{4}"">",
apc.ToString(), apc.Index, apc.ILOffset, apc.PrimarySourceContext(), HybridLayer.Decoder.Context.MethodContext.SourceContext(apc));
Console.WriteLine("<code>");
HybridLayer.Printer(apc, "", Console.Out);
Console.WriteLine("</code>");
optimisticHeapAnalysis.Dump(apc);
Console.WriteLine("</apc>");
}
Console.WriteLine("</block>");
}
Console.WriteLine("</subroutine>");
Console.WriteLine("</assumptions>");
#endregion
}
}
public Converter<ExternalExpression<APC, SymbolicValue>, string> ExpressionToString { get { return expr2String; } }
public State BackwardTransfer<State, Visitor>(APC from, APC to, State state, Visitor visitor)
where Visitor : IEdgeVisit<APC, Local, Parameter, Method, Field, Type, SymbolicValue, State>
{
if (this.IsUnreachable(to)) { throw new InvalidOperationException("Can not transfer to unreachable point"); }
if (from.Block != to.Block)
{
var renaming = optimisticHeapAnalysis.BackwardEdgeRenaming(from, to);
if (renaming != null)
{
return visitor.Rename(from, to, state, renaming);
}
else
{
return state;
}
}
return this.ValueLayer.Decoder.ForwardDecode<State, State, Visitor>(to, visitor, state);
}
#region IMethodDriver<APC,Local,Parameter,Method,Field,Type,Attribute,Assembly,ExternalExpression<APC,SymbolicValue>,SymbolicValue,LogOptions> Members
public IFullExpressionDecoder<Type, SymbolicValue, ExternalExpression<APC, SymbolicValue>> ExpressionDecoder
{
get
{
if (expressionDecoder == null)
{
Contract.Assert(this.Context != null);
expressionDecoder = ExternalExpressionDecoder.Create(this.MetaDataDecoder, this.Context);
}
return expressionDecoder;
}
}
public IFactBase<SymbolicValue> BasicFacts { get { return this; } }
public override bool CanAddRequires()
{
return this.CanAddContracts();
}
public override bool CanAddEnsures()
{
return !this.MetaDataDecoder.IsVirtual(this.Context.MethodContext.CurrentMethod) && this.CanAddContracts();
}
protected override bool CanAddInvariants()
{
if (classDriver == null)
return false;
return classDriver.CanAddInvariants();
}
protected override bool CanAddAssumes()
{
return this.Options.InferAssumesForBaseLining;
}
private bool CanAddContracts()
{
return !this.MetaDataDecoder.IsCompilerGenerated(this.Context.MethodContext.CurrentMethod) &&
(!this.MetaDataDecoder.IsVirtual(this.Context.MethodContext.CurrentMethod) ||
this.MetaDataDecoder.OverriddenAndImplementedMethods(this.method).AsIndexable(1).Count == 0);
}
public void EndAnalysis()
{
if (RemoveInferredPreconditions)
{
// we are done validating the inferred preconditions, so we can remove them from the method cache
specializedParent.RemoveInferredPrecondition(this.method);
}
else
{
specializedParent.InstallPreconditions(this.inferredPreconditions, this.method);
}
specializedParent.InstallPostconditions(this.inferredPostconditions, this.method);
// Let's add the witness
specializedParent.MethodCache.AddWitness(this.method, this.MayReturnNull);
// Install postconditons for other methods
if (otherPostconditions != null)
{
foreach (var tuple in otherPostconditions.GroupBy(t => t.Item1))
{
Contract.Assume(tuple.Any());
specializedParent.InstallPostconditions(tuple.Select(t => t.Item2).ToList(), tuple.First().Item1);
}
}
if (classDriver != null)
{
var methodThis = this.MetaDataDecoder.This(this.method);
classDriver.InstallInvariantsAsConstructorPostconditions(methodThis, this.inferredObjectInvariants, this.method);
// Really install object invariants. TODO: readonly fields only
// Missing something... how do I build a Contract.Invariant(...)?
var asAssume = this.inferredObjectInvariants.Select(be => (new BoxedExpression.AssumeExpression(be.One, "invariant", this.CFG.EntryAfterRequires, be.Two, be.One.ToString<Type>(type => OutputPrettyCS.TypeHelper.TypeFullName(this.MetaDataDecoder, type))))).Cast<BoxedExpression>();
specializedParent.InstallObjectInvariants(asAssume.ToList(), classDriver.ClassType);
}
}
#endregion
#region IFactBase<SymbolicValue> Members
public ProofOutcome IsNull(APC pc, SymbolicValue value)
{
return ProofOutcome.Top;
//this.ValueLayer.Decoder.Context.ValueContext.IsZero(pc, value);
}
public ProofOutcome IsNonNull(APC pc, SymbolicValue value)
{
return ProofOutcome.Top;
//this.ValueLayer.Decoder.Context.ValueContext.IsZero(pc, value);
}
public FList<BoxedExpression> InvariantAt(APC pc, FList<SymbolicValue> filter, bool replaceVarsWithAccessPath = true)
{
return FList<BoxedExpression>.Empty;
}
public bool IsUnreachable(APC pc)
{
return optimisticHeapAnalysis.IsUnreachable(pc);
}
#endregion
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SubnetsOperations.
/// </summary>
public static partial class SubnetsOperationsExtensions
{
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
public static void Delete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName)
{
operations.DeleteAsync(resourceGroupName, virtualNetworkName, subnetName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static Subnet Get(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, virtualNetworkName, subnetName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> GetAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
public static Subnet CreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> CreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
public static IPage<Subnet> List(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName)
{
return operations.ListAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Subnet>> ListAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
public static void BeginDelete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName)
{
operations.BeginDeleteAsync(resourceGroupName, virtualNetworkName, subnetName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
public static Subnet BeginCreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> BeginCreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Subnet> ListNext(this ISubnetsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Subnet>> ListNextAsync(this ISubnetsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using OpenADK.Library;
using OpenADK.Library.Infra;
using OpenADK.Library.Tools.XPath;
using OpenADK.Util;
using Library.Examples;
namespace SIFQuery
{
public class SIFQuery : Agent, IQueryResults {
private static readonly SIFQuery _agent = new SIFQuery();
private static IDictionary<string, ComparisonOperators> supportedComparisons = new Dictionary<string, ComparisonOperators>();
public SIFQuery() :
base("SIFQuery")
{
}
private static void InitializeComparisonList()
{
lock (supportedComparisons) {
if (supportedComparisons.Count == 0) {
supportedComparisons.Add("=", ComparisonOperators.EQ);
supportedComparisons.Add(">", ComparisonOperators.GT);
supportedComparisons.Add("<", ComparisonOperators.LT);
supportedComparisons.Add(">=", ComparisonOperators.GE);
supportedComparisons.Add("<=", ComparisonOperators.LE);
supportedComparisons.Add("!=", ComparisonOperators.NE);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
[STAThread]
public static void Main(string[] args) {
try {
if( args.Length < 2 ) {
Console.WriteLine("Usage: SIFQuery /zone zone /url url [/events] [options]");
Console.WriteLine(" /zone zone The name of the zone");
Console.WriteLine(" /url url The zone URL");
AdkExamples.printHelp();
return;
}
// Pre-parse the command-line before initializing the ADK
Adk.Debug = AdkDebugFlags.Moderate;
AdkExamples.parseCL( null, args);
// Initialize the ADK with the specified version, loading only the Student SDO package
int sdoLibs;
sdoLibs = (int)OpenADK.Library.uk.SdoLibraryType.All;
Adk.Initialize(SifVersion.LATEST,SIFVariant.SIF_UK,sdoLibs);
// Call StartAgent.
_agent.StartAgent(args);
// Turn down debugging
Adk.Debug = AdkDebugFlags.None;
// Call runConsole() This method does not return until the agent shuts down
_agent.RunConsole();
// Wait for Ctrl-C to be pressed
Console.WriteLine( "Agent is running (Press Ctrl-C to stop)" );
new AdkConsoleWait().WaitForExit();
} catch(Exception e) {
Console.WriteLine(e);
} finally {
if( _agent != null && _agent.Initialized ){
// Always shutdown the agent on exit
try {
_agent.Shutdown( AdkExamples.Unreg ? ProvisioningFlags.Unprovide : ProvisioningFlags.None );
}
catch( AdkException adkEx ){
Console.WriteLine( adkEx );
}
}
}
}
private void StartAgent(String[] args)
{
this.Initialize();
NameValueCollection parameters = AdkExamples.parseCL(this, args);
string zoneId = parameters["zone"];
string url = parameters["url"];
if( zoneId == null || url == null ) {
Console.WriteLine("The /zone and /url parameters are required");
Environment.Exit(0);
}
// 1) Get an instance of the zone to connect to
IZone zone = ZoneFactory.GetInstance(zoneId, url);
zone.SetQueryResults( this );
// 2) Connect to zones
zone.Connect( AdkExamples.Reg ? ProvisioningFlags.Register : ProvisioningFlags.None );
}
private void RunConsole()
{
Console.WriteLine( "SIFQuery Command Line" );
Version version = Assembly.GetExecutingAssembly().GetName().Version;
Console.WriteLine( "Version " + version.ToString(3) );
Console.WriteLine( "Copyright " + DateTime.Now.Year + ", Data Solutions" );
PrintSQLHelp();
Regex sqlPattern = new Regex("(?:select)(.*)(?:from)(.*)(?:where)(.*)$", RegexOptions.IgnoreCase);
bool finished = false;
while( !finished ){
PrintPrompt();
string query = Console.ReadLine().Trim();
if( query.Length == 0 ){
continue;
}
string lcaseQuery = query.ToLower();
if( lcaseQuery.StartsWith("q")){
finished = true;
continue;
}
if( lcaseQuery.IndexOf("where") == -1 ){
// The regular expression requires a where clause
query = query + " where ";
}
Match results;
try {
results = sqlPattern.Match(query);
} catch( Exception ex ){
Console.WriteLine( "ERROR evaluating expression: " + ex );
continue;
}
if(results.Captures.Count == 0 ){
Console.WriteLine( "Unknown error evaluating expression." );
continue;
}
if( results.Groups.Count >= 3 ){
Query q = CreateQuery(results.Groups[2].Value);
if( q != null &&
AddConditions( q, results.Groups[3].Value ) &&
AddSelectFields( q, results.Groups[1].Value ) )
{
Console.WriteLine( "Sending Query to zone.... " );
string queryXML = q.ToXml(SifVersion.LATEST);
Console.WriteLine( queryXML );
// Store the original source query in the userData property
q.UserData = queryXML;
this.ZoneFactory.GetAllZones()[0].Query(q);
}
} else {
Console.WriteLine( "ERROR: Unrecognized query syntax..." );
PrintSQLHelp();
}
}
}
private void PrintPrompt(){
Console.Write( "SIF: " );
}
private void PrintSQLHelp(){
Console.WriteLine( "Syntax: Select {fields} From {SIF Object} [Where {field}={value}] " );
Console.WriteLine( " {fields} one or more field names, seperated by a comma" );
Console.WriteLine( " (may by empty or * )" );
Console.WriteLine( " {SIF Object} the name of a SIF Object that is provided in the zone" );
Console.WriteLine( " {field} a field name" );
Console.WriteLine( " {value} a value" );
Console.WriteLine( "Examples:" );
Console.WriteLine( "SIF: Select * from StudentPersonal" );
Console.WriteLine( "SIF: Select * from StudentPersonal where RefId=43203167CFF14D08BB9C8E3FD0F9EC3C" );
Console.WriteLine( "SIF: Select * from StudentPersonal where Name/FirstName=Amber" );
Console.WriteLine( "SIF: Select Name/FirstName, Name/LastName from StudentPersonal where Demographics/Gender=F" );
Console.WriteLine( "SIF: Select * from StudentSchoolEnrollment where RefId=43203167CFF14D08BB9C8E3FD0F9EC3C" );
Console.WriteLine();
}
private Query CreateQuery( String fromClause ){
IElementDef queryDef = Adk.Dtd.LookupElementDef( fromClause.Trim() );
if( queryDef == null ){
Console.WriteLine( "ERROR: Unrecognized FROM statement: " + fromClause );
PrintSQLHelp();
return null;
} else{
return new Query( queryDef );
}
}
private bool AddSelectFields(Query q, String selectClause )
{
if( selectClause.Length == 0 || selectClause.IndexOf( "*" ) > -1 ){
return true;
}
string[] fields = selectClause.Split(new char[] { ',' });
foreach(string field in fields){
string val = field.Trim();
if( val.Length > 0 ){
IElementDef restriction = Adk.Dtd.LookupElementDefBySQP( q.ObjectType, val );
if( restriction == null ){
Console.WriteLine( "ERROR: Unrecognized SELECT field: " + val );
PrintSQLHelp();
return false;
} else {
q.AddFieldRestriction(restriction);
}
}
}
return true;
}
private bool AddConditions(Query q, String whereClause )
{
InitializeComparisonList();
bool added = true;
whereClause = whereClause.Trim();
if( whereClause.Length == 0 ){
return added;
}
string[] whereConditions = Regex.Split(whereClause, "[aA][nN][dD]");
ComparisonOperators cmpOperator = ComparisonOperators.EQ;
string[] fields = null;
if (whereConditions.Length > 0) {
foreach (String condition in whereConditions) {
fields = null;
foreach (KeyValuePair<string, ComparisonOperators> kvp in supportedComparisons) {
string cmpString = kvp.Key;
cmpOperator = kvp.Value;
if (cmpOperator == ComparisonOperators.EQ) {
int index = condition.LastIndexOf(cmpString);
fields = new string[2];
if (index > 0) {
fields[0] = condition.Substring(0, index);
fields[1] = condition.Substring((index + 1));
} else {
fields[0] = condition;
}
}//end if
if (fields == null) {
fields = Regex.Split(condition, cmpString);
}
if (fields[0] == condition) {
//Means no match found using that current comparison operator
//so skip this condition
fields = null;
continue;
}
if (fields.Length != 2) {
Console.WriteLine("ERROR: Unsupported where clause: " + whereClause);
PrintSQLHelp();
added = false;
break;
}
string fieldExpr = fields[0].Trim();
IElementDef def = Adk.Dtd.LookupElementDefBySQP(q.ObjectType, fieldExpr );
if (def == null) {
Console.WriteLine("ERROR: Unrecognized field in where clause: " + fieldExpr );
PrintSQLHelp();
added = false;
break;
} else {
if (fieldExpr.IndexOf('[') > 0)
{
// If there is a square bracket in the field syntax, use the raw XPath,
// rather then the ElementDef because using ElementDef restrictions
// does not work for XPath expressions that contain predicates
// Note that using raw XPath expressions works fine, but the ADK is no longer
// going to be able to use version-independent rendering of the query
q.AddCondition(fieldExpr, cmpOperator, fields[1].Trim());
}
else
{
q.AddCondition( def, cmpOperator, fields[1].Trim() );
}
//our condition has been found, no need to check the other comparison
//operators for a match so move to the next condition
break;
}
}//end foreach
}//end foreach
}
return added;
}
public void OnQueryPending(IMessageInfo info, IZone zone){
SifMessageInfo smi = (SifMessageInfo)info;
Console.WriteLine( "Sending SIF Request with MsgId " + smi.MsgId + " to zone " + zone.ZoneId );
}
public void OnQueryResults(IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info) {
SifMessageInfo smi = (SifMessageInfo)info;
DateTime start = DateTime.Now;
if (smi.Timestamp.HasValue) {
start = smi.Timestamp.Value;
}
Console.WriteLine();
Console.WriteLine( "********************************************* " );
Console.WriteLine( "Received SIF_Response packet from zone" + zone.ZoneId );
Console.WriteLine( "Details... " );
Console.WriteLine( "Request MsgId: " + smi.SIFRequestMsgId );
Console.WriteLine( "Packet Number: " + smi.PacketNumber );
Console.WriteLine();
if( error != null ){
Console.WriteLine( "The publisher returned an error: " );
Console.WriteLine( "Category: " + error.SIF_Category + " Code: " + error.SIF_Code );
Console.WriteLine( "Description " + error.SIF_Desc );
if( error.SIF_ExtendedDesc != null )
{
Console.WriteLine( "Details: " + error.SIF_ExtendedDesc );
}
return;
}
try
{
int objectCount = 0;
while( data.Available ){
SifDataObject next = data.ReadDataObject();
objectCount++;
Console.WriteLine();
Console.WriteLine( "Text Values for " + next.ElementDef.Name + " " + objectCount + " {" + next.Key + "}" );
SifXPathContext context = SifXPathContext.NewSIFContext(next);
// Print out all attributes
Console.WriteLine("Attributes:");
XPathNodeIterator textNodes = context.Select("//@*");
while( textNodes.MoveNext() ) {
XPathNavigator navigator = textNodes.Current;
Element value = (Element)navigator.UnderlyingObject;
IElementDef valueDef = value.ElementDef;
Console.WriteLine( valueDef.Parent.Tag( SifVersion.LATEST ) + "/@" + valueDef.Tag( SifVersion.LATEST ) + "=" + value.TextValue + ", " );
}
Console.WriteLine();
// Print out all elements that have a text value
Console.WriteLine("Element:");
textNodes = context.Select("//*");
while( textNodes.MoveNext() ) {
XPathNavigator navigator = textNodes.Current;
Element value = (Element)navigator.UnderlyingObject;
String textValue = value.TextValue;
if( textValue != null ){
IElementDef valueDef = value.ElementDef;
Console.WriteLine( valueDef.Tag( SifVersion.LATEST ) + "=" + textValue + ", " );
}
}
}
Console.WriteLine();
Console.WriteLine( "Total Objects in Packet: " + objectCount );
} catch( Exception ex ){
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
if (!smi.MorePackets) {
// This is the final packet. Print stats
Console.WriteLine( "Final Packet has been received." );
IRequestInfo ri = smi.SIFRequestInfo;
if( ri != null ){
Console.WriteLine( "Source Query: " );
Console.WriteLine( ri.UserData );
TimeSpan difference = start.Subtract(ri.RequestTime);
Console.WriteLine( "Query execution time: " + difference.Milliseconds + " ms" );
}
} else {
Console.WriteLine( "This is not the final packet for this SIF_Response" );
}
Console.WriteLine( "********************************************* " );
Console.WriteLine( );
PrintPrompt();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace NAudio.Wave.Compression
{
/// <summary>
/// AcmStream encapsulates an Audio Compression Manager Stream
/// used to convert audio from one format to another
/// </summary>
class AcmStream : IDisposable
{
private IntPtr streamHandle;
private IntPtr driverHandle;
private AcmStreamHeader streamHeader;
private WaveFormat sourceFormat;
/// <summary>
/// Creates a new ACM stream to convert one format to another. Note that
/// not all conversions can be done in one step
/// </summary>
/// <param name="sourceFormat">The source audio format</param>
/// <param name="destFormat">The destination audio format</param>
public AcmStream(WaveFormat sourceFormat, WaveFormat destFormat)
{
try
{
streamHandle = IntPtr.Zero;
this.sourceFormat = sourceFormat;
int sourceBufferSize = Math.Max(65536, sourceFormat.AverageBytesPerSecond);
sourceBufferSize -= (sourceBufferSize % sourceFormat.BlockAlign);
MmException.Try(AcmInterop.acmStreamOpen(out streamHandle, IntPtr.Zero, sourceFormat, destFormat, null, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen");
int destBufferSize = SourceToDest(sourceBufferSize);
streamHeader = new AcmStreamHeader(streamHandle, sourceBufferSize, destBufferSize);
driverHandle = IntPtr.Zero;
}
catch
{
// suppress the finalise and clean up resources
Dispose();
throw;
}
}
/// <summary>
/// Creates a new ACM stream to convert one format to another, using a
/// specified driver identified and wave filter
/// </summary>
/// <param name="driverId">the driver identifier</param>
/// <param name="sourceFormat">the source format</param>
/// <param name="waveFilter">the wave filter</param>
public AcmStream(IntPtr driverId, WaveFormat sourceFormat, WaveFilter waveFilter)
{
int sourceBufferSize = Math.Max(16384, sourceFormat.AverageBytesPerSecond);
this.sourceFormat = sourceFormat;
sourceBufferSize -= (sourceBufferSize % sourceFormat.BlockAlign);
MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, driverId, 0), "acmDriverOpen");
MmException.Try(AcmInterop.acmStreamOpen(out streamHandle, driverHandle,
sourceFormat, sourceFormat, waveFilter, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen");
streamHeader = new AcmStreamHeader(streamHandle, sourceBufferSize, SourceToDest(sourceBufferSize));
}
/// <summary>
/// Returns the number of output bytes for a given number of input bytes
/// </summary>
/// <param name="source">Number of input bytes</param>
/// <returns>Number of output bytes</returns>
public int SourceToDest(int source)
{
if (source == 0) // zero is an invalid parameter to acmStreamSize
return 0;
int convertedBytes;
MmException.Try(AcmInterop.acmStreamSize(streamHandle, source, out convertedBytes, AcmStreamSizeFlags.Source), "acmStreamSize");
return convertedBytes;
}
/// <summary>
/// Returns the number of source bytes for a given number of destination bytes
/// </summary>
/// <param name="dest">Number of destination bytes</param>
/// <returns>Number of source bytes</returns>
public int DestToSource(int dest)
{
if (dest == 0) // zero is an invalid parameter to acmStreamSize
return 0;
int convertedBytes;
MmException.Try(AcmInterop.acmStreamSize(streamHandle, dest, out convertedBytes, AcmStreamSizeFlags.Destination), "acmStreamSize");
return convertedBytes;
}
/// <summary>
/// Suggests an appropriate PCM format that the compressed format can be converted
/// to in one step
/// </summary>
/// <param name="compressedFormat">The compressed format</param>
/// <returns>The PCM format</returns>
public static WaveFormat SuggestPcmFormat(WaveFormat compressedFormat)
{
// create a PCM format
WaveFormat suggestedFormat = new WaveFormat(compressedFormat.SampleRate, 16, compressedFormat.Channels);
MmException.Try(AcmInterop.acmFormatSuggest(IntPtr.Zero, compressedFormat, suggestedFormat, Marshal.SizeOf(suggestedFormat), AcmFormatSuggestFlags.FormatTag), "acmFormatSuggest");
/*IntPtr suggestedFormatPointer = WaveFormat.MarshalToPtr(suggestedFormat);
IntPtr compressedFormatPointer = WaveFormat.MarshalToPtr(compressedFormat);
MmResult result = AcmInterop.acmFormatSuggest2(IntPtr.Zero, compressedFormatPointer, suggestedFormatPointer, Marshal.SizeOf(suggestedFormat), AcmFormatSuggestFlags.FormatTag);
suggestedFormat = WaveFormat.MarshalFromPtr(suggestedFormatPointer);
Marshal.FreeHGlobal(suggestedFormatPointer);
Marshal.FreeHGlobal(compressedFormatPointer);
MmException.Try(result, "acmFormatSuggest");*/
return suggestedFormat;
}
/// <summary>
/// Returns the Source Buffer. Fill this with data prior to calling convert
/// </summary>
public byte[] SourceBuffer
{
get
{
return streamHeader.SourceBuffer;
}
}
/// <summary>
/// Returns the Destination buffer. This will contain the converted data
/// after a successful call to Convert
/// </summary>
public byte[] DestBuffer
{
get
{
return streamHeader.DestBuffer;
}
}
/// <summary>
/// Converts the contents of the SourceBuffer into the DestinationBuffer
/// </summary>
/// <param name="bytesToConvert">The number of bytes in the SourceBuffer
/// that need to be converted</param>
/// <param name="sourceBytesConverted">The number of source bytes actually converted</param>
/// <returns>The number of converted bytes in the DestinationBuffer</returns>
public int Convert(int bytesToConvert, out int sourceBytesConverted)
{
if (bytesToConvert % sourceFormat.BlockAlign != 0)
{
System.Diagnostics.Debug.WriteLine(String.Format("NOT A WHOLE NUMBER OF BLOCKS", bytesToConvert));
bytesToConvert -= (bytesToConvert % sourceFormat.BlockAlign);
}
return streamHeader.Convert(bytesToConvert, out sourceBytesConverted);
}
/// <summary>
/// Converts the contents of the SourceBuffer into the DestinationBuffer
/// </summary>
/// <param name="bytesToConvert">The number of bytes in the SourceBuffer
/// that need to be converted</param>
/// <returns>The number of converted bytes in the DestinationBuffer</returns>
public int Convert(int bytesToConvert)
{
int sourceBytesConverted;
int destBytes = Convert(bytesToConvert, out sourceBytesConverted);
if (sourceBytesConverted != bytesToConvert)
{
throw new MmException(MmResult.NotSupported, "AcmStreamHeader.Convert didn't convert everything");
}
return destBytes;
}
/* Relevant only for async conversion streams
public void Reset()
{
MmException.Try(AcmInterop.acmStreamReset(streamHandle,0),"acmStreamReset");
}
*/
#region IDisposable Members
/// <summary>
/// Frees resources associated with this ACM Stream
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Frees resources associated with this ACM Stream
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free other state (managed objects).
if (streamHeader != null)
{
streamHeader.Dispose();
streamHeader = null;
}
}
// Free your own state (unmanaged objects).
if (streamHandle != IntPtr.Zero)
{
MmResult result = AcmInterop.acmStreamClose(streamHandle, 0);
streamHandle = IntPtr.Zero;
if (result != MmResult.NoError)
{
throw new MmException(result, "acmStreamClose");
}
}
// Set large fields to null.
if (driverHandle != IntPtr.Zero)
{
AcmInterop.acmDriverClose(driverHandle, 0);
driverHandle = IntPtr.Zero;
}
}
/// <summary>
/// Frees resources associated with this ACM Stream
/// </summary>
~AcmStream()
{
// Simply call Dispose(false).
System.Diagnostics.Debug.Assert(false, "AcmStream Dispose was not called");
Dispose(false);
}
#endregion
}
}
| |
// 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.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkWatchersOperations operations.
/// </summary>
public partial interface INetworkWatchersOperations
{
/// <summary>
/// Creates or updates a network watcher in the specified resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the network watcher resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkWatcher>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NetworkWatcher parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified network watcher by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkWatcher>> GetWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network watcher resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network watchers by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<NetworkWatcher>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network watchers by subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<NetworkWatcher>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the current network topology by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the representation of topology.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Topology>> GetTopologyWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TopologyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify IP flow from the specified VM to a location given the
/// currently configured NSG rules.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the IP flow to be verified.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VerificationIPFlowResult>> VerifyIPFlowWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the next hop from the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the source and destination endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NextHopResult>> GetNextHopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NextHopParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the configured and effective security group rules on the
/// specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the VM to check security groups for.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SecurityGroupViewResult>> GetVMSecurityRulesWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiate troubleshooting on a specified resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to troubleshoot.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<TroubleshootingResult>> GetTroubleshootingWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the last completed troubleshooting result on a specified
/// resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to query the troubleshooting
/// result.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<TroubleshootingResult>> GetTroubleshootingResultWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Configures flow log on a specified resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the configuration of flow log.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FlowLogInformation>> SetFlowLogConfigurationWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Queries status of flow log on a specified resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define a resource to query flow log status.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FlowLogInformation>> GetFlowLogStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verifies the possibility of establishing a direct TCP connection
/// from a virtual machine to a given endpoint including another VM or
/// an arbitrary remote server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that determine how the connectivity check will be
/// performed.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectivityInformation>> CheckConnectivityWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, ConnectivityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network watcher resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify IP flow from the specified VM to a location given the
/// currently configured NSG rules.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the IP flow to be verified.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VerificationIPFlowResult>> BeginVerifyIPFlowWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the next hop from the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the source and destination endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NextHopResult>> BeginGetNextHopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NextHopParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the configured and effective security group rules on the
/// specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the VM to check security groups for.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SecurityGroupViewResult>> BeginGetVMSecurityRulesWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiate troubleshooting on a specified resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to troubleshoot.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<TroubleshootingResult>> BeginGetTroubleshootingWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the last completed troubleshooting result on a specified
/// resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to query the troubleshooting
/// result.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<TroubleshootingResult>> BeginGetTroubleshootingResultWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Configures flow log on a specified resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the configuration of flow log.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FlowLogInformation>> BeginSetFlowLogConfigurationWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Queries status of flow log on a specified resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define a resource to query flow log status.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FlowLogInformation>> BeginGetFlowLogStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verifies the possibility of establishing a direct TCP connection
/// from a virtual machine to a given endpoint including another VM or
/// an arbitrary remote server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that determine how the connectivity check will be
/// performed.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectivityInformation>> BeginCheckConnectivityWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, ConnectivityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.MediaServices;
using Microsoft.WindowsAzure.Management.MediaServices.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.WindowsAzure.Management.MediaServices
{
internal partial class AccountOperations : IServiceOperations<MediaServicesManagementClient>, Microsoft.WindowsAzure.Management.MediaServices.IAccountOperations
{
/// <summary>
/// Initializes a new instance of the AccountOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AccountOperations(MediaServicesManagementClient client)
{
this._client = client;
}
private MediaServicesManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.MediaServices.MediaServicesManagementClient.
/// </summary>
public MediaServicesManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Create Media Services Account operation creates a new media
/// services account in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Media Services Account
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Create Media Services Account operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.MediaServices.Models.MediaServicesAccountCreateResponse> CreateAsync(MediaServicesAccountCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.AccountName == null)
{
throw new ArgumentNullException("parameters.AccountName");
}
if (parameters.AccountName.Length < 3)
{
throw new ArgumentOutOfRangeException("parameters.AccountName");
}
if (parameters.AccountName.Length > 24)
{
throw new ArgumentOutOfRangeException("parameters.AccountName");
}
if (parameters.BlobStorageEndpointUri == null)
{
throw new ArgumentNullException("parameters.BlobStorageEndpointUri");
}
if (parameters.Region == null)
{
throw new ArgumentNullException("parameters.Region");
}
if (parameters.Region.Length < 3)
{
throw new ArgumentOutOfRangeException("parameters.Region");
}
if (parameters.Region.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.Region");
}
if (parameters.StorageAccountKey == null)
{
throw new ArgumentNullException("parameters.StorageAccountKey");
}
if (parameters.StorageAccountKey.Length < 14)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountKey");
}
if (parameters.StorageAccountKey.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountKey");
}
if (parameters.StorageAccountName == null)
{
throw new ArgumentNullException("parameters.StorageAccountName");
}
if (parameters.StorageAccountName.Length < 3)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
}
if (parameters.StorageAccountName.Length > 24)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
}
foreach (char storageAccountNameChar in parameters.StorageAccountName)
{
if (char.IsLower(storageAccountNameChar) == false && char.IsDigit(storageAccountNameChar) == false)
{
throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
}
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/mediaservices/Accounts";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement accountCreationRequestElement = new XElement(XName.Get("AccountCreationRequest", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
requestDoc.Add(accountCreationRequestElement);
XElement accountNameElement = new XElement(XName.Get("AccountName", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
accountNameElement.Value = parameters.AccountName;
accountCreationRequestElement.Add(accountNameElement);
XElement blobStorageEndpointUriElement = new XElement(XName.Get("BlobStorageEndpointUri", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
blobStorageEndpointUriElement.Value = parameters.BlobStorageEndpointUri.AbsoluteUri;
accountCreationRequestElement.Add(blobStorageEndpointUriElement);
XElement regionElement = new XElement(XName.Get("Region", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
regionElement.Value = parameters.Region;
accountCreationRequestElement.Add(regionElement);
XElement storageAccountKeyElement = new XElement(XName.Get("StorageAccountKey", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
storageAccountKeyElement.Value = parameters.StorageAccountKey;
accountCreationRequestElement.Add(storageAccountKeyElement);
XElement storageAccountNameElement = new XElement(XName.Get("StorageAccountName", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
storageAccountNameElement.Value = parameters.StorageAccountName;
accountCreationRequestElement.Add(storageAccountNameElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
MediaServicesAccountCreateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MediaServicesAccountCreateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
MediaServicesCreatedAccount accountInstance = new MediaServicesCreatedAccount();
result.Account = accountInstance;
JToken accountIdValue = responseDoc["AccountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
string accountIdInstance = ((string)accountIdValue);
accountInstance.AccountId = accountIdInstance;
}
JToken accountNameValue = responseDoc["AccountName"];
if (accountNameValue != null && accountNameValue.Type != JTokenType.Null)
{
string accountNameInstance = ((string)accountNameValue);
accountInstance.AccountName = accountNameInstance;
}
JToken subscriptionValue = responseDoc["Subscription"];
if (subscriptionValue != null && subscriptionValue.Type != JTokenType.Null)
{
string subscriptionInstance = ((string)subscriptionValue);
accountInstance.SubscriptionId = subscriptionInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete Media Services Account operation deletes an existing
/// media services account in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn194273.aspx
/// for more information)
/// </summary>
/// <param name='accountName'>
/// Required. The name of the media services account.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string accountName, CancellationToken cancellationToken)
{
// Validate
if (accountName == null)
{
throw new ArgumentNullException("accountName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/mediaservices/Accounts/" + accountName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Media Services Account operation gets detailed information
/// about a media services account in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166974.aspx
/// for more information)
/// </summary>
/// <param name='accountName'>
/// Required. The name of the Media Services account.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Media Services Account operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.MediaServices.Models.MediaServicesAccountGetResponse> GetAsync(string accountName, CancellationToken cancellationToken)
{
// Validate
if (accountName == null)
{
throw new ArgumentNullException("accountName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/mediaservices/Accounts/" + accountName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
MediaServicesAccountGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MediaServicesAccountGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
MediaServicesAccount accountInstance = new MediaServicesAccount();
result.Account = accountInstance;
JToken accountNameValue = responseDoc["AccountName"];
if (accountNameValue != null && accountNameValue.Type != JTokenType.Null)
{
string accountNameInstance = ((string)accountNameValue);
accountInstance.AccountName = accountNameInstance;
}
JToken accountKeyValue = responseDoc["AccountKey"];
if (accountKeyValue != null && accountKeyValue.Type != JTokenType.Null)
{
string accountKeyInstance = ((string)accountKeyValue);
accountInstance.AccountKey = accountKeyInstance;
}
JToken accountKeysValue = responseDoc["AccountKeys"];
if (accountKeysValue != null && accountKeysValue.Type != JTokenType.Null)
{
MediaServicesAccount.AccountKeys accountKeysInstance = new MediaServicesAccount.AccountKeys();
accountInstance.StorageAccountKeys = accountKeysInstance;
JToken primaryValue = accountKeysValue["Primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
string primaryInstance = ((string)primaryValue);
accountKeysInstance.Primary = primaryInstance;
}
JToken secondaryValue = accountKeysValue["Secondary"];
if (secondaryValue != null && secondaryValue.Type != JTokenType.Null)
{
string secondaryInstance = ((string)secondaryValue);
accountKeysInstance.Secondary = secondaryInstance;
}
}
JToken accountRegionValue = responseDoc["AccountRegion"];
if (accountRegionValue != null && accountRegionValue.Type != JTokenType.Null)
{
string accountRegionInstance = ((string)accountRegionValue);
accountInstance.AccountRegion = accountRegionInstance;
}
JToken storageAccountNameValue = responseDoc["StorageAccountName"];
if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
{
string storageAccountNameInstance = ((string)storageAccountNameValue);
accountInstance.StorageAccountName = storageAccountNameInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Media Services Account operation gets information about
/// all existing media services accounts associated with the current
/// subscription in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166989.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Media Accounts operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.MediaServices.Models.MediaServicesAccountListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/mediaservices/Accounts";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
MediaServicesAccountListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MediaServicesAccountListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourcesSequenceElement != null)
{
foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
MediaServicesAccountListResponse.MediaServiceAccount serviceResourceInstance = new MediaServicesAccountListResponse.MediaServiceAccount();
result.Accounts.Add(serviceResourceInstance);
XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
XElement selfLinkElement = serviceResourcesElement.Element(XName.Get("SelfLink", "http://schemas.microsoft.com/windowsazure"));
if (selfLinkElement != null)
{
Uri selfLinkInstance = TypeConversion.TryParseUri(selfLinkElement.Value);
serviceResourceInstance.Uri = selfLinkInstance;
}
XElement parentLinkElement = serviceResourcesElement.Element(XName.Get("ParentLink", "http://schemas.microsoft.com/windowsazure"));
if (parentLinkElement != null)
{
Uri parentLinkInstance = TypeConversion.TryParseUri(parentLinkElement.Value);
serviceResourceInstance.ParentUri = parentLinkInstance;
}
XElement accountIdElement = serviceResourcesElement.Element(XName.Get("AccountId", "http://schemas.microsoft.com/windowsazure"));
if (accountIdElement != null)
{
string accountIdInstance = accountIdElement.Value;
serviceResourceInstance.AccountId = accountIdInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Regenerate Media Services Account Key operation regenerates an
/// account key for the given Media Services account in Windows Azure.
/// (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn167010.aspx
/// for more information)
/// </summary>
/// <param name='accountName'>
/// Required. The name of the Media Services Account.
/// </param>
/// <param name='keyType'>
/// Required. The type of key to regenerate (primary or secondary)
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> RegenerateKeyAsync(string accountName, MediaServicesKeyType keyType, CancellationToken cancellationToken)
{
// Validate
if (accountName == null)
{
throw new ArgumentNullException("accountName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("keyType", keyType);
Tracing.Enter(invocationId, this, "RegenerateKeyAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/mediaservices/Accounts/" + accountName.Trim() + "/AccountKeys/" + keyType + "/Regenerate";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
#if FEATURE_UTF32
namespace System.Text
{
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
// Encodes text into and out of UTF-32. UTF-32 is a way of writing
// Unicode characters with a single storage unit (32 bits) per character,
//
// The UTF-32 byte order mark is simply the Unicode byte order mark
// (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order
// mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't
// switch the byte orderings.
[Serializable]
public sealed class UTF32Encoding : Encoding
{
/*
words bits UTF-32 representation
----- ---- -----------------------------------
1 16 00000000 00000000 xxxxxxxx xxxxxxxx
2 21 00000000 000xxxxx hhhhhhll llllllll
----- ---- -----------------------------------
Surrogate:
Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
*/
//
private bool emitUTF32ByteOrderMark = false;
private bool isThrowException = false;
private bool bigEndian = false;
public UTF32Encoding(): this(false, true, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark):
this(bigEndian, byteOrderMark, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters):
base(bigEndian ? 12001 : 12000)
{
this.bigEndian = bigEndian;
this.emitUTF32ByteOrderMark = byteOrderMark;
this.isThrowException = throwOnInvalidCharacters;
// Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions
if (this.isThrowException)
SetDefaultFallbacks();
}
internal override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
if (this.isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
}
else
{
this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
}
}
//
// The following methods are copied from EncodingNLS.cs.
// Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here.
// These should be kept in sync for the following classes:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
//
// Returns the number of bytes required to encode a range of characters in
// a character array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException("chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// If no input, return 0, avoid fixed empty array problem
if (chars.Length == 0)
return 0;
// Just call the pointer version
fixed (char* pChars = chars)
return GetByteCount(pChars + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetByteCount(String s)
{
// Validate input
if (s==null)
throw new ArgumentNullException("s");
Contract.EndContractBlock();
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
// Validate Parameters
if (chars == null)
throw new ArgumentNullException("chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
}
// Parent method is safe.
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if (s == null || bytes == null)
throw new ArgumentNullException((s == null ? "s" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("s",
Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = s)
fixed ( byte* pBytes = bytes)
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
// If nothing to encode return 0, avoid fixed problem
if (chars.Length == 0)
return 0;
// Just call pointer version
int byteCount = bytes.Length - byteIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
// Remember that byteCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// If no input just return 0, fixed doesn't like 0 length arrays.
if (bytes.Length == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
// If no input, return 0 & avoid fixed problem
if (bytes.Length == 0)
return 0;
// Just call pointer version
int charCount = chars.Length - charIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (chars.Length == 0)
chars = new char[1];
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe String GetString(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid problems with empty input buffer
if (bytes.Length == 0) return String.Empty;
fixed (byte* pBytes = bytes)
return String.CreateStringFromEncoding(
pBytes + index, count, this);
}
//
// End of standard methods copied from EncodingNLS.cs
//
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder)
{
Contract.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
Contract.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
int byteCount = 0;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
highSurrogate = encoder.charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when counting
if (fallbackBuffer.Remaining > 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, end, encoder, false);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encounter a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// They're all legal
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
byteCount += 4;
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Contract.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Try again with fallback buffer
continue;
}
// We get to add the character (4 bytes UTF32)
byteCount += 4;
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
highSurrogate = (char)0;
goto TryAgain;
}
// Check for overflows.
if (byteCount < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString(
"ArgumentOutOfRange_GetByteCountOverflow"));
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check m_throwOnOverflow for count)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
// Return our count
return byteCount;
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char *chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
Contract.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
Contract.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
Contract.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
Contract.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
highSurrogate = encoder.charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when not converting
if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encountered a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// Is it a legal one?
uint iTemp = GetSurrogate(highSurrogate, ch);
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
if (bytes+3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
{
fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars
fallbackBuffer.MovePrevious();
}
else
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
Contract.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars-=2; // Aren't using those 2 chars
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary)
break;
}
if (bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(0x00);
}
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Contract.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?, if so remember it
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters (low surrogate)
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Try again with fallback buffer
continue;
}
// We get to add the character, yippee.
if (bytes+3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
fallbackBuffer.MovePrevious(); // Aren't using this fallback char
else
{
// Must've advanced already
Contract.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
chars--; // Aren't using this char
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
break; // Didn't throw, stop
}
if (bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(ch); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(ch); // Implies & 0xFF
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
}
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
fallbackBuffer.InternalFallback(highSurrogate, ref chars);
highSurrogate = (char)0;
goto TryAgain;
}
// Fix our encoder if we have one
Contract.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
"[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
if (encoder != null)
{
// Remember our left over surrogate (or 0 if flushing)
encoder.charLeftOver = highSurrogate;
// Need # chars used
encoder.m_charsUsed = (int)(chars-charStart);
}
// return the new length
return (int)(bytes - byteStart);
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
Contract.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
Contract.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
int charCount = 0;
byte* end = bytes + count;
byte* byteStart = bytes;
// Set up decoder
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = decoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(byteStart, null);
// Loop through our input, 4 characters at a time!
while (bytes < end && charCount >= 0)
{
// Get our next character
if(bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (this.bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
charCount++;
}
// Add the rest of the surrogate or our normal character
charCount++;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
if (this.bigEndian)
{
while(readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)(iChar>>24));
iChar <<= 8;
}
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
}
// Check for overflows.
if (charCount < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
[System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
Contract.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
Contract.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
Contract.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
Contract.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
// See if there's anything in our decoder (but don't clear it yet)
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = baseDecoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(bytes, chars + charCount);
// Loop through our input, 4 characters at a time!
while (bytes < byteEnd)
{
// Get our next character
if(bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (this.bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
// Chars won't be updated unless this works.
if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars))
{
// Couldn't fallback, throw or wait til next time
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
if (chars >= charEnd - 1)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
*(chars++) = GetHighSurrogate(iChar);
iChar = GetLowSurrogate(iChar);
}
// Bounds check for normal character
else if (chars >= charEnd)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Add the rest of the surrogate or our normal character
*(chars++) = (char)iChar;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
int tempCount = readCount;
if (this.bigEndian)
{
while(tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)(iChar>>24));
iChar <<= 8;
}
}
if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars))
{
// Couldn't fallback.
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
// Stop here, didn't throw, backed up, so still nothing in buffer
}
else
{
// Don't clear our decoder unless we could fall it back.
// If we caught the if above, then we're a convert() and will catch this next time.
readCount = 0;
iChar = 0;
}
}
// Remember any left over stuff, clearing buffer as well for MustFlush
if (decoder != null)
{
decoder.iChar = (int)iChar;
decoder.readByteCount = readCount;
decoder.m_bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
Contract.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
// Return our count
return (int)(chars - charStart);
}
private uint GetSurrogate(char cHigh, char cLow)
{
return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000;
}
private char GetHighSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) / 0x400 + 0xD800);
}
private char GetLowSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) % 0x400 + 0xDC00);
}
public override Decoder GetDecoder()
{
return new UTF32Decoder(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 4 bytes per char
byteCount *= 4;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars,
// plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char.
// Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair
int charCount = (byteCount / 2) + 2;
// Also consider fallback because our input bytes could be out of range of unicode.
// Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount.
if (DecoderFallback.MaxCharCount > 2)
{
// Multiply time fallback size
charCount *= DecoderFallback.MaxCharCount;
// We were already figuring 2 chars per 4 bytes, but fallback will be different #
charCount /= 2;
}
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
return (int)charCount;
}
public override byte[] GetPreamble()
{
if (emitUTF32ByteOrderMark)
{
// Allocate new array to prevent users from modifying it.
if (bigEndian)
{
return new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
}
else
{
return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF
}
}
else
return EmptyArray<Byte>.Value;
}
public override bool Equals(Object value)
{
UTF32Encoding that = value as UTF32Encoding;
if (that != null)
{
return (emitUTF32ByteOrderMark == that.emitUTF32ByteOrderMark) &&
(bigEndian == that.bigEndian) &&
// (isThrowException == that.isThrowException) && // same as encoder/decoderfallback being exceptions
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
return (false);
}
public override int GetHashCode()
{
//Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
CodePage + (emitUTF32ByteOrderMark?4:0) + (bigEndian?8:0);
}
[Serializable]
internal class UTF32Decoder : DecoderNLS
{
// Need a place to store any extra bytes we may have picked up
internal int iChar = 0;
internal int readByteCount = 0;
public UTF32Decoder(UTF32Encoding encoding) : base(encoding)
{
// base calls reset
}
public override void Reset()
{
this.iChar = 0;
this.readByteCount = 0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
// ReadByteCount is our flag. (iChar==0 doesn't mean much).
return (this.readByteCount != 0);
}
}
}
}
}
#endif // FEATURE_UTF32
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: SystemMessageFormats.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 Akka.Remote.Serialization.Proto.Msg {
/// <summary>Holder for reflection information generated from SystemMessageFormats.proto</summary>
internal static partial class SystemMessageFormatsReflection {
#region Descriptor
/// <summary>File descriptor for SystemMessageFormats.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static SystemMessageFormatsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChpTeXN0ZW1NZXNzYWdlRm9ybWF0cy5wcm90bxIjQWtrYS5SZW1vdGUuU2Vy",
"aWFsaXphdGlvbi5Qcm90by5Nc2caFkNvbnRhaW5lckZvcm1hdHMucHJvdG8i",
"TwoKQ3JlYXRlRGF0YRJBCgVjYXVzZRgBIAEoCzIyLkFra2EuUmVtb3RlLlNl",
"cmlhbGl6YXRpb24uUHJvdG8uTXNnLkV4Y2VwdGlvbkRhdGEiUQoMUmVjcmVh",
"dGVEYXRhEkEKBWNhdXNlGAEgASgLMjIuQWtrYS5SZW1vdGUuU2VyaWFsaXph",
"dGlvbi5Qcm90by5Nc2cuRXhjZXB0aW9uRGF0YSJPCgpSZXN1bWVEYXRhEkEK",
"BWNhdXNlGAEgASgLMjIuQWtrYS5SZW1vdGUuU2VyaWFsaXphdGlvbi5Qcm90",
"by5Nc2cuRXhjZXB0aW9uRGF0YSJgCg1TdXBlcnZpc2VEYXRhEkAKBWNoaWxk",
"GAEgASgLMjEuQWtrYS5SZW1vdGUuU2VyaWFsaXphdGlvbi5Qcm90by5Nc2cu",
"QWN0b3JSZWZEYXRhEg0KBWFzeW5jGAIgASgIIpMBCglXYXRjaERhdGESQgoH",
"d2F0Y2hlZRgBIAEoCzIxLkFra2EuUmVtb3RlLlNlcmlhbGl6YXRpb24uUHJv",
"dG8uTXNnLkFjdG9yUmVmRGF0YRJCCgd3YXRjaGVyGAIgASgLMjEuQWtrYS5S",
"ZW1vdGUuU2VyaWFsaXphdGlvbi5Qcm90by5Nc2cuQWN0b3JSZWZEYXRhIp4B",
"CgpGYWlsZWREYXRhEkAKBWNoaWxkGAEgASgLMjEuQWtrYS5SZW1vdGUuU2Vy",
"aWFsaXphdGlvbi5Qcm90by5Nc2cuQWN0b3JSZWZEYXRhEkEKBWNhdXNlGAIg",
"ASgLMjIuQWtrYS5SZW1vdGUuU2VyaWFsaXphdGlvbi5Qcm90by5Nc2cuRXhj",
"ZXB0aW9uRGF0YRILCgN1aWQYAyABKAQilQEKGkRlYXRoV2F0Y2hOb3RpZmlj",
"YXRpb25EYXRhEkAKBWFjdG9yGAEgASgLMjEuQWtrYS5SZW1vdGUuU2VyaWFs",
"aXphdGlvbi5Qcm90by5Nc2cuQWN0b3JSZWZEYXRhEhoKEmV4aXN0ZW5jZUNv",
"bmZpcm1lZBgCIAEoCBIZChFhZGRyZXNzVGVybWluYXRlZBgDIAEoCGIGcHJv",
"dG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.CreateData), global::Akka.Remote.Serialization.Proto.Msg.CreateData.Parser, new[]{ "Cause" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.RecreateData), global::Akka.Remote.Serialization.Proto.Msg.RecreateData.Parser, new[]{ "Cause" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.ResumeData), global::Akka.Remote.Serialization.Proto.Msg.ResumeData.Parser, new[]{ "Cause" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.SuperviseData), global::Akka.Remote.Serialization.Proto.Msg.SuperviseData.Parser, new[]{ "Child", "Async" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.WatchData), global::Akka.Remote.Serialization.Proto.Msg.WatchData.Parser, new[]{ "Watchee", "Watcher" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.FailedData), global::Akka.Remote.Serialization.Proto.Msg.FailedData.Parser, new[]{ "Child", "Cause", "Uid" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.DeathWatchNotificationData), global::Akka.Remote.Serialization.Proto.Msg.DeathWatchNotificationData.Parser, new[]{ "Actor", "ExistenceConfirmed", "AddressTerminated" }, null, null, null)
}));
}
#endregion
}
#region Messages
internal sealed partial class CreateData : pb::IMessage<CreateData> {
private static readonly pb::MessageParser<CreateData> _parser = new pb::MessageParser<CreateData>(() => new CreateData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CreateData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Remote.Serialization.Proto.Msg.SystemMessageFormatsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateData(CreateData other) : this() {
Cause = other.cause_ != null ? other.Cause.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateData Clone() {
return new CreateData(this);
}
/// <summary>Field number for the "cause" field.</summary>
public const int CauseFieldNumber = 1;
private global::Akka.Remote.Serialization.Proto.Msg.ExceptionData cause_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ExceptionData Cause {
get { return cause_; }
set {
cause_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CreateData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CreateData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Cause, other.Cause)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (cause_ != null) hash ^= Cause.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 (cause_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Cause);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (cause_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Cause);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CreateData other) {
if (other == null) {
return;
}
if (other.cause_ != null) {
if (cause_ == null) {
cause_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData();
}
Cause.MergeFrom(other.Cause);
}
}
[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 (cause_ == null) {
cause_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData();
}
input.ReadMessage(cause_);
break;
}
}
}
}
}
internal sealed partial class RecreateData : pb::IMessage<RecreateData> {
private static readonly pb::MessageParser<RecreateData> _parser = new pb::MessageParser<RecreateData>(() => new RecreateData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RecreateData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Remote.Serialization.Proto.Msg.SystemMessageFormatsReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecreateData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecreateData(RecreateData other) : this() {
Cause = other.cause_ != null ? other.Cause.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecreateData Clone() {
return new RecreateData(this);
}
/// <summary>Field number for the "cause" field.</summary>
public const int CauseFieldNumber = 1;
private global::Akka.Remote.Serialization.Proto.Msg.ExceptionData cause_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ExceptionData Cause {
get { return cause_; }
set {
cause_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RecreateData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RecreateData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Cause, other.Cause)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (cause_ != null) hash ^= Cause.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 (cause_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Cause);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (cause_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Cause);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RecreateData other) {
if (other == null) {
return;
}
if (other.cause_ != null) {
if (cause_ == null) {
cause_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData();
}
Cause.MergeFrom(other.Cause);
}
}
[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 (cause_ == null) {
cause_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData();
}
input.ReadMessage(cause_);
break;
}
}
}
}
}
internal sealed partial class ResumeData : pb::IMessage<ResumeData> {
private static readonly pb::MessageParser<ResumeData> _parser = new pb::MessageParser<ResumeData>(() => new ResumeData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ResumeData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Remote.Serialization.Proto.Msg.SystemMessageFormatsReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResumeData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResumeData(ResumeData other) : this() {
Cause = other.cause_ != null ? other.Cause.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResumeData Clone() {
return new ResumeData(this);
}
/// <summary>Field number for the "cause" field.</summary>
public const int CauseFieldNumber = 1;
private global::Akka.Remote.Serialization.Proto.Msg.ExceptionData cause_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ExceptionData Cause {
get { return cause_; }
set {
cause_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ResumeData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ResumeData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Cause, other.Cause)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (cause_ != null) hash ^= Cause.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 (cause_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Cause);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (cause_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Cause);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ResumeData other) {
if (other == null) {
return;
}
if (other.cause_ != null) {
if (cause_ == null) {
cause_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData();
}
Cause.MergeFrom(other.Cause);
}
}
[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 (cause_ == null) {
cause_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData();
}
input.ReadMessage(cause_);
break;
}
}
}
}
}
internal sealed partial class SuperviseData : pb::IMessage<SuperviseData> {
private static readonly pb::MessageParser<SuperviseData> _parser = new pb::MessageParser<SuperviseData>(() => new SuperviseData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<SuperviseData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Remote.Serialization.Proto.Msg.SystemMessageFormatsReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SuperviseData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SuperviseData(SuperviseData other) : this() {
Child = other.child_ != null ? other.Child.Clone() : null;
async_ = other.async_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SuperviseData Clone() {
return new SuperviseData(this);
}
/// <summary>Field number for the "child" field.</summary>
public const int ChildFieldNumber = 1;
private global::Akka.Remote.Serialization.Proto.Msg.ActorRefData child_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ActorRefData Child {
get { return child_; }
set {
child_ = value;
}
}
/// <summary>Field number for the "async" field.</summary>
public const int AsyncFieldNumber = 2;
private bool async_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Async {
get { return async_; }
set {
async_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as SuperviseData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(SuperviseData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Child, other.Child)) return false;
if (Async != other.Async) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (child_ != null) hash ^= Child.GetHashCode();
if (Async != false) hash ^= Async.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 (child_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Child);
}
if (Async != false) {
output.WriteRawTag(16);
output.WriteBool(Async);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (child_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Child);
}
if (Async != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(SuperviseData other) {
if (other == null) {
return;
}
if (other.child_ != null) {
if (child_ == null) {
child_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
Child.MergeFrom(other.Child);
}
if (other.Async != false) {
Async = other.Async;
}
}
[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 (child_ == null) {
child_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
input.ReadMessage(child_);
break;
}
case 16: {
Async = input.ReadBool();
break;
}
}
}
}
}
internal sealed partial class WatchData : pb::IMessage<WatchData> {
private static readonly pb::MessageParser<WatchData> _parser = new pb::MessageParser<WatchData>(() => new WatchData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<WatchData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Remote.Serialization.Proto.Msg.SystemMessageFormatsReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WatchData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WatchData(WatchData other) : this() {
Watchee = other.watchee_ != null ? other.Watchee.Clone() : null;
Watcher = other.watcher_ != null ? other.Watcher.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WatchData Clone() {
return new WatchData(this);
}
/// <summary>Field number for the "watchee" field.</summary>
public const int WatcheeFieldNumber = 1;
private global::Akka.Remote.Serialization.Proto.Msg.ActorRefData watchee_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ActorRefData Watchee {
get { return watchee_; }
set {
watchee_ = value;
}
}
/// <summary>Field number for the "watcher" field.</summary>
public const int WatcherFieldNumber = 2;
private global::Akka.Remote.Serialization.Proto.Msg.ActorRefData watcher_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ActorRefData Watcher {
get { return watcher_; }
set {
watcher_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as WatchData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(WatchData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Watchee, other.Watchee)) return false;
if (!object.Equals(Watcher, other.Watcher)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (watchee_ != null) hash ^= Watchee.GetHashCode();
if (watcher_ != null) hash ^= Watcher.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 (watchee_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Watchee);
}
if (watcher_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Watcher);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (watchee_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Watchee);
}
if (watcher_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Watcher);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(WatchData other) {
if (other == null) {
return;
}
if (other.watchee_ != null) {
if (watchee_ == null) {
watchee_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
Watchee.MergeFrom(other.Watchee);
}
if (other.watcher_ != null) {
if (watcher_ == null) {
watcher_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
Watcher.MergeFrom(other.Watcher);
}
}
[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 (watchee_ == null) {
watchee_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
input.ReadMessage(watchee_);
break;
}
case 18: {
if (watcher_ == null) {
watcher_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
input.ReadMessage(watcher_);
break;
}
}
}
}
}
internal sealed partial class FailedData : pb::IMessage<FailedData> {
private static readonly pb::MessageParser<FailedData> _parser = new pb::MessageParser<FailedData>(() => new FailedData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FailedData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Remote.Serialization.Proto.Msg.SystemMessageFormatsReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FailedData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FailedData(FailedData other) : this() {
Child = other.child_ != null ? other.Child.Clone() : null;
Cause = other.cause_ != null ? other.Cause.Clone() : null;
uid_ = other.uid_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FailedData Clone() {
return new FailedData(this);
}
/// <summary>Field number for the "child" field.</summary>
public const int ChildFieldNumber = 1;
private global::Akka.Remote.Serialization.Proto.Msg.ActorRefData child_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ActorRefData Child {
get { return child_; }
set {
child_ = value;
}
}
/// <summary>Field number for the "cause" field.</summary>
public const int CauseFieldNumber = 2;
private global::Akka.Remote.Serialization.Proto.Msg.ExceptionData cause_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ExceptionData Cause {
get { return cause_; }
set {
cause_ = value;
}
}
/// <summary>Field number for the "uid" field.</summary>
public const int UidFieldNumber = 3;
private ulong uid_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong Uid {
get { return uid_; }
set {
uid_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FailedData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FailedData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Child, other.Child)) return false;
if (!object.Equals(Cause, other.Cause)) return false;
if (Uid != other.Uid) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (child_ != null) hash ^= Child.GetHashCode();
if (cause_ != null) hash ^= Cause.GetHashCode();
if (Uid != 0UL) hash ^= Uid.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 (child_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Child);
}
if (cause_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Cause);
}
if (Uid != 0UL) {
output.WriteRawTag(24);
output.WriteUInt64(Uid);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (child_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Child);
}
if (cause_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Cause);
}
if (Uid != 0UL) {
size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Uid);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FailedData other) {
if (other == null) {
return;
}
if (other.child_ != null) {
if (child_ == null) {
child_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
Child.MergeFrom(other.Child);
}
if (other.cause_ != null) {
if (cause_ == null) {
cause_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData();
}
Cause.MergeFrom(other.Cause);
}
if (other.Uid != 0UL) {
Uid = other.Uid;
}
}
[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 (child_ == null) {
child_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
input.ReadMessage(child_);
break;
}
case 18: {
if (cause_ == null) {
cause_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData();
}
input.ReadMessage(cause_);
break;
}
case 24: {
Uid = input.ReadUInt64();
break;
}
}
}
}
}
internal sealed partial class DeathWatchNotificationData : pb::IMessage<DeathWatchNotificationData> {
private static readonly pb::MessageParser<DeathWatchNotificationData> _parser = new pb::MessageParser<DeathWatchNotificationData>(() => new DeathWatchNotificationData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DeathWatchNotificationData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Remote.Serialization.Proto.Msg.SystemMessageFormatsReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeathWatchNotificationData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeathWatchNotificationData(DeathWatchNotificationData other) : this() {
Actor = other.actor_ != null ? other.Actor.Clone() : null;
existenceConfirmed_ = other.existenceConfirmed_;
addressTerminated_ = other.addressTerminated_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeathWatchNotificationData Clone() {
return new DeathWatchNotificationData(this);
}
/// <summary>Field number for the "actor" field.</summary>
public const int ActorFieldNumber = 1;
private global::Akka.Remote.Serialization.Proto.Msg.ActorRefData actor_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Remote.Serialization.Proto.Msg.ActorRefData Actor {
get { return actor_; }
set {
actor_ = value;
}
}
/// <summary>Field number for the "existenceConfirmed" field.</summary>
public const int ExistenceConfirmedFieldNumber = 2;
private bool existenceConfirmed_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ExistenceConfirmed {
get { return existenceConfirmed_; }
set {
existenceConfirmed_ = value;
}
}
/// <summary>Field number for the "addressTerminated" field.</summary>
public const int AddressTerminatedFieldNumber = 3;
private bool addressTerminated_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool AddressTerminated {
get { return addressTerminated_; }
set {
addressTerminated_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DeathWatchNotificationData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DeathWatchNotificationData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Actor, other.Actor)) return false;
if (ExistenceConfirmed != other.ExistenceConfirmed) return false;
if (AddressTerminated != other.AddressTerminated) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (actor_ != null) hash ^= Actor.GetHashCode();
if (ExistenceConfirmed != false) hash ^= ExistenceConfirmed.GetHashCode();
if (AddressTerminated != false) hash ^= AddressTerminated.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 (actor_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Actor);
}
if (ExistenceConfirmed != false) {
output.WriteRawTag(16);
output.WriteBool(ExistenceConfirmed);
}
if (AddressTerminated != false) {
output.WriteRawTag(24);
output.WriteBool(AddressTerminated);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (actor_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Actor);
}
if (ExistenceConfirmed != false) {
size += 1 + 1;
}
if (AddressTerminated != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DeathWatchNotificationData other) {
if (other == null) {
return;
}
if (other.actor_ != null) {
if (actor_ == null) {
actor_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
Actor.MergeFrom(other.Actor);
}
if (other.ExistenceConfirmed != false) {
ExistenceConfirmed = other.ExistenceConfirmed;
}
if (other.AddressTerminated != false) {
AddressTerminated = other.AddressTerminated;
}
}
[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 (actor_ == null) {
actor_ = new global::Akka.Remote.Serialization.Proto.Msg.ActorRefData();
}
input.ReadMessage(actor_);
break;
}
case 16: {
ExistenceConfirmed = input.ReadBool();
break;
}
case 24: {
AddressTerminated = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.