context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// DeflateStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2010 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-July-31 14:48:11>
//
// ------------------------------------------------------------------
//
// This module defines the DeflateStream class, which can be used as a replacement for
// the System.IO.Compression.DeflateStream class in the .NET BCL.
//
// ------------------------------------------------------------------
using System;
namespace Ionic2.Zlib
{
/// <summary>
/// A class for compressing and decompressing streams using the Deflate algorithm.
/// </summary>
///
/// <remarks>
///
/// <para>
/// The DeflateStream is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see
/// cref="System.IO.Stream"/>. It adds DEFLATE compression or decompression to any
/// stream.
/// </para>
///
/// <para>
/// Using this stream, applications can compress or decompress data via stream
/// <c>Read</c> and <c>Write</c> operations. Either compresssion or decompression
/// can occur through either reading or writing. The compression format used is
/// DEFLATE, which is documented in <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE
/// Compressed Data Format Specification version 1.3.".
/// </para>
///
/// <para>
/// This class is similar to <see cref="ZlibStream"/>, except that
/// <c>ZlibStream</c> adds the <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950 - ZLIB</see> framing bytes to a compressed stream when compressing, or
/// expects the RFC1950 framing bytes when decompressing. The <c>DeflateStream</c>
/// does not.
/// </para>
///
/// </remarks>
///
/// <seealso cref="ZlibStream" />
/// <seealso cref="GZipStream" />
public class DeflateStream : System.IO.Stream
{
internal ZlibBaseStream _baseStream;
internal System.IO.Stream _innerStream;
bool _disposed;
/// <summary>
/// Create a DeflateStream using the specified CompressionMode.
/// </summary>
///
/// <remarks>
/// When mode is <c>CompressionMode.Compress</c>, the DeflateStream will use
/// the default compression level. The "captive" stream will be closed when
/// the DeflateStream is closed.
/// </remarks>
///
/// <example>
/// This example uses a DeflateStream to compress data from a file, and writes
/// the compressed data to another file.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".deflated")
/// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a DeflateStream using the specified CompressionMode and the specified CompressionLevel.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is
/// ignored. The "captive" stream will be closed when the DeflateStream is
/// closed.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example uses a DeflateStream to compress data from a file, and writes
/// the compressed data to another file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (Stream compressor = new DeflateStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// while (n != 0)
/// {
/// if (n > 0)
/// compressor.Write(buffer, 0, n);
/// n= input.Read(buffer, 0, buffer.Length);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".deflated")
/// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the <c>DeflateStream</c> will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>DeflateStream</c> using the specified
/// <c>CompressionMode</c>, and explicitly specify whether the
/// stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compression. Specify true for
/// the <paramref name="leaveOpen"/> parameter to leave the stream open.
/// </para>
///
/// <para>
/// The <c>DeflateStream</c> will use the default compression level.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
/// </remarks>
///
/// <param name="stream">
/// The stream which will be read or written. This is called the
/// "captive" stream in other places in this documentation.
/// </param>
///
/// <param name="mode">
/// Indicates whether the <c>DeflateStream</c> will compress or decompress.
/// </param>
///
/// <param name="leaveOpen">true if the application would like the stream to
/// remain open after inflation/deflation.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>DeflateStream</c> using the specified <c>CompressionMode</c>
/// and the specified <c>CompressionLevel</c>, and explicitly specify whether
/// the stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored.
/// </para>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// <see cref="System.IO.MemoryStream"/> that will be re-read after
/// compression. Specify true for the <paramref name="leaveOpen"/> parameter
/// to leave the stream open.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a <c>DeflateStream</c> to compress data from
/// a file, and store the compressed data into another file.
///
/// <code>
/// using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// while (n != 0)
/// {
/// if (n > 0)
/// compressor.Write(buffer, 0, n);
/// n= input.Read(buffer, 0, buffer.Length);
/// }
/// }
/// }
/// // can write additional data to the output stream here
/// }
/// </code>
///
/// <code lang="VB">
/// Using output As FileStream = File.Create(fileToCompress & ".deflated")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// ' can write additional data to the output stream here.
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_innerStream = stream;
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.DEFLATE, leaveOpen);
}
/// <summary>
/// This property sets the flush behavior on the stream.
/// </summary>
/// <remarks> See the ZLIB documentation for the meaning of the flush behavior.
/// </remarks>
virtual public FlushType FlushMode
{
get { return (_baseStream._flushMode); }
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return _baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
if (_baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
_baseStream._bufferSize = value;
}
}
/// <summary>
/// The ZLIB strategy to be used during compression.
/// </summary>
///
/// <remarks>
/// By tweaking this parameter, you may be able to optimize the compression for
/// data with particular characteristics.
/// </remarks>
public CompressionStrategy Strategy
{
get
{
return _baseStream.Strategy;
}
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Strategy = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get
{
return _baseStream._z.TotalBytesIn;
}
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get
{
return _baseStream._z.TotalBytesOut;
}
}
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// Application code won't call this code directly. This method may be
/// invoked in two distinct scenarios. If disposing == true, the method
/// has been called directly or indirectly by a user's code, for example
/// via the public Dispose() method. In this case, both managed and
/// unmanaged resources can be referenced and disposed. If disposing ==
/// false, the method has been called by the runtime from inside the
/// object finalizer and this method should not reference other objects;
/// in that case only unmanaged resources must be referenced or
/// disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// true if the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (_baseStream != null))
_baseStream.Close();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (_baseStream._streamMode == Ionic2.Zlib.ZlibBaseStream.StreamMode.Writer)
return _baseStream._z.TotalBytesOut;
if (_baseStream._streamMode == Ionic2.Zlib.ZlibBaseStream.StreamMode.Reader)
return _baseStream._z.TotalBytesIn;
return 0;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Read data from the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// If you wish to use the <c>DeflateStream</c> to compress data while
/// reading, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Compress</c>, providing an uncompressed data stream.
/// Then call Read() on that <c>DeflateStream</c>, and the data read will be
/// compressed as you read. If you wish to use the <c>DeflateStream</c> to
/// decompress data while reading, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Decompress</c>, providing a readable compressed data
/// stream. Then call Read() on that <c>DeflateStream</c>, and the data read
/// will be decompressed as you read.
/// </para>
///
/// <para>
/// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer into which the read data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream.Read(buffer, offset, count);
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">this is irrelevant, since it will always throw!</param>
/// <param name="origin">this is irrelevant, since it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">this is irrelevant, since it will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// If you wish to use the <c>DeflateStream</c> to compress data while
/// writing, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Compress</c>, and a writable output stream. Then call
/// <c>Write()</c> on that <c>DeflateStream</c>, providing uncompressed data
/// as input. The data sent to the output stream will be the compressed form
/// of the data written. If you wish to use the <c>DeflateStream</c> to
/// decompress data while writing, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Decompress</c>, and a writable output stream. Then
/// call <c>Write()</c> on that stream, providing previously compressed
/// data. The data sent to the output stream will be the decompressed form of
/// the data written.
/// </para>
///
/// <para>
/// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>,
/// but not both.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Write(buffer, offset, count);
}
/// <summary>
/// Compress a string into a byte array using DEFLATE (RFC 1951).
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="DeflateStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso>
/// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.CompressString(string)">GZipStream.CompressString(string)</seealso>
/// <seealso cref="ZlibStream.CompressString(string)">ZlibStream.CompressString(string)</seealso>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new System.IO.MemoryStream())
{
System.IO.Stream compressor =
new DeflateStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using DEFLATE.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="DeflateStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="DeflateStream.CompressString(string)">DeflateStream.CompressString(string)</seealso>
/// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.CompressBuffer(byte[])">GZipStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="ZlibStream.CompressBuffer(byte[])">ZlibStream.CompressBuffer(byte[])</seealso>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new System.IO.MemoryStream())
{
System.IO.Stream compressor =
new DeflateStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a DEFLATE'd byte array into a single string.
/// </summary>
///
/// <seealso cref="DeflateStream.CompressString(String)">DeflateStream.CompressString(String)</seealso>
/// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.UncompressString(byte[])">GZipStream.UncompressString(byte[])</seealso>
/// <seealso cref="ZlibStream.UncompressString(byte[])">ZlibStream.UncompressString(byte[])</seealso>
///
/// <param name="compressed">
/// A buffer containing DEFLATE-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new DeflateStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a DEFLATE'd byte array into a byte array.
/// </summary>
///
/// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])">GZipStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])">ZlibStream.UncompressBuffer(byte[])</seealso>
///
/// <param name="compressed">
/// A buffer containing data that has been compressed with DEFLATE.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new DeflateStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| |
// 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 System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SharpGen.Config;
using SharpGen.CppModel;
namespace SharpGen.Generator
{
/// <summary>
/// This class handles renaming according to conventions. Pascal case (NamingRulesManager) for global types,
/// Camel case (namingRulesManager) for parameters.
/// </summary>
public class NamingRulesManager
{
private readonly List<ShortNameMapper> _expandShortName = new List<ShortNameMapper>();
/// <summary>
/// The recorded names, a list of previous name and new name.
/// </summary>
public readonly List<Tuple<CppElement, string>> RecordNames = new List<Tuple<CppElement, string>>();
/// <summary>
/// Adds the short name rule.
/// </summary>
/// <param name="regexShortName">Short name of the regex.</param>
/// <param name="expandedName">Name of the expanded.</param>
public void AddShortNameRule(string regexShortName, string expandedName)
{
_expandShortName.Add(new ShortNameMapper(regexShortName, expandedName));
// Not efficient, but we order from longest to shortest regex
_expandShortName.Sort((left, right) => -left.Regex.ToString().Length.CompareTo(right.Regex.ToString().Length));
}
/// <summary>
/// Renames a C++++ element
/// </summary>
/// <param name="cppElement">The C++ element.</param>
/// <param name="rootName">Name of the root.</param>
/// <returns>The new name</returns>
private string RenameCore(CppElement cppElement, string rootName = null)
{
string originalName = cppElement.Name;
string name = cppElement.Name;
var namingFlags = NamingFlags.Default;
bool nameModifiedByTag = false;
// Handle Tag
var tag = cppElement.GetTagOrDefault<MappingRule>();
if (tag != null)
{
if (!string.IsNullOrEmpty(tag.MappingName))
{
nameModifiedByTag = true;
name = tag.MappingName;
// If Final Mapping name then don't proceed further
if (tag.IsFinalMappingName.HasValue && tag.IsFinalMappingName.Value)
return name;
}
if (tag.NamingFlags.HasValue)
namingFlags = tag.NamingFlags.Value;
}
// Rename is tagged as final, then return the string
// If the string still contains some "_" then continue while processing
if (!name.Contains("_") && name.ToUpper() != name && char.IsUpper(name[0]))
return name;
// Remove Prefix (for enums). Don't modify names that are modified by tag
if (!nameModifiedByTag && rootName != null && originalName.StartsWith(rootName))
name = originalName.Substring(rootName.Length, originalName.Length - rootName.Length);
// Remove leading '_'
name = name.TrimStart('_');
// Convert rest of the string in CamelCase
name = ConvertToPascalCase(name, namingFlags);
return name;
}
/// <summary>
/// Renames the specified C++ element.
/// </summary>
/// <param name="cppElement">The C++ element.</param>
/// <returns>The C# name</returns>
public string Rename(CppElement cppElement)
{
return RecordRename(cppElement, UnKeyword(RenameCore(cppElement)));
}
/// <summary>
/// Renames the specified C++ enum item.
/// </summary>
/// <param name="cppEnumItem">The C++ enum item.</param>
/// <param name="rootEnumName">Name of the root C++ enum.</param>
/// <returns>The C# name of this enum item</returns>
public string Rename(CppEnumItem cppEnumItem, string rootEnumName)
{
return RecordRename(cppEnumItem, UnKeyword(RenameCore(cppEnumItem, rootEnumName)));
}
/// <summary>
/// Renames the specified C++ parameter.
/// </summary>
/// <param name="cppParameter">The C++ parameter.</param>
/// <returns>The C# name of this parameter.</returns>
public string Rename(CppParameter cppParameter)
{
string oldName = cppParameter.Name;
string name = RenameCore(cppParameter, null);
bool hasPointer = !string.IsNullOrEmpty(cppParameter.Pointer) &&
(cppParameter.Pointer.Contains("*") || cppParameter.Pointer.Contains("&"));
if (hasPointer)
{
if (oldName.StartsWith("pp"))
name = name.Substring(2) + "Out";
else if (oldName.StartsWith("p"))
name = name.Substring(1) + "Ref";
}
if (char.IsDigit(name[0]))
name = "arg" + name;
name = new string(name[0], 1).ToLower() + name.Substring(1);
return RecordRename(cppParameter, UnKeyword(name));
}
/// <summary>
/// Dump the names changes as a comma separated list of [FromName,ToName]
/// </summary>
/// <param name="writer">Text output of the dump</param>
public void DumpRenames(TextWriter writer)
{
foreach (var recordName in RecordNames)
{
writer.WriteLine("{0},{1}", recordName.Item1.FullName, recordName.Item2);
}
}
/// <summary>
/// Record the name source and the modified name.
/// </summary>
/// <param name="fromElement">The element to rename</param>
/// <param name="toName">The new name</param>
/// <returns>The new name</returns>
private string RecordRename(CppElement fromElement, string toName)
{
RecordNames.Add(new Tuple<CppElement, string>(fromElement, toName));
return toName;
}
/// <summary>
/// Protect the name from all C# reserved words.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
private static string UnKeyword(string name)
{
if (IsKeyword(name))
{
if (name == "string")
return "text";
name = "@" + name;
}
return name;
}
/// <summary>
/// Determines whether the specified string is a valid Pascal case.
/// </summary>
/// <param name="str">The string to validate.</param>
/// <param name="lowerCount">The lower count.</param>
/// <returns>
/// <c>true</c> if the specified string is a valid Pascal case; otherwise, <c>false</c>.
/// </returns>
private static bool IsPascalCase(string str, out int lowerCount)
{
// Count the number of char in lower case
lowerCount = str.Count(charInStr => char.IsLower(charInStr));
if (str.Length == 0)
return false;
// First char must be a letter
if (!char.IsLetter(str[0]))
return false;
// First letter must be upper
if (!char.IsUpper(str[0]))
return false;
// Second letter must be lower
if (str.Length > 1 && char.IsUpper(str[1]))
return false;
// other chars must be letter or numbers
//foreach (char charInStr in str)
//{
// if (!char.IsLetterOrDigit(charInStr))
// return false;
//}
return str.All(charInStr => char.IsLetterOrDigit(charInStr));
}
/// <summary>
/// Converts a string to PascalCase..
/// </summary>
/// <param name="text">The text to convert.</param>
/// <param name="namingFlags">The naming options to apply to the given string to convert.</param>
/// <returns>The given string in PascalCase.</returns>
public string ConvertToPascalCase(string text, NamingFlags namingFlags)
{
string[] splittedPhrase = text.Split('_');
var sb = new StringBuilder();
for (int i = 0; i < splittedPhrase.Length; i++)
{
string subPart = splittedPhrase[i];
// Don't perform expansion when asked
if ((namingFlags & NamingFlags.NoShortNameExpand) == 0)
{
while (subPart.Length > 0)
{
bool continueReplace = false;
foreach (var regExp in _expandShortName)
{
var regex = regExp.Regex;
var newText = regExp.Replace;
if (regex.Match(subPart).Success)
{
if (regExp.HasRegexReplace)
{
subPart = regex.Replace(subPart, regExp.Replace);
sb.Append(subPart);
subPart = string.Empty;
}
else
{
subPart = regex.Replace(subPart, string.Empty);
sb.Append(newText);
continueReplace = true;
}
break;
}
}
if (!continueReplace)
{
break;
}
}
}
// Else, perform a standard conversion
if (subPart.Length > 0)
{
int numberOfCharLowercase;
// If string is not Pascal Case, then Pascal Case it
if (IsPascalCase(subPart, out numberOfCharLowercase))
{
sb.Append(subPart);
}
else
{
char[] splittedPhraseChars = (numberOfCharLowercase > 0)
? subPart.ToCharArray()
: subPart.ToLower().ToCharArray();
if (splittedPhraseChars.Length > 0)
splittedPhraseChars[0] = char.ToUpper(splittedPhraseChars[0]);
sb.Append(new String(splittedPhraseChars));
}
}
if ( (namingFlags & NamingFlags.KeepUnderscore) != 0 && (i + 1) < splittedPhrase.Length)
sb.Append("_");
}
return sb.ToString();
}
/// <summary>
/// Checks if a given string is a C# keyword.
/// </summary>
/// <param name="name">The name to check.</param>
/// <returns>true if the name is a C# keyword; false otherwise.</returns>
private static bool IsKeyword(string name)
{
return CSharpKeywords.Contains(name);
}
private class ShortNameMapper
{
public ShortNameMapper(string regex, string replace)
{
Regex = new Regex("^" + regex);
Replace = replace;
HasRegexReplace = replace.Contains("$");
}
public Regex Regex;
public string Replace;
public bool HasRegexReplace;
}
/// <summary>
/// Reserved C# keywords.
/// </summary>
private static readonly string[] CSharpKeywords = new[]
{
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"fixed",
"float",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"stackalloc",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"virtual",
"volatile",
"void",
"while",
};
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using ASC.Web.Studio.UserControls.Statistics;
using ASC.Web.Studio.Utility;
namespace ASC.Web.Studio.Core
{
public static class SetupInfo
{
private static string web_autotest_secret_email;
private static string[] web_display_mobapps_banner;
private static string[] hideSettings;
public static string MetaImageURL
{
get;
private set;
}
public static string StatisticTrackURL
{
get;
private set;
}
public static bool EnableAppServer
{
get;
private set;
}
public static string DemoOrder
{
get;
private set;
}
public static string RequestTraining
{
get;
private set;
}
public static string ZendeskKey
{
get;
private set;
}
public static string UserVoiceURL
{
get;
private set;
}
public static string MainLogoURL
{
get;
private set;
}
public static string MainLogoMailTmplURL
{
get;
private set;
}
public static List<CultureInfo> EnabledCultures
{
get;
private set;
}
private static List<CultureInfo> EnabledCulturesPersonal
{
get;
set;
}
public static List<KeyValuePair<string, CultureInfo>> PersonalCultures
{
get;
private set;
}
public static decimal ExchangeRateRuble
{
get;
private set;
}
public static long MaxImageUploadSize
{
get;
private set;
}
/// <summary>
/// Max possible file size for not chunked upload. Less or equal than 100 mb.
/// </summary>
public static long MaxUploadSize
{
get { return Math.Min(AvailableFileSize, MaxChunkedUploadSize); }
}
public static long AvailableFileSize
{
get;
private set;
}
/// <summary>
/// Max possible file size for chunked upload.
/// </summary>
public static long MaxChunkedUploadSize
{
get
{
var diskQuota = TenantExtra.GetTenantQuota();
if (diskQuota != null)
{
var usedSize = TenantStatisticsProvider.GetUsedSize();
var freeSize = Math.Max(diskQuota.MaxTotalSize - usedSize, 0);
return Math.Min(freeSize, diskQuota.MaxFileSize);
}
return ChunkUploadSize;
}
}
public static string TeamlabSiteRedirect
{
get;
private set;
}
public static long ChunkUploadSize
{
get;
private set;
}
public static bool ThirdPartyAuthEnabled
{
get;
private set;
}
public static bool ThirdPartyBannerEnabled
{
get;
private set;
}
public static string NoTenantRedirectURL
{
get;
private set;
}
public static string NotifyAddress
{
get;
private set;
}
public static string TipsAddress
{
get;
private set;
}
public static string UserForum
{
get;
private set;
}
public static string SupportFeedback
{
get;
private set;
}
public static string WebApiBaseUrl
{
get { return VirtualPathUtility.ToAbsolute(GetAppSettings("api.url", "~/api/2.0/")); }
}
public static TimeSpan ValidEmailKeyInterval
{
get;
private set;
}
public static TimeSpan ValidAuthKeyInterval
{
get;
private set;
}
public static string SalesEmail
{
get;
private set;
}
public static bool IsSecretEmail(string email)
{
//the point is not needed in gmail.com
email = Regex.Replace(email ?? "", "\\.*(?=\\S*(@gmail.com$))", "").ToLower();
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(web_autotest_secret_email))
return false;
var regex = new Regex(web_autotest_secret_email, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
return regex.IsMatch(email);
}
public static bool DisplayMobappBanner(string product)
{
return web_display_mobapps_banner.Contains(product, StringComparer.InvariantCultureIgnoreCase);
}
public static string ShareTwitterUrl
{
get;
private set;
}
public static string ShareFacebookUrl
{
get;
private set;
}
public static string ControlPanelUrl
{
get;
private set;
}
public static string FontOpenSansUrl
{
get;
private set;
}
public static bool VoipEnabled
{
get;
private set;
}
public static string StartProductList
{
get;
private set;
}
public static string SsoSamlLoginUrl
{
get;
private set;
}
public static string DownloadForDesktopUrl
{
get;
private set;
}
public static string DownloadForIosDocuments
{
get;
private set;
}
public static string DownloadForIosProjects
{
get;
private set;
}
public static string DownloadForAndroidDocuments
{
get;
private set;
}
public static string SsoSamlLogoutUrl
{
get;
private set;
}
public static bool SmsTrial
{
get;
private set;
}
public static string TfaRegistration
{
get;
private set;
}
public static int TfaAppBackupCodeLength
{
get;
private set;
}
public static int TfaAppBackupCodeCount
{
get;
private set;
}
public static string TfaAppSender
{
get;
private set;
}
public static string RecaptchaPublicKey
{
get;
private set;
}
public static string RecaptchaPrivateKey
{
get;
private set;
}
public static string RecaptchaVerifyUrl
{
get;
private set;
}
public static int LoginThreshold
{
get;
private set;
}
public static string AmiMetaUrl
{
get;
private set;
}
static SetupInfo()
{
Refresh();
}
public static void Refresh()
{
EnableAppServer = GetAppSettings("appserver.enable", "false") == "true";
MetaImageURL = GetAppSettings("web.meta-image-url", "https://download.onlyoffice.com/assets/fb/fb_icon_325x325.jpg");
StatisticTrackURL = GetAppSettings("web.track-url", string.Empty);
UserVoiceURL = GetAppSettings("web.uservoice", string.Empty);
DemoOrder = GetAppSettings("web.demo-order", string.Empty);
ZendeskKey = GetAppSettings("web.zendesk-key", string.Empty);
RequestTraining = GetAppSettings("web.request-training", string.Empty);
MainLogoURL = GetAppSettings("web.logo.main", string.Empty);
MainLogoMailTmplURL = GetAppSettings("web.logo.mail.tmpl", string.Empty);
DownloadForDesktopUrl = GetAppSettings("web.download.for.desktop.url", "https://www.onlyoffice.com/desktop.aspx");
DownloadForIosDocuments = GetAppSettings("web.download.for.ios.doc", "https://itunes.apple.com/app/onlyoffice-documents/id944896972");
DownloadForIosProjects = GetAppSettings("web.download.for.ios.proj", "https://itunes.apple.com/app/onlyoffice-projects/id1353395928?mt=8");
DownloadForAndroidDocuments = GetAppSettings("web.download.for.android.doc", "https://play.google.com/store/apps/details?id=com.onlyoffice.documents");
EnabledCultures = GetAppSettings("web.cultures", "en-US")
.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Distinct()
.Select(l => CultureInfo.GetCultureInfo(l.Trim()))
.OrderBy(l => l.DisplayName)
.ToList();
EnabledCulturesPersonal = GetAppSettings("web.cultures.personal", GetAppSettings("web.cultures", "en-US"))
.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Distinct()
.Select(l => CultureInfo.GetCultureInfo(l.Trim()))
.ToList();
PersonalCultures = GetPersonalCultures();
ExchangeRateRuble = GetAppSettings("exchange-rate.ruble", 65);
MaxImageUploadSize = GetAppSettings<long>("web.max-upload-size", 1024 * 1024);
AvailableFileSize = GetAppSettings("web.available-file-size", 100L * 1024L * 1024L);
TeamlabSiteRedirect = GetAppSettings("web.teamlab-site", string.Empty);
ChunkUploadSize = GetAppSettings("files.uploader.chunk-size", 5 * 1024 * 1024);
ThirdPartyAuthEnabled = string.Equals(GetAppSettings("web.thirdparty-auth", "true"), "true");
ThirdPartyBannerEnabled = string.Equals(GetAppSettings("web.thirdparty-banner", "false"), "true");
NoTenantRedirectURL = GetAppSettings("web.notenant-url", "");
NotifyAddress = GetAppSettings("web.promo-url", string.Empty);
TipsAddress = GetAppSettings("web.promo-tips-url", string.Empty);
UserForum = GetAppSettings("web.user-forum", string.Empty);
SupportFeedback = GetAppSettings("web.support-feedback", string.Empty);
ValidEmailKeyInterval = GetAppSettings("email.validinterval", TimeSpan.FromDays(7));
ValidAuthKeyInterval = GetAppSettings("auth.validinterval", TimeSpan.FromHours(1));
SalesEmail = GetAppSettings("web.payment.email", "sales@onlyoffice.com");
web_autotest_secret_email = (ConfigurationManagerExtension.AppSettings["web.autotest.secret-email"] ?? "").Trim();
RecaptchaPublicKey = GetAppSettings("web.recaptcha.public-key", "");
RecaptchaPrivateKey = GetAppSettings("web.recaptcha.private-key", "");
RecaptchaVerifyUrl = GetAppSettings("web.recaptcha.verify-url", "https://www.recaptcha.net/recaptcha/api/siteverify");
LoginThreshold = Convert.ToInt32(GetAppSettings("web.login.threshold", "0"));
if (LoginThreshold < 1) LoginThreshold = 5;
web_display_mobapps_banner = (ConfigurationManagerExtension.AppSettings["web.display.mobapps.banner"] ?? "").Trim().Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
ShareTwitterUrl = GetAppSettings("web.share.twitter", "https://twitter.com/intent/tweet?text={0}");
ShareFacebookUrl = GetAppSettings("web.share.facebook", "");
ControlPanelUrl = GetAppSettings("web.controlpanel.url", "");
FontOpenSansUrl = GetAppSettings("web.font.opensans.url", "");
VoipEnabled = GetAppSettings("voip.enabled", true);
StartProductList = GetAppSettings("web.start.product.list", "");
SsoSamlLoginUrl = GetAppSettings("web.sso.saml.login.url", "");
SsoSamlLogoutUrl = GetAppSettings("web.sso.saml.logout.url", "");
hideSettings = GetAppSettings("web.hide-settings", string.Empty).Split(new[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
SmsTrial = GetAppSettings("core.sms.trial", false);
TfaRegistration = (GetAppSettings("core.tfa.registration", "") ?? "").Trim().ToLower();
TfaAppBackupCodeLength = GetAppSettings("web.tfaapp.backup.length", 6);
TfaAppBackupCodeCount = GetAppSettings("web.tfaapp.backup.count", 5);
TfaAppSender = GetAppSettings("web.tfaapp.backup.title", "ONLYOFFICE");
AmiMetaUrl = GetAppSettings("web.ami.meta", "");
}
public static bool IsVisibleSettings<TSettings>()
{
return IsVisibleSettings(typeof(TSettings).Name);
}
public static bool IsVisibleSettings(string settings)
{
return hideSettings == null || !hideSettings.Contains(settings, StringComparer.CurrentCultureIgnoreCase);
}
private static string GetAppSettings(string key, string defaultValue)
{
var result = ConfigurationManagerExtension.AppSettings[key] ?? defaultValue;
if (!string.IsNullOrEmpty(result))
result = result.Trim();
return result;
}
private static T GetAppSettings<T>(string key, T defaultValue)
{
var configSetting = ConfigurationManagerExtension.AppSettings[key];
if (!string.IsNullOrEmpty(configSetting))
{
configSetting = configSetting.Trim();
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null && converter.CanConvertFrom(typeof(string)))
{
return (T)converter.ConvertFromString(configSetting);
}
}
return defaultValue;
}
private static List<KeyValuePair<string, CultureInfo>> GetPersonalCultures()
{
var result = new Dictionary<string, CultureInfo>();
foreach (var culture in EnabledCulturesPersonal)
{
if (result.ContainsKey(culture.TwoLetterISOLanguageName))
{
result.Add(culture.Name, culture);
}
else
{
result.Add(culture.TwoLetterISOLanguageName, culture);
}
}
return result.OrderBy(item => item.Value.DisplayName).ToList();
}
public static KeyValuePair<string, CultureInfo> GetPersonalCulture(string lang)
{
foreach (var item in PersonalCultures)
{
if (string.Equals(item.Key, lang, StringComparison.InvariantCultureIgnoreCase))
{
return item;
}
}
var cultureInfo = EnabledCulturesPersonal.Find(c => string.Equals(c.Name, lang, StringComparison.InvariantCultureIgnoreCase));
if (cultureInfo == null)
{
cultureInfo = EnabledCulturesPersonal.Find(c => string.Equals(c.TwoLetterISOLanguageName, lang, StringComparison.InvariantCultureIgnoreCase));
}
if (cultureInfo != null)
{
foreach (var item in PersonalCultures)
{
if (item.Value == cultureInfo)
{
return item;
}
}
}
return new KeyValuePair<string, CultureInfo>(lang, cultureInfo);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tenancy_config/rpc/kce_config_svc.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.TenancyConfig.RPC {
/// <summary>Holder for reflection information generated from tenancy_config/rpc/kce_config_svc.proto</summary>
public static partial class KceConfigSvcReflection {
#region Descriptor
/// <summary>File descriptor for tenancy_config/rpc/kce_config_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static KceConfigSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cid0ZW5hbmN5X2NvbmZpZy9ycGMva2NlX2NvbmZpZ19zdmMucHJvdG8SHmhv",
"bG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLnJwYxoodGVuYW5jeV9jb25maWcv",
"a2FiYV9lbmNvZGVyX2NvbmZpZy5wcm90bxoodGVuYW5jeV9jb25maWcvbWl3",
"YV9lbmNvZGVyX2NvbmZpZy5wcm90bxordGVuYW5jeV9jb25maWcvYWN0aXZl",
"X2tleV9jYXJkX3N5c3RlbS5wcm90bxobZ29vZ2xlL3Byb3RvYnVmL2VtcHR5",
"LnByb3RvIvcBChRHZXRLQ0VDb25maWdSZXNwb25zZRJJChJrYWJhX2NvbmZp",
"Z3VyYXRpb24YASABKAsyLS5ob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZy5L",
"YWJhRW5jb2RlckNvbmZpZxJJChJtaXdhX2NvbmZpZ3VyYXRpb24YAiABKAsy",
"LS5ob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZy5NaXdhRW5jb2RlckNvbmZp",
"ZxJJChBhY3RpdmVfa2Nfc3lzdGVtGAMgASgOMi8uaG9sbXMudHlwZXMudGVu",
"YW5jeV9jb25maWcuQWN0aXZlS2V5Q2FyZFN5c3RlbSJiChVTZXRLYWJhQ29u",
"ZmlnUmVzcG9uc2USSQoGcmVzdWx0GAEgASgOMjkuaG9sbXMudHlwZXMudGVu",
"YW5jeV9jb25maWcucnBjLktDRVN2Y1NldEthYmFDb25maWdSZXN1bHQiYgob",
"S0NFU3ZjU2V0TWl3YUNvbmZpZ1Jlc3BvbnNlEkMKBnJlc3VsdBgBIAEoDjIz",
"LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLnJwYy5TZXRNaXdhQ29uZmln",
"UmVzdWx0ImwKH0tDRVN2Y1NldEFjdGl2ZUtDRUNvbmZpZ1JlcXVlc3QSSQoQ",
"YWN0aXZlX2tjX3N5c3RlbRgBIAEoDjIvLmhvbG1zLnR5cGVzLnRlbmFuY3lf",
"Y29uZmlnLkFjdGl2ZUtleUNhcmRTeXN0ZW0qzQEKGUtDRVN2Y1NldEthYmFD",
"b25maWdSZXN1bHQSJQohU0VUX0tDRV9DT05GSUdfSU5WQUxJRF9JUF9BRERS",
"RVNTEAASKQolU0VUX0tDRV9DT05GSUdfSU5WQUxJRF9FTkNPREVSX05VTUJF",
"UhABEh4KGlNFVF9LQ0VfQ09ORklHX0lOVkFMSURfUFdEEAISIgoeU0VUX0tD",
"RV9DT05GSUdfVU5LTk9XTl9GQUlMVVJFEAMSGgoWU0VUX0tDRV9DT05GSUdf",
"U1VDQ0VTUxAEKqwBChNTZXRNaXdhQ29uZmlnUmVzdWx0EiYKIlNFVF9NSVdB",
"X0NPTkZJR19JTlZBTElEX0lQX0FERFJFU1MQABIrCidTRVRfTUlXQV9DT05G",
"SUdfSU5WQUxJRF9URVJNSU5BTF9OVU1CRVIQARIjCh9TRVRfTUlXQV9DT05G",
"SUdfVU5LTk9XTl9GQUlMVVJFEAISGwoXU0VUX01JV0FfQ09ORklHX1NVQ0NF",
"U1MQAzLNAwoMS0NFQ29uZmlnU3ZjElMKA0dldBIWLmdvb2dsZS5wcm90b2J1",
"Zi5FbXB0eRo0LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLnJwYy5HZXRL",
"Q0VDb25maWdSZXNwb25zZRJ1Cg1TZXRLYWJhQ29uZmlnEi0uaG9sbXMudHlw",
"ZXMudGVuYW5jeV9jb25maWcuS2FiYUVuY29kZXJDb25maWcaNS5ob2xtcy50",
"eXBlcy50ZW5hbmN5X2NvbmZpZy5ycGMuU2V0S2FiYUNvbmZpZ1Jlc3BvbnNl",
"EnsKDVNldE1pd2FDb25maWcSLS5ob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZp",
"Zy5NaXdhRW5jb2RlckNvbmZpZxo7LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29u",
"ZmlnLnJwYy5LQ0VTdmNTZXRNaXdhQ29uZmlnUmVzcG9uc2USdAoZU2V0QWN0",
"aXZlS0NFQ29uZmlndXJhdGlvbhI/LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29u",
"ZmlnLnJwYy5LQ0VTdmNTZXRBY3RpdmVLQ0VDb25maWdSZXF1ZXN0GhYuZ29v",
"Z2xlLnByb3RvYnVmLkVtcHR5QjNaEXRlbmFuY3ljb25maWcvcnBjqgIdSE9M",
"TVMuVHlwZXMuVGVuYW5jeUNvbmZpZy5SUENiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.TenancyConfig.KabaEncoderConfigReflection.Descriptor, global::HOLMS.Types.TenancyConfig.MiwaEncoderConfigReflection.Descriptor, global::HOLMS.Types.TenancyConfig.ActiveKeyCardSystemReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.TenancyConfig.RPC.KCESvcSetKabaConfigResult), typeof(global::HOLMS.Types.TenancyConfig.RPC.SetMiwaConfigResult), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.GetKCEConfigResponse), global::HOLMS.Types.TenancyConfig.RPC.GetKCEConfigResponse.Parser, new[]{ "KabaConfiguration", "MiwaConfiguration", "ActiveKcSystem" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.SetKabaConfigResponse), global::HOLMS.Types.TenancyConfig.RPC.SetKabaConfigResponse.Parser, new[]{ "Result" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.KCESvcSetMiwaConfigResponse), global::HOLMS.Types.TenancyConfig.RPC.KCESvcSetMiwaConfigResponse.Parser, new[]{ "Result" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.RPC.KCESvcSetActiveKCEConfigRequest), global::HOLMS.Types.TenancyConfig.RPC.KCESvcSetActiveKCEConfigRequest.Parser, new[]{ "ActiveKcSystem" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum KCESvcSetKabaConfigResult {
[pbr::OriginalName("SET_KCE_CONFIG_INVALID_IP_ADDRESS")] SetKceConfigInvalidIpAddress = 0,
[pbr::OriginalName("SET_KCE_CONFIG_INVALID_ENCODER_NUMBER")] SetKceConfigInvalidEncoderNumber = 1,
[pbr::OriginalName("SET_KCE_CONFIG_INVALID_PWD")] SetKceConfigInvalidPwd = 2,
[pbr::OriginalName("SET_KCE_CONFIG_UNKNOWN_FAILURE")] SetKceConfigUnknownFailure = 3,
[pbr::OriginalName("SET_KCE_CONFIG_SUCCESS")] SetKceConfigSuccess = 4,
}
public enum SetMiwaConfigResult {
[pbr::OriginalName("SET_MIWA_CONFIG_INVALID_IP_ADDRESS")] SetMiwaConfigInvalidIpAddress = 0,
[pbr::OriginalName("SET_MIWA_CONFIG_INVALID_TERMINAL_NUMBER")] SetMiwaConfigInvalidTerminalNumber = 1,
[pbr::OriginalName("SET_MIWA_CONFIG_UNKNOWN_FAILURE")] SetMiwaConfigUnknownFailure = 2,
[pbr::OriginalName("SET_MIWA_CONFIG_SUCCESS")] SetMiwaConfigSuccess = 3,
}
#endregion
#region Messages
public sealed partial class GetKCEConfigResponse : pb::IMessage<GetKCEConfigResponse> {
private static readonly pb::MessageParser<GetKCEConfigResponse> _parser = new pb::MessageParser<GetKCEConfigResponse>(() => new GetKCEConfigResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetKCEConfigResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.KceConfigSvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetKCEConfigResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetKCEConfigResponse(GetKCEConfigResponse other) : this() {
KabaConfiguration = other.kabaConfiguration_ != null ? other.KabaConfiguration.Clone() : null;
MiwaConfiguration = other.miwaConfiguration_ != null ? other.MiwaConfiguration.Clone() : null;
activeKcSystem_ = other.activeKcSystem_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetKCEConfigResponse Clone() {
return new GetKCEConfigResponse(this);
}
/// <summary>Field number for the "kaba_configuration" field.</summary>
public const int KabaConfigurationFieldNumber = 1;
private global::HOLMS.Types.TenancyConfig.KabaEncoderConfig kabaConfiguration_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.KabaEncoderConfig KabaConfiguration {
get { return kabaConfiguration_; }
set {
kabaConfiguration_ = value;
}
}
/// <summary>Field number for the "miwa_configuration" field.</summary>
public const int MiwaConfigurationFieldNumber = 2;
private global::HOLMS.Types.TenancyConfig.MiwaEncoderConfig miwaConfiguration_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.MiwaEncoderConfig MiwaConfiguration {
get { return miwaConfiguration_; }
set {
miwaConfiguration_ = value;
}
}
/// <summary>Field number for the "active_kc_system" field.</summary>
public const int ActiveKcSystemFieldNumber = 3;
private global::HOLMS.Types.TenancyConfig.ActiveKeyCardSystem activeKcSystem_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.ActiveKeyCardSystem ActiveKcSystem {
get { return activeKcSystem_; }
set {
activeKcSystem_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetKCEConfigResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetKCEConfigResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(KabaConfiguration, other.KabaConfiguration)) return false;
if (!object.Equals(MiwaConfiguration, other.MiwaConfiguration)) return false;
if (ActiveKcSystem != other.ActiveKcSystem) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (kabaConfiguration_ != null) hash ^= KabaConfiguration.GetHashCode();
if (miwaConfiguration_ != null) hash ^= MiwaConfiguration.GetHashCode();
if (ActiveKcSystem != 0) hash ^= ActiveKcSystem.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 (kabaConfiguration_ != null) {
output.WriteRawTag(10);
output.WriteMessage(KabaConfiguration);
}
if (miwaConfiguration_ != null) {
output.WriteRawTag(18);
output.WriteMessage(MiwaConfiguration);
}
if (ActiveKcSystem != 0) {
output.WriteRawTag(24);
output.WriteEnum((int) ActiveKcSystem);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (kabaConfiguration_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(KabaConfiguration);
}
if (miwaConfiguration_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(MiwaConfiguration);
}
if (ActiveKcSystem != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ActiveKcSystem);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetKCEConfigResponse other) {
if (other == null) {
return;
}
if (other.kabaConfiguration_ != null) {
if (kabaConfiguration_ == null) {
kabaConfiguration_ = new global::HOLMS.Types.TenancyConfig.KabaEncoderConfig();
}
KabaConfiguration.MergeFrom(other.KabaConfiguration);
}
if (other.miwaConfiguration_ != null) {
if (miwaConfiguration_ == null) {
miwaConfiguration_ = new global::HOLMS.Types.TenancyConfig.MiwaEncoderConfig();
}
MiwaConfiguration.MergeFrom(other.MiwaConfiguration);
}
if (other.ActiveKcSystem != 0) {
ActiveKcSystem = other.ActiveKcSystem;
}
}
[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 (kabaConfiguration_ == null) {
kabaConfiguration_ = new global::HOLMS.Types.TenancyConfig.KabaEncoderConfig();
}
input.ReadMessage(kabaConfiguration_);
break;
}
case 18: {
if (miwaConfiguration_ == null) {
miwaConfiguration_ = new global::HOLMS.Types.TenancyConfig.MiwaEncoderConfig();
}
input.ReadMessage(miwaConfiguration_);
break;
}
case 24: {
activeKcSystem_ = (global::HOLMS.Types.TenancyConfig.ActiveKeyCardSystem) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class SetKabaConfigResponse : pb::IMessage<SetKabaConfigResponse> {
private static readonly pb::MessageParser<SetKabaConfigResponse> _parser = new pb::MessageParser<SetKabaConfigResponse>(() => new SetKabaConfigResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<SetKabaConfigResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.KceConfigSvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SetKabaConfigResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SetKabaConfigResponse(SetKabaConfigResponse other) : this() {
result_ = other.result_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SetKabaConfigResponse Clone() {
return new SetKabaConfigResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.TenancyConfig.RPC.KCESvcSetKabaConfigResult result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.RPC.KCESvcSetKabaConfigResult Result {
get { return result_; }
set {
result_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as SetKabaConfigResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(SetKabaConfigResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.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 (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(SetKabaConfigResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.TenancyConfig.RPC.KCESvcSetKabaConfigResult) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class KCESvcSetMiwaConfigResponse : pb::IMessage<KCESvcSetMiwaConfigResponse> {
private static readonly pb::MessageParser<KCESvcSetMiwaConfigResponse> _parser = new pb::MessageParser<KCESvcSetMiwaConfigResponse>(() => new KCESvcSetMiwaConfigResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<KCESvcSetMiwaConfigResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.KceConfigSvcReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KCESvcSetMiwaConfigResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KCESvcSetMiwaConfigResponse(KCESvcSetMiwaConfigResponse other) : this() {
result_ = other.result_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KCESvcSetMiwaConfigResponse Clone() {
return new KCESvcSetMiwaConfigResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.TenancyConfig.RPC.SetMiwaConfigResult result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.RPC.SetMiwaConfigResult Result {
get { return result_; }
set {
result_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as KCESvcSetMiwaConfigResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(KCESvcSetMiwaConfigResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.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 (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(KCESvcSetMiwaConfigResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.TenancyConfig.RPC.SetMiwaConfigResult) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class KCESvcSetActiveKCEConfigRequest : pb::IMessage<KCESvcSetActiveKCEConfigRequest> {
private static readonly pb::MessageParser<KCESvcSetActiveKCEConfigRequest> _parser = new pb::MessageParser<KCESvcSetActiveKCEConfigRequest>(() => new KCESvcSetActiveKCEConfigRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<KCESvcSetActiveKCEConfigRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.RPC.KceConfigSvcReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KCESvcSetActiveKCEConfigRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KCESvcSetActiveKCEConfigRequest(KCESvcSetActiveKCEConfigRequest other) : this() {
activeKcSystem_ = other.activeKcSystem_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KCESvcSetActiveKCEConfigRequest Clone() {
return new KCESvcSetActiveKCEConfigRequest(this);
}
/// <summary>Field number for the "active_kc_system" field.</summary>
public const int ActiveKcSystemFieldNumber = 1;
private global::HOLMS.Types.TenancyConfig.ActiveKeyCardSystem activeKcSystem_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.ActiveKeyCardSystem ActiveKcSystem {
get { return activeKcSystem_; }
set {
activeKcSystem_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as KCESvcSetActiveKCEConfigRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(KCESvcSetActiveKCEConfigRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ActiveKcSystem != other.ActiveKcSystem) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ActiveKcSystem != 0) hash ^= ActiveKcSystem.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 (ActiveKcSystem != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) ActiveKcSystem);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ActiveKcSystem != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ActiveKcSystem);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(KCESvcSetActiveKCEConfigRequest other) {
if (other == null) {
return;
}
if (other.ActiveKcSystem != 0) {
ActiveKcSystem = other.ActiveKcSystem;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
activeKcSystem_ = (global::HOLMS.Types.TenancyConfig.ActiveKeyCardSystem) input.ReadEnum();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
* DotGNU XmlRpc implementation
*
* Copyright (C) 2003 Free Software Foundation, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* $Revision: 1.3 $ $Date: 2006/05/14 11:22:47 $
*
* --------------------------------------------------------------------------
*/
using System.Collections;
using System.IO;
using System.Text;
using System.Xml;
namespace DotGNU.XmlRpc
{
// For now, indentation is the default since it makes it easier for
// a human to read the output. later the output should not be
// formatted at all. ideally it should be an unindented block.
// Ideally XmlTextWriter should write the tags, but it's indentation
// is too broken so that its more human readable and debuggable.
// Grrr Grrr Grrrrr
public class XmlRpcWriter : XmlTextWriter
{
// TODO: build node tree in memory, then flush this tree at the
// end which avoids us to do the WriteEndElements and allows us
// for consistency checking
private StringWriter sw;
private XmlRpcMethod m;
public XmlRpcWriter( TextWriter w ) : base( w )
{
}
public XmlRpcWriter( Stream stream, Encoding encoding ) : base( stream, encoding )
{
}
public XmlRpcWriter( String filename, Encoding encoding ) : base( filename, encoding )
{
}
public void Write( XmlRpcMethod method )
{
if(method == null)
{
throw new ArgumentNullException("method", "Argument cannot be null");
}
WriteStartDocument();
WriteStartElement( "methodCall" );
WriteElementString( "methodName", method.Name );
WriteParams();
foreach( object o in method ) {
WriteParam( o );
}
WriteEndDocument();
}
private void WriteMethodResponse()
{
WriteStartElement( "methodResponse" );
}
public void Write( XmlRpcResponse response )
{
if(response == null)
{
throw new ArgumentNullException("response", "Argument cannot be null");
}
WriteStartDocument();
WriteMethodResponse();
WriteParams();
foreach( object o in response ) {
WriteParam( o );
}
WriteEndDocument();
}
public void Write( XmlRpcException e )
{
if(e == null)
{
throw new ArgumentNullException("e", "Argument cannot be null");
}
WriteStartDocument();
WriteMethodResponse();
WriteStartElement( "fault" );
XmlRpcStruct s = new XmlRpcStruct();
s.Add( "faultCode", e.FaultCode );
s.Add( "faultString", e.Message );
WriteValue( s );
WriteEndElement();
WriteEndDocument();
}
public void WriteMethodResponse( Exception e )
{
XmlRpcException ex = new XmlRpcException( e );
WriteMethodResponse( ex );
}
private void WriteParams()
{
WriteStartElement( "params" );
}
private void WriteParam( object o )
{
WriteStartElement( "param" );
WriteValue( o );
WriteEndElement();
}
private void WriteValue()
{
WriteStartElement( "value" );
}
private void WriteInt( int v )
{
WriteElementString( "i4", XmlConvert.ToString( v ) );
}
private void WriteStringValue( string v)
{
WriteElementString( "string", v );
}
private void WriteDouble( double v )
{
// XmlConvert is HORRID doing this!!!! Try this with a value
// of 2.0 and see what i mean
WriteElementString( "double", v.ToString() );
}
private void WriteBoolean( bool v )
{
WriteElementString( "boolean", XmlConvert.ToString( v ) );
}
private void WriteDateTime( DateTime v )
{
// ensure this is iso compliant
// Why has MS got no clue about ISO 8601??? Horrid. All
// these newbies working on specs. this is as close as it
// gets but not exactly since the 'T' can be left out
WriteElementString( "dateTime.iso8601", v.ToString( "s", null ) );
}
private void WriteBase64( byte[] v )
{
WriteStartElement( "base64" );
WriteBase64( v, 0, v.Length);
WriteEndElement();
}
private void WriteStruct( XmlRpcStruct v )
{
WriteStartElement( "struct" );
foreach( DictionaryEntry entry in v ) {
WriteStartElement( "member" );
WriteElementString( "name", (string)entry.Key );
WriteValue( entry.Value );
WriteEndElement(); // member
}
WriteEndElement(); // struct
}
private void WriteArray( XmlRpcArray v )
{
WriteStartElement( "array" );
WriteStartElement( "data" );
foreach( object entry in v ) {
WriteValue( entry );
}
WriteEndElement(); // data
WriteEndElement(); // array
}
private void WriteValue( object o )
{
WriteStartElement( "value" );
if( o is int ) {
WriteInt( (int)o );
}
else if( o is double ) {
WriteDouble( (double)o );
}
else if( o is string ) {
WriteStringValue( (string)o );
}
else if( o is bool ) {
WriteBoolean( (bool)o );
}
else if( o is DateTime ) {
WriteDateTime( (DateTime)o );
}
else if( o is byte[] ) {
WriteBase64( (byte[])o );
}
else if( o is XmlRpcStruct ) {
WriteStruct( (XmlRpcStruct)o );
}
else if( o is XmlRpcArray ) {
WriteArray( (XmlRpcArray)o );
}
WriteEndElement();
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Catalog.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// Represents catalog configuration. By default stored in /system/modules/Ecommerce/Catalogs/[Catalog Name] item.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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 Sitecore.Ecommerce.Shell.Applications.Catalogs.Models
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using Data;
using Globalization;
using Search;
using Sitecore.Data;
using Sitecore.Data.Items;
using Text;
/// <summary>
/// Represents catalog configuration. By default stored in /system/modules/Ecommerce/Catalogs/[Catalog Name] item.
/// </summary>
public class Catalog
{
/// <summary>
/// The catalog data source field name.
/// </summary>
public const string CatalogDataSourceFieldName = "Catalog Data Source";
/// <summary>
/// The data mapper.
/// </summary>
private readonly IDataMapper dataMapper;
/// <summary>
/// The catalog item.
/// </summary>
private Item catalogItem;
/// <summary>
/// Initializes a new instance of the <see cref="Catalog"/> class.
/// </summary>
public Catalog()
: this(Context.Entity.Resolve<DataMapper>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Catalog"/> class.
/// </summary>
/// <param name="dataMapper">The data mapper.</param>
public Catalog(IDataMapper dataMapper)
{
this.dataMapper = dataMapper;
}
/// <summary>
/// Gets or sets the item URI.
/// </summary>
/// <value>The item URI.</value>
public ItemUri ItemUri { get; set; }
/// <summary>
/// Gets or sets the database.
/// </summary>
/// <value>
/// The database.
/// </value>
public Database Database { get; set; }
/// <summary>
/// Gets or sets Language.
/// </summary>
public Language Language { get; set; }
/// <summary>
/// Gets the search provider.
/// </summary>
/// <value>The search provider.</value>
public virtual CatalogBaseSource CatalogSource
{
get
{
if (this.CatalogItem != null && !string.IsNullOrEmpty(this.CatalogItem[CatalogDataSourceFieldName]))
{
CatalogBaseSource source = this.CreateCatalogSource();
if (source != null)
{
source.Database = this.Database;
source.Language = this.Language;
return source;
}
}
return null;
}
}
/// <summary>
/// Gets the row editor fields.
/// </summary>
/// <value>The row editor fields.</value>
public virtual StringCollection EditorFields
{
get
{
return this.GetFieldValueList("Editor Fields").ToStringCollection();
}
}
/// <summary>
/// Gets the data mapper.
/// </summary>
[NotNull]
protected IDataMapper DataMapper
{
get { return this.dataMapper; }
}
/// <summary>
/// Gets the catalog item.
/// </summary>
/// <value>The catalog item.</value>
protected Item CatalogItem
{
get
{
if (this.catalogItem != null)
{
return this.catalogItem;
}
if (this.ItemUri == null)
{
return null;
}
this.catalogItem = Database.GetItem(this.ItemUri);
return this.catalogItem;
}
}
/// <summary>
/// Gets the ribbon URI.
/// </summary>
/// <returns>The ribbon URI.</returns>
public virtual ItemUri GetRibbonSourceUri()
{
var uri = this.CatalogItem["Ribbon Source Uri"];
return string.IsNullOrEmpty(uri) ? null : new ItemUri(uri);
}
/// <summary>
/// Gets the textbox definitions.
/// </summary>
/// <returns>The textbox definitions.</returns>
public virtual List<TextBoxDefinition> GetTextBoxDefinitions()
{
var list = new List<TextBoxDefinition>();
if (this.CatalogItem == null)
{
return list;
}
var searchFieldsRoot = this.CatalogItem.Children["Search Text Fields"];
if (searchFieldsRoot == null || searchFieldsRoot.Children.Count <= 0)
{
return list;
}
foreach (Item searchTextField in searchFieldsRoot.Children)
{
list.Add(this.dataMapper.GetEntity<TextBoxDefinition>(searchTextField));
}
return list;
}
/// <summary>
/// Gets the search templates.
/// </summary>
/// <returns>The search templates</returns>
public virtual ListString GetSearchTemplates()
{
return this.GetFieldValueList("Templates");
}
/// <summary>
/// Gets the checklists.
/// </summary>
/// <returns>Gets the checklist definitions.</returns>
public virtual List<ChecklistDefinition> GetChecklistDefinitions()
{
var checklists = new ChecklistCollection();
if (this.CatalogItem == null)
{
return checklists;
}
var checklistsRoot = this.CatalogItem.Children["Checklists"];
if (checklistsRoot == null || checklistsRoot.Children.Count <= 0)
{
return checklists;
}
foreach (Item checklistItem in checklistsRoot.Children)
{
var checkboxes = new Collection<ChecklistItem>();
var checkboxesRoot = this.Database.GetItem(checklistItem["Root"]);
if (checkboxesRoot != null)
{
foreach (Item item in checkboxesRoot.Children)
{
checkboxes.Add(new ChecklistItem { Text = item["Title"], Value = item.ID.ToString() });
}
}
var checklist = new ChecklistDefinition { Header = checklistItem["Title"], Field = checklistItem["Field"], Checkboxes = checkboxes };
checklists.Add(checklist);
}
return checklists;
}
/// <summary>
/// Gets the catalog grid column definitions. Used to construct a grid in catalog view.
/// </summary>
/// <returns>The catalog grid column definitions.</returns>
[NotNull]
public virtual List<GridColumn> GetGridColumns()
{
var columns = new List<GridColumn>();
if (this.CatalogItem == null)
{
return columns;
}
var row = this.CatalogItem.Children["Grid"];
if (row == null || row.Children.Count <= 0)
{
return columns;
}
foreach (Item columnItem in row.Children)
{
columns.Add(this.dataMapper.GetEntity<GridColumn>(columnItem));
}
return columns;
}
/// <summary>
/// Creates the catalog source.
/// </summary>
/// <returns>The catalog source.</returns>
[CanBeNull]
protected virtual CatalogBaseSource CreateCatalogSource()
{
return Reflection.ReflectionUtil.CreateObject(this.CatalogItem[CatalogDataSourceFieldName]) as CatalogBaseSource;
}
/// <summary>
/// Gets the field value list.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <returns>The field value list</returns>
[NotNull]
private ListString GetFieldValueList([NotNull] string fieldName)
{
return this.CatalogItem == null ? new ListString() : new ListString(this.CatalogItem[fieldName]);
}
}
}
| |
#region Header
/**
* JsonMapper.cs
* JSON to .Net object and object to JSON conversions.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace LitJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
Type underlying_type = Nullable.GetUnderlyingType(inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClass || underlying_type != null) {
return null;
}
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
if (value_type.IsAssignableFrom (json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
custom_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
base_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (value_type.IsEnum)
return Enum.ToObject (value_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (value_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
//throw new JsonException (String.Format (
// "Can't assign value '{0}' (type {1}) to type {2}",
// reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (value_type);
ObjectMetadata t_data = object_metadata[value_type];
instance = Activator.CreateInstance (value_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary) {
if (! reader.SkipNonMembers) {
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
} else {
ReadSkip (reader);
continue;
}
}
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void ReadSkip (JsonReader reader)
{
ToWrapper (
delegate { return new JsonMockWrapper (); }, reader);
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
#nullable enable
namespace Microsoft.Build.Collections
{
/// <summary>
/// A dictionary that has copy-on-write semantics.
/// KEYS AND VALUES MUST BE IMMUTABLE OR COPY-ON-WRITE FOR THIS TO WORK.
/// </summary>
/// <typeparam name="V">The value type.</typeparam>
/// <remarks>
/// Thread safety: for all users, this class is as thread safe as the underlying Dictionary implementation, that is,
/// safe for concurrent readers or one writer from EACH user. It achieves this by locking itself and cloning before
/// any write, if it is being shared - i.e., stopping sharing before any writes occur.
/// </remarks>
/// <comment>
/// This class must be serializable as it is used for metadata passed to tasks, which may
/// be run in a separate appdomain.
/// </comment>
[Serializable]
internal class CopyOnWriteDictionary<V> : IDictionary<string, V>, IDictionary, ISerializable
{
#if !NET35 // MSBuildNameIgnoreCaseComparer not compiled into MSBuildTaskHost but also allocations not interesting there.
/// <summary>
/// Empty dictionary with a <see cref="MSBuildNameIgnoreCaseComparer" />,
/// used as the basis of new dictionaries with that comparer to avoid
/// allocating new comparers objects.
/// </summary>
private readonly static ImmutableDictionary<string, V> NameComparerDictionaryPrototype = ImmutableDictionary.Create<string, V>((IEqualityComparer<string>)MSBuildNameIgnoreCaseComparer.Default);
/// <summary>
/// Empty dictionary with <see cref="StringComparer.OrdinalIgnoreCase" />,
/// used as the basis of new dictionaries with that comparer to avoid
/// allocating new comparers objects.
/// </summary>
private readonly static ImmutableDictionary<string, V> OrdinalIgnoreCaseComparerDictionaryPrototype = ImmutableDictionary.Create<string, V>((IEqualityComparer<string>)StringComparer.OrdinalIgnoreCase);
#endif
/// <summary>
/// The backing dictionary.
/// Lazily created.
/// </summary>
private ImmutableDictionary<string, V> _backing;
/// <summary>
/// Constructor. Consider supplying a comparer instead.
/// </summary>
internal CopyOnWriteDictionary()
{
_backing = ImmutableDictionary<string, V>.Empty;
}
/// <summary>
/// Constructor taking an initial capacity
/// </summary>
internal CopyOnWriteDictionary(int capacity)
: this(capacity, null)
{
}
/// <summary>
/// Constructor taking a specified comparer for the keys
/// </summary>
internal CopyOnWriteDictionary(IEqualityComparer<string> keyComparer)
: this(0, keyComparer)
{
}
/// <summary>
/// Constructor taking a specified comparer for the keys and an initial capacity
/// </summary>
internal CopyOnWriteDictionary(int capacity, IEqualityComparer<string>? keyComparer)
{
_backing = GetInitialDictionary(keyComparer);
}
/// <summary>
/// Serialization constructor, for crossing appdomain boundaries
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context", Justification = "Not needed")]
protected CopyOnWriteDictionary(SerializationInfo info, StreamingContext context)
{
object v = info.GetValue(nameof(_backing), typeof(KeyValuePair<string, V>[]))!;
object comparer = info.GetValue(nameof(Comparer), typeof(IEqualityComparer<string>))!;
var b = GetInitialDictionary((IEqualityComparer<string>?)comparer);
_backing = b.AddRange((KeyValuePair<string, V>[])v);
}
private static ImmutableDictionary<string, V> GetInitialDictionary(IEqualityComparer<string>? keyComparer)
{
#if NET35
return ImmutableDictionary.Create<string, V>(keyComparer);
#else
return keyComparer is MSBuildNameIgnoreCaseComparer
? NameComparerDictionaryPrototype
: keyComparer == StringComparer.OrdinalIgnoreCase
? OrdinalIgnoreCaseComparerDictionaryPrototype
: ImmutableDictionary.Create<string, V>(keyComparer);
#endif
}
/// <summary>
/// Cloning constructor. Defers the actual clone.
/// </summary>
private CopyOnWriteDictionary(CopyOnWriteDictionary<V> that)
{
_backing = that._backing;
}
public CopyOnWriteDictionary(IDictionary<string, V> dictionary)
{
_backing = dictionary.ToImmutableDictionary();
}
/// <summary>
/// Returns the collection of keys in the dictionary.
/// </summary>
public ICollection<string> Keys => ((IDictionary<string, V>)_backing).Keys;
/// <summary>
/// Returns the collection of values in the dictionary.
/// </summary>
public ICollection<V> Values => ((IDictionary<string, V>)_backing).Values;
/// <summary>
/// Returns the number of items in the collection.
/// </summary>
public int Count => _backing.Count;
/// <summary>
/// Returns true if the collection is read-only.
/// </summary>
public bool IsReadOnly => ((IDictionary<string, V>)_backing).IsReadOnly;
/// <summary>
/// IDictionary implementation
/// </summary>
bool IDictionary.IsFixedSize => false;
/// <summary>
/// IDictionary implementation
/// </summary>
bool IDictionary.IsReadOnly => IsReadOnly;
/// <summary>
/// IDictionary implementation
/// </summary>
ICollection IDictionary.Keys => (ICollection)Keys;
/// <summary>
/// IDictionary implementation
/// </summary>
ICollection IDictionary.Values => (ICollection)Values;
/// <summary>
/// IDictionary implementation
/// </summary>
int ICollection.Count => Count;
/// <summary>
/// IDictionary implementation
/// </summary>
bool ICollection.IsSynchronized => false;
/// <summary>
/// IDictionary implementation
/// </summary>
object ICollection.SyncRoot => this;
/// <summary>
/// Comparer used for keys
/// </summary>
internal IEqualityComparer<string> Comparer
{
get => _backing.KeyComparer;
private set => _backing = _backing.WithComparers(keyComparer: value);
}
/// <summary>
/// Accesses the value for the specified key.
/// </summary>
public V this[string key]
{
get => _backing[key];
set
{
_backing = _backing.SetItem(key, value);
}
}
#nullable disable
/// <summary>
/// IDictionary implementation
/// </summary>
object IDictionary.this[object key]
{
get
{
TryGetValue((string) key, out V val);
return val;
}
set => this[(string)key] = (V)value;
}
#nullable restore
/// <summary>
/// Adds a value to the dictionary.
/// </summary>
public void Add(string key, V value)
{
_backing = _backing.SetItem(key, value);
}
/// <summary>
/// Returns true if the dictionary contains the specified key.
/// </summary>
public bool ContainsKey(string key)
{
return _backing.ContainsKey(key);
}
/// <summary>
/// Removes the entry for the specified key from the dictionary.
/// </summary>
public bool Remove(string key)
{
ImmutableDictionary<string, V> initial = _backing;
_backing = _backing.Remove(key);
return initial != _backing; // whether the removal occured
}
/// <summary>
/// Attempts to find the value for the specified key in the dictionary.
/// </summary>
public bool TryGetValue(string key, out V value)
{
return _backing.TryGetValue(key, out value);
}
/// <summary>
/// Adds an item to the collection.
/// </summary>
public void Add(KeyValuePair<string, V> item)
{
_backing = _backing.SetItem(item.Key, item.Value);
}
/// <summary>
/// Clears the collection.
/// </summary>
public void Clear()
{
_backing = _backing.Clear();
}
/// <summary>
/// Returns true ff the collection contains the specified item.
/// </summary>
public bool Contains(KeyValuePair<string, V> item)
{
return _backing.Contains(item);
}
/// <summary>
/// Copies all of the elements of the collection to the specified array.
/// </summary>
public void CopyTo(KeyValuePair<string, V>[] array, int arrayIndex)
{
((IDictionary<string, V>)_backing).CopyTo(array, arrayIndex);
}
/// <summary>
/// Remove an item from the dictionary.
/// </summary>
public bool Remove(KeyValuePair<string, V> item)
{
ImmutableDictionary<string, V> initial = _backing;
_backing = _backing.Remove(item.Key);
return initial != _backing; // whether the removal occured
}
/// <summary>
/// Implementation of generic IEnumerable.GetEnumerator()
/// </summary>
public IEnumerator<KeyValuePair<string, V>> GetEnumerator()
{
return _backing.GetEnumerator();
}
/// <summary>
/// Implementation of IEnumerable.GetEnumerator()
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<KeyValuePair<string, V>>)this).GetEnumerator();
}
/// <summary>
/// IDictionary implementation.
/// </summary>
void IDictionary.Add(object key, object value)
{
Add((string)key, (V)value);
}
/// <summary>
/// IDictionary implementation.
/// </summary>
void IDictionary.Clear()
{
Clear();
}
/// <summary>
/// IDictionary implementation.
/// </summary>
bool IDictionary.Contains(object key)
{
return ContainsKey((string)key);
}
/// <summary>
/// IDictionary implementation.
/// </summary>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return ((IDictionary)_backing).GetEnumerator();
}
/// <summary>
/// IDictionary implementation.
/// </summary>
void IDictionary.Remove(object key)
{
Remove((string)key);
}
/// <summary>
/// IDictionary implementation.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
int i = 0;
foreach (KeyValuePair<string, V> entry in this)
{
array.SetValue(new DictionaryEntry(entry.Key, entry.Value), index + i);
i++;
}
}
/// <summary>
/// Clone, with the actual clone deferred
/// </summary>
internal CopyOnWriteDictionary<V> Clone()
{
return new CopyOnWriteDictionary<V>(this);
}
/// <summary>
/// Returns true if these dictionaries have the same backing.
/// </summary>
internal bool HasSameBacking(CopyOnWriteDictionary<V> other)
{
return ReferenceEquals(other._backing, _backing);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
ImmutableDictionary<string, V> snapshot = _backing;
KeyValuePair<string, V>[] array = snapshot.ToArray();
info.AddValue(nameof(_backing), array);
info.AddValue(nameof(Comparer), Comparer);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
/// <summary>
/// Circuit data for an agent. Connection information shared between
/// regions that accept UDP connections from a client
/// </summary>
public class AgentCircuitData
{
/// <summary>
/// Avatar Unique Agent Identifier
/// </summary>
public UUID AgentID;
/// <summary>
/// Avatar's Appearance
/// </summary>
public AvatarAppearance Appearance;
/// <summary>
/// Agent's root inventory folder
/// </summary>
public UUID BaseFolder;
/// <summary>
/// Base Caps path for user
/// </summary>
public string CapsPath = String.Empty;
/// <summary>
/// Seed caps for neighbor regions that the user can see into
/// </summary>
public Dictionary<ulong, string> ChildrenCapSeeds;
/// <summary>
/// Root agent, or Child agent
/// </summary>
public bool child;
/// <summary>
/// Number given to the client when they log-in that they provide
/// as credentials to the UDP server
/// </summary>
public uint circuitcode;
/// <summary>
/// Agent's account first name
/// </summary>
public string firstname;
public UUID InventoryFolder;
/// <summary>
/// Agent's account last name
/// </summary>
public string lastname;
/// <summary>
/// Random Unique GUID for this session. Client gets this at login and it's
/// only supposed to be disclosed over secure channels
/// </summary>
public UUID SecureSessionID;
/// <summary>
/// Non secure Session ID
/// </summary>
public UUID SessionID;
/// <summary>
/// Position the Agent's Avatar starts in the region
/// </summary>
public Vector3 startpos;
public AgentCircuitData()
{
}
/// <summary>
/// Create AgentCircuitData from a Serializable AgentCircuitData
/// </summary>
/// <param name="cAgent"></param>
public AgentCircuitData(sAgentCircuitData cAgent)
{
AgentID = new UUID(cAgent.AgentID);
SessionID = new UUID(cAgent.SessionID);
SecureSessionID = new UUID(cAgent.SecureSessionID);
startpos = new Vector3(cAgent.startposx, cAgent.startposy, cAgent.startposz);
firstname = cAgent.firstname;
lastname = cAgent.lastname;
circuitcode = cAgent.circuitcode;
child = cAgent.child;
InventoryFolder = new UUID(cAgent.InventoryFolder);
BaseFolder = new UUID(cAgent.BaseFolder);
CapsPath = cAgent.CapsPath;
ChildrenCapSeeds = cAgent.ChildrenCapSeeds;
}
/// <summary>
/// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json
/// </summary>
/// <returns>map of the agent circuit data</returns>
public OSDMap PackAgentCircuitData()
{
OSDMap args = new OSDMap();
args["agent_id"] = OSD.FromUUID(AgentID);
args["base_folder"] = OSD.FromUUID(BaseFolder);
args["caps_path"] = OSD.FromString(CapsPath);
OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count);
foreach (KeyValuePair<ulong, string> kvp in ChildrenCapSeeds)
{
OSDMap pair = new OSDMap();
pair["handle"] = OSD.FromString(kvp.Key.ToString());
pair["seed"] = OSD.FromString(kvp.Value);
childrenSeeds.Add(pair);
}
if (ChildrenCapSeeds.Count > 0)
args["children_seeds"] = childrenSeeds;
args["child"] = OSD.FromBoolean(child);
args["circuit_code"] = OSD.FromString(circuitcode.ToString());
args["first_name"] = OSD.FromString(firstname);
args["last_name"] = OSD.FromString(lastname);
args["inventory_folder"] = OSD.FromUUID(InventoryFolder);
args["secure_session_id"] = OSD.FromUUID(SecureSessionID);
args["session_id"] = OSD.FromUUID(SessionID);
args["start_pos"] = OSD.FromString(startpos.ToString());
return args;
}
/// <summary>
/// Unpack agent circuit data map into an AgentCiruitData object
/// </summary>
/// <param name="args"></param>
public void UnpackAgentCircuitData(OSDMap args)
{
if (args["agent_id"] != null)
AgentID = args["agent_id"].AsUUID();
if (args["base_folder"] != null)
BaseFolder = args["base_folder"].AsUUID();
if (args["caps_path"] != null)
CapsPath = args["caps_path"].AsString();
if ((args["children_seeds"] != null) && (args["children_seeds"].Type == OSDType.Array))
{
OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]);
ChildrenCapSeeds = new Dictionary<ulong, string>();
foreach (OSD o in childrenSeeds)
{
if (o.Type == OSDType.Map)
{
ulong handle = 0;
string seed = "";
OSDMap pair = (OSDMap)o;
if (pair["handle"] != null)
if (!UInt64.TryParse(pair["handle"].AsString(), out handle))
continue;
if (pair["seed"] != null)
seed = pair["seed"].AsString();
if (!ChildrenCapSeeds.ContainsKey(handle))
ChildrenCapSeeds.Add(handle, seed);
}
}
}
if (args["child"] != null)
child = args["child"].AsBoolean();
if (args["circuit_code"] != null)
UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode);
if (args["first_name"] != null)
firstname = args["first_name"].AsString();
if (args["last_name"] != null)
lastname = args["last_name"].AsString();
if (args["inventory_folder"] != null)
InventoryFolder = args["inventory_folder"].AsUUID();
if (args["secure_session_id"] != null)
SecureSessionID = args["secure_session_id"].AsUUID();
if (args["session_id"] != null)
SessionID = args["session_id"].AsUUID();
if (args["start_pos"] != null)
Vector3.TryParse(args["start_pos"].AsString(), out startpos);
}
}
/// <summary>
/// Serializable Agent Circuit Data
/// </summary>
[Serializable]
public class sAgentCircuitData
{
public Guid AgentID;
public Guid BaseFolder;
public string CapsPath = String.Empty;
public Dictionary<ulong, string> ChildrenCapSeeds;
public bool child;
public uint circuitcode;
public string firstname;
public Guid InventoryFolder;
public string lastname;
public Guid SecureSessionID;
public Guid SessionID;
public float startposx;
public float startposy;
public float startposz;
public sAgentCircuitData()
{
}
public sAgentCircuitData(AgentCircuitData cAgent)
{
AgentID = cAgent.AgentID.Guid;
SessionID = cAgent.SessionID.Guid;
SecureSessionID = cAgent.SecureSessionID.Guid;
startposx = cAgent.startpos.X;
startposy = cAgent.startpos.Y;
startposz = cAgent.startpos.Z;
firstname = cAgent.firstname;
lastname = cAgent.lastname;
circuitcode = cAgent.circuitcode;
child = cAgent.child;
InventoryFolder = cAgent.InventoryFolder.Guid;
BaseFolder = cAgent.BaseFolder.Guid;
CapsPath = cAgent.CapsPath;
ChildrenCapSeeds = cAgent.ChildrenCapSeeds;
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2016 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using CoreTweet.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CoreTweet.Streaming
{
/// <summary>
/// Provides disconnect codes in Twitter Streaming API.
/// </summary>
public enum DisconnectCode
{
/// <summary>
/// The feed was shutdown (possibly a machine restart)
/// </summary>
Shutdown = 1,
/// <summary>
/// The same endpoint was connected too many times.
/// </summary>
DuplicateStream,
/// <summary>
/// Control streams was used to close a stream (applies to sitestreams).
/// </summary>
ControlRequest,
/// <summary>
/// The client was reading too slowly and was disconnected by the server.
/// </summary>
Stall,
/// <summary>
/// The client appeared to have initiated a disconnect.
/// </summary>
Normal,
/// <summary>
/// An oauth token was revoked for a user (applies to site and userstreams).
/// </summary>
TokenRevoked,
/// <summary>
/// The same credentials were used to connect a new stream and the oldest was disconnected.
/// </summary>
AdminLogout,
/// <summary>
/// <para>Reserved for internal use.</para>
/// <para>Will not be delivered to external clients.</para>
/// </summary>
Reserved,
/// <summary>
/// The stream connected with a negative count parameter and was disconnected after all backfill was delivered.
/// </summary>
MaxMessageLimit,
/// <summary>
/// An internal issue disconnected the stream.
/// </summary>
StreamException,
/// <summary>
/// An internal issue disconnected the stream.
/// </summary>
BrokerStall,
/// <summary>
/// <para>The host the stream was connected to became overloaded and streams were disconnected to balance load.</para>
/// <para>Reconnect as usual.</para>
/// </summary>
ShedLoad
}
/// <summary>
/// Provides event codes in Twitter Streaming API.
/// </summary>
public enum EventCode
{
/// <summary>
/// The user revokes his access token.
/// </summary>
AccessRevoked,
/// <summary>
/// The user blocks a user.
/// </summary>
Block,
/// <summary>
/// The user unblocks a user.
/// </summary>
Unblock,
/// <summary>
/// The user favorites a Tweet.
/// </summary>
Favorite,
/// <summary>
/// The user unfavorites a Tweet.
/// </summary>
Unfavorite,
/// <summary>
/// The user follows a user.
/// </summary>
Follow,
/// <summary>
/// The user unfollows a user.
/// </summary>
Unfollow,
/// <summary>
/// The user creates a List.
/// </summary>
ListCreated,
/// <summary>
/// The user destroys a List.
/// </summary>
ListDestroyed,
/// <summary>
/// The user updates a List.
/// </summary>
ListUpdated,
/// <summary>
/// The user adds a user to a List.
/// </summary>
ListMemberAdded,
/// <summary>
/// The user removes a user from a List.
/// </summary>
ListMemberRemoved,
/// <summary>
/// The user subscribes a List.
/// </summary>
ListUserSubscribed,
/// <summary>
/// The user unsubscribes a List.
/// </summary>
ListUserUnsubscribed,
/// <summary>
/// The user updates a List.
/// </summary>
UserUpdate,
/// <summary>
/// The user mutes a user.
/// </summary>
Mute,
/// <summary>
/// The user unmutes a user.
/// </summary>
Unmute,
/// <summary>
/// The user favorites a retweet.
/// </summary>
FavoritedRetweet,
/// <summary>
/// The user retweets a retweet.
/// </summary>
RetweetedRetweet,
/// <summary>
/// The user quotes a Tweet.
/// </summary>
QuotedTweet
}
/// <summary>
/// Provides message types in Twitter Streaming API.
/// </summary>
public enum MessageType
{
/// <summary>
/// The message indicates the Tweet has been deleted.
/// </summary>
DeleteStatus,
/// <summary>
/// The message indicates the Direct Message has been deleted.
/// </summary>
DeleteDirectMessage,
/// <summary>
/// The message indicates that geolocated data must be stripped from a range of Tweets.
/// </summary>
ScrubGeo,
/// <summary>
/// The message indicates that the indicated tweet has had their content withheld.
/// </summary>
StatusWithheld,
/// <summary>
/// The message indicates that indicated user has had their content withheld.
/// </summary>
UserWithheld,
/// <summary>
/// The message indicates that the user has been deleted.
/// </summary>
UserDelete,
/// <summary>
/// The message indicates that the user has canceled the deletion.
/// </summary>
//TODO: need investigation
UserUndelete,
/// <summary>
/// The message indicates that the user has been suspended.
/// </summary>
UserSuspend,
/// <summary>
/// The message indicates that the streams may be shut down for a variety of reasons.
/// </summary>
Disconnect,
/// <summary>
/// <para>The message indicates the current health of the connection.</para>
/// <para>This can be only sent when connected to a stream using the stall_warnings parameter.</para>
/// </summary>
Warning,
/// <summary>
/// The message is about non-Tweet events.
/// </summary>
Event,
/// <summary>
/// <para>The message is sent to identify the target of each message.</para>
/// <para>In Site Streams, an additional wrapper is placed around every message, except for blank keep-alive lines.</para>
/// </summary>
Envelopes,
/// <summary>
/// The message is a new Tweet.
/// </summary>
Create,
/// <summary>
/// The message is a new Direct Message.
/// </summary>
DirectMesssage,
/// <summary>
/// <para>The message is a list of the user's friends.</para>
/// <para>Twitter sends a preamble before starting regular message delivery upon establishing a User Stream connection.</para>
/// </summary>
Friends,
/// <summary>
/// The message indicates that a filtered stream has matched more Tweets than its current rate limit allows to be delivered.
/// </summary>
Limit,
/// <summary>
/// The message is sent to modify the Site Streams connection without reconnecting.
/// </summary>
Control,
/// <summary>
/// The message is in raw JSON format.
/// </summary>
RawJson
}
/// <summary>
/// Represents a streaming message. This class is an abstract class.
/// </summary>
public abstract class StreamingMessage : CoreBase
{
/// <summary>
/// Gets the type of the message.
/// </summary>
public MessageType Type => this.GetMessageType();
/// <summary>
/// Gets or sets the raw JSON.
/// </summary>
public string Json { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected abstract MessageType GetMessageType();
/// <summary>
/// Converts the JSON to a <see cref="StreamingMessage"/> object.
/// </summary>
/// <param name="x">The JSON value.</param>
/// <returns>The <see cref="StreamingMessage"/> object.</returns>
public static StreamingMessage Parse(string x)
{
try
{
var j = JObject.Parse(x);
StreamingMessage m;
if(j["text"] != null)
m = StatusMessage.Parse(j);
else if(j["direct_message"] != null)
m = CoreBase.Convert<DirectMessageMessage>(x);
else if(j["friends"] != null)
m = CoreBase.Convert<FriendsMessage>(x);
else if(j["event"] != null)
m = EventMessage.Parse(j);
else if(j["for_user"] != null)
m = EnvelopesMessage.Parse(j);
else if(j["control"] != null)
m = CoreBase.Convert<ControlMessage>(x);
else
m = ExtractRoot(j);
m.Json = x;
return m;
}
catch(ParsingException)
{
throw;
}
catch(Exception e)
{
throw new ParsingException("on streaming, cannot parse the json", x, e);
}
}
static StreamingMessage ExtractRoot(JObject jo)
{
JToken jt;
if(jo.TryGetValue("disconnect", out jt))
return jt.ToObject<DisconnectMessage>();
if(jo.TryGetValue("warning", out jt))
return jt.ToObject<WarningMessage>();
if(jo.TryGetValue("control", out jt))
return jt.ToObject<ControlMessage>();
if(jo.TryGetValue("delete", out jt))
{
JToken status;
DeleteMessage id;
if (((JObject)jt).TryGetValue("status", out status))
{
id = status.ToObject<DeleteMessage>();
id.messageType = MessageType.DeleteStatus;
}
else
{
id = jt["direct_message"].ToObject<DeleteMessage>();
id.messageType = MessageType.DeleteDirectMessage;
}
var timestamp = jt["timestamp_ms"];
if (timestamp != null)
id.Timestamp = InternalUtils.GetUnixTimeMs(long.Parse((string)timestamp));
return id;
}
if(jo.TryGetValue("scrub_geo", out jt))
{
return jt.ToObject<ScrubGeoMessage>();
}
if(jo.TryGetValue("limit", out jt))
{
return jt.ToObject<LimitMessage>();
}
if(jo.TryGetValue("status_withheld", out jt))
{
return jt.ToObject<StatusWithheldMessage>();
}
if(jo.TryGetValue("user_withheld", out jt))
{
return jt.ToObject<UserWithheldMessage>();
}
if(jo.TryGetValue("user_delete", out jt))
{
var m = jt.ToObject<UserMessage>();
m.messageType = MessageType.UserDelete;
return m;
}
if(jo.TryGetValue("user_undelete", out jt))
{
var m = jt.ToObject<UserMessage>();
m.messageType = MessageType.UserUndelete;
return m;
}
if(jo.TryGetValue("user_suspend", out jt))
{
// user_suspend doesn't have 'timestamp_ms' field
var m = jt.ToObject<UserMessage>();
m.messageType = MessageType.UserSuspend;
return m;
}
throw new ParsingException("on streaming, cannot parse the json: unsupported type", jo.ToString(Formatting.Indented), null);
}
}
/// <summary>
/// Represents a streaming message containing a timestamp.
/// </summary>
public abstract class TimestampMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the timestamp.
/// </summary>
[JsonProperty("timestamp_ms")]
[JsonConverter(typeof(TimestampConverter))]
public DateTimeOffset Timestamp { get; set; }
}
/// <summary>
/// Represents a status message.
/// </summary>
public class StatusMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the status.
/// </summary>
public Status Status { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Create;
}
internal static StatusMessage Parse(JObject j)
{
var m = new StatusMessage()
{
Status = j.ToObject<Status>()
};
var timestamp = j["timestamp_ms"];
if (timestamp != null)
m.Timestamp = InternalUtils.GetUnixTimeMs(long.Parse((string)timestamp));
return m;
}
}
/// <summary>
/// Represents a Direct message message.
/// </summary>
public class DirectMessageMessage : StreamingMessage
{
/// <summary>
/// The direct message.
/// </summary>
/// <value>The direct message.</value>
[JsonProperty("direct_message")]
public DirectMessage DirectMessage { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.DirectMesssage;
}
}
/// <summary>
/// Represents a message contains ids of friends.
/// </summary>
[JsonObject]
public class FriendsMessage : StreamingMessage,IEnumerable<long>
{
/// <summary>
/// Gets or sets the ids of friends.
/// </summary>
[JsonProperty("friends")]
public long[] Friends { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Friends;
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator<long> GetEnumerator()
{
return ((IEnumerable<long>)Friends).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return Friends.GetEnumerator();
}
}
/// <summary>
/// Represents the message with the rate limit.
/// </summary>
public class LimitMessage : TimestampMessage
{
/// <summary>
/// Gets or sets a total count of the number of undelivered Tweets since the connection was opened.
/// </summary>
[JsonProperty("track")]
public int Track { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Limit;
}
}
/// <summary>
/// Represents a delete message of a status or a direct message.
/// </summary>
public class DeleteMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("user_id")]
public long UserId { get; set; }
internal MessageType messageType { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return messageType;
}
}
/// <summary>
/// Represents a scrub-get message.
/// </summary>
public class ScrubGeoMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("user_id")]
public long UserId { get; set; }
/// <summary>
/// Gets or sets the ID of the status.
/// </summary>
//TODO: improve this comment
[JsonProperty("up_to_status_id")]
public long UpToStatusId { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.ScrubGeo;
}
}
/// <summary>
/// Represents a withheld message.
/// </summary>
public class UserWithheldMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the withhelds in countries.
/// </summary>
[JsonProperty("withheld_in_countries")]
public string[] WithheldInCountries { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.UserWithheld;
}
}
/// <summary>
/// Represents a withheld message.
/// </summary>
public class StatusWithheldMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("user_id")]
public long UserId { get; set; }
/// <summary>
/// Gets or sets the withhelds in countries.
/// </summary>
[JsonProperty("withheld_in_countries")]
public string[] WithheldInCountries { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.StatusWithheld;
}
}
/// <summary>
/// Represents a message contains the ID of an user.
/// </summary>
public class UserMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
internal MessageType messageType { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return messageType;
}
}
/// <summary>
/// Represents the message published when Twitter disconnects the stream.
/// </summary>
public class DisconnectMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the disconnect code.
/// </summary>
[JsonProperty("code")]
public DisconnectCode Code { get; set; }
/// <summary>
/// Gets or sets the stream name of current stream.
/// </summary>
[JsonProperty("stream_name")]
public string StreamName { get; set; }
/// <summary>
/// Gets or sets the human readable message of the reason.
/// </summary>
[JsonProperty("reason")]
public string Reason { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Disconnect;
}
}
/// <summary>
/// Represents a warning message.
/// </summary>
public class WarningMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the warning code.
/// </summary>
[JsonProperty("code")]
public string Code { get; set; }
/// <summary>
/// Gets or sets the warning message.
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
/// <summary>
/// Gets or sets the percentage of the stall messages
/// </summary>
[JsonProperty("percent_full")]
public int? PercentFull { get; set; }
/// <summary>
/// Gets or sets the target user ID.
/// </summary>
[JsonProperty("user_id")]
public long? UserId { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Warning;
}
}
/// <summary>
/// Provides the event target type.
/// </summary>
public enum EventTargetType
{
/// <summary>
/// The event is about a List.
/// </summary>
List,
/// <summary>
/// The event is about a Tweet.
/// </summary>
Status,
/// <summary>
/// The event is that the user revoked his access token.
/// </summary>
AccessRevocation,
/// <summary>
/// The event is unknown.
/// </summary>
Null
}
/// <summary>
/// Represents a revoked token.
/// </summary>
public class AccessRevocation
{
/// <summary>
/// The client application.
/// </summary>
[JsonProperty("client_application")]
public ClientApplication ClientApplication { get; set; }
/// <summary>
/// The revoked access token.
/// </summary>
[JsonProperty("token")]
public string Token { get; set; }
}
/// <summary>
/// Represents a client application.
/// </summary>
public class ClientApplication
{
/// <summary>
/// Gets or sets the URL of the application's publicly accessible home page.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
/// <summary>
/// Gets or sets the ID.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; } // int is better?
/// <summary>
/// Gets or sets the consumer key.
/// </summary>
[JsonProperty("consumer_key")]
public string ConsumerKey { get; set; }
/// <summary>
/// Gets or sets the application name.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
}
/// <summary>
/// Represents an event message.
/// </summary>
public class EventMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the target user.
/// </summary>
public User Target { get; set; }
/// <summary>
/// Gets or sets the source.
/// </summary>
public User Source { get; set; }
/// <summary>
/// Gets or sets the event code.
/// </summary>
public EventCode Event { get; set; }
/// <summary>
/// Gets or sets the type of target.
/// </summary>
public EventTargetType TargetType { get; set; }
/// <summary>
/// Gets or sets the target status.
/// </summary>
public Status TargetStatus { get; set; }
/// <summary>
/// Gets or sets the target List.
/// </summary>
public List TargetList { get; set; }
/// <summary>
/// Gets or sets the target access token.
/// </summary>
public AccessRevocation TargetToken { get; set; }
/// <summary>
/// Gets or sets the time when the event happened.
/// </summary>
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Event;
}
internal static EventMessage Parse(JObject j)
{
var e = new EventMessage();
e.Target = j["target"].ToObject<User>();
e.Source = j["source"].ToObject<User>();
e.Event = (EventCode)Enum.Parse(typeof(EventCode),
((string)j["event"])
.Replace("objectType", "")
.Replace("_",""),
true);
e.CreatedAt = DateTimeOffset.ParseExact((string)j["created_at"], "ddd MMM dd HH:mm:ss K yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo,
System.Globalization.DateTimeStyles.AllowWhiteSpaces);
var eventstr = (string)j["event"];
e.TargetType = eventstr.Contains("list")
? EventTargetType.List
: (eventstr.Contains("favorite") || eventstr.Contains("tweet"))
? EventTargetType.Status
: e.Event == EventCode.AccessRevoked
? EventTargetType.AccessRevocation
: EventTargetType.Null;
switch(e.TargetType)
{
case EventTargetType.Status:
e.TargetStatus = j["target_object"].ToObject<Status>();
break;
case EventTargetType.List:
e.TargetList = j["target_object"].ToObject<List>();
break;
case EventTargetType.AccessRevocation:
e.TargetToken = j["target_object"].ToObject<AccessRevocation>();
break;
}
return e;
}
}
/// <summary>
/// Provides an envelopes message.
/// </summary>
public class EnvelopesMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
public long ForUser { get; set; }
/// <summary>
/// Gets or sets the message.
/// </summary>
public StreamingMessage Message { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Envelopes;
}
internal static EnvelopesMessage Parse(JObject j)
{
return new EnvelopesMessage()
{
ForUser = (long)j["for_user"],
Message = StreamingMessage.Parse(j["message"].ToString(Formatting.None))
};
}
}
/// <summary>
/// Represents a control message.
/// </summary>
public class ControlMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the URI.
/// </summary>
[JsonProperty("control_uri")]
public string ControlUri { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Control;
}
}
/// <summary>
/// Represents a raw JSON message. This message means an exception was thrown when parsing.
/// </summary>
public class RawJsonMessage : StreamingMessage
{
/// <summary>
/// Gets the exception when parsing.
/// </summary>
public ParsingException Exception { get; private set; }
internal static RawJsonMessage Create(string json, ParsingException exception)
{
return new RawJsonMessage
{
Json = json,
Exception = exception
};
}
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.RawJson;
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Application = Autodesk.Revit.ApplicationServices.Application;
using Element = Autodesk.Revit.DB.Element;
namespace Revit.SDK.Samples.ManipulateForm.CS
{
/// <summary>
/// Implements the Revit add-in interface IExternalCommand
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class Command : IExternalCommand
{
/// <summary>
/// Revit document
/// </summary>
Document m_revitDoc;
/// <summary>
/// Revit application
/// </summary>
Application m_revitApp;
/// <summary>
/// Rectangle length of bottom profile
/// </summary>
double m_bottomLength = 200;
/// <summary>
/// Rectangle width of bottom profile
/// </summary>
double m_bottomWidth = 120;
/// <summary>
/// Height of bottom profile
/// </summary>
double m_bottomHeight = 0;
/// <summary>
/// Rectangle length of top profile
/// </summary>
double m_topLength = 140;
/// <summary>
/// Rectangle width of top profile
/// </summary>
double m_topWidth = 60;
/// <summary>
/// Height of top profile
/// </summary>
double m_topHeight = 40;
/// <summary>
/// offset of profile
/// </summary>
double m_profileOffset = 10;
/// <summary>
/// offset of vertex on bottom profile
/// </summary>
double m_vertexOffsetOnBottomProfile = 20;
/// <summary>
/// offset of vertex on middle profile
/// </summary>
double m_vertexOffsetOnMiddleProfile = 10;
/// <summary>
/// Used for double compare
/// </summary>
const double Epsilon = 0.000001;
/// <summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
public virtual Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData
, ref string message, Autodesk.Revit.DB.ElementSet elements)
{
m_revitApp = commandData.Application.Application;
m_revitDoc = commandData.Application.ActiveUIDocument.Document;
Transaction transaction = new Transaction(m_revitDoc, "ManipulateForm");
try
{
transaction.Start();
// Create a loft form
Form form = CreateLoft();
m_revitDoc.Regenerate();
// Add profile to the loft form
int profileIndex = AddProfile(form);
m_revitDoc.Regenerate();
// Move the edges on added profile
MoveEdgesOnProfile(form, profileIndex);
m_revitDoc.Regenerate();
// Move the added profile
MoveProfile(form, profileIndex);
m_revitDoc.Regenerate();
// Move the vertex on bottom profile
MoveVertexesOnBottomProfile(form);
m_revitDoc.Regenerate();
// Add edge to the loft form
Reference edgeReference = AddEdge(form);
m_revitDoc.Regenerate();
// Move the added edge
Autodesk.Revit.DB.XYZ offset = new Autodesk.Revit.DB.XYZ (0, -40, 0);
MoveSubElement(form, edgeReference, offset);
m_revitDoc.Regenerate();
// Move the vertex on added profile
MoveVertexesOnAddedProfile(form, profileIndex);
m_revitDoc.Regenerate();
transaction.Commit();
}
catch (Exception ex)
{
message = ex.Message;
transaction.RollBack();
return Autodesk.Revit.UI.Result.Failed;
}
return Autodesk.Revit.UI.Result.Succeeded;
}
/// <summary>
/// Create a loft form
/// </summary>
/// <returns>Created loft form</returns>
private Form CreateLoft()
{
// Prepare profiles for loft creation
ReferenceArrayArray profiles = new ReferenceArrayArray();
ReferenceArray bottomProfile = new ReferenceArray();
bottomProfile = CreateProfile(m_bottomLength, m_bottomWidth, m_bottomHeight);
profiles.Append(bottomProfile);
ReferenceArray topProfile = new ReferenceArray();
topProfile = CreateProfile(m_topLength, m_topWidth, m_topHeight);
profiles.Append(topProfile);
// return the created loft form
return m_revitDoc.FamilyCreate.NewLoftForm(true, profiles);
}
/// <summary>
/// Create a rectangle profile with provided length, width and height
/// </summary>
/// <param name="length">Length of the rectangle</param>
/// <param name="width">Width of the rectangle</param>
/// <param name="height">Height of the profile</param>
/// <returns>The created profile</returns>
private ReferenceArray CreateProfile(double length, double width, double height)
{
ReferenceArray profile = new ReferenceArray();
// Prepare points to create lines
List<XYZ> points = new List<XYZ>();
points.Add(new Autodesk.Revit.DB.XYZ (-1 * length / 2, -1 * width / 2, height));
points.Add(new Autodesk.Revit.DB.XYZ(length / 2, -1 * width / 2, height));
points.Add(new Autodesk.Revit.DB.XYZ(length / 2, width / 2, height));
points.Add(new Autodesk.Revit.DB.XYZ(-1 * length / 2, width / 2, height));
// Prepare sketch plane to create model line
Autodesk.Revit.DB.XYZ normal = new Autodesk.Revit.DB.XYZ (0, 0, 1);
Autodesk.Revit.DB.XYZ origin = new Autodesk.Revit.DB.XYZ (0, 0, height);
Plane geometryPlane = m_revitApp.Create.NewPlane(normal, origin);
SketchPlane sketchPlane = m_revitDoc.FamilyCreate.NewSketchPlane(geometryPlane);
// Create model lines and get their references as the profile
for (int i = 0; i < 4; i++)
{
Autodesk.Revit.DB.XYZ startPoint = points[i];
Autodesk.Revit.DB.XYZ endPoint = (i == 3 ? points[0] : points[i + 1]);
Line line = m_revitApp.Create.NewLineBound(startPoint, endPoint);
ModelCurve modelLine = m_revitDoc.FamilyCreate.NewModelCurve(line, sketchPlane);
profile.Append(modelLine.GeometryCurve.Reference);
}
return profile;
}
/// <summary>
/// Add profile to the loft form
/// </summary>
/// <param name="form">The loft form to be added edge</param>
/// <returns>Index of the added profile</returns>
private int AddProfile(Form form)
{
// Get a connecting edge from the form
Autodesk.Revit.DB.XYZ startOfTop = new Autodesk.Revit.DB.XYZ (-1 * m_topLength / 2, -1 * m_topWidth / 2, m_topHeight);
Autodesk.Revit.DB.XYZ startOfBottom = new Autodesk.Revit.DB.XYZ (-1 * m_bottomLength / 2, -1 * m_bottomWidth / 2, m_bottomHeight);
Edge connectingEdge = GetEdgeByEndPoints(form, startOfTop, startOfBottom);
// Add an profile with specific parameters
double param = 0.5;
return form.AddProfile(connectingEdge.Reference, param);
}
/// <summary>
/// Move the profile
/// </summary>
/// <param name="form">The form contains the edge</param>
/// <param name="profileIndex">Index of the profile to be moved</param>
private void MoveProfile(Form form, int profileIndex)
{
Autodesk.Revit.DB.XYZ offset = new Autodesk.Revit.DB.XYZ (0, 0, 5);
if (form.CanManipulateProfile(profileIndex))
{
form.MoveProfile(profileIndex, offset);
}
}
/// <summary>
/// Move the edges on profile
/// </summary>
/// <param name="form">The form contains the edge</param>
/// <param name="profileIndex">Index of the profile to be moved</param>
private void MoveEdgesOnProfile(Form form, int profileIndex)
{
Autodesk.Revit.DB.XYZ startOfTop = new Autodesk.Revit.DB.XYZ (-1 * m_topLength / 2, -1 * m_topWidth / 2, m_topHeight);
Autodesk.Revit.DB.XYZ offset1 = new Autodesk.Revit.DB.XYZ (m_profileOffset, 0, 0);
Autodesk.Revit.DB.XYZ offset2 = new Autodesk.Revit.DB.XYZ (-m_profileOffset, 0, 0);
Reference r1 = null;
Reference r2 = null;
ReferenceArray ra = form.get_CurveLoopReferencesOnProfile(profileIndex, 0);
foreach (Reference r in ra)
{
Line line = form.GetGeometryObjectFromReference(r) as Line;
if (line == null)
{
throw new Exception("Get curve reference on profile as line error.");
}
Autodesk.Revit.DB.XYZ pnt1 = line.Evaluate(0, false);
Autodesk.Revit.DB.XYZ pnt2 = line.Evaluate(1, false);
if (Math.Abs(pnt1.X - pnt2.X) < Epsilon)
{
if (pnt1.X < startOfTop.X)
{
r1 = r;
}
else
{
r2 = r;
}
}
}
if ((r1 == null) || (r2 == null))
{
throw new Exception("Get line on profile error.");
}
MoveSubElement(form, r1, offset1);
MoveSubElement(form, r2, offset2);
}
/// <summary>
/// Move the form vertexes
/// </summary>
/// <param name="form">The form contains the vertexes</param>
private void MoveVertexesOnBottomProfile(Form form)
{
Autodesk.Revit.DB.XYZ offset1 = new Autodesk.Revit.DB.XYZ (-m_vertexOffsetOnBottomProfile, -m_vertexOffsetOnBottomProfile, 0);
Autodesk.Revit.DB.XYZ offset2 = new Autodesk.Revit.DB.XYZ (m_vertexOffsetOnBottomProfile, -m_vertexOffsetOnBottomProfile, 0);
Autodesk.Revit.DB.XYZ startOfBottom = new Autodesk.Revit.DB.XYZ (-1 * m_bottomLength / 2, -1 * m_bottomWidth / 2, m_bottomHeight);
Autodesk.Revit.DB.XYZ endOfBottom = new Autodesk.Revit.DB.XYZ (m_bottomLength / 2, -1 * m_bottomWidth / 2, m_bottomHeight);
Edge bottomEdge = GetEdgeByEndPoints(form, startOfBottom, endOfBottom);
ReferenceArray pntsRef = form.GetControlPoints(bottomEdge.Reference);
Reference r1 = null;
Reference r2 = null;
foreach (Reference r in pntsRef)
{
Point pnt = form.GetGeometryObjectFromReference(r) as Point;
if (pnt.Coord.IsAlmostEqualTo(startOfBottom))
{
r1 = r;
}
else
{
r2 = r;
}
}
MoveSubElement(form, r1, offset1);
MoveSubElement(form, r2, offset2);
}
/// <summary>
/// Move the form vertexes on added profile
/// </summary>
/// <param name="form">The form contains the vertexes</param>
/// <param name="profileIndex">Index of added profile</param>
private void MoveVertexesOnAddedProfile(Form form, int profileIndex)
{
Autodesk.Revit.DB.XYZ offset = new Autodesk.Revit.DB.XYZ (0, m_vertexOffsetOnMiddleProfile, 0);
ReferenceArray ra = form.get_CurveLoopReferencesOnProfile(profileIndex, 0);
foreach (Reference r in ra)
{
ReferenceArray ra2 = form.GetControlPoints(r);
foreach (Reference r2 in ra2)
{
Point vertex = form.GetGeometryObjectFromReference(r2) as Point;
if (Math.Abs(vertex.Coord.X) < Epsilon)
{
MoveSubElement(form, r2, offset);
break;
}
}
}
}
/// <summary>
/// Add edge to the loft form
/// </summary>
/// <param name="form">The loft form to be added edge</param>
/// <returns>Reference of the added edge</returns>
private Reference AddEdge(Form form)
{
// Get two specific edges from the form
Autodesk.Revit.DB.XYZ startOfTop = new Autodesk.Revit.DB.XYZ (-1 * m_topLength / 2, -1 * m_topWidth / 2, m_topHeight);
Autodesk.Revit.DB.XYZ endOfTop = new Autodesk.Revit.DB.XYZ (m_topLength / 2, -1 * m_topWidth / 2, m_topHeight);
Edge topEdge = GetEdgeByEndPoints(form, startOfTop, endOfTop);
Autodesk.Revit.DB.XYZ startOfBottom = new Autodesk.Revit.DB.XYZ (-1 * (m_bottomLength / 2 + m_vertexOffsetOnBottomProfile), -1 * (m_bottomWidth / 2 + m_vertexOffsetOnBottomProfile), m_bottomHeight);
Autodesk.Revit.DB.XYZ endOfBottom = new Autodesk.Revit.DB.XYZ ((m_bottomLength / 2 + m_vertexOffsetOnBottomProfile), -1 * (m_bottomWidth / 2 + m_vertexOffsetOnBottomProfile), m_bottomHeight);
Edge bottomEdge = GetEdgeByEndPoints(form, startOfBottom, endOfBottom);
// Add an edge between the two edges with specific parameters
double topParam = 0.5;
double bottomParam = 0.5;
form.AddEdge(topEdge.Reference, topParam, bottomEdge.Reference, bottomParam);
m_revitDoc.Regenerate();
// Get the added edge and return its reference
Autodesk.Revit.DB.XYZ startOfAddedEdge = startOfTop.Add(endOfTop.Subtract(startOfTop).Multiply(topParam));
Autodesk.Revit.DB.XYZ endOfAddedEdge = startOfBottom.Add(endOfBottom.Subtract(startOfBottom).Multiply(bottomParam));
return GetEdgeByEndPoints(form, startOfAddedEdge, endOfAddedEdge).Reference;
}
/// <summary>
/// Get an edge from the form by its endpoints
/// </summary>
/// <param name="form">The form contains the edge</param>
/// <param name="startPoint">Start point of the edge</param>
/// <param name="endPoint">End point of the edge</param>
/// <returns>The edge found</returns>
private Edge GetEdgeByEndPoints(Form form, Autodesk.Revit.DB.XYZ startPoint, Autodesk.Revit.DB.XYZ endPoint)
{
Edge edge = null;
// Get all edges of the form
EdgeArray edges = null;
Options geoOptions = m_revitApp.Create.NewGeometryOptions();
geoOptions.ComputeReferences = true;
Autodesk.Revit.DB.GeometryElement geoElement = form.get_Geometry(geoOptions);
foreach (GeometryObject geoObject in geoElement.Objects)
{
Solid solid = geoObject as Solid;
if (null == solid)
continue;
edges = solid.Edges;
}
// Traverse the edges and look for the edge with the right endpoints
foreach (Edge ed in edges)
{
Autodesk.Revit.DB.XYZ rpPos1 = ed.Evaluate(0);
Autodesk.Revit.DB.XYZ rpPos2 = ed.Evaluate(1);
if ((startPoint.IsAlmostEqualTo(rpPos1) && endPoint.IsAlmostEqualTo(rpPos2)) ||
(startPoint.IsAlmostEqualTo(rpPos2) && endPoint.IsAlmostEqualTo(rpPos1)))
{
edge = ed;
break;
}
}
return edge;
}
/// <summary>
/// Move the sub element
/// </summary>
/// <param name="form">The form contains the sub element</param>
/// <param name="subElemReference">Reference of the sub element to be moved</param>
/// <param name="offset">offset to be moved</param>
private void MoveSubElement(Form form, Reference subElemReference, Autodesk.Revit.DB.XYZ offset)
{
if (form.CanManipulateSubElement(subElemReference))
{
form.MoveSubElement(subElemReference, offset);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
{
public class SymbolEquivalenceComparerTests
{
public static readonly CS.CSharpCompilationOptions CSharpDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
public static readonly CS.CSharpCompilationOptions CSharpSignedDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).
WithCryptoKeyFile(SigningTestHelpers.KeyPairFile).
WithStrongNameProvider(new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create<string>()));
[Fact]
public void TestArraysAreEquivalent()
{
var csharpCode =
@"class C
{
int intField1;
int[] intArrayField1;
string[] stringArrayField1;
int[][] intArrayArrayField1;
int[,] intArrayRank2Field1;
System.Int32 int32Field1;
int intField2;
int[] intArrayField2;
string[] stringArrayField2;
int[][] intArrayArrayField2;
int[,] intArrayRank2Field2;
System.Int32 int32Field2;
}";
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode))
{
var type = (ITypeSymbol)workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var intField1 = (IFieldSymbol)type.GetMembers("intField1").Single();
var intArrayField1 = (IFieldSymbol)type.GetMembers("intArrayField1").Single();
var stringArrayField1 = (IFieldSymbol)type.GetMembers("stringArrayField1").Single();
var intArrayArrayField1 = (IFieldSymbol)type.GetMembers("intArrayArrayField1").Single();
var intArrayRank2Field1 = (IFieldSymbol)type.GetMembers("intArrayRank2Field1").Single();
var int32Field1 = (IFieldSymbol)type.GetMembers("int32Field1").Single();
var intField2 = (IFieldSymbol)type.GetMembers("intField2").Single();
var intArrayField2 = (IFieldSymbol)type.GetMembers("intArrayField2").Single();
var stringArrayField2 = (IFieldSymbol)type.GetMembers("stringArrayField2").Single();
var intArrayArrayField2 = (IFieldSymbol)type.GetMembers("intArrayArrayField2").Single();
var intArrayRank2Field2 = (IFieldSymbol)type.GetMembers("intArrayRank2Field2").Single();
var int32Field2 = (IFieldSymbol)type.GetMembers("int32Field2").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField2.Type));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intField1.Type),
SymbolEquivalenceComparer.Instance.GetHashCode(intField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField2.Type));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField1.Type),
SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field2.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, stringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, intArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, int32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, intField1.Type));
}
}
[Fact]
public void TestArraysInDifferentLanguagesAreEquivalent()
{
var csharpCode =
@"class C
{
int intField1;
int[] intArrayField1;
string[] stringArrayField1;
int[][] intArrayArrayField1;
int[,] intArrayRank2Field1;
System.Int32 int32Field1;
}";
var vbCode =
@"class C
dim intField1 as Integer;
dim intArrayField1 as Integer()
dim stringArrayField1 as String()
dim intArrayArrayField1 as Integer()()
dim intArrayRank2Field1 as Integer(,)
dim int32Field1 as System.Int32
end class";
using (var csharpWorkspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode))
using (var vbWorkspace = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode))
{
var csharpType = (ITypeSymbol)csharpWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var vbType = vbWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var csharpIntField1 = (IFieldSymbol)csharpType.GetMembers("intField1").Single();
var csharpIntArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayField1").Single();
var csharpStringArrayField1 = (IFieldSymbol)csharpType.GetMembers("stringArrayField1").Single();
var csharpIntArrayArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayArrayField1").Single();
var csharpIntArrayRank2Field1 = (IFieldSymbol)csharpType.GetMembers("intArrayRank2Field1").Single();
var csharpInt32Field1 = (IFieldSymbol)csharpType.GetMembers("int32Field1").Single();
var vbIntField1 = (IFieldSymbol)vbType.GetMembers("intField1").Single();
var vbIntArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayField1").Single();
var vbStringArrayField1 = (IFieldSymbol)vbType.GetMembers("stringArrayField1").Single();
var vbIntArrayArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayArrayField1").Single();
var vbIntArrayRank2Field1 = (IFieldSymbol)vbType.GetMembers("intArrayRank2Field1").Single();
var vbInt32Field1 = (IFieldSymbol)vbType.GetMembers("int32Field1").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbIntArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbStringArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbInt32Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayField1.Type, csharpStringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbIntArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayArrayField1.Type, csharpIntArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayRank2Field1.Type, vbInt32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbIntField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntField1.Type, csharpIntArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbStringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbStringArrayField1.Type, csharpIntArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayRank2Field1.Type, csharpInt32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(vbInt32Field1.Type, csharpIntField1.Type));
}
}
[Fact]
public void TestFields()
{
var csharpCode1 =
@"class Type1
{
int field1;
string field2;
}
class Type2
{
bool field3;
short field4;
}";
var csharpCode2 =
@"class Type1
{
int field1;
short field4;
}
class Type2
{
bool field3;
string field2;
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field1_v2 = type1_v2.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
var field2_v2 = type2_v2.GetMembers("field2").Single();
var field3_v1 = type2_v1.GetMembers("field3").Single();
var field3_v2 = type2_v2.GetMembers("field3").Single();
var field4_v1 = type2_v1.GetMembers("field4").Single();
var field4_v2 = type1_v2.GetMembers("field4").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(field1_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(field1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2));
}
}
[WorkItem(538124)]
[Fact]
public void TestFieldsAcrossLanguages()
{
var csharpCode1 =
@"class Type1
{
int field1;
string field2;
}
class Type2
{
bool field3;
short field4;
}";
var vbCode1 =
@"class Type1
dim field1 as Integer;
dim field4 as Short;
end class
class Type2
dim field3 as Boolean;
dim field2 as String;
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field1_v2 = type1_v2.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
var field2_v2 = type2_v2.GetMembers("field2").Single();
var field3_v1 = type2_v1.GetMembers("field3").Single();
var field3_v2 = type2_v2.GetMembers("field3").Single();
var field4_v1 = type2_v1.GetMembers("field4").Single();
var field4_v2 = type1_v2.GetMembers("field4").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2));
}
}
[Fact]
public void TestFieldsInGenericTypes()
{
var code =
@"class C<T>
{
int foo;
C<int> intInstantiation1;
C<string> stringInstantiation;
C<T> instanceInstantiation;
}
class D
{
C<int> intInstantiation2;
}
";
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var typeC = workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var typeD = workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("D").Single();
var intInstantiation1 = (IFieldSymbol)typeC.GetMembers("intInstantiation1").Single();
var stringInstantiation = (IFieldSymbol)typeC.GetMembers("stringInstantiation").Single();
var instanceInstantiation = (IFieldSymbol)typeC.GetMembers("instanceInstantiation").Single();
var intInstantiation2 = (IFieldSymbol)typeD.GetMembers("intInstantiation2").Single();
var foo = typeC.GetMembers("foo").Single();
var foo_intInstantiation1 = intInstantiation1.Type.GetMembers("foo").Single();
var foo_stringInstantiation = stringInstantiation.Type.GetMembers("foo").Single();
var foo_instanceInstantiation = instanceInstantiation.Type.GetMembers("foo").Single();
var foo_intInstantiation2 = intInstantiation2.Type.GetMembers("foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_stringInstantiation));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_stringInstantiation));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo, foo_instanceInstantiation));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo),
SymbolEquivalenceComparer.Instance.GetHashCode(foo_instanceInstantiation));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_intInstantiation2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation1),
SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation2));
}
}
[Fact]
public void TestMethodsWithDifferentReturnTypeNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
int Foo() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentNamesAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo1() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentAritiesAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo<T>() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentParametersAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentTypeParameters()
{
var csharpCode1 =
@"class Type1
{
void Foo<A>(A a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo<B>(B a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsWithSameParameters()
{
var csharpCode1 =
@"class Type1
{
void Foo(int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentParameterNames()
{
var csharpCode1 =
@"class Type1
{
void Foo(int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int b) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsAreEquivalentOutToRef()
{
var csharpCode1 =
@"class Type1
{
void Foo(out int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(ref int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsNotEquivalentRemoveOut()
{
var csharpCode1 =
@"class Type1
{
void Foo(out int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsAreEquivalentIgnoreParams()
{
var csharpCode1 =
@"class Type1
{
void Foo(params int[] a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int[] a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsNotEquivalentDifferentParameterTypes()
{
var csharpCode1 =
@"class Type1
{
void Foo(int[] a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(string[] a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsAcrossLanguages()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
T Foo<T>(IList<T> list, int a) {}
void Bar() { }
}";
var vbCode1 =
@"
Imports System.Collections.Generic
class Type1
function Foo(of U)(list as IList(of U), a as Integer) as U
end function
sub Quux()
end sub
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var csharpType1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var vbType1 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var csharpFooMethod = csharpType1.GetMembers("Foo").Single();
var csharpBarMethod = csharpType1.GetMembers("Bar").Single();
var vbFooMethod = vbType1.GetMembers("Foo").Single();
var vbQuuxMethod = vbType1.GetMembers("Quux").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod),
SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbQuuxMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbQuuxMethod));
}
}
[Fact]
public void TestMethodsInGenericTypesAcrossLanguages()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1<X>
{
T Foo<T>(IList<T> list, X a) {}
void Bar(X x) { }
}";
var vbCode1 =
@"
Imports System.Collections.Generic
class Type1(of M)
function Foo(of U)(list as IList(of U), a as M) as U
end function
sub Bar(x as Object)
end sub
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var csharpType1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var vbType1 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var csharpFooMethod = csharpType1.GetMembers("Foo").Single();
var csharpBarMethod = csharpType1.GetMembers("Bar").Single();
var vbFooMethod = vbType1.GetMembers("Foo").Single();
var vbBarMethod = vbType1.GetMembers("Bar").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod),
SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbBarMethod));
}
}
[Fact]
public void TestObjectAndDynamicAreNotEqualNormally()
{
var csharpCode1 =
@"class Type1
{
object field1;
dynamic field2;
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field2_v1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field1_v1));
}
}
[Fact]
public void TestObjectAndDynamicAreEqualInSignatures()
{
var csharpCode1 =
@"class Type1
{
void Foo(object o1) { }
}";
var csharpCode2 =
@"class Type1
{
void Foo(dynamic o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestUnequalGenericsInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<int> o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<string> o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
}
}
[Fact]
public void TestGenericsWithDynamicAndObjectInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<object> o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<dynamic> o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestDynamicAndUnrelatedTypeInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(dynamic o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(string o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
}
}
[Fact]
public void TestNamespaces()
{
var csharpCode1 =
@"namespace Outer
{
namespace Inner
{
class Type
{
}
}
class Type
{
}
}
";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
{
var outer1 = (INamespaceSymbol)workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetMembers("Outer").Single();
var outer2 = (INamespaceSymbol)workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetMembers("Outer").Single();
var inner1 = (INamespaceSymbol)outer1.GetMembers("Inner").Single();
var inner2 = (INamespaceSymbol)outer2.GetMembers("Inner").Single();
var outerType1 = outer1.GetTypeMembers("Type").Single();
var outerType2 = outer2.GetTypeMembers("Type").Single();
var innerType1 = inner1.GetTypeMembers("Type").Single();
var innerType2 = inner2.GetTypeMembers("Type").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outer2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(outer2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, inner2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1),
SymbolEquivalenceComparer.Instance.GetHashCode(inner2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outerType1, outerType2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outerType1),
SymbolEquivalenceComparer.Instance.GetHashCode(outerType2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(innerType1, innerType2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(innerType1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(inner1, outerType1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(outerType1, innerType1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(innerType1, outer1));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(inner1.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, innerType1.ContainingSymbol.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, innerType1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outerType1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(outerType1.ContainingSymbol));
}
}
[Fact]
public void TestNamedTypesEquivalent()
{
var csharpCode1 =
@"
class Type1
{
}
class Type2<X>
{
}
";
var csharpCode2 =
@"
class Type1
{
void Foo();
}
class Type2<Y>
{
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type1_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(type1_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v2, type2_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type2_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(type2_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type2_v1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfNameChanges()
{
var csharpCode1 =
@"
class Type1
{
}";
var csharpCode2 =
@"
class Type2
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfTypeKindChanges()
{
var csharpCode1 =
@"
struct Type1
{
}";
var csharpCode2 =
@"
class Type1
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfArityChanges()
{
var csharpCode1 =
@"
class Type1
{
}";
var csharpCode2 =
@"
class Type1<T>
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfContainerDifferent()
{
var csharpCode1 =
@"
class Outer
{
class Type1
{
}
}";
var csharpCode2 =
@"
class Other
{
class Type1
{
void Foo();
}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var outer = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Outer").Single();
var other = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Other").Single();
var type1_v1 = outer.GetTypeMembers("Type1").Single();
var type1_v2 = other.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestAliasedTypes1()
{
var csharpCode1 =
@"
using i = System.Int32;
class Type1
{
void Foo(i o1) { }
}";
var csharpCode2 =
@"
class Type1
{
void Foo(int o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")]
[Fact]
public void TestRefVersusOut()
{
var csharpCode1 =
@"
class C
{
void M(out int i) { }
}";
var csharpCode2 =
@"
class C
{
void M(ref int i) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var method_v1 = type1_v1.GetMembers("M").Single();
var method_v2 = type1_v2.GetMembers("M").Single();
var trueComp = new SymbolEquivalenceComparer(assemblyComparerOpt: null, distinguishRefFromOut: true);
var falseComp = new SymbolEquivalenceComparer(assemblyComparerOpt: null, distinguishRefFromOut: false);
Assert.False(trueComp.Equals(method_v1, method_v2));
Assert.False(trueComp.Equals(method_v2, method_v1));
// The hashcodes of distinct objects don't have to be distinct.
Assert.True(falseComp.Equals(method_v1, method_v2));
Assert.True(falseComp.Equals(method_v2, method_v1));
Assert.Equal(falseComp.GetHashCode(method_v1),
falseComp.GetHashCode(method_v2));
}
}
[Fact]
public void TestCSharpReducedExtensionMethodsAreEquivalent()
{
var code = @"
class Zed {}
public static class Extensions
{
public static void NotGeneric(this Zed z, int data) { }
public static void GenericThis<T>(this T me, int data) where T : Zed { }
public static void GenericNotThis<T>(this Zed z, T data) { }
public static void GenericThisAndMore<T,S>(this T me, S data) where T : Zed { }
public static void GenericThisAndOther<T>(this T me, T data) where T : Zed { }
}
class Test
{
void NotGeneric()
{
Zed z;
int n;
z.NotGeneric(n);
}
void GenericThis()
{
Zed z;
int n;
z.GenericThis(n);
}
void GenericNotThis()
{
Zed z;
int n;
z.GenericNotThis(n);
}
void GenericThisAndMore()
{
Zed z;
int n;
z.GenericThisAndMore(n);
}
void GenericThisAndOther()
{
Zed z;
z.GenericThisAndOther(z);
}
}
";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var comp1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
var comp2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther");
}
}
[Fact]
public void TestVisualBasicReducedExtensionMethodsAreEquivalent()
{
var code = @"
Imports System.Runtime.CompilerServices
Class Zed
End Class
Module Extensions
<Extension>
Public Sub NotGeneric(z As Zed, data As Integer)
End Sub
<Extension>
Public Sub GenericThis(Of T As Zed)(m As T, data as Integer)
End Sub
<Extension>
Public Sub GenericNotThis(Of T)(z As Zed, data As T)
End Sub
<Extension>
Public Sub GenericThisAndMore(Of T As Zed, S)(m As T, data As S)
End Sub
<Extension>
Public Sub GenericThisAndOther(Of T As Zed)(m As T, data As T)
End Sub
End Module
Class Test
Sub NotGeneric()
Dim z As Zed
Dim n As Integer
z.NotGeneric(n)
End Sub
Sub GenericThis()
Dim z As Zed
Dim n As Integer
z.GenericThis(n)
End Sub
Sub GenericNotThis()
Dim z As Zed
Dim n As Integer
z.GenericNotThis(n)
End Sub
Sub GenericThisAndMore()
Dim z As Zed
Dim n As Integer
z.GenericThisAndMore(n)
End Sub
Sub GenericThisAndOther()
Dim z As Zed
z.GenericThisAndOther(z)
End Sub
End Class
";
using (var workspace1 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var comp1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
var comp2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther");
}
}
[Fact]
public void TestDifferentModules()
{
var csharpCode =
@"namespace N
{
namespace M
{
}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "FooModule")))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "BarModule")))
{
var namespace1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M");
var namespace2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M");
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(namespace1, namespace2));
Assert.Equal(SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace1),
SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(namespace1, namespace2));
Assert.NotEqual(SymbolEquivalenceComparer.Instance.GetHashCode(namespace1),
SymbolEquivalenceComparer.Instance.GetHashCode(namespace2));
}
}
[Fact]
public void AssemblyComparer1()
{
var references = new[] { TestReferences.NetFx.v4_0_30319.mscorlib };
string source = "public class T {}";
string sourceV1 = "[assembly: System.Reflection.AssemblyVersion(\"1.0.0.0\")] public class T {}";
string sourceV2 = "[assembly: System.Reflection.AssemblyVersion(\"2.0.0.0\")] public class T {}";
var a1 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions);
var a2 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions);
var b1 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV1) }, references, CSharpSignedDllOptions);
var b2 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions);
var b3 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions);
var ta1 = (ITypeSymbol)a1.GlobalNamespace.GetMembers("T").Single();
var ta2 = (ITypeSymbol)a2.GlobalNamespace.GetMembers("T").Single();
var tb1 = (ITypeSymbol)b1.GlobalNamespace.GetMembers("T").Single();
var tb2 = (ITypeSymbol)b2.GlobalNamespace.GetMembers("T").Single();
var tb3 = (ITypeSymbol)b3.GlobalNamespace.GetMembers("T").Single();
var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance, distinguishRefFromOut: false);
// same name:
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, ta2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(ta1, ta2));
Assert.True(identityComparer.Equals(ta1, ta2));
// different name:
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, tb1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(ta1, tb1));
Assert.False(identityComparer.Equals(ta1, tb1));
// different identity
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb1, tb2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb1, tb2));
Assert.False(identityComparer.Equals(tb1, tb2));
// same identity
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb2, tb3));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb2, tb3));
Assert.True(identityComparer.Equals(tb2, tb3));
}
private sealed class AssemblySymbolIdentityComparer : IEqualityComparer<IAssemblySymbol>
{
public static readonly IEqualityComparer<IAssemblySymbol> Instance = new AssemblySymbolIdentityComparer();
public bool Equals(IAssemblySymbol x, IAssemblySymbol y)
{
return x.Identity.Equals(y.Identity);
}
public int GetHashCode(IAssemblySymbol obj)
{
return obj.Identity.GetHashCode();
}
}
[Fact]
public void CustomModifiers_Methods1()
{
const string ilSource = @"
.class public C
{
.method public instance int32 [] modopt([mscorlib]System.Int64) F( // 0
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b)
{
ldnull
throw
}
.method public instance int32 [] modopt([mscorlib]System.Boolean) F( // 1
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b)
{
ldnull
throw
}
.method public instance int32[] F( // 2
int32 a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b)
{
ldnull
throw
}
.method public instance int32[] F( // 3
int32 a,
int32 b)
{
ldnull
throw
}
}
";
MetadataReference r1, r2;
using (var tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource))
{
byte[] bytes = File.ReadAllBytes(tempAssembly.Path);
r1 = MetadataReference.CreateFromImage(bytes);
r2 = MetadataReference.CreateFromImage(bytes);
}
var c1 = CS.CSharpCompilation.Create("comp1", Array.Empty<SyntaxTree>(), new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r1 });
var c2 = CS.CSharpCompilation.Create("comp2", Array.Empty<SyntaxTree>(), new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r2 });
var type1 = (ITypeSymbol)c1.GlobalNamespace.GetMembers("C").Single();
var type2 = (ITypeSymbol)c2.GlobalNamespace.GetMembers("C").Single();
var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance, distinguishRefFromOut: false);
var f1 = type1.GetMembers("F");
var f2 = type2.GetMembers("F");
Assert.True(identityComparer.Equals(f1[0], f2[0]));
Assert.False(identityComparer.Equals(f1[0], f2[1]));
Assert.False(identityComparer.Equals(f1[0], f2[2]));
Assert.False(identityComparer.Equals(f1[0], f2[3]));
Assert.False(identityComparer.Equals(f1[1], f2[0]));
Assert.True(identityComparer.Equals(f1[1], f2[1]));
Assert.False(identityComparer.Equals(f1[1], f2[2]));
Assert.False(identityComparer.Equals(f1[1], f2[3]));
Assert.False(identityComparer.Equals(f1[2], f2[0]));
Assert.False(identityComparer.Equals(f1[2], f2[1]));
Assert.True(identityComparer.Equals(f1[2], f2[2]));
Assert.False(identityComparer.Equals(f1[2], f2[3]));
Assert.False(identityComparer.Equals(f1[3], f2[0]));
Assert.False(identityComparer.Equals(f1[3], f2[1]));
Assert.False(identityComparer.Equals(f1[3], f2[2]));
Assert.True(identityComparer.Equals(f1[3], f2[3]));
}
private void TestReducedExtension<TInvocation>(Compilation comp1, Compilation comp2, string typeName, string methodName)
where TInvocation : SyntaxNode
{
var method1 = GetInvokedSymbol<TInvocation>(comp1, typeName, methodName);
var method2 = GetInvokedSymbol<TInvocation>(comp2, typeName, methodName);
Assert.NotNull(method1);
Assert.Equal(method1.MethodKind, MethodKind.ReducedExtension);
Assert.NotNull(method2);
Assert.Equal(method2.MethodKind, MethodKind.ReducedExtension);
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method1, method2));
var cfmethod1 = method1.ConstructedFrom;
var cfmethod2 = method2.ConstructedFrom;
Assert.True(SymbolEquivalenceComparer.Instance.Equals(cfmethod1, cfmethod2));
}
private IMethodSymbol GetInvokedSymbol<TInvocation>(Compilation compilation, string typeName, string methodName)
where TInvocation : SyntaxNode
{
var type1 = compilation.GlobalNamespace.GetTypeMembers(typeName).Single();
var method = type1.GetMembers(methodName).Single();
var method_root = method.DeclaringSyntaxReferences[0].GetSyntax();
var invocation = method_root.DescendantNodes().OfType<TInvocation>().FirstOrDefault();
if (invocation == null)
{
// vb method root is statement, but we need block to find body with invocation
invocation = method_root.Parent.DescendantNodes().OfType<TInvocation>().First();
}
var model = compilation.GetSemanticModel(invocation.SyntaxTree);
var info = model.GetSymbolInfo(invocation);
return info.Symbol as IMethodSymbol;
}
}
}
| |
/*===============================================================================================
3d Example
Copyright (c), Firelight Technologies Pty, Ltd 2004-2011.
This example shows how to basic 3d positioning
===============================================================================================*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
namespace _3d
{
public class threeD : System.Windows.Forms.Form
{
private const int INTERFACE_UPDATETIME = 50;
private const float DISTANCEFACTOR = 1.0f; // Units per meter. I.e feet would = 3.28. centimeters would = 100.
private FMOD.System system = null;
private FMOD.Sound sound1 = null, sound2 = null, sound3 = null;
private FMOD.Channel channel1 = null, channel2 = null, channel3 = null;
private bool listenerflag = true;
private FMOD.VECTOR lastpos = new FMOD.VECTOR();
private FMOD.VECTOR listenerpos = new FMOD.VECTOR();
private static float t = 0;
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.Button exit_button;
private System.Windows.Forms.Label label;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Timer timer;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TrackBar trackBarPosition;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.ComponentModel.IContainer components;
public threeD()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
FMOD.RESULT result;
/*
Shut down
*/
if (sound1 != null)
{
result = sound1.release();
ERRCHECK(result);
}
if (sound2 != null)
{
result = sound2.release();
ERRCHECK(result);
}
if (sound3 != null)
{
result = sound3.release();
ERRCHECK(result);
}
if (system != null)
{
result = system.close();
ERRCHECK(result);
result = system.release();
ERRCHECK(result);
}
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.statusBar = new System.Windows.Forms.StatusBar();
this.exit_button = new System.Windows.Forms.Button();
this.label = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.timer = new System.Windows.Forms.Timer(this.components);
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.trackBarPosition = new System.Windows.Forms.TrackBar();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trackBarPosition)).BeginInit();
this.SuspendLayout();
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 291);
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size(264, 24);
this.statusBar.TabIndex = 18;
//
// exit_button
//
this.exit_button.Location = new System.Drawing.Point(96, 264);
this.exit_button.Name = "exit_button";
this.exit_button.Size = new System.Drawing.Size(72, 24);
this.exit_button.TabIndex = 17;
this.exit_button.Text = "Exit";
this.exit_button.Click += new System.EventHandler(this.exit_button_Click);
//
// label
//
this.label.Location = new System.Drawing.Point(0, 0);
this.label.Name = "label";
this.label.Size = new System.Drawing.Size(264, 32);
this.label.TabIndex = 16;
this.label.Text = "Copyright (c) Firelight Technologies 2004-2011";
this.label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// button1
//
this.button1.Location = new System.Drawing.Point(16, 32);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(232, 32);
this.button1.TabIndex = 19;
this.button1.Text = "Pause/Unpause 16bit 3D sound at any time";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(16, 72);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(232, 32);
this.button2.TabIndex = 20;
this.button2.Text = "Pause/Unpause 8bit 3D sound at any time";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(16, 112);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(232, 32);
this.button3.TabIndex = 21;
this.button3.Text = "Play 16bit STEREO 2D sound at any time";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(16, 152);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(232, 32);
this.button4.TabIndex = 22;
this.button4.Text = "Stop/Start listener automatic movement";
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// timer
//
this.timer.Enabled = true;
this.timer.Interval = 49;
this.timer.Tick += new System.EventHandler(this.timer_Tick);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.trackBarPosition);
this.groupBox1.Location = new System.Drawing.Point(16, 192);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(232, 64);
this.groupBox1.TabIndex = 23;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Listener Position";
//
// trackBarPosition
//
this.trackBarPosition.Location = new System.Drawing.Point(8, 16);
this.trackBarPosition.Maximum = 35;
this.trackBarPosition.Minimum = -35;
this.trackBarPosition.Name = "trackBarPosition";
this.trackBarPosition.Size = new System.Drawing.Size(216, 45);
this.trackBarPosition.TabIndex = 0;
this.trackBarPosition.TickStyle = System.Windows.Forms.TickStyle.None;
this.trackBarPosition.Scroll += new System.EventHandler(this.trackBarPosition_Scroll);
//
// label1
//
this.label1.Location = new System.Drawing.Point(80, 40);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(32, 16);
this.label1.TabIndex = 1;
this.label1.Text = "<1>";
//
// label2
//
this.label2.Location = new System.Drawing.Point(144, 40);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(24, 16);
this.label2.TabIndex = 2;
this.label2.Text = "<2>";
//
// threeD
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(264, 315);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.statusBar);
this.Controls.Add(this.exit_button);
this.Controls.Add(this.label);
this.Name = "threeD";
this.Text = "3D Example";
this.Load += new System.EventHandler(this.threeD_Load);
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.trackBarPosition)).EndInit();
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new threeD());
}
private void threeD_Load(object sender, System.EventArgs e)
{
uint version = 0;
FMOD.RESULT result;
trackBarPosition.Enabled = false;
/*
Create a System object and initialize.
*/
result = FMOD.Factory.System_Create(ref system);
ERRCHECK(result);
result = system.getVersion(ref version);
ERRCHECK(result);
if (version < FMOD.VERSION.number)
{
MessageBox.Show("Error! You are using an old version of FMOD " + version.ToString("X") + ". This program requires " + FMOD.VERSION.number.ToString("X") + ".");
Application.Exit();
}
FMOD.CAPS caps = FMOD.CAPS.NONE;
FMOD.SPEAKERMODE speakermode = FMOD.SPEAKERMODE.STEREO;
int outputrate = 0;
StringBuilder name = new StringBuilder(128);
result = system.getDriverCaps(0, ref caps, ref outputrate, ref speakermode);
ERRCHECK(result);
result = system.setSpeakerMode(speakermode); /* Set the user selected speaker mode. */
ERRCHECK(result);
if ((caps & FMOD.CAPS.HARDWARE_EMULATED) == FMOD.CAPS.HARDWARE_EMULATED) /* The user has the 'Acceleration' slider set to off! This is really bad for latency!. */
{ /* You might want to warn the user about this. */
result = system.setDSPBufferSize(1024, 10); /* At 48khz, the latency between issuing an fmod command and hearing it will now be about 213ms. */
ERRCHECK(result);
}
FMOD.GUID guid = new FMOD.GUID();
result = system.getDriverInfo(0, name, 256, ref guid);
ERRCHECK(result);
if (name.ToString().IndexOf("SigmaTel") != -1) /* Sigmatel sound devices crackle for some reason if the format is pcm 16bit. pcm floating point output seems to solve it. */
{
result = system.setSoftwareFormat(48000, FMOD.SOUND_FORMAT.PCMFLOAT, 0,0, FMOD.DSP_RESAMPLER.LINEAR);
ERRCHECK(result);
}
result = system.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)null);
if (result == FMOD.RESULT.ERR_OUTPUT_CREATEBUFFER)
{
result = system.setSpeakerMode(FMOD.SPEAKERMODE.STEREO); /* Ok, the speaker mode selected isn't supported by this soundcard. Switch it back to stereo... */
ERRCHECK(result);
result = system.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)null); /* Replace with whatever channel count and flags you use! */
ERRCHECK(result);
}
/*
Set the distance units. (meters/feet etc).
*/
result = system.set3DSettings(1.0f, DISTANCEFACTOR, 1.0f);
ERRCHECK(result);
/*
Load some sounds
*/
result = system.createSound("../../../../../examples/media/drumloop.wav", (FMOD.MODE.HARDWARE | FMOD.MODE._3D), ref sound1);
ERRCHECK(result);
result = sound1.set3DMinMaxDistance(2.0f * DISTANCEFACTOR, 10000.0f * DISTANCEFACTOR);
ERRCHECK(result);
result = sound1.setMode(FMOD.MODE.LOOP_NORMAL);
ERRCHECK(result);
result = system.createSound("../../../../../examples/media/jaguar.wav", (FMOD.MODE.HARDWARE | FMOD.MODE._3D), ref sound2);
ERRCHECK(result);
result = sound2.set3DMinMaxDistance(2.0f * DISTANCEFACTOR, 10000.0f * DISTANCEFACTOR);
ERRCHECK(result);
result = sound2.setMode(FMOD.MODE.LOOP_NORMAL);
ERRCHECK(result);
result = system.createSound("../../../../../examples/media/swish.wav", (FMOD.MODE.HARDWARE | FMOD.MODE._2D), ref sound3);
ERRCHECK(result);
/*
Play sounds at certain positions
*/
{
FMOD.VECTOR pos1 = new FMOD.VECTOR();
pos1.x = -10.0f * DISTANCEFACTOR; pos1.y = -0.0f; pos1.z = 0.0f;
FMOD.VECTOR vel1 = new FMOD.VECTOR();
vel1.x = 0.0f; vel1.y = 0.0f; vel1.z = 0.0f;
result = system.playSound(FMOD.CHANNELINDEX.FREE, sound1, true, ref channel1);
ERRCHECK(result);
result = channel1.set3DAttributes(ref pos1, ref vel1);
ERRCHECK(result);
result = channel1.setPaused(false);
ERRCHECK(result);
}
{
FMOD.VECTOR pos2 = new FMOD.VECTOR();
pos2.x = 15.0f * DISTANCEFACTOR; pos2.y = -0.0f; pos2.z = -0.0f;
FMOD.VECTOR vel2 = new FMOD.VECTOR();
vel2.x = 0.0f; vel2.y = 0.0f; vel2.z = 0.0f;
result = system.playSound(FMOD.CHANNELINDEX.FREE, sound2, true, ref channel2);
ERRCHECK(result);
result = channel2.set3DAttributes(ref pos2, ref vel2);
ERRCHECK(result);
result = channel2.setPaused(false);
ERRCHECK(result);
}
lastpos.x = 0.0f;
lastpos.y = 0.0f;
lastpos.z = 0.0f;
listenerpos.x = 0.0f;
listenerpos.y = 0.0f;
listenerpos.z = -1.0f * DISTANCEFACTOR;
}
private void button1_Click(object sender, System.EventArgs e)
{
FMOD.RESULT result;
bool paused = false;
result = channel1.getPaused(ref paused);
ERRCHECK(result);
result = channel1.setPaused(!paused);
ERRCHECK(result);
}
private void button2_Click(object sender, System.EventArgs e)
{
FMOD.RESULT result;
bool paused = false;
result = channel2.getPaused(ref paused);
ERRCHECK(result);
result = channel2.setPaused(!paused);
ERRCHECK(result);
}
private void button3_Click(object sender, System.EventArgs e)
{
FMOD.RESULT result;
result = system.playSound(FMOD.CHANNELINDEX.FREE, sound3, false, ref channel3);
ERRCHECK(result);
}
private void button4_Click(object sender, System.EventArgs e)
{
trackBarPosition.Enabled = listenerflag;
listenerflag = !listenerflag;
}
private void trackBarPosition_Scroll(object sender, System.EventArgs e)
{
listenerpos.x = trackBarPosition.Value * DISTANCEFACTOR;
}
private void exit_button_Click(object sender, System.EventArgs e)
{
Application.Exit();
}
private void timer_Tick(object sender, System.EventArgs e)
{
FMOD.RESULT result;
// ==========================================================================================
// UPDATE THE LISTENER
// ==========================================================================================
FMOD.VECTOR forward = new FMOD.VECTOR();
forward.x = 0.0f; forward.y = 0.0f; forward.z = 1.0f;
FMOD.VECTOR up = new FMOD.VECTOR();
up.x = 0.0f; up.y = 1.0f; up.z = 0.0f;
FMOD.VECTOR vel = new FMOD.VECTOR();
if (listenerflag)
{
listenerpos.x = ((float)Math.Sin(t * 0.05f) * 33.0f * DISTANCEFACTOR); // left right pingpong
trackBarPosition.Value = (int)listenerpos.x;
}
// ********* NOTE ******* READ NEXT COMMENT!!!!!
// vel = how far we moved last FRAME (m/f), then time compensate it to SECONDS (m/s).
vel.x = (listenerpos.x - lastpos.x) * (1000 / INTERFACE_UPDATETIME);
vel.y = (listenerpos.y - lastpos.y) * (1000 / INTERFACE_UPDATETIME);
vel.z = (listenerpos.z - lastpos.z) * (1000 / INTERFACE_UPDATETIME);
// store pos for next time
lastpos = listenerpos;
result = system.set3DListenerAttributes(0, ref listenerpos, ref vel, ref forward, ref up);
ERRCHECK(result);
t += (30 * (1.0f / (float)INTERFACE_UPDATETIME)); // t is just a time value .. it increments in 30m/s steps in this example
if (system != null)
{
system.update();
}
}
private void ERRCHECK(FMOD.RESULT result)
{
if (result != FMOD.RESULT.OK)
{
timer.Stop();
MessageBox.Show("FMOD error! " + result + " - " + FMOD.Error.String(result));
Environment.Exit(-1);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using System.Diagnostics;
namespace System.Text
{
public sealed class EncoderReplacementFallback : EncoderFallback
{
// Our variables
private string _strDefault;
// Construction. Default replacement fallback uses no best fit and ? replacement string
public EncoderReplacementFallback() : this("?")
{
}
public EncoderReplacementFallback(string replacement)
{
// Must not be null
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
// Make sure it doesn't have bad surrogate pairs
bool bFoundHigh = false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
if (char.IsSurrogate(replacement, i))
{
// High or Low?
if (char.IsHighSurrogate(replacement, i))
{
// if already had a high one, stop
if (bFoundHigh)
break; // break & throw at the bFoundHIgh below
bFoundHigh = true;
}
else
{
// Low, did we have a high?
if (!bFoundHigh)
{
// Didn't have one, make if fail when we stop
bFoundHigh = true;
break;
}
// Clear flag
bFoundHigh = false;
}
}
// If last was high we're in trouble (not surrogate so not low surrogate, so break)
else if (bFoundHigh)
break;
}
if (bFoundHigh)
throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequenceNoIndex, nameof(replacement)));
_strDefault = replacement;
}
public string DefaultString
{
get
{
return _strDefault;
}
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new EncoderReplacementFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return _strDefault.Length;
}
}
public override bool Equals(object value)
{
if (value is EncoderReplacementFallback that)
{
return (_strDefault == that._strDefault);
}
return (false);
}
public override int GetHashCode()
{
return _strDefault.GetHashCode();
}
}
public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer
{
// Store our default string
private string _strDefault;
private int _fallbackCount = -1;
private int _fallbackIndex = -1;
// Construction
public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback)
{
// 2X in case we're a surrogate pair
_strDefault = fallback.DefaultString + fallback.DefaultString;
}
// Fallback Methods
public override bool Fallback(char charUnknown, int index)
{
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
if (_fallbackCount >= 1)
{
// If we're recursive we may still have something in our buffer that makes this a surrogate
if (char.IsHighSurrogate(charUnknown) && _fallbackCount >= 0 &&
char.IsLowSurrogate(_strDefault[_fallbackIndex + 1]))
ThrowLastCharRecursive(char.ConvertToUtf32(charUnknown, _strDefault[_fallbackIndex + 1]));
// Nope, just one character
ThrowLastCharRecursive(unchecked((int)charUnknown));
}
// Go ahead and get our fallback
// Divide by 2 because we aren't a surrogate pair
_fallbackCount = _strDefault.Length / 2;
_fallbackIndex = -1;
return _fallbackCount != 0;
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
// Double check input surrogate pair
if (!char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
if (!char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
if (_fallbackCount >= 1)
ThrowLastCharRecursive(char.ConvertToUtf32(charUnknownHigh, charUnknownLow));
// Go ahead and get our fallback
_fallbackCount = _strDefault.Length;
_fallbackIndex = -1;
return _fallbackCount != 0;
}
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_fallbackCount--;
_fallbackIndex++;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_fallbackCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_fallbackCount == int.MaxValue)
{
_fallbackCount = -1;
return '\0';
}
// Now make sure its in the expected range
Debug.Assert(_fallbackIndex < _strDefault.Length && _fallbackIndex >= 0,
"Index exceeds buffer range");
return _strDefault[_fallbackIndex];
}
public override bool MovePrevious()
{
// Back up one, only if we just processed the last character (or earlier)
if (_fallbackCount >= -1 && _fallbackIndex >= 0)
{
_fallbackIndex--;
_fallbackCount++;
return true;
}
// Return false 'cause we couldn't do it.
return false;
}
// How many characters left to output?
public override int Remaining
{
get
{
// Our count is 0 for 1 character left.
return (_fallbackCount < 0) ? 0 : _fallbackCount;
}
}
// Clear the buffer
public override unsafe void Reset()
{
_fallbackCount = -1;
_fallbackIndex = 0;
charStart = null;
bFallingBack = false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Utilities;
using Signum.Utilities.Reflection;
using System.Text.RegularExpressions;
using Signum.Entities.DynamicQuery;
using System.Reflection;
using System.Globalization;
using System.Collections;
using Newtonsoft.Json;
namespace Signum.Entities.Chart
{
[JsonConverter(typeof(ChartScriptParameterGroupJsonConverter))]
public class ChartScriptParameterGroup : IEnumerable<ChartScriptParameter>
{
public string? Name { get; }
public ChartScriptParameterGroup(string? name = null)
{
this.Name = name;
}
public void Add(ChartScriptParameter p)
{
this.Parameters.Add(p);
}
public IEnumerator<ChartScriptParameter> GetEnumerator() => Parameters.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => Parameters.GetEnumerator();
public List<ChartScriptParameter> Parameters = new List<ChartScriptParameter>();
class ChartScriptParameterGroupJsonConverter : JsonConverter
{
public override bool CanWrite => true;
public override bool CanRead => false;
public override bool CanConvert(Type objectType) => typeof(ChartScriptParameterGroup) == objectType;
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) => throw new NotImplementedException();
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
var group = (ChartScriptParameterGroup)value!;
writer.WriteStartObject();
writer.WritePropertyName("name");
writer.WriteValue(group.Name);
writer.WritePropertyName("parameters");
serializer.Serialize(writer, group.Parameters);
writer.WriteEndObject();
}
}
}
public class ChartScriptParameter
{
public ChartScriptParameter(string name, ChartParameterType type)
{
Name = name;
Type = type;
}
public string Name { get; set; }
public int? ColumnIndex { get; set; }
public ChartParameterType Type { get; set; }
public IChartParameterValueDefinition ValueDefinition { get; set; }
public QueryToken? GetToken(IChartBase chartBase)
{
if (this.ColumnIndex == null)
return null;
return chartBase.Columns[this.ColumnIndex.Value].Token?.Token;
}
public string? Validate(string? value, QueryToken? token)
{
return ValueDefinition?.Validate(value, token);
}
internal string DefaultValue(QueryToken? token)
{
return this.ValueDefinition.DefaultValue(token);
}
}
public interface IChartParameterValueDefinition
{
string DefaultValue(QueryToken? token);
string? Validate(string? parameter, QueryToken? token);
}
public class NumberInterval : IChartParameterValueDefinition
{
public decimal DefaultValue;
public decimal? MinValue;
public decimal? MaxValue;
public static string? TryParse(string valueDefinition, out NumberInterval? interval)
{
interval = null;
var m = Regex.Match(valueDefinition, @"^\s*(?<def>.+)\s*(\[(?<min>.+)?\s*,\s*(?<max>.+)?\s*\])?\s*$");
if (!m.Success)
return "Invalid number interval, [min?, max?]";
interval = new NumberInterval();
if (!ReflectionTools.TryParse(m.Groups["def"].Value, CultureInfo.InvariantCulture, out interval!.DefaultValue))
return "Invalid default value";
if (!ReflectionTools.TryParse(m.Groups["min"].Value, CultureInfo.InvariantCulture, out interval.MinValue))
return "Invalid min value";
if (!ReflectionTools.TryParse(m.Groups["max"].Value, CultureInfo.InvariantCulture, out interval.MaxValue))
return "Invalid max value";
return null;
}
public override string ToString()
{
return "{0}[{1},{2}]".FormatWith(DefaultValue, MinValue, MaxValue);
}
public string? Validate(string? parameter, QueryToken? token)
{
if (!decimal.TryParse(parameter, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal value))
return "{0} is not a valid number".FormatWith(parameter);
if (MinValue.HasValue && value < MinValue)
return "{0} is lesser than the minimum {1}".FormatWith(value, MinValue);
if (MaxValue.HasValue && MaxValue < value)
return "{0} is grater than the maximum {1}".FormatWith(value, MinValue);
return null;
}
string IChartParameterValueDefinition.DefaultValue(QueryToken? token)
{
return DefaultValue.ToString(CultureInfo.InvariantCulture);
}
private string ToDecimal(decimal? val)
{
if (val == null)
return "null";
return val.ToString() + "m";
}
}
public class EnumValueList : List<EnumValue>, IChartParameterValueDefinition
{
public static string? TryParse(string valueDefinition, out EnumValueList list)
{
list = new EnumValueList();
foreach (var item in valueDefinition.SplitNoEmpty('|'))
{
string? error = EnumValue.TryParse(item, out EnumValue? val);
if (error.HasText())
return error;
list.Add(val!);
}
if (list.Count == 0)
return "No parameter values set";
return null;
}
public static EnumValueList Parse(string valueDefinition)
{
var error = TryParse(valueDefinition, out var list);
if (error == null)
return list;
throw new Exception(error);
}
public string? Validate(string? parameter, QueryToken? token)
{
if (token == null)
return null; //?
var enumValue = this.SingleOrDefault(a => a.Name == parameter);
if (enumValue == null)
return "{0} is not in the list".FormatWith(parameter);
if (!enumValue.CompatibleWith(token))
return "{0} is not compatible with {1}".FormatWith(parameter, token?.NiceName());
return null;
}
public string DefaultValue(QueryToken? token)
{
return this.Where(a => a.CompatibleWith(token)).FirstEx(() => "No default parameter value for {0} found".FormatWith(token?.NiceName())).Name;
}
internal string ToCode()
{
return $@"EnumValueList.Parse(""{this.ToString("|")}"")";
}
}
public class EnumValue
{
public string Name;
public ChartColumnType? TypeFilter;
public override string ToString()
{
if (TypeFilter == null)
return Name;
return "{0} ({1})".FormatWith(Name, TypeFilter.Value.GetComposedCode());
}
public static string? TryParse(string value, out EnumValue? enumValue)
{
var m = Regex.Match(value, @"^\s*(?<name>[^\(]*)\s*(\((?<filter>.*?)\))?\s*$");
if (!m.Success)
{
enumValue = null;
return "Invalid EnumValue";
}
enumValue = new EnumValue()
{
Name = m.Groups["name"].Value.Trim()
};
if (string.IsNullOrEmpty(enumValue!.Name))
return "Parameter has no name";
string composedCode = m.Groups["filter"].Value;
if (!composedCode.HasText())
return null;
string? error = ChartColumnTypeUtils.TryParseComposed(composedCode, out ChartColumnType filter);
if (error.HasText())
return enumValue.Name + ": " + error;
enumValue.TypeFilter = filter;
return null;
}
public bool CompatibleWith(QueryToken? token)
{
return TypeFilter == null || token != null && ChartUtils.IsChartColumnType(token, TypeFilter.Value);
}
internal string ToCode()
{
if (this.TypeFilter.HasValue)
return $@"new EnumValue(""{ this.Name }"", ChartColumnType.{this.TypeFilter.Value})";
else
return $@"new EnumValue(""{ this.Name }"")";
}
}
[InTypeScript(true)]
public enum ChartParameterType
{
Enum,
Number,
String,
}
public class StringValue : IChartParameterValueDefinition
{
public string DefaultValue;
public StringValue(string defaultValue)
{
this.DefaultValue = defaultValue;
}
public string? Validate(string? parameter, QueryToken? token)
{
return null;
}
string IChartParameterValueDefinition.DefaultValue(QueryToken? token)
{
return DefaultValue;
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using Duality;
namespace FarseerPhysics.Dynamics.Joints
{
public enum JointType
{
Revolute,
Prismatic,
Distance,
Pulley,
Gear,
Line,
Weld,
Friction,
Slider,
Angle,
Rope
}
public enum LimitState
{
Inactive,
AtLower,
AtUpper,
Equal,
}
internal struct Jacobian
{
public float AngularA;
public float AngularB;
public Vector2 LinearA;
public Vector2 LinearB;
public void SetZero()
{
this.LinearA = Vector2.Zero;
this.AngularA = 0.0f;
this.LinearB = Vector2.Zero;
this.AngularB = 0.0f;
}
public void Set(Vector2 x1, float a1, Vector2 x2, float a2)
{
this.LinearA = x1;
this.AngularA = a1;
this.LinearB = x2;
this.AngularB = a2;
}
public float Compute(Vector2 x1, float a1, Vector2 x2, float a2)
{
return Vector2.Dot(this.LinearA, x1) + this.AngularA * a1 + Vector2.Dot(this.LinearB, x2) + this.AngularB * a2;
}
}
/// <summary>
/// A joint edge is used to connect bodies and joints together
/// in a joint graph where each body is a node and each joint
/// is an edge. A joint edge belongs to a doubly linked list
/// maintained in each attached body. Each joint has two joint
/// nodes, one for each attached body.
/// </summary>
public sealed class JointEdge
{
/// <summary>
/// The joint.
/// </summary>
public Joint Joint;
/// <summary>
/// The next joint edge in the body's joint list.
/// </summary>
public JointEdge Next;
/// <summary>
/// Provides quick access to the other body attached.
/// </summary>
public Body Other;
/// <summary>
/// The previous joint edge in the body's joint list.
/// </summary>
public JointEdge Prev;
}
public abstract class Joint
{
/// <summary>
/// The Breakpoint simply indicates the maximum Value the JointError can be before it breaks.
/// The default value is float.MaxValue
/// </summary>
public float Breakpoint = float.MaxValue;
internal JointEdge EdgeA = new JointEdge();
internal JointEdge EdgeB = new JointEdge();
public bool Enabled = true;
protected float InvIA;
protected float InvIB;
protected float InvMassA;
protected float InvMassB;
internal bool IslandFlag;
protected Vector2 LocalCenterA, LocalCenterB;
protected Joint()
{
}
protected Joint(Body body, Body bodyB)
{
Debug.Assert(body != bodyB);
this.BodyA = body;
this.BodyB = bodyB;
//Connected bodies should not collide by default
this.CollideConnected = false;
}
/// <summary>
/// Constructor for fixed joint
/// </summary>
protected Joint(Body body)
{
this.BodyA = body;
//Connected bodies should not collide by default
this.CollideConnected = false;
}
/// <summary>
/// Gets or sets the type of the joint.
/// </summary>
/// <value>The type of the joint.</value>
public JointType JointType { get; protected set; }
/// <summary>
/// Get the first body attached to this joint.
/// </summary>
/// <value></value>
public Body BodyA { get; set; }
/// <summary>
/// Get the second body attached to this joint.
/// </summary>
/// <value></value>
public Body BodyB { get; set; }
/// <summary>
/// Get the anchor point on body1 in world coordinates.
/// </summary>
/// <value></value>
public abstract Vector2 WorldAnchorA { get; }
/// <summary>
/// Get the anchor point on body2 in world coordinates.
/// </summary>
/// <value></value>
public abstract Vector2 WorldAnchorB { get; set; }
/// <summary>
/// Set the user data pointer.
/// </summary>
/// <value>The data.</value>
public object UserData { get; set; }
/// <summary>
/// Short-cut function to determine if either body is inactive.
/// </summary>
/// <value><c>true</c> if active; otherwise, <c>false</c>.</value>
public bool Active
{
get { return this.BodyA.Enabled && this.BodyB.Enabled; }
}
/// <summary>
/// Set this flag to true if the attached bodies should collide.
/// </summary>
public bool CollideConnected { get; set; }
/// <summary>
/// Fires when the joint is broken.
/// </summary>
public event Action<Joint, float> Broke;
/// <summary>
/// Get the reaction force on body2 at the joint anchor in Newtons.
/// </summary>
/// <param name="inv_dt">The inv_dt.</param>
/// <returns></returns>
public abstract Vector2 GetReactionForce(float inv_dt);
/// <summary>
/// Get the reaction torque on body2 in N*m.
/// </summary>
/// <param name="inv_dt">The inv_dt.</param>
/// <returns></returns>
public abstract float GetReactionTorque(float inv_dt);
protected void WakeBodies()
{
this.BodyA.Awake = true;
if (this.BodyB != null)
{
this.BodyB.Awake = true;
}
}
internal abstract void InitVelocityConstraints(ref TimeStep step);
internal void Validate(float invDT)
{
if (!this.Enabled)
return;
float jointError = GetReactionForce(invDT).Length;
if (Math.Abs(jointError) <= this.Breakpoint)
return;
this.Enabled = false;
if (Broke != null)
Broke(this, jointError);
}
internal abstract void SolveVelocityConstraints(ref TimeStep step);
/// <summary>
/// Solves the position constraints.
/// </summary>
/// <returns>returns true if the position errors are within tolerance.</returns>
internal abstract bool SolvePositionConstraints();
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for listing API associated Products.
/// </summary>
internal partial class ApiProductsOperations : IServiceOperations<ApiManagementClient>, IApiProductsOperations
{
/// <summary>
/// Initializes a new instance of the ApiProductsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ApiProductsOperations(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>
/// List all API associated products.
/// </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='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Products operation response details.
/// </returns>
public async Task<ProductListResponse> ListAsync(string resourceGroupName, string serviceName, string aid, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (aid == null)
{
throw new ArgumentNullException("aid");
}
// 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("aid", aid);
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 + "/apis/";
url = url + Uri.EscapeDataString(aid);
url = url + "/products";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
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
ProductListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProductListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProductPaged resultInstance = new ProductPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ProductContract productContractInstance = new ProductContract();
resultInstance.Values.Add(productContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
productContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
productContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
productContractInstance.Description = descriptionInstance;
}
JToken termsValue = valueValue["terms"];
if (termsValue != null && termsValue.Type != JTokenType.Null)
{
string termsInstance = ((string)termsValue);
productContractInstance.Terms = termsInstance;
}
JToken subscriptionRequiredValue = valueValue["subscriptionRequired"];
if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
{
bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
productContractInstance.SubscriptionRequired = subscriptionRequiredInstance;
}
JToken approvalRequiredValue = valueValue["approvalRequired"];
if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
{
bool approvalRequiredInstance = ((bool)approvalRequiredValue);
productContractInstance.ApprovalRequired = approvalRequiredInstance;
}
JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"];
if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
{
int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance;
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
productContractInstance.State = stateInstance;
}
}
}
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 all API associated products.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Products operation response details.
/// </returns>
public async Task<ProductListResponse> 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
ProductListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProductListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProductPaged resultInstance = new ProductPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ProductContract productContractInstance = new ProductContract();
resultInstance.Values.Add(productContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
productContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
productContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
productContractInstance.Description = descriptionInstance;
}
JToken termsValue = valueValue["terms"];
if (termsValue != null && termsValue.Type != JTokenType.Null)
{
string termsInstance = ((string)termsValue);
productContractInstance.Terms = termsInstance;
}
JToken subscriptionRequiredValue = valueValue["subscriptionRequired"];
if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
{
bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
productContractInstance.SubscriptionRequired = subscriptionRequiredInstance;
}
JToken approvalRequiredValue = valueValue["approvalRequired"];
if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
{
bool approvalRequiredInstance = ((bool)approvalRequiredValue);
productContractInstance.ApprovalRequired = approvalRequiredInstance;
}
JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"];
if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
{
int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance;
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
productContractInstance.State = stateInstance;
}
}
}
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();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.MembershipService
{
internal class MembershipOracleData
{
private readonly Dictionary<SiloAddress, MembershipEntry> localTable; // all silos not including current silo
private Dictionary<SiloAddress, SiloStatus> localTableCopy; // a cached copy of a local table, including current silo, for fast access
private Dictionary<SiloAddress, SiloStatus> localTableCopyOnlyActive; // a cached copy of a local table, for fast access, including only active nodes and current silo (if active)
private Dictionary<SiloAddress, string> localNamesTableCopy; // a cached copy of a map from SiloAddress to Silo Name, not including current silo, for fast access
private readonly List<ISiloStatusListener> statusListeners;
private readonly TraceLogger logger;
private IntValueStatistic clusterSizeStatistic;
private StringValueStatistic clusterStatistic;
internal readonly DateTime SiloStartTime;
internal readonly SiloAddress MyAddress;
internal readonly string MyHostname;
internal SiloStatus CurrentStatus { get; private set; } // current status of this silo.
internal string SiloName { get; private set; } // name of this silo.
internal MembershipOracleData(Silo silo, TraceLogger log)
{
logger = log;
localTable = new Dictionary<SiloAddress, MembershipEntry>();
localTableCopy = new Dictionary<SiloAddress, SiloStatus>();
localTableCopyOnlyActive = new Dictionary<SiloAddress, SiloStatus>();
localNamesTableCopy = new Dictionary<SiloAddress, string>();
statusListeners = new List<ISiloStatusListener>();
SiloStartTime = DateTime.UtcNow;
MyAddress = silo.SiloAddress;
MyHostname = silo.LocalConfig.DNSHostName;
SiloName = silo.LocalConfig.SiloName;
CurrentStatus = SiloStatus.Created;
clusterSizeStatistic = IntValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER_SIZE, () => localTableCopyOnlyActive.Count);
clusterStatistic = StringValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER,
() =>
{
List<string> list = localTableCopyOnlyActive.Keys.Select(addr => addr.ToLongString()).ToList();
list.Sort();
return Utils.EnumerableToString(list);
});
}
// ONLY access localTableCopy and not the localTable, to prevent races, as this method may be called outside the turn.
internal SiloStatus GetApproximateSiloStatus(SiloAddress siloAddress)
{
var status = SiloStatus.None;
if (siloAddress.Equals(MyAddress))
{
status = CurrentStatus;
}
else
{
if (!localTableCopy.TryGetValue(siloAddress, out status))
{
if (CurrentStatus.Equals(SiloStatus.Active))
if (logger.IsVerbose) logger.Verbose(ErrorCode.Runtime_Error_100209, "-The given siloAddress {0} is not registered in this MembershipOracle.", siloAddress.ToLongString());
status = SiloStatus.None;
}
}
if (logger.IsVerbose3) logger.Verbose3("-GetApproximateSiloStatus returned {0} for silo: {1}", status, siloAddress.ToLongString());
return status;
}
// ONLY access localTableCopy or localTableCopyOnlyActive and not the localTable, to prevent races, as this method may be called outside the turn.
internal Dictionary<SiloAddress, SiloStatus> GetApproximateSiloStatuses(bool onlyActive = false)
{
Dictionary<SiloAddress, SiloStatus> dict = onlyActive ? localTableCopyOnlyActive : localTableCopy;
if (logger.IsVerbose3) logger.Verbose3("-GetApproximateSiloStatuses returned {0} silos: {1}", dict.Count, Utils.DictionaryToString(dict));
return dict;
}
internal bool TryGetSiloName(SiloAddress siloAddress, out string siloName)
{
if (siloAddress.Equals(MyAddress))
{
siloName = SiloName;
return true;
}
return localNamesTableCopy.TryGetValue(siloAddress, out siloName);
}
internal bool SubscribeToSiloStatusEvents(ISiloStatusListener observer)
{
lock (statusListeners)
{
if (statusListeners.Contains(observer))
return false;
statusListeners.Add(observer);
return true;
}
}
internal bool UnSubscribeFromSiloStatusEvents(ISiloStatusListener observer)
{
lock (statusListeners)
{
return statusListeners.Contains(observer) && statusListeners.Remove(observer);
}
}
internal void UpdateMyStatusLocal(SiloStatus status)
{
if (CurrentStatus == status) return;
// make copies
var tmpLocalTableCopy = GetSiloStatuses(st => true, true); // all the silos including me.
var tmpLocalTableCopyOnlyActive = GetSiloStatuses(st => st.Equals(SiloStatus.Active), true); // only active silos including me.
var tmpLocalTableNamesCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.SiloName); // all the silos excluding me.
CurrentStatus = status;
tmpLocalTableCopy[MyAddress] = status;
if (status.Equals(SiloStatus.Active))
{
tmpLocalTableCopyOnlyActive[MyAddress] = status;
}
else if (tmpLocalTableCopyOnlyActive.ContainsKey(MyAddress))
{
tmpLocalTableCopyOnlyActive.Remove(MyAddress);
}
localTableCopy = tmpLocalTableCopy;
localTableCopyOnlyActive = tmpLocalTableCopyOnlyActive;
localNamesTableCopy = tmpLocalTableNamesCopy;
NotifyLocalSubscribers(MyAddress, CurrentStatus);
}
private SiloStatus GetSiloStatus(SiloAddress siloAddress)
{
if (siloAddress.Equals(MyAddress))
return CurrentStatus;
MembershipEntry data;
return !localTable.TryGetValue(siloAddress, out data) ? SiloStatus.None : data.Status;
}
internal MembershipEntry GetSiloEntry(SiloAddress siloAddress)
{
return localTable[siloAddress];
}
internal Dictionary<SiloAddress, SiloStatus> GetSiloStatuses(Func<SiloStatus, bool> filter, bool includeMyself)
{
Dictionary<SiloAddress, SiloStatus> dict = localTable.Where(
pair => filter(pair.Value.Status)).ToDictionary(pair => pair.Key, pair => pair.Value.Status);
if (includeMyself && filter(CurrentStatus)) // add myself
dict.Add(MyAddress, CurrentStatus);
return dict;
}
internal MembershipEntry CreateNewMembershipEntry(NodeConfiguration nodeConf, SiloStatus myStatus)
{
return CreateNewMembershipEntry(nodeConf, MyAddress, MyHostname, myStatus, SiloStartTime);
}
private static MembershipEntry CreateNewMembershipEntry(NodeConfiguration nodeConf, SiloAddress myAddress, string myHostname, SiloStatus myStatus, DateTime startTime)
{
var assy = Assembly.GetEntryAssembly() ?? typeof(MembershipOracleData).GetTypeInfo().Assembly;
var roleName = assy.GetName().Name;
var entry = new MembershipEntry
{
SiloAddress = myAddress,
HostName = myHostname,
SiloName = nodeConf.SiloName,
Status = myStatus,
ProxyPort = (nodeConf.IsGatewayNode ? nodeConf.ProxyGatewayEndpoint.Port : 0),
RoleName = roleName,
SuspectTimes = new List<Tuple<SiloAddress, DateTime>>(),
StartTime = startTime,
IAmAliveTime = DateTime.UtcNow
};
return entry;
}
internal bool TryUpdateStatusAndNotify(MembershipEntry entry)
{
if (!TryUpdateStatus(entry)) return false;
localTableCopy = GetSiloStatuses(status => true, true); // all the silos including me.
localTableCopyOnlyActive = GetSiloStatuses(status => status.Equals(SiloStatus.Active), true); // only active silos including me.
localNamesTableCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.SiloName); // all the silos excluding me.
if (logger.IsVerbose) logger.Verbose("-Updated my local view of {0} status. It is now {1}.", entry.SiloAddress.ToLongString(), GetSiloStatus(entry.SiloAddress));
NotifyLocalSubscribers(entry.SiloAddress, entry.Status);
return true;
}
// return true if the status changed
private bool TryUpdateStatus(MembershipEntry updatedSilo)
{
MembershipEntry currSiloData = null;
if (!localTable.TryGetValue(updatedSilo.SiloAddress, out currSiloData))
{
// an optimization - if I learn about dead silo and I never knew about him before, I don't care, can just ignore him.
if (updatedSilo.Status == SiloStatus.Dead) return false;
localTable.Add(updatedSilo.SiloAddress, updatedSilo);
return true;
}
if (currSiloData.Status == updatedSilo.Status) return false;
currSiloData.Update(updatedSilo);
return true;
}
private void NotifyLocalSubscribers(SiloAddress siloAddress, SiloStatus newStatus)
{
if (logger.IsVerbose2) logger.Verbose2("-NotifyLocalSubscribers about {0} status {1}", siloAddress.ToLongString(), newStatus);
List<ISiloStatusListener> copy;
lock (statusListeners)
{
copy = statusListeners.ToList();
}
foreach (ISiloStatusListener listener in copy)
{
try
{
listener.SiloStatusChangeNotification(siloAddress, newStatus);
}
catch (Exception exc)
{
logger.Error(ErrorCode.MembershipLocalSubscriberException,
String.Format("Local ISiloStatusListener {0} has thrown an exception when was notified about SiloStatusChangeNotification about silo {1} new status {2}",
listener.GetType().FullName, siloAddress.ToLongString(), newStatus), exc);
}
}
}
public override string ToString()
{
return string.Format("CurrentSiloStatus = {0}, {1} silos: {2}.",
CurrentStatus,
localTableCopy.Count,
Utils.EnumerableToString(localTableCopy, pair =>
String.Format("SiloAddress={0} Status={1}", pair.Key.ToLongString(), pair.Value)));
}
}
}
| |
using System;
using System.Collections;
using System.Web;
using MbUnit.Framework;
using Moq;
using Subtext.Extensibility;
using Subtext.Extensibility.Interfaces;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Data;
using Subtext.Framework.Services;
using Subtext.Framework.Web.HttpModules;
namespace UnitTests.Subtext.Framework.Components.CommentTests
{
[TestFixture]
public class FeedbackTests
{
string _hostName = string.Empty;
[RowTest]
[Row(FeedbackStatusFlag.Approved, true, false, false, false)]
[Row(FeedbackStatusFlag.ApprovedByModerator, true, false, false, false)]
[Row(FeedbackStatusFlag.FalsePositive, true, false, false, true)]
[Row(FeedbackStatusFlag.ConfirmedSpam, false, false, true, true)]
[Row(FeedbackStatusFlag.FlaggedAsSpam, false, false, false, true)]
[Row(FeedbackStatusFlag.NeedsModeration, false, true, false, false)]
[Row(FeedbackStatusFlag.Deleted, false, false, true, false)]
[RollBack2]
public void CanCreateCommentWithStatus(FeedbackStatusFlag status, bool expectedApproved,
bool expectedNeedsModeratorApproval, bool expectedDeleted,
bool expectedFlaggedAsSpam)
{
Entry entry = SetupBlogForCommentsAndCreateEntry();
FeedbackItem comment = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, status);
Assert.IsTrue((comment.Status & status) == status, "Expected the " + status + "bit to be set.");
Assert.AreEqual(expectedApproved, comment.Approved, "We expected 'Approved' to be " + expectedApproved);
Assert.AreEqual(expectedNeedsModeratorApproval, comment.NeedsModeratorApproval,
"Expected 'NeedsModeratorApproval' to be " + expectedNeedsModeratorApproval);
Assert.AreEqual(expectedDeleted, comment.Deleted, "Expected 'Deleted' to be " + expectedDeleted);
Assert.AreEqual(expectedFlaggedAsSpam,
((comment.Status & FeedbackStatusFlag.FlaggedAsSpam) == FeedbackStatusFlag.FlaggedAsSpam),
"Expected that this item was ever flagged as spam to be " + expectedFlaggedAsSpam);
}
[Test]
[RollBack2]
public void ConfirmSpamRemovesApprovedBitAndSetsDeletedBit()
{
Entry entry = SetupBlogForCommentsAndCreateEntry();
var repository = new DatabaseObjectProvider();
FeedbackItem comment = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.Approved);
Assert.IsTrue(comment.Approved, "should be approved");
repository.ConfirmSpam(comment, null);
comment = repository.Get(comment.Id);
Assert.IsFalse(comment.Approved, "Should not be approved now.");
Assert.IsTrue(comment.Deleted, "Should be moved to deleted folder now.");
}
[Test]
[RollBack2]
public void DeleteCommentSetsDeletedBit()
{
Entry entry = SetupBlogForCommentsAndCreateEntry();
var repository = new DatabaseObjectProvider();
FeedbackItem comment = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.Approved);
Assert.IsTrue(comment.Approved, "should be approved");
repository.Delete(comment);
comment = repository.Get(comment.Id);
Assert.IsFalse(comment.Approved, "Should not be approved now.");
Assert.IsTrue(comment.Deleted, "Should be moved to deleted folder now.");
}
[Test]
[RollBack2]
public void DestroyCommentByStatusDestroysOnlyThatStatus()
{
Entry entry = SetupBlogForCommentsAndCreateEntry();
var repository = new DatabaseObjectProvider();
CreateApprovedComments(3, entry);
CreateFlaggedSpam(2, entry);
CreateDeletedComments(3, entry);
FeedbackItem newComment = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.Approved);
repository.ConfirmSpam(newComment, null);
newComment = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.FlaggedAsSpam);
Assert.IsFalse(newComment.Approved, "should not be approved");
repository.Delete(newComment); //Move it to trash.
FeedbackCounts counts = repository.GetFeedbackCounts();
Assert.AreEqual(3, counts.ApprovedCount, "Expected three approved still");
Assert.AreEqual(2, counts.FlaggedAsSpamCount, "Expected two items flagged as spam.");
Assert.AreEqual(5, counts.DeletedCount, "Expected five in the trash");
repository.Destroy(FeedbackStatusFlag.FlaggedAsSpam);
counts = repository.GetFeedbackCounts();
Assert.AreEqual(3, counts.ApprovedCount, "Expected three approved still");
Assert.AreEqual(0, counts.FlaggedAsSpamCount, "Expected the items flagged as spam to be gone.");
Assert.AreEqual(5, counts.DeletedCount, "Destroying all flagged items should not touch the trash bin.");
CreateFlaggedSpam(3, entry);
counts = repository.GetFeedbackCounts();
Assert.AreEqual(3, counts.FlaggedAsSpamCount, "Expected three items flagged as spam.");
repository.Destroy(FeedbackStatusFlag.Deleted);
counts = repository.GetFeedbackCounts();
Assert.AreEqual(3, counts.ApprovedCount, "Expected three approved still");
Assert.AreEqual(3, counts.FlaggedAsSpamCount, "Expected three approved still");
Assert.AreEqual(0, counts.DeletedCount, "Destroying all deleted items should not touch the flagged items.");
}
private static void CreateComments(int count, Entry entry, FeedbackStatusFlag status)
{
for (int i = 0; i < count; i++)
{
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, status);
}
}
private static void CreateFlaggedSpam(int count, Entry entry)
{
CreateComments(count, entry, FeedbackStatusFlag.FlaggedAsSpam);
}
private static void CreateApprovedComments(int count, Entry entry)
{
CreateComments(count, entry, FeedbackStatusFlag.Approved);
}
private static void CreateDeletedComments(int count, Entry entry)
{
CreateComments(count, entry, FeedbackStatusFlag.Deleted);
}
[Test]
[RollBack2]
public void CreateFeedbackSetsBlogStatsCorrectly()
{
var repository = new DatabaseObjectProvider();
Entry entry = SetupBlogForCommentsAndCreateEntry();
Blog info = Config.CurrentBlog;
Assert.AreEqual(0, info.CommentCount);
Assert.AreEqual(0, info.PingTrackCount);
info = repository.GetBlog(info.Host, info.Subfolder); // pull back the updated info from the datastore.
Assert.AreEqual(0, info.CommentCount);
Assert.AreEqual(0, info.PingTrackCount);
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.Approved);
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.PingTrack, FeedbackStatusFlag.Approved);
info = repository.GetBlog(info.Host, info.Subfolder);
Assert.AreEqual(1, info.CommentCount, "Blog CommentCount should be 1");
Assert.AreEqual(1, info.PingTrackCount, "Blog Ping/Trackback count should be 1");
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.Approved);
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.PingTrack, FeedbackStatusFlag.Approved);
info = repository.GetBlog(info.Host, info.Subfolder);
Assert.AreEqual(2, info.CommentCount, "Blog CommentCount should be 2");
Assert.AreEqual(2, info.PingTrackCount, "Blog Ping/Trackback count should be 2");
}
[Test]
[RollBack2]
public void CreateEntryDoesNotResetBlogStats()
{
var repository = new DatabaseObjectProvider();
Entry entry = SetupBlogForCommentsAndCreateEntry();
Blog info = Config.CurrentBlog;
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.Approved);
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.PingTrack, FeedbackStatusFlag.Approved);
Entry entry2 = UnitTestHelper.CreateEntryInstanceForSyndication("johnny b goode", "foo-bar", "zaa zaa zoo.");
UnitTestHelper.Create(entry2);
info = repository.GetBlog(info.Host, info.Subfolder); // pull back the updated info from the datastore
Assert.AreEqual(1, info.CommentCount, "Blog CommentCount should be 1");
Assert.AreEqual(1, info.PingTrackCount, "Blog Ping/Trackback count should be 1");
}
[Test]
[RollBack2]
public void DeleteEntrySetsBlogStats()
{
var repository = new DatabaseObjectProvider();
Entry entry = SetupBlogForCommentsAndCreateEntry(repository);
Blog info = Config.CurrentBlog;
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.Approved);
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.PingTrack, FeedbackStatusFlag.Approved);
Blog blog = repository.GetBlog(info.Host, info.Subfolder);
Assert.AreEqual(1, blog.CommentCount, "Blog CommentCount should be 1");
Assert.AreEqual(1, blog.PingTrackCount, "Blog Ping/Trackback count should be 1");
repository.DeleteEntry(entry.Id);
blog = repository.GetBlog(info.Host, info.Subfolder);
Assert.AreEqual(0, blog.CommentCount, "Blog CommentCount should be 0");
Assert.AreEqual(0, blog.PingTrackCount, "Blog Ping/Trackback count should be 0");
}
[Test]
public void DestroyCommentCannotDestroyActiveComment()
{
// arrange
var comment = new FeedbackItem(FeedbackType.Comment) { Approved = true };
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Repository.GetFeedback(123)).Returns(comment);
var service = new CommentService(context.Object, null);
// act, assert
UnitTestHelper.AssertThrows<InvalidOperationException>(() => service.Destroy(123));
}
[Test]
[RollBack2]
public void ApproveCommentRemovesDeletedAndConfirmedSpamBits()
{
Entry entry = SetupBlogForCommentsAndCreateEntry();
var repository = new DatabaseObjectProvider();
FeedbackItem comment = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.ConfirmedSpam |
FeedbackStatusFlag.Deleted);
Assert.IsFalse(comment.Approved, "should not be approved");
Assert.IsTrue(comment.Deleted, "should be deleted");
Assert.IsTrue(comment.ConfirmedSpam, "should be confirmed spam");
repository.Approve(comment, null);
comment = repository.Get(comment.Id);
Assert.IsTrue(comment.Approved, "Should be approved now.");
Assert.IsFalse(comment.Deleted, "Should not be deleted.");
Assert.IsFalse(comment.ConfirmedSpam, "Should not be confirmed spam.");
}
/// <summary>
/// Create some comments that are approved, approved with moderation,
/// approved as not spam. Make sure we get all of them when we get comments.
/// </summary>
[Test]
[RollBack2]
public void CanGetAllApprovedComments()
{
Entry entry = SetupBlogForCommentsAndCreateEntry();
var repository = new DatabaseObjectProvider();
FeedbackItem commentOne = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.Approved);
FeedbackItem commentTwo = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.ApprovedByModerator);
FeedbackItem commentThree = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.ConfirmedSpam);
repository.ConfirmSpam(commentThree, null);
FeedbackItem commentFour = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.FalsePositive);
//We expect three of the four.
IPagedCollection<FeedbackItem> feedback = repository.GetPagedFeedback(0, 10,
FeedbackStatusFlag.
Approved,
FeedbackStatusFlag.None,
FeedbackType.Comment);
Assert.AreEqual(3, feedback.Count, "We expected three to match.");
//Expect reverse order
Assert.AreEqual(commentOne.Id, feedback[2].Id, "The first does not match");
Assert.AreEqual(commentTwo.Id, feedback[1].Id, "The first does not match");
Assert.AreEqual(commentFour.Id, feedback[0].Id, "The first does not match");
}
[Test]
[RollBack2]
public void OnlyApprovedItemsContributeToEntryFeedbackCount()
{
Entry entry = SetupBlogForCommentsAndCreateEntry();
var repository = new DatabaseObjectProvider();
int entryId = entry.Id;
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.Approved);
entry = UnitTestHelper.GetEntry(entryId, PostConfig.None, false);
Assert.AreEqual(1, entry.FeedBackCount, "Expected one approved feedback entry.");
FeedbackItem comment = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.FlaggedAsSpam);
entry = UnitTestHelper.GetEntry(entryId, PostConfig.None, false);
Assert.AreEqual(1, entry.FeedBackCount, "Expected one approved feedback entry.");
comment.Approved = true;
repository.Update(comment);
entry = UnitTestHelper.GetEntry(entryId, PostConfig.None, false);
Assert.AreEqual(2, entry.FeedBackCount,
"After approving the second comment, expected two approved feedback entry.");
comment.Approved = false;
repository.Update(comment);
entry = UnitTestHelper.GetEntry(entryId, PostConfig.None, false);
Assert.AreEqual(1, entry.FeedBackCount,
"After un-approving the second comment, expected one approved feedback entry.");
repository.Delete(comment);
entry = UnitTestHelper.GetEntry(entryId, PostConfig.None, false);
Assert.AreEqual(1, entry.FeedBackCount,
"After un-approving the second comment, expected one approved feedback entry.");
}
/// <summary>
/// Make sure that we can get all feedback that is flagged as
/// spam. This should exclude items marked as deleted and
/// items that were flagged as spam, but subsequently approved.
/// (FlaggedAsSpam | Approved).
/// </summary>
[Test]
[RollBack2]
public void CanGetItemsFlaggedAsSpam()
{
Entry entry = SetupBlogForCommentsAndCreateEntry();
var repository = new DatabaseObjectProvider();
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.FalsePositive);
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.Approved);
CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.ConfirmedSpam);
FeedbackItem included = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.FlaggedAsSpam);
FeedbackItem includedToo = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
FeedbackStatusFlag.FlaggedAsSpam |
FeedbackStatusFlag.NeedsModeration);
//We expect 2 of the four.
IPagedCollection<FeedbackItem> feedback = repository.GetPagedFeedback(0, 10,
FeedbackStatusFlag.
FlaggedAsSpam,
FeedbackStatusFlag.
Approved |
FeedbackStatusFlag.
Deleted,
FeedbackType.Comment);
Assert.AreEqual(2, feedback.Count, "We expected two to match.");
//Expect reverse order
Assert.AreEqual(included.Id, feedback[1].Id, "The first does not match");
Assert.AreEqual(includedToo.Id, feedback[0].Id, "The second does not match");
}
/// <summary>
/// Makes sure that the content checksum hash is being created correctly.
/// </summary>
[Test]
public void ChecksumHashReturnsChecksumOfCommentBody()
{
var comment = new FeedbackItem(FeedbackType.Comment) { Body = "Some Body" };
Console.WriteLine(comment.ChecksumHash);
Assert.AreEqual("834.5baPHSvKBNtABZePE+OpeQ==", comment.ChecksumHash);
}
static FeedbackItem CreateAndUpdateFeedbackWithExactStatus(Entry entry, FeedbackType type,
FeedbackStatusFlag status)
{
var repository = new DatabaseObjectProvider();
var feedback = new FeedbackItem(type);
feedback.Title = UnitTestHelper.GenerateUniqueString();
feedback.Body = UnitTestHelper.GenerateUniqueString();
feedback.EntryId = entry.Id;
feedback.Author = "TestAuthor";
var subtextContext = new Mock<ISubtextContext>();
subtextContext.Setup(c => c.Cache).Returns(new TestCache());
subtextContext.SetupBlog(Config.CurrentBlog);
subtextContext.SetupRepository(repository);
subtextContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());
subtextContext.Setup(c => c.HttpContext).Returns(new HttpContextWrapper(HttpContext.Current));
var service = new CommentService(subtextContext.Object, null);
int id = service.Create(feedback, true/*runFilters*/);
feedback = repository.Get(id);
feedback.Status = status;
repository.Update(feedback);
return repository.Get(id);
}
Entry SetupBlogForCommentsAndCreateEntry(DatabaseObjectProvider repository = null)
{
repository = repository ?? new DatabaseObjectProvider();
repository.CreateBlog(string.Empty, "username", "password", _hostName, string.Empty);
Blog info = repository.GetBlog(_hostName, string.Empty);
BlogRequest.Current.Blog = info;
info.Email = "test@example.com";
info.Title = "You've been haacked";
info.CommentsEnabled = true;
info.ModerationEnabled = false;
repository.UpdateConfigData(info);
Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("blah", "blah", "blah");
UnitTestHelper.Create(entry);
return entry;
}
[SetUp]
public void SetUp()
{
_hostName = UnitTestHelper.GenerateUniqueString();
UnitTestHelper.SetHttpContextWithBlogRequest(_hostName, string.Empty);
}
[TearDown]
public void TearDown()
{
}
[Test]
public void UpdateThrowsArgumentNull()
{
UnitTestHelper.AssertThrowsArgumentNullException(() => new DatabaseObjectProvider().Update((FeedbackItem)null));
}
[Test]
public void ApproveThrowsArgumentNull()
{
// arrange
var service = new Mock<ICommentSpamService>().Object;
// act, assert
UnitTestHelper.AssertThrowsArgumentNullException(() => new DatabaseObjectProvider().Approve(null, service));
}
[Test]
public void ConfirmSpamThrowsArgumentNull()
{
// arrange
var service = new Mock<ICommentSpamService>().Object;
// act, assert
UnitTestHelper.AssertThrowsArgumentNullException(() => new DatabaseObjectProvider().ConfirmSpam(null, service));
}
[Test]
public void DeleteNullCommentThrowsArgumentNull()
{
// arrange
var service = new Mock<ICommentSpamService>().Object;
// act, assert
UnitTestHelper.AssertThrowsArgumentNullException(() => new DatabaseObjectProvider().Delete((FeedbackItem)null));
}
}
}
| |
using System;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[AddComponentMenu("UI/Slider", 33)]
[RequireComponent(typeof(RectTransform))]
public class Slider : Selectable, IDragHandler, IInitializePotentialDragHandler, ICanvasElement
{
public enum Direction
{
LeftToRight,
RightToLeft,
BottomToTop,
TopToBottom,
}
[Serializable]
public class SliderEvent : UnityEvent<float> {}
[SerializeField]
private RectTransform m_FillRect;
public RectTransform fillRect { get { return m_FillRect; } set { if (SetPropertyUtility.SetClass(ref m_FillRect, value)) {UpdateCachedReferences(); UpdateVisuals(); } } }
[SerializeField]
private RectTransform m_HandleRect;
public RectTransform handleRect { get { return m_HandleRect; } set { if (SetPropertyUtility.SetClass(ref m_HandleRect, value)) { UpdateCachedReferences(); UpdateVisuals(); } } }
[Space]
[SerializeField]
private Direction m_Direction = Direction.LeftToRight;
public Direction direction { get { return m_Direction; } set { if (SetPropertyUtility.SetStruct(ref m_Direction, value)) UpdateVisuals(); } }
[SerializeField]
private float m_MinValue = 0;
public float minValue { get { return m_MinValue; } set { if (SetPropertyUtility.SetStruct(ref m_MinValue, value)) { Set(m_Value); UpdateVisuals(); } } }
[SerializeField]
private float m_MaxValue = 1;
public float maxValue { get { return m_MaxValue; } set { if (SetPropertyUtility.SetStruct(ref m_MaxValue, value)) { Set(m_Value); UpdateVisuals(); } } }
[SerializeField]
private bool m_WholeNumbers = false;
public bool wholeNumbers { get { return m_WholeNumbers; } set { if (SetPropertyUtility.SetStruct(ref m_WholeNumbers, value)) { Set(m_Value); UpdateVisuals(); } } }
[SerializeField]
protected float m_Value;
public virtual float value
{
get
{
if (wholeNumbers)
return Mathf.Round(m_Value);
return m_Value;
}
set
{
Set(value);
}
}
public float normalizedValue
{
get
{
if (Mathf.Approximately(minValue, maxValue))
return 0;
return Mathf.InverseLerp(minValue, maxValue, value);
}
set
{
this.value = Mathf.Lerp(minValue, maxValue, value);
}
}
[Space]
// Allow for delegate-based subscriptions for faster events than 'eventReceiver', and allowing for multiple receivers.
[SerializeField]
private SliderEvent m_OnValueChanged = new SliderEvent();
public SliderEvent onValueChanged { get { return m_OnValueChanged; } set { m_OnValueChanged = value; } }
// Private fields
private Image m_FillImage;
private Transform m_FillTransform;
private RectTransform m_FillContainerRect;
private Transform m_HandleTransform;
private RectTransform m_HandleContainerRect;
// The offset from handle position to mouse down position
private Vector2 m_Offset = Vector2.zero;
private DrivenRectTransformTracker m_Tracker;
// Size of each step.
float stepSize { get { return wholeNumbers ? 1 : (maxValue - minValue) * 0.1f; } }
protected Slider()
{}
#if UNITY_EDITOR
protected override void OnValidate()
{
base.OnValidate();
if (wholeNumbers)
{
m_MinValue = Mathf.Round(m_MinValue);
m_MaxValue = Mathf.Round(m_MaxValue);
}
//Onvalidate is called before OnEnabled. We need to make sure not to touch any other objects before OnEnable is run.
if (IsActive())
{
UpdateCachedReferences();
Set(m_Value, false);
// Update rects since other things might affect them even if value didn't change.
UpdateVisuals();
}
var prefabType = UnityEditor.PrefabUtility.GetPrefabType(this);
if (prefabType != UnityEditor.PrefabType.Prefab && !Application.isPlaying)
CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
}
#endif // if UNITY_EDITOR
public virtual void Rebuild(CanvasUpdate executing)
{
#if UNITY_EDITOR
if (executing == CanvasUpdate.Prelayout)
onValueChanged.Invoke(value);
#endif
}
public virtual void LayoutComplete()
{}
public virtual void GraphicUpdateComplete()
{}
protected override void OnEnable()
{
base.OnEnable();
UpdateCachedReferences();
Set(m_Value, false);
// Update rects since they need to be initialized correctly.
UpdateVisuals();
}
protected override void OnDisable()
{
m_Tracker.Clear();
base.OnDisable();
}
protected override void OnDidApplyAnimationProperties()
{
// Has value changed? Various elements of the slider have the old normalisedValue assigned, we can use this to perform a comparison.
// We also need to ensure the value stays within min/max.
m_Value = ClampValue(m_Value);
float oldNormalizedValue = normalizedValue;
if (m_FillContainerRect != null)
{
if (m_FillImage != null && m_FillImage.type == Image.Type.Filled)
oldNormalizedValue = m_FillImage.fillAmount;
else
oldNormalizedValue = (reverseValue ? 1 - m_FillRect.anchorMin[(int)axis] : m_FillRect.anchorMax[(int)axis]);
}
else if (m_HandleContainerRect != null)
oldNormalizedValue = (reverseValue ? 1 - m_HandleRect.anchorMin[(int)axis] : m_HandleRect.anchorMin[(int)axis]);
UpdateVisuals();
if (oldNormalizedValue != normalizedValue)
onValueChanged.Invoke(m_Value);
}
void UpdateCachedReferences()
{
if (m_FillRect)
{
m_FillTransform = m_FillRect.transform;
m_FillImage = m_FillRect.GetComponent<Image>();
if (m_FillTransform.parent != null)
m_FillContainerRect = m_FillTransform.parent.GetComponent<RectTransform>();
}
else
{
m_FillContainerRect = null;
m_FillImage = null;
}
if (m_HandleRect)
{
m_HandleTransform = m_HandleRect.transform;
if (m_HandleTransform.parent != null)
m_HandleContainerRect = m_HandleTransform.parent.GetComponent<RectTransform>();
}
else
{
m_HandleContainerRect = null;
}
}
float ClampValue(float input)
{
float newValue = Mathf.Clamp(input, minValue, maxValue);
if (wholeNumbers)
newValue = Mathf.Round(newValue);
return newValue;
}
// Set the valueUpdate the visible Image.
void Set(float input)
{
Set(input, true);
}
protected virtual void Set(float input, bool sendCallback)
{
// Clamp the input
float newValue = ClampValue(input);
// If the stepped value doesn't match the last one, it's time to update
if (m_Value == newValue)
return;
m_Value = newValue;
UpdateVisuals();
if (sendCallback)
m_OnValueChanged.Invoke(newValue);
}
protected override void OnRectTransformDimensionsChange()
{
base.OnRectTransformDimensionsChange();
//This can be invoked before OnEnabled is called. So we shouldn't be accessing other objects, before OnEnable is called.
if (!IsActive())
return;
UpdateVisuals();
}
enum Axis
{
Horizontal = 0,
Vertical = 1
}
Axis axis { get { return (m_Direction == Direction.LeftToRight || m_Direction == Direction.RightToLeft) ? Axis.Horizontal : Axis.Vertical; } }
bool reverseValue { get { return m_Direction == Direction.RightToLeft || m_Direction == Direction.TopToBottom; } }
// Force-update the slider. Useful if you've changed the properties and want it to update visually.
private void UpdateVisuals()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
UpdateCachedReferences();
#endif
m_Tracker.Clear();
if (m_FillContainerRect != null)
{
m_Tracker.Add(this, m_FillRect, DrivenTransformProperties.Anchors);
Vector2 anchorMin = Vector2.zero;
Vector2 anchorMax = Vector2.one;
if (m_FillImage != null && m_FillImage.type == Image.Type.Filled)
{
m_FillImage.fillAmount = normalizedValue;
}
else
{
if (reverseValue)
anchorMin[(int)axis] = 1 - normalizedValue;
else
anchorMax[(int)axis] = normalizedValue;
}
m_FillRect.anchorMin = anchorMin;
m_FillRect.anchorMax = anchorMax;
}
if (m_HandleContainerRect != null)
{
m_Tracker.Add(this, m_HandleRect, DrivenTransformProperties.Anchors);
Vector2 anchorMin = Vector2.zero;
Vector2 anchorMax = Vector2.one;
anchorMin[(int)axis] = anchorMax[(int)axis] = (reverseValue ? (1 - normalizedValue) : normalizedValue);
m_HandleRect.anchorMin = anchorMin;
m_HandleRect.anchorMax = anchorMax;
}
}
// Update the slider's position based on the mouse.
void UpdateDrag(PointerEventData eventData, Camera cam)
{
RectTransform clickRect = m_HandleContainerRect ?? m_FillContainerRect;
if (clickRect != null && clickRect.rect.size[(int)axis] > 0)
{
Vector2 localCursor;
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(clickRect, eventData.position, cam, out localCursor))
return;
localCursor -= clickRect.rect.position;
float val = Mathf.Clamp01((localCursor - m_Offset)[(int)axis] / clickRect.rect.size[(int)axis]);
normalizedValue = (reverseValue ? 1f - val : val);
}
}
private bool MayDrag(PointerEventData eventData)
{
return IsActive() && IsInteractable() && eventData.button == PointerEventData.InputButton.Left;
}
public override void OnPointerDown(PointerEventData eventData)
{
if (!MayDrag(eventData))
return;
base.OnPointerDown(eventData);
m_Offset = Vector2.zero;
if (m_HandleContainerRect != null && RectTransformUtility.RectangleContainsScreenPoint(m_HandleRect, eventData.position, eventData.enterEventCamera))
{
Vector2 localMousePos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(m_HandleRect, eventData.position, eventData.pressEventCamera, out localMousePos))
m_Offset = localMousePos;
}
else
{
// Outside the slider handle - jump to this point instead
UpdateDrag(eventData, eventData.pressEventCamera);
}
}
public virtual void OnDrag(PointerEventData eventData)
{
if (!MayDrag(eventData))
return;
UpdateDrag(eventData, eventData.pressEventCamera);
}
public override void OnMove(AxisEventData eventData)
{
if (!IsActive() || !IsInteractable())
{
base.OnMove(eventData);
return;
}
switch (eventData.moveDir)
{
case MoveDirection.Left:
if (axis == Axis.Horizontal && FindSelectableOnLeft() == null)
Set(reverseValue ? value + stepSize : value - stepSize);
else
base.OnMove(eventData);
break;
case MoveDirection.Right:
if (axis == Axis.Horizontal && FindSelectableOnRight() == null)
Set(reverseValue ? value - stepSize : value + stepSize);
else
base.OnMove(eventData);
break;
case MoveDirection.Up:
if (axis == Axis.Vertical && FindSelectableOnUp() == null)
Set(reverseValue ? value - stepSize : value + stepSize);
else
base.OnMove(eventData);
break;
case MoveDirection.Down:
if (axis == Axis.Vertical && FindSelectableOnDown() == null)
Set(reverseValue ? value + stepSize : value - stepSize);
else
base.OnMove(eventData);
break;
}
}
public override Selectable FindSelectableOnLeft()
{
if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Horizontal)
return null;
return base.FindSelectableOnLeft();
}
public override Selectable FindSelectableOnRight()
{
if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Horizontal)
return null;
return base.FindSelectableOnRight();
}
public override Selectable FindSelectableOnUp()
{
if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Vertical)
return null;
return base.FindSelectableOnUp();
}
public override Selectable FindSelectableOnDown()
{
if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Vertical)
return null;
return base.FindSelectableOnDown();
}
public virtual void OnInitializePotentialDrag(PointerEventData eventData)
{
eventData.useDragThreshold = false;
}
public void SetDirection(Direction direction, bool includeRectLayouts)
{
Axis oldAxis = axis;
bool oldReverse = reverseValue;
this.direction = direction;
if (!includeRectLayouts)
return;
if (axis != oldAxis)
RectTransformUtility.FlipLayoutAxes(transform as RectTransform, true, true);
if (reverseValue != oldReverse)
RectTransformUtility.FlipLayoutOnAxis(transform as RectTransform, (int)axis, true, true);
}
}
}
| |
#if !(NETCF_1_0 || SILVERLIGHT)
using System;
using System.Security.Cryptography;
using SystemX509 = System.Security.Cryptography.X509Certificates;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Security
{
/// <summary>
/// A class containing methods to interface the BouncyCastle world to the .NET Crypto world.
/// </summary>
public sealed class DotNetUtilities
{
private DotNetUtilities()
{
}
/// <summary>
/// Create an System.Security.Cryptography.X509Certificate from an X509Certificate Structure.
/// </summary>
/// <param name="x509Struct"></param>
/// <returns>A System.Security.Cryptography.X509Certificate.</returns>
public static SystemX509.X509Certificate ToX509Certificate(
X509CertificateStructure x509Struct)
{
return new SystemX509.X509Certificate(x509Struct.GetDerEncoded());
}
public static SystemX509.X509Certificate ToX509Certificate(
X509Certificate x509Cert)
{
return new SystemX509.X509Certificate(x509Cert.GetEncoded());
}
public static X509Certificate FromX509Certificate(
SystemX509.X509Certificate x509Cert)
{
return new X509CertificateParser().ReadCertificate(x509Cert.GetRawCertData());
}
public static AsymmetricCipherKeyPair GetDsaKeyPair(
DSA dsa)
{
return GetDsaKeyPair(dsa.ExportParameters(true));
}
public static AsymmetricCipherKeyPair GetDsaKeyPair(
DSAParameters dp)
{
DsaValidationParameters validationParameters = (dp.Seed != null)
? new DsaValidationParameters(dp.Seed, dp.Counter)
: null;
DsaParameters parameters = new DsaParameters(
new BigInteger(1, dp.P),
new BigInteger(1, dp.Q),
new BigInteger(1, dp.G),
validationParameters);
DsaPublicKeyParameters pubKey = new DsaPublicKeyParameters(
new BigInteger(1, dp.Y),
parameters);
DsaPrivateKeyParameters privKey = new DsaPrivateKeyParameters(
new BigInteger(1, dp.X),
parameters);
return new AsymmetricCipherKeyPair(pubKey, privKey);
}
public static DsaPublicKeyParameters GetDsaPublicKey(
DSA dsa)
{
return GetDsaPublicKey(dsa.ExportParameters(false));
}
public static DsaPublicKeyParameters GetDsaPublicKey(
DSAParameters dp)
{
DsaValidationParameters validationParameters = (dp.Seed != null)
? new DsaValidationParameters(dp.Seed, dp.Counter)
: null;
DsaParameters parameters = new DsaParameters(
new BigInteger(1, dp.P),
new BigInteger(1, dp.Q),
new BigInteger(1, dp.G),
validationParameters);
return new DsaPublicKeyParameters(
new BigInteger(1, dp.Y),
parameters);
}
public static AsymmetricCipherKeyPair GetRsaKeyPair(
RSA rsa)
{
return GetRsaKeyPair(rsa.ExportParameters(true));
}
public static AsymmetricCipherKeyPair GetRsaKeyPair(
RSAParameters rp)
{
BigInteger modulus = new BigInteger(1, rp.Modulus);
BigInteger pubExp = new BigInteger(1, rp.Exponent);
RsaKeyParameters pubKey = new RsaKeyParameters(
false,
modulus,
pubExp);
RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
modulus,
pubExp,
new BigInteger(1, rp.D),
new BigInteger(1, rp.P),
new BigInteger(1, rp.Q),
new BigInteger(1, rp.DP),
new BigInteger(1, rp.DQ),
new BigInteger(1, rp.InverseQ));
return new AsymmetricCipherKeyPair(pubKey, privKey);
}
public static RsaKeyParameters GetRsaPublicKey(
RSA rsa)
{
return GetRsaPublicKey(rsa.ExportParameters(false));
}
public static RsaKeyParameters GetRsaPublicKey(
RSAParameters rp)
{
return new RsaKeyParameters(
false,
new BigInteger(1, rp.Modulus),
new BigInteger(1, rp.Exponent));
}
public static AsymmetricCipherKeyPair GetKeyPair(AsymmetricAlgorithm privateKey)
{
if (privateKey is DSA)
{
return GetDsaKeyPair((DSA)privateKey);
}
if (privateKey is RSA)
{
return GetRsaKeyPair((RSA)privateKey);
}
throw new ArgumentException("Unsupported algorithm specified", "privateKey");
}
public static RSA ToRSA(RsaKeyParameters rsaKey)
{
// TODO This appears to not work for private keys (when no CRT info)
return CreateRSAProvider(ToRSAParameters(rsaKey));
}
public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey)
{
return CreateRSAProvider(ToRSAParameters(privKey));
}
public static RSA ToRSA(RsaPrivateKeyStructure privKey)
{
return CreateRSAProvider(ToRSAParameters(privKey));
}
public static RSAParameters ToRSAParameters(RsaKeyParameters rsaKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = rsaKey.Modulus.ToByteArrayUnsigned();
if (rsaKey.IsPrivate)
rp.D = ConvertRSAParametersField(rsaKey.Exponent, rp.Modulus.Length);
else
rp.Exponent = rsaKey.Exponent.ToByteArrayUnsigned();
return rp;
}
public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
rp.P = privKey.P.ToByteArrayUnsigned();
rp.Q = privKey.Q.ToByteArrayUnsigned();
rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length);
rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length);
rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length);
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length);
return rp;
}
public static RSAParameters ToRSAParameters(RsaPrivateKeyStructure privKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
rp.P = privKey.Prime1.ToByteArrayUnsigned();
rp.Q = privKey.Prime2.ToByteArrayUnsigned();
rp.D = ConvertRSAParametersField(privKey.PrivateExponent, rp.Modulus.Length);
rp.DP = ConvertRSAParametersField(privKey.Exponent1, rp.P.Length);
rp.DQ = ConvertRSAParametersField(privKey.Exponent2, rp.Q.Length);
rp.InverseQ = ConvertRSAParametersField(privKey.Coefficient, rp.Q.Length);
return rp;
}
// TODO Move functionality to more general class
private static byte[] ConvertRSAParametersField(BigInteger n, int size)
{
byte[] bs = n.ToByteArrayUnsigned();
if (bs.Length == size)
return bs;
if (bs.Length > size)
throw new ArgumentException("Specified size too small", "size");
byte[] padded = new byte[size];
Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
return padded;
}
private static RSA CreateRSAProvider(RSAParameters rp)
{
CspParameters csp = new CspParameters();
csp.KeyContainerName = string.Format("BouncyCastle-{0}", Guid.NewGuid());
RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(csp);
rsaCsp.ImportParameters(rp);
return rsaCsp;
}
}
}
#endif
| |
//
// UnityOSC - Open Sound Control interface for the Unity3d game engine
//
// Copyright (c) 2012 Jorge Garcia Martin
//
// 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.
//
// Inspired by http://www.unifycommunity.com/wiki/index.php?title=AManagerClass
using SentienceLab.OSC;
using System.Collections.Generic;
using System.Net;
using System.Text;
using UnityEngine;
using UnityOSC;
/// <summary>
/// Handles all the OSC servers and clients of the current Unity game/application.
/// Tracks incoming and outgoing messages.
/// </summary>
///
[AddComponentMenu("OSC/Manager")]
[DisallowMultipleComponent]
public class OSC_Manager : MonoBehaviour
{
public int portIncoming = 57110;
public int portOutgoing = 57111;
public string[] startClientList = { "127.0.0.1" };
[Tooltip("Enable to see output of incoming and outgoing messages")]
public bool debugDataStream = false;
/// <summary>
/// Initializes the OSC Handler.
/// Here you can create the OSC servers and clientes.
/// </summary>
public void Awake()
{
// start server
server = new OSCServer(portIncoming);
server.PacketReceivedEvent += OnPacketReceived;
// prepare clients
clients = new Dictionary<string, OSCClient>();
foreach (string addr in startClientList)
{
clients.Add(addr, new OSCClient(IPAddress.Parse(addr), portOutgoing));
}
// do the variable gathering in the first Update call
// because some Components might not have had Start() called until now.
variableList = null;
clientToExclude = null;
}
/// <summary>
/// Ensure that the instance is destroyed properly, closing all ports and clients.
/// </summary>
void OnDestroy()
{
if ( server != null )
{
server.Close();
server = null;
}
foreach (OSCClient client in clients.Values)
{
client.Close();
}
clients.Clear();
}
public void Update()
{
// do we need to update the variable list
if (variableList == null)
{
// wait one frame so every script has started
if (Time.frameCount > 1)
{
GatherOSC_Variables();
}
}
else
{
// run Update on each variable
foreach (OSC_Variable variable in variableList)
{
if (variable != null) variable.Update();
}
}
}
protected void GatherOSC_Variables()
{
// gather all OSC variables in the scene
variableList = new List<OSC_Variable>();
ICollection<IOSCVariableContainer> containers = SentienceLab.ClassUtils.FindAll<IOSCVariableContainer>();
foreach (IOSCVariableContainer container in containers)
{
variableList.AddRange(container.GetOSC_Variables());
}
if (variableList.Contains(null))
{
Debug.Log("Some OSC variables are not properly initialised");
}
// register this manager with all OSC variables
string varNames = "";
foreach (OSC_Variable variable in variableList)
{
if (variable != null)
{
varNames += ((varNames.Length == 0) ? "" : ", ") + variable.Name;
variable.SetManager(this);
}
}
Debug.Log("OSC Variables: " + varNames);
UpdateAllClients();
}
protected void UpdateAllClients()
{
foreach (OSC_Variable variable in variableList)
{
if (variable != null) variable.SendUpdate();
}
}
public void SendPacket(OSCPacket packet)
{
if (clients == null)
return;
if (debugDataStream) DumpPacket("Sending", packet);
foreach (OSCClient client in clients.Values)
{
if (client != clientToExclude)
{
client.Send(packet);
}
}
}
/// <summary>
/// Raises the packet received event.
/// </summary>
/// <param name="server">the server that needs to process a packet.</param>
/// <param name="packet">the packet to process.</param>
///
void OnPacketReceived(OSCServer server, OSCPacket packet)
{
// check if we have a new client
string clientAddr = server.LastEndPoint.Address.ToString();
if (!clients.ContainsKey(clientAddr))
{
// Yes: add to the list of addresses to send updates back to
clients.Add(clientAddr, new OSCClient(IPAddress.Parse(clientAddr), portOutgoing));
Debug.Log("Added OSC client " + clientAddr);
UpdateAllClients();
}
else
{
// exclude client from receiving its own value
clientToExclude = clients[clientAddr];
}
if (debugDataStream) DumpPacket("Recevied", packet);
// check which variable will accept the packet
foreach (OSC_Variable var in variableList)
{
if ((var != null) && (var.CanAccept(packet)))
{
var.Accept(packet);
var.SendUpdate();
break;
}
}
clientToExclude = null;
}
private void DumpPacket(string prefix, OSCPacket packet)
{
string output = prefix + " '" + packet.Address + "': [";
for (int idx = 0; idx < packet.Data.Count; idx++)
{
if (idx > 0) output += ", ";
output += packet.Data[idx].GetType().ToString().Replace("System.", "");
}
output += "]";
Debug.Log(output);
}
private OSCServer server;
private List<OSC_Variable> variableList;
private Dictionary<string, OSCClient> clients;
private OSCClient clientToExclude;
}
| |
#region License
// Copyright 2010 John Sheehan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using RestSharp.Serializers;
namespace RestSharp
{
public interface IRestRequest
{
/// <summary>
/// Always send a multipart/form-data request - even when no Files are present.
/// </summary>
bool AlwaysMultipartFormData { get; set; }
/// <summary>
/// Serializer to use when writing JSON request bodies. Used if RequestFormat is Json.
/// By default the included JsonSerializer is used (currently using JSON.NET default serialization).
/// </summary>
ISerializer JsonSerializer { get; set; }
/// <summary>
/// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml.
/// By default the included XmlSerializer is used.
/// </summary>
ISerializer XmlSerializer { get; set; }
/// <summary>
/// Set this to write response to Stream rather than reading into memory.
/// </summary>
Action<Stream> ResponseWriter { get; set; }
/// <summary>
/// Container of all HTTP parameters to be passed with the request.
/// See AddParameter() for explanation of the types of parameters that can be passed
/// </summary>
List<Parameter> Parameters { get; }
/// <summary>
/// Container of all the files to be uploaded with the request.
/// </summary>
List<FileParameter> Files { get; }
/// <summary>
/// Determines what HTTP method to use for this request. Supported methods: GET, POST, PUT, DELETE, HEAD, OPTIONS
/// Default is GET
/// </summary>
Method Method { get; set; }
/// <summary>
/// The Resource URL to make the request against.
/// Tokens are substituted with UrlSegment parameters and match by name.
/// Should not include the scheme or domain. Do not include leading slash.
/// Combined with RestClient.BaseUrl to assemble final URL:
/// {BaseUrl}/{Resource} (BaseUrl is scheme + domain, e.g. http://example.com)
/// </summary>
/// <example>
/// // example for url token replacement
/// request.Resource = "Products/{ProductId}";
/// request.AddParameter("ProductId", 123, ParameterType.UrlSegment);
/// </example>
string Resource { get; set; }
/// <summary>
/// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml.
/// By default XmlSerializer is used.
/// </summary>
DataFormat RequestFormat { get; set; }
/// <summary>
/// Used by the default deserializers to determine where to start deserializing from.
/// Can be used to skip container or root elements that do not have corresponding deserialzation targets.
/// </summary>
string RootElement { get; set; }
/// <summary>
/// Used by the default deserializers to explicitly set which date format string to use when parsing dates.
/// </summary>
string DateFormat { get; set; }
/// <summary>
/// Used by XmlDeserializer. If not specified, XmlDeserializer will flatten response by removing namespaces from element names.
/// </summary>
string XmlNamespace { get; set; }
/// <summary>
/// In general you would not need to set this directly. Used by the NtlmAuthenticator.
/// </summary>
ICredentials Credentials { get; set; }
/// <summary>
/// Timeout in milliseconds to be used for the request. This timeout value overrides a timeout set on the RestClient.
/// </summary>
int Timeout { get; set; }
/// <summary>
/// The number of milliseconds before the writing or reading times out. This timeout value overrides a timeout set on the RestClient.
/// </summary>
int ReadWriteTimeout { get; set; }
/// <summary>
/// How many attempts were made to send this Request?
/// </summary>
/// <remarks>
/// This Number is incremented each time the RestClient sends the request.
/// Useful when using Asynchronous Execution with Callbacks
/// </remarks>
int Attempts { get; }
/// <summary>
/// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running)
/// will be sent along to the server. The default is false.
/// </summary>
bool UseDefaultCredentials { get; set; }
#if FRAMEWORK
/// <summary>
/// Adds a file to the Files collection to be included with a POST or PUT request
/// (other methods do not support file uploads).
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="path">Full path to file to upload</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
IRestRequest AddFile(string name, string path, string contentType = null);
/// <summary>
/// Adds the bytes to the Files collection with the specified file name and content type
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="bytes">The file data</param>
/// <param name="fileName">The file name to use for the uploaded file</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType = null);
/// <summary>
/// Adds the bytes to the Files collection with the specified file name and content type
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="writer">A function that writes directly to the stream. Should NOT close the stream.</param>
/// <param name="fileName">The file name to use for the uploaded file</param>
/// <param name="contentLength">The length (in bytes) of the file content.</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
IRestRequest AddFile(string name, Action<Stream> writer, string fileName, long contentLength, string contentType = null);
/// <summary>
/// Add bytes to the Files collection as if it was a file of specific type
/// </summary>
/// <param name="name">A form parameter name</param>
/// <param name="bytes">The file data</param>
/// <param name="filename">The file name to use for the uploaded file</param>
/// <param name="contentType">Specific content type. Es: application/x-gzip </param>
/// <returns></returns>
IRestRequest AddFileBytes(string name, byte[] bytes, string filename, string contentType = "application/x-gzip");
#endif
/// <summary>
/// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer
/// The default format is XML. Change RequestFormat if you wish to use a different serialization format.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <param name="xmlNamespace">The XML namespace to use when serializing</param>
/// <returns>This request</returns>
IRestRequest AddBody(object obj, string xmlNamespace);
/// <summary>
/// Serializes obj to data format specified by RequestFormat and adds it to the request body.
/// The default format is XML. Change RequestFormat if you wish to use a different serialization format.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
IRestRequest AddBody(object obj);
/// <summary>
/// Serializes obj to JSON format and adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
IRestRequest AddJsonBody(object obj);
/// <summary>
/// Serializes obj to XML format and adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
IRestRequest AddXmlBody(object obj);
/// <summary>
/// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer
/// Serializes obj to XML format and passes xmlNamespace then adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <param name="xmlNamespace">The XML namespace to use when serializing</param>
/// <returns>This request</returns>
IRestRequest AddXmlBody(object obj, string xmlNamespace);
/// <summary>
/// Calls AddParameter() for all public, readable properties specified in the includedProperties list
/// </summary>
/// <example>
/// request.AddObject(product, "ProductId", "Price", ...);
/// </example>
/// <param name="obj">The object with properties to add as parameters</param>
/// <param name="includedProperties">The names of the properties to include</param>
/// <returns>This request</returns>
IRestRequest AddObject(object obj, params string[] includedProperties);
/// <summary>
/// Calls AddParameter() for all public, readable properties of obj
/// </summary>
/// <param name="obj">The object with properties to add as parameters</param>
/// <returns>This request</returns>
IRestRequest AddObject(object obj);
/// <summary>
/// Add the parameter to the request
/// </summary>
/// <param name="p">Parameter to add</param>
/// <returns></returns>
IRestRequest AddParameter(Parameter p);
/// <summary>
/// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <returns>This request</returns>
IRestRequest AddParameter(string name, object value);
/// <summary>
/// Adds a parameter to the request. There are five types of parameters:
/// - GetOrPost: Either a QueryString value or encoded form value based on method
/// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
/// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
/// - Cookie: Adds the name/value pair to the HTTP request's Cookies collection
/// - RequestBody: Used by AddBody() (not recommended to use directly)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <param name="type">The type of parameter to add</param>
/// <returns>This request</returns>
IRestRequest AddParameter(string name, object value, ParameterType type);
/// <summary>
/// Adds a parameter to the request. There are five types of parameters:
/// - GetOrPost: Either a QueryString value or encoded form value based on method
/// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
/// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
/// - Cookie: Adds the name/value pair to the HTTP request's Cookies collection
/// - RequestBody: Used by AddBody() (not recommended to use directly)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <param name="contentType">Content-Type of the parameter</param>
/// <param name="type">The type of parameter to add</param>
/// <returns>This request</returns>
IRestRequest AddParameter(string name, object value, string contentType, ParameterType type);
/// <summary>
/// Shortcut to AddParameter(name, value, HttpHeader) overload
/// </summary>
/// <param name="name">Name of the header to add</param>
/// <param name="value">Value of the header to add</param>
/// <returns></returns>
IRestRequest AddHeader(string name, string value);
/// <summary>
/// Shortcut to AddParameter(name, value, Cookie) overload
/// </summary>
/// <param name="name">Name of the cookie to add</param>
/// <param name="value">Value of the cookie to add</param>
/// <returns></returns>
IRestRequest AddCookie(string name, string value);
/// <summary>
/// Shortcut to AddParameter(name, value, UrlSegment) overload
/// </summary>
/// <param name="name">Name of the segment to add</param>
/// <param name="value">Value of the segment to add</param>
/// <returns></returns>
IRestRequest AddUrlSegment(string name, string value);
/// <summary>
/// Shortcut to AddParameter(name, value, QueryString) overload
/// </summary>
/// <param name="name">Name of the parameter to add</param>
/// <param name="value">Value of the parameter to add</param>
/// <returns></returns>
IRestRequest AddQueryParameter(string name, string value);
Action<IRestResponse> OnBeforeDeserialization { get; set; }
void IncreaseNumAttempts();
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
using System;
using System.Collections;
using System.Web.SessionState;
using System.Collections.Specialized;
using System.Reflection;
using Alachisoft.NosDB.Serialization.Surrogates;
using System.Collections.Generic;
namespace Alachisoft.NosDB.Serialization
{
/// <summary>
/// Provides the common type identification system. Takes care of registering type surrogates
/// and type handles. Provides methods to register <see cref="ICompactSerializable"/> implementations
/// utilizing the built-in surrogate for <see cref="ICompactSerializable"/>.
/// </summary>
public sealed class TypeSurrogateSelector
{
private static readonly Type s_typeofList = typeof(List<>);
private static IDictionary typeSurrogateMap = Hashtable.Synchronized(new Hashtable());
private static IDictionary handleSurrogateMap = Hashtable.Synchronized(new Hashtable());
private static IDictionary userTypeSurrogateMap = Hashtable.Synchronized(new Hashtable());
private static IDictionary userTypeHandleSurrogateMap = Hashtable.Synchronized(new Hashtable());
private static ISerializationSurrogate nullSurrogate = new NullSerializationSurrogate();
private static ISerializationSurrogate defaultSurrogate = new ObjectSerializationSurrogate(typeof(object));
private static ISerializationSurrogate defaultArraySurrogate = new ObjectArraySerializationSurrogate();
private static short typeHandle = short.MinValue;
private static short CUSTOM_TYPE_RANGE = 1000;
/// <summary>
/// Static constructor registers built-in surrogates with the system.
/// </summary>
static TypeSurrogateSelector()
{
RegisterTypeSurrogate(nullSurrogate);
RegisterTypeSurrogate(defaultSurrogate);
RegisterTypeSurrogate(defaultArraySurrogate);
RegisterBuiltinSurrogates();
}
/// <summary>
/// Finds and returns an appropriate <see cref="ISerializationSurrogate"/> for the given
/// object.
/// </summary>
/// <param name="graph">specified object</param>
/// <returns><see cref="ISerializationSurrogate"/> object</returns>
static internal ISerializationSurrogate GetSurrogateForObject(object graph, string cacheContext)
{
if (graph == null)
return nullSurrogate;
Type type = null;
if (graph is ArrayList)
type = typeof(ArrayList);
else if (graph is Hashtable)
type = typeof(Hashtable);
else if (graph is SortedList)
type = typeof(SortedList);
else if (graph is Common.DataStructures.Clustered.HashVector)
type = typeof(Common.DataStructures.Clustered.HashVector);
else if (graph is Common.DataStructures.Clustered.ClusteredArrayList)
type = typeof(Common.DataStructures.Clustered.ClusteredArrayList);
//else if (graph is IList && graph.GetType().FullName.Contains("System.Collections.Generic") && graph.GetType().IsGenericType)
// ///Its IList<> but see if it is a user defined type that derived from IList<>
// type = typeof(IList<>);
//else if (graph is IDictionary && graph.GetType().IsGenericType && graph.GetType().FullName.Contains("System.Collections.Generic"))
// type = typeof(IDictionary<,>);
else if (graph.GetType().IsGenericType && typeof(List<>).Equals(graph.GetType().GetGenericTypeDefinition()) && graph.GetType().FullName.Contains("System.Collections.Generic"))
///Its IList<> but see if it is a user defined type that derived from IList<>
type = typeof(IList<>);
else if (graph.GetType().IsGenericType && typeof(Dictionary<,>).Equals(graph.GetType().GetGenericTypeDefinition()) && graph.GetType().FullName.Contains("System.Collections.Generic"))
type = typeof(IDictionary<,>);
else if (graph.GetType().IsArray && UserTypeSurrogateExists(graph.GetType().GetElementType(), cacheContext))
type = (new ObjectArraySerializationSurrogate()).ActualType;
else
type = graph.GetType();
return GetSurrogateForType(type, cacheContext);
}
private static bool UserTypeSurrogateExists(Type type, string cacheContext)
{
bool exists = false;
if (cacheContext != null)
{
Hashtable userTypeMap = (Hashtable)userTypeSurrogateMap[cacheContext];
if (userTypeMap != null)
exists = userTypeMap.Contains(type);
}
return exists;
}
/// <summary>
/// Finds and returns an appropriate <see cref="ISerializationSurrogate"/> for the given
/// type if not found returns defaultSurrogate
/// </summary>
/// <param name="type">specified type</param>
/// <param name="cacheContext">CacheName, incase of null only builting registered map is searched</param>
/// <returns><see cref="ISerializationSurrogate"/> object</returns>
static public ISerializationSurrogate GetSurrogateForType(Type type,string cacheContext)
{
ISerializationSurrogate surrogate = (ISerializationSurrogate)typeSurrogateMap[type];
if(surrogate == null && cacheContext != null)
{
Hashtable userTypeMap = (Hashtable)userTypeSurrogateMap[cacheContext];
if(userTypeMap != null)
surrogate = (ISerializationSurrogate)userTypeMap[type];
}
if (surrogate == null)
surrogate = defaultSurrogate;
return surrogate;
}
/// <summary>
/// Finds and returns <see cref="ISerializationSurrogate"/> for the given
/// type if not found returns null
/// </summary>
/// <param name="type">specified type</param>
/// <returns><see cref="ISerializationSurrogate"/> object</returns>
static internal ISerializationSurrogate GetSurrogateForTypeStrict(Type type,string cacheContext)
{
ISerializationSurrogate surrogate = null;
surrogate = (ISerializationSurrogate)typeSurrogateMap[type];
if(surrogate == null && cacheContext != null)
{
Hashtable userTypeMap = (Hashtable)userTypeSurrogateMap[cacheContext];
if(userTypeMap != null)
surrogate = (ISerializationSurrogate)userTypeMap[type];
}
//For List and Dictionary used in any Generic class produce problems which leads to bud id 2905, so here is the fix
if (surrogate == null && (type.FullName == typeof(List<>).FullName || type.FullName == typeof(Dictionary<,>).FullName))
surrogate = CheckForListAndDictionaryTypes(type, cacheContext);
return surrogate;
}
/// <summary>
/// this method will filter out any IList or IDictionary surrogate if already exists in userTypeMap
/// </summary>
/// <param name="type"></param>
/// <param name="cacheContext"></param>
/// <returns></returns>
static internal ISerializationSurrogate CheckForListAndDictionaryTypes(Type type, string cacheContext)
{
ISerializationSurrogate surrogate = null;
if (cacheContext != null)
{
Hashtable userTypeMap = (Hashtable)userTypeSurrogateMap[cacheContext];
if (userTypeMap != null)
{
Type listOrDictionaryType = null;
IDictionaryEnumerator ide = userTypeMap.GetEnumerator();
while (ide.MoveNext())
{
listOrDictionaryType = (Type)ide.Key;
if (listOrDictionaryType != null && listOrDictionaryType.FullName == typeof(IList<>).FullName && type.FullName == typeof(List<>).FullName)
{
surrogate = (ISerializationSurrogate)userTypeMap[listOrDictionaryType];
break;
}
if (listOrDictionaryType != null && listOrDictionaryType.FullName == typeof(IDictionary<,>).FullName && type.FullName == typeof(Dictionary<,>).FullName)
{
surrogate = (ISerializationSurrogate)userTypeMap[listOrDictionaryType];
break;
}
}
}
}
return surrogate;
}
/// <summary>
/// Finds and returns an appropriate <see cref="ISerializationSurrogate"/> for the given
/// type handle.
/// </summary>
/// <param name="handle">type handle</param>
/// <returns><see cref="ISerializationSurrogate"/>Object otherwise returns null if typeHandle is base Handle if Portable</returns>
static internal ISerializationSurrogate GetSurrogateForTypeHandle(short handle,string cacheContext)
{
ISerializationSurrogate surrogate = null;
if(handle < CUSTOM_TYPE_RANGE)
surrogate = (ISerializationSurrogate)handleSurrogateMap[handle];
else
{
Hashtable userTypeMap = (Hashtable)userTypeHandleSurrogateMap[cacheContext];
if (userTypeMap != null)
if (userTypeMap.Contains(handle))
{
if (userTypeMap[handle] is ISerializationSurrogate)
surrogate = (ISerializationSurrogate)userTypeMap[handle];
else
return null;
}
}
if (surrogate == null)
surrogate = defaultSurrogate;
return surrogate;
}
/// <summary>
/// Finds and returns an appropriate <see cref="ISerializationSurrogate"/> for the given
/// type handle.
/// </summary>
/// <param name="handle">type handle</param>
/// <returns><see cref="ISerializationSurrogate"/>Object otherwise returns null if typeHandle is base Handle if Portable</returns>
static internal ISerializationSurrogate GetSurrogateForSubTypeHandle(short handle, short subHandle, string cacheContext)
{
ISerializationSurrogate surrogate = null;
Hashtable userTypeMap = (Hashtable)userTypeHandleSurrogateMap[cacheContext];
if (userTypeMap != null && userTypeMap[handle] != null)
{
surrogate = (ISerializationSurrogate)((Hashtable)userTypeMap[handle])[subHandle];
if (surrogate == null && ((Hashtable)userTypeMap[handle]).Count > 0)
{
IDictionaryEnumerator surr = (IDictionaryEnumerator)((Hashtable)userTypeMap[handle]).Values.GetEnumerator();
surr.MoveNext();
surrogate = (ISerializationSurrogate)surr.Value;
}
}
if (surrogate == null)
surrogate = defaultSurrogate;
return surrogate;
}
#region / ISerializationSurrogate registration specific /
/// <summary>
/// Registers built-in surrogates with the system.
/// </summary>
static public void RegisterBuiltinSurrogates()
{
RegisterTypeSurrogate(new BooleanSerializationSurrogate());
RegisterTypeSurrogate(new ByteSerializationSurrogate());
RegisterTypeSurrogate(new CharSerializationSurrogate());
RegisterTypeSurrogate(new SingleSerializationSurrogate());
RegisterTypeSurrogate(new DoubleSerializationSurrogate());
RegisterTypeSurrogate(new DecimalSerializationSurrogate());
RegisterTypeSurrogate(new Int16SerializationSurrogate());
RegisterTypeSurrogate(new Int32SerializationSurrogate());
RegisterTypeSurrogate(new Int64SerializationSurrogate());
RegisterTypeSurrogate(new StringSerializationSurrogate());
RegisterTypeSurrogate(new DateTimeSerializationSurrogate());
RegisterTypeSurrogate(new NullSerializationSurrogate());
RegisterTypeSurrogate(new BooleanArraySerializationSurrogate());
RegisterTypeSurrogate(new ByteArraySerializationSurrogate());
RegisterTypeSurrogate(new CharArraySerializationSurrogate());
RegisterTypeSurrogate(new SingleArraySerializationSurrogate());
RegisterTypeSurrogate(new DoubleArraySerializationSurrogate());
RegisterTypeSurrogate(new Int16ArraySerializationSurrogate());
RegisterTypeSurrogate(new Int32ArraySerializationSurrogate());
RegisterTypeSurrogate(new Int64ArraySerializationSurrogate());
RegisterTypeSurrogate(new StringArraySerializationSurrogate());
RegisterTypeSurrogate(new AverageResultSerializationSurrogate());
//End of File for Java, ie denotes further types are not supported in java
RegisterTypeSurrogate(new EOFJavaSerializationSurrogate());
//End of File for Net, provided by Java ie it denotes not supported in Dot Net
RegisterTypeSurrogate(new EOFNetSerializationSurrogate());
//Skip this value Surrogate
RegisterTypeSurrogate(new SkipSerializationSurrogate());
RegisterTypeSurrogate(new DecimalArraySerializationSurrogate());
RegisterTypeSurrogate(new DateTimeArraySerializationSurrogate());
RegisterTypeSurrogate(new GuidArraySerializationSurrogate());
RegisterTypeSurrogate(new SByteArraySerializationSurrogate());
RegisterTypeSurrogate(new UInt16ArraySerializationSurrogate());
RegisterTypeSurrogate(new UInt32ArraySerializationSurrogate());
RegisterTypeSurrogate(new UInt64ArraySerializationSurrogate());
RegisterTypeSurrogate(new GuidSerializationSurrogate());
RegisterTypeSurrogate(new SByteSerializationSurrogate());
RegisterTypeSurrogate(new UInt16SerializationSurrogate());
RegisterTypeSurrogate(new UInt32SerializationSurrogate());
RegisterTypeSurrogate(new UInt64SerializationSurrogate());
RegisterTypeSurrogate(new ArraySerializationSurrogate(typeof(Array)));
RegisterTypeSurrogate(new IListSerializationSurrogate(typeof(ArrayList)));
RegisterTypeSurrogate(new IListSerializationSurrogate(typeof(Common.DataStructures.Clustered.ClusteredArrayList)));
//TODO:
//Thanks to the chaapa of this framework directly from NCache,
//the generics were excluded from support of Compact Serialization,
//courtesy of Data Sharing with Java which was obviously not needed
//here, so I uncommented their support. So for future reference, if
//you're trying some type of inter-platform compact serialization,
//be sure that both platforms support generics. For example, Java doesnt.
//The concerned handles are that of IList<> and IDictionary<>.
// -
RegisterTypeSurrogate(new GenericIListSerializationSurrogate(typeof(IList<>)));
//RegisterTypeSurrogate(new NullSerializationSurrogate());
RegisterTypeSurrogate(new IDictionarySerializationSurrogate(typeof(Hashtable)));
RegisterTypeSurrogate(new IDictionarySerializationSurrogate(typeof(SortedList)));
RegisterTypeSurrogate(new IDictionarySerializationSurrogate(typeof(Common.DataStructures.Clustered.HashVector)));
///Generics are not supportorted onwards from 4.1
RegisterTypeSurrogate(new GenericIDictionarySerializationSurrogate(typeof(IDictionary<,>)));
//RegisterTypeSurrogate(new NullSerializationSurrogate());
//RegisterTypeSurrogate((SerializationSurrogate)SurrogateHelper.CreateGenericTypeInstance(typeof(KeyValuePairSerializationSurrogate<,>), typeof(KeyValuePair<,>).GetGenericArguments()));
RegisterTypeSurrogate(new SessionStateCollectionSerializationSurrogate(typeof(SessionStateItemCollection)));
RegisterTypeSurrogate(new SessionStateStaticObjectCollectionSerializationSurrogate(typeof(System.Web.HttpStaticObjectsCollection)));
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Boolean>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Byte>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Char>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Single>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Double>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Decimal>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Int16>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Int32>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Int64>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<DateTime>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Guid>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<SByte>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<UInt16>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<UInt32>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<UInt64>());
}
/// <summary>
/// Registers the specified <see cref="ISerializationSurrogate"/> with the system.
/// </summary>
/// <param name="surrogate">specified surrogate</param>
/// <returns>false if the surrogated type already has a surrogate</returns>
static public bool RegisterTypeSurrogate(ISerializationSurrogate surrogate)
{
for (; ; )
{
try
{
return RegisterTypeSurrogate(surrogate, ++typeHandle);
}
catch (ArgumentException) { }
catch (Exception)
{
throw;
}
}
}
/// <summary>
/// Registers the specified <see cref="ISerializationSurrogate"/> with the given type handle.
/// Gives more control over the way type handles are generated by the system and allows the
/// user to supply *HARD* handles for better interoperability among applications.
/// </summary>
/// <param name="surrogate">specified surrogate</param>
/// <param name="typeHandle">specified HARD handle for type</param>
/// <returns>false if the surrogated type already has a surrogate</returns>
static public bool RegisterTypeSurrogate(ISerializationSurrogate surrogate, short typehandle)
{
if (surrogate == null) throw new ArgumentNullException("surrogate");
lock (typeSurrogateMap.SyncRoot)
{
if (handleSurrogateMap.Contains(typehandle))
throw new ArgumentException("Specified type handle is already registered.");
if (!typeSurrogateMap.Contains(surrogate.ActualType))
{
surrogate.TypeHandle = typehandle;
typeSurrogateMap.Add(surrogate.ActualType, surrogate);
handleSurrogateMap.Add(surrogate.TypeHandle, surrogate);
return true;
}
}
return false;
}
/// <summary>
/// Registers the specified <see cref="ISerializationSurrogate"/> with the given type handle.
/// Gives more control over the way type handles are generated by the system and allows the
/// user to supply *HARD* handles for better interoperability among applications.
/// </summary>
/// <param name="surrogate">specified surrogate</param>
/// <param name="typeHandle">specified HARD handle for type</param>
/// <param name="cacheContext">Cache Name</param>
/// <param name="portable">if Data Sharable class; includes Versioning and portablity</param>
/// <param name="subTypeHandle">if Portable this should not be 0, surrogate is registered by this handle if portability is true</param>
/// <param name="typehandle">Base TypeHandle provided by config, Surrogate is registered in reference to this handle if portability is false else it holds reference to subTypeHandles</param>
/// <returns>false if the surrogated type already has a surrogate</returns>
static public bool RegisterTypeSurrogate(ISerializationSurrogate surrogate, short typehandle,string cacheContext, short subTypeHandle, bool portable)
{
if (surrogate == null) throw new ArgumentNullException("surrogate");
lock (typeSurrogateMap.SyncRoot)
{
if(cacheContext != null)
{
Hashtable userTypeHandleMap = (Hashtable)userTypeHandleSurrogateMap[cacheContext];
if(userTypeHandleMap == null)
{
userTypeHandleMap = new Hashtable();
userTypeHandleSurrogateMap.Add(cacheContext,userTypeHandleMap);
}
if (portable)
{
if (userTypeHandleMap.Contains(typehandle))
{
if(((Hashtable)userTypeHandleMap[typehandle]).Contains(subTypeHandle))
throw new ArgumentException("Specified sub-type handle is already registered.");
}
}
else
{
if (userTypeHandleMap.Contains(typehandle))
throw new ArgumentException("Specified type handle is already registered.");
}
Hashtable userTypeMap = (Hashtable)userTypeSurrogateMap[cacheContext];
if(userTypeMap == null)
{
userTypeMap = new Hashtable();
userTypeSurrogateMap.Add(cacheContext,userTypeMap);
}
if (!userTypeMap.Contains(surrogate.ActualType))
{
if (portable)
{
//Surrogate will write the subhandle itself when the write method is called
surrogate.TypeHandle = typehandle;
surrogate.SubTypeHandle = subTypeHandle;
if (!userTypeHandleMap.Contains(typehandle) || userTypeHandleMap[typehandle] == null)
userTypeHandleMap[typehandle] = new Hashtable();
((Hashtable)userTypeHandleMap[typehandle]).Add(subTypeHandle, surrogate);
userTypeMap.Add(surrogate.ActualType, surrogate);
return true;
}
surrogate.TypeHandle = typehandle;
userTypeMap.Add(surrogate.ActualType, surrogate);
userTypeHandleMap.Add(surrogate.TypeHandle, surrogate);
return true;
}
}
}
return false;
}
/// <summary>
/// Unregisters the specified <see cref="ISerializationSurrogate"/> from the system.
/// <b><u>NOTE: </u></b> <b>CODE COMMENTED, NOT IMPLEMENTED</b>
/// </summary>
/// <param name="surrogate">specified surrogate</param>
static public void UnregisterTypeSurrogate(ISerializationSurrogate surrogate)
{
//if (surrogate == null) throw new ArgumentNullException("surrogate");
//lock (typeSurrogateMap.SyncRoot)
//{
// typeSurrogateMap.Remove(surrogate.ActualType);
// handleSurrogateMap.Remove(surrogate.TypeHandle);
//}
}
/// <summary>
/// <b><u>NOTE: </u></b> <b>CODE COMMENTED, NOT IMPLEMENTED</b>
/// </summary>
/// <param name="surrogate"></param>
/// <param name="cacheContext"></param>
static public void UnregisterTypeSurrogate(ISerializationSurrogate surrogate,string cacheContext)
{
//if (surrogate == null) throw new ArgumentNullException("surrogate");
//lock (typeSurrogateMap.SyncRoot)
//{
// if(cacheContext != null)
// {
// Hashtable userTypeHandleMap = (Hashtable)userTypeHandleSurrogateMap[cacheContext];
// if(userTypeHandleMap != null) userTypeHandleMap.Remove(surrogate.TypeHandle);
// Hashtable userTypeMap = (Hashtable)userTypeSurrogateMap[cacheContext];
// if(userTypeMap != null) userTypeMap.Remove(surrogate);
// }
//}
}
/// <summary>
/// Unregisters all surrogates associalted with the caceh context.
/// </summary>
/// <param name="cacheContext"></param>
static public void UnregisterAllSurrogates(string cacheContext)
{
lock (typeSurrogateMap.SyncRoot)
{
if (cacheContext != null)
{
if (userTypeHandleSurrogateMap.Contains(cacheContext))
userTypeHandleSurrogateMap.Remove(cacheContext);
if (userTypeSurrogateMap.Contains(cacheContext))
userTypeSurrogateMap.Remove(cacheContext);
}
}
}
/// <summary>
/// Unregisters all surrogates, except null and default ones.
/// </summary>
static public void UnregisterAllSurrogates()
{
lock (typeSurrogateMap.SyncRoot)
{
typeSurrogateMap.Clear();
handleSurrogateMap.Clear();
userTypeHandleSurrogateMap.Clear();
userTypeSurrogateMap.Clear();
typeHandle = short.MinValue;
RegisterTypeSurrogate(nullSurrogate);
RegisterTypeSurrogate(defaultSurrogate);
}
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.Campaigns;
using AllReady.Models;
using AllReady.Services;
using AllReady.UnitTest.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Moq;
using Xunit;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System;
using AllReady.Extensions;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using AllReady.Areas.Admin.ViewModels.Campaign;
using AllReady.Areas.Admin.ViewModels.Shared;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class CampaignAdminControllerTests
{
[Fact]
public async Task IndexSendsIndexQueryWithCorrectData_WhenUserIsOrgAdmin()
{
const int organizationId = 99;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
await sut.Index();
mockMediator.Verify(mock => mock.SendAsync(It.Is<IndexQuery>(q => q.OrganizationId == organizationId)));
}
[Fact]
public async Task IndexSendsIndexQueryWithCorrectData_WhenUserIsNotOrgAdmin()
{
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserNotAnOrgAdmin();
await sut.Index();
mockMediator.Verify(mock => mock.SendAsync(It.Is<IndexQuery>(q => q.OrganizationId == null)));
}
[Fact]
public async Task DetailsSendsCampaignDetailQueryWithCorrectCampaignId()
{
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
await sut.Details(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c => c.CampaignId == campaignId)));
}
[Fact]
public async Task DetailsReturnsHttpNotFoundResultWhenVieModelIsNull()
{
CampaignController sut;
MockMediatorCampaignDetailQuery(out sut);
Assert.IsType<NotFoundResult>(await sut.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsHttpUnauthorizedResultIfUserIsNotOrgAdmin()
{
var sut = CampaignControllerWithDetailQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<UnauthorizedResult>(await sut.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsCorrectViewWhenViewModelIsNotNullAndUserIsOrgAdmin()
{
var sut = CampaignControllerWithDetailQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await sut.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsCorrectViewModelWhenViewModelIsNotNullAndUserIsOrgAdmin()
{
const int campaignId = 100;
const int organizationId = 99;
var mockMediator = new Mock<IMediator>();
// model is not null
mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c=>c.CampaignId == campaignId))).ReturnsAsync(new CampaignDetailViewModel { OrganizationId = organizationId, Id = campaignId }).Verifiable();
// user is org admin
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var view = (ViewResult)(await sut.Details(campaignId));
var viewModel = (CampaignDetailViewModel)view.ViewData.Model;
Assert.Equal(viewModel.Id, campaignId);
Assert.Equal(viewModel.OrganizationId, organizationId);
}
[Fact]
public void CreateReturnsCorrectViewWithCorrectViewModel()
{
var sut = new CampaignController(Mock.Of<IMediator>(), null);
var view = (ViewResult) sut.Create();
var viewModel = (CampaignSummaryViewModel)view.ViewData.Model;
Assert.Equal(view.ViewName, "Edit");
Assert.NotNull(viewModel);
}
[Fact]
public async Task EditGetSendsCampaignSummaryQueryWithCorrectCampaignId()
{
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
await sut.Edit(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == campaignId)));
}
[Fact]
public async Task EditGetReturnsHttpNotFoundResultWhenViewModelIsNull()
{
CampaignController sut;
MockMediatorCampaignSummaryQuery(out sut);
Assert.IsType<NotFoundResult>(await sut.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditGetReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
{
var sut = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<UnauthorizedResult>(await sut.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditGetReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
var sut = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await sut.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditPostReturnsBadRequestWhenCampaignIsNull()
{
var sut = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var result = await sut.Edit(null, null);
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task EditPostAddsCorrectKeyAndErrorMessageToModelStateWhenCampaignEndDateIsLessThanCampainStartDate()
{
var campaignSummaryModel = new CampaignSummaryViewModel { OrganizationId = 1, StartDate = DateTime.Now.AddDays(1), EndDate = DateTime.Now.AddDays(-1)};
var sut = new CampaignController(null, null);
sut.MakeUserAnOrgAdmin(campaignSummaryModel.OrganizationId.ToString());
await sut.Edit(campaignSummaryModel, null);
var modelStateErrorCollection = sut.ModelState.GetErrorMessagesByKey(nameof(CampaignSummaryViewModel.EndDate));
Assert.Equal(modelStateErrorCollection.Single().ErrorMessage, "The end date must fall on or after the start date.");
}
[Fact]
public async Task EditPostInsertsCampaign()
{
const int organizationId = 99;
const int newCampaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.SendAsync(It.IsAny<EditCampaignCommand>()))
.Returns((EditCampaignCommand q) => Task.FromResult<int>(newCampaignId) );
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var model = MassiveTrafficLightOutageModel;
model.OrganizationId = organizationId;
// verify the model is valid
var validationContext = new ValidationContext(model, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(model, validationContext, validationResults);
Assert.Equal(0, validationResults.Count());
var file = FormFile("image/jpeg");
var view = (RedirectToActionResult) await sut.Edit(model, file);
// verify the edit(add) is called
mockMediator.Verify(mock => mock.SendAsync(It.Is<EditCampaignCommand>(c => c.Campaign.OrganizationId == organizationId)));
// verify that the next route
Assert.Equal(view.RouteValues["area"], "Admin");
Assert.Equal(view.RouteValues["id"], newCampaignId);
}
[Fact]
public async Task EditPostReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
{
var sut = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
var result = await sut.Edit(new CampaignSummaryViewModel { OrganizationId = It.IsAny<int>() }, null);
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task EditPostRedirectsToCorrectActionWithCorrectRouteValuesWhenModelStateIsValid()
{
const int organizationId = 99;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.SendAsync(It.IsAny<EditCampaignCommand>())).ReturnsAsync(campaignId);
var sut = new CampaignController(mockMediator.Object, new Mock<IImageService>().Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var result = (RedirectToActionResult) await sut.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = organizationId, Id = campaignId }, null);
Assert.Equal(result.ActionName, "Details");
Assert.Equal(result.RouteValues["area"], "Admin");
Assert.Equal(result.RouteValues["id"], campaignId);
}
[Fact]
public async Task EditPostAddsErrorToModelStateWhenInvalidImageFormatIsSupplied()
{
var sut = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var file = FormFile("");
await sut.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, file);
Assert.False(sut.ModelState.IsValid);
Assert.Equal(sut.ModelState["ImageUrl"].Errors.Single().ErrorMessage, "You must upload a valid image file for the logo (.jpg, .png, .gif)");
}
[Fact]
public async Task EditPostReturnsCorrectViewModelWhenInvalidImageFormatIsSupplied()
{
const int organizationId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var file = FormFile("audio/mpeg3");
var model = MassiveTrafficLightOutageModel;
model.OrganizationId = organizationId;
var view = await sut.Edit(model, file) as ViewResult;
var viewModel = view.ViewData.Model as CampaignSummaryViewModel;
Assert.True(ReferenceEquals(model, viewModel));
}
[Fact]
public async Task EditPostInvokesUploadCampaignImageAsyncWithTheCorrectParameters_WhenFileUploadIsNotNull_AndFileIsAcceptableContentType()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var file = FormFile("image/jpeg");
await sut.Edit(new CampaignSummaryViewModel { Name = "Foo", OrganizationId = organizationId, Id = campaignId}, file);
mockImageService.Verify(mock => mock.UploadCampaignImageAsync(
It.Is<int>(i => i == organizationId),
It.Is<int>(i => i == campaignId),
It.Is<IFormFile>(i => i == file)), Times.Once);
}
[Fact]
public async Task EditPostInvokesDeleteImageAsync_WhenCampaignHasAnImage()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var file = FormFile("image/jpeg");
mockImageService.Setup(x => x.UploadCampaignImageAsync(It.IsAny<int>(), It.IsAny<int>(), file)).ReturnsAsync("newImageUrl");
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = organizationId,
ImageUrl = "existingImageUrl",
Id = campaignId,
StartDate = new DateTimeOffset(new DateTime(2016, 2, 13)),
EndDate = new DateTimeOffset(new DateTime(2016, 2, 14)),
};
await sut.Edit(campaignSummaryViewModel, file);
mockImageService.Verify(mock => mock.DeleteImageAsync(It.Is<string>(x => x == "existingImageUrl")), Times.Once);
}
[Fact]
public async Task EditPostDoesNotInvokeDeleteImageAsync__WhenCampaignDoesNotHaveAnImage()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var file = FormFile("image/jpeg");
mockImageService.Setup(x => x.UploadCampaignImageAsync(It.IsAny<int>(), It.IsAny<int>(), file)).ReturnsAsync("newImageUrl");
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var campaignSummaryViewModel = new CampaignSummaryViewModel
{
OrganizationId = organizationId,
Id = campaignId,
StartDate = new DateTimeOffset(new DateTime(2016, 2, 13)),
EndDate = new DateTimeOffset(new DateTime(2016, 2, 14)),
};
await sut.Edit(campaignSummaryViewModel, file);
mockImageService.Verify(mock => mock.DeleteImageAsync(It.IsAny<string>()), Times.Never);
}
[Fact]
public void EditPostHasHttpPostAttribute()
{
var attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryViewModel), typeof(IFormFile) }).GetCustomAttribute(typeof(HttpPostAttribute));
Assert.NotNull(attr);
}
[Fact]
public void EditPostHasValidateAntiForgeryTokenttribute()
{
var attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryViewModel), typeof(IFormFile) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute));
Assert.NotNull(attr);
}
[Fact]
public async Task DeleteSendsDeleteQueryWithCorrectCampaignId()
{
const int organizationId = 99;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.Is<DeleteViewModelQuery>(c => c.CampaignId == campaignId))).ReturnsAsync(new DeleteViewModel { Id = campaignId, OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
await sut.Delete(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<DeleteViewModelQuery>(c => c.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task DeleteReturnsHttpNotFoundResultWhenCampaignIsNotFound()
{
CampaignController sut;
MockMediatorCampaignSummaryQuery(out sut);
Assert.IsType<NotFoundResult>(await sut.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<DeleteViewModelQuery>())).ReturnsAsync(new DeleteViewModel());
var sut = new CampaignController(mediator.Object, null);
sut.MakeUserNotAnOrgAdmin();
Assert.IsType<UnauthorizedResult>(await sut.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsCorrectViewWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<DeleteViewModelQuery>())).ReturnsAsync(new DeleteViewModel { OrganizationId = organizationId });
var sut = new CampaignController(mediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
Assert.IsType<ViewResult>(await sut.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
const int organizationId = 99;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.Is<DeleteViewModelQuery>(c => c.CampaignId == campaignId))).ReturnsAsync(new DeleteViewModel { Id = campaignId, OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var view = (ViewResult)await sut.Delete(campaignId);
var viewModel = (DeleteViewModel)view.ViewData.Model;
Assert.Equal(viewModel.Id, campaignId);
}
public async Task DeleteConfirmedSendsDeleteCampaignCommandWithCorrectCampaignId()
{
var viewModel = new DeleteViewModel { Id = 1 };
var mediator = new Mock<IMediator>();
var sut = new CampaignController(mediator.Object, null);
await sut.DeleteConfirmed(viewModel);
mediator.Verify(mock => mock.SendAsync(It.Is<DeleteCampaignCommand>(i => i.CampaignId == viewModel.Id)), Times.Once);
}
[Fact]
public async Task DetailConfirmedReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var sut = new CampaignController(Mock.Of<IMediator>(), null);
Assert.IsType<UnauthorizedResult>(await sut.DeleteConfirmed(new DeleteViewModel { UserIsOrgAdmin = false }));
}
[Fact]
public async Task DetailConfirmedSendsDeleteCampaignCommandWithCorrectCampaignIdWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var mockMediator = new Mock<IMediator>();
var viewModel = new DeleteViewModel { Id = 100, UserIsOrgAdmin = true };
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
await sut.DeleteConfirmed(viewModel);
mockMediator.Verify(mock => mock.SendAsync(It.Is<DeleteCampaignCommand>(i => i.CampaignId == viewModel.Id)), Times.Once);
}
[Fact]
public async Task DetailConfirmedRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsOrgAdmin()
{
const int organizationId = 1;
var viewModel = new DeleteViewModel { Id = 100, UserIsOrgAdmin = true };
var sut = new CampaignController(Mock.Of<IMediator>(), null);
sut.MakeUserAnOrgAdmin(organizationId.ToString());
var routeValues = new Dictionary<string, object> { ["area"] = "Admin" };
var result = await sut.DeleteConfirmed(viewModel) as RedirectToActionResult;
Assert.Equal(result.ActionName, nameof(CampaignController.Index));
Assert.Equal(result.RouteValues, routeValues);
}
[Fact]
public void DeleteConfirmedHasHttpPostAttribute()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<DeleteViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void DeleteConfirmedHasActionNameAttributeWithCorrectName()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<DeleteViewModel>())).OfType<ActionNameAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
Assert.Equal(attribute.Name, "Delete");
}
[Fact]
public void DeleteConfirmedHasValidateAntiForgeryTokenAttribute()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.DeleteConfirmed(It.IsAny<DeleteViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task LockUnlockReturnsHttpUnauthorizedResultWhenUserIsNotSiteAdmin()
{
var sut = CreateCampaignControllerWithNoInjectedDependencies();
sut.MakeUserAnOrgAdmin("1");
Assert.IsType<UnauthorizedResult>(await sut.LockUnlock(100));
}
[Fact]
public async Task LockUnlockSendsLockUnlockCampaignCommandWithCorrectCampaignIdWhenUserIsSiteAdmin()
{
const int campaignId = 99;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserASiteAdmin();
await sut.LockUnlock(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<LockUnlockCampaignCommand>(q => q.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task LockUnlockRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsSiteAdmin()
{
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var sut = new CampaignController(mockMediator.Object, null);
sut.MakeUserASiteAdmin();
var view = (RedirectToActionResult)await sut.LockUnlock(campaignId);
// verify the next route
Assert.Equal(view.ActionName, nameof(CampaignController.Details));
Assert.Equal(view.RouteValues["area"], "Admin");
Assert.Equal(view.RouteValues["id"], campaignId);
}
[Fact]
public void LockUnlockHasHttpPostAttribute()
{
var attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(HttpPostAttribute));
Assert.NotNull(attr);
}
[Fact]
public void LockUnlockdHasValidateAntiForgeryTokenAttribute()
{
var attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute));
Assert.NotNull(attr);
}
private static CampaignController CreateCampaignControllerWithNoInjectedDependencies()
{
return new CampaignController(null, null);
}
private static Mock<IMediator> MockMediatorCampaignDetailQuery(out CampaignController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(null).Verifiable();
controller = new CampaignController(mockMediator.Object, null);
return mockMediator;
}
private static Mock<IMediator> MockMediatorCampaignSummaryQuery(out CampaignController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(null).Verifiable();
controller = new CampaignController(mockMediator.Object, null);
return mockMediator;
}
private static CampaignController CampaignControllerWithDetailQuery(string userType, int organizationId)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(new CampaignDetailViewModel { OrganizationId = organizationId }).Verifiable();
var sut = new CampaignController(mockMediator.Object, null);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, userType),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
return sut;
}
private static CampaignController CampaignControllerWithSummaryQuery(string userType, int organizationId)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryViewModel { OrganizationId = organizationId, Location = new LocationEditViewModel() }).Verifiable();
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, userType),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
return sut;
}
private static IFormFile FormFile(string fileType)
{
var mockFormFile = new Mock<IFormFile>();
mockFormFile.Setup(mock => mock.ContentType).Returns(fileType);
return mockFormFile.Object;
}
private static LocationEditViewModel BogusAveModel => new LocationEditViewModel
{
Address1 = "25 Bogus Ave",
City = "Agincourt",
State = "Ontario",
Country = "Canada",
PostalCode = "M1T2T9"
};
private static CampaignSummaryViewModel MassiveTrafficLightOutageModel => new CampaignSummaryViewModel
{
Description = "Preparations to be ready to deal with a wide-area traffic outage.",
EndDate = DateTime.Today.AddMonths(1),
ExternalUrl = "http://agincourtaware.trafficlightoutage.com",
ExternalUrlText = "Agincourt Aware: Traffic Light Outage",
Featured = false,
FileUpload = null,
FullDescription = "<h1><strong>Massive Traffic Light Outage Plan</strong></h1>\r\n<p>The Massive Traffic Light Outage Plan (MTLOP) is the official plan to handle a major traffic light failure.</p>\r\n<p>In the event of a wide-area traffic light outage, an alternative method of controlling traffic flow will be necessary. The MTLOP calls for the recruitment and training of volunteers to be ready to direct traffic at designated intersections and to schedule and follow-up with volunteers in the event of an outage.</p>",
Id = 0,
ImageUrl = null,
Location = BogusAveModel,
Locked = false,
Name = "Massive Traffic Light Outage Plan",
PrimaryContactEmail = "mlong@agincourtawareness.com",
PrimaryContactFirstName = "Miles",
PrimaryContactLastName = "Long",
PrimaryContactPhoneNumber = "416-555-0119",
StartDate = DateTime.Today,
TimeZoneId = "Eastern Standard Time",
};
}
}
| |
using System;
using System.Data;
using System.Runtime.CompilerServices;
namespace ServiceStack.OrmLite.Dapper
{
public static partial class SqlMapper
{
internal sealed class Identity<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh> : Identity
{
private static readonly int s_typeHash;
private static readonly int s_typeCount = CountNonTrivial(out s_typeHash);
internal Identity(string sql, CommandType? commandType, string connectionString, Type type, Type parametersType, int gridIndex = 0)
: base(sql, commandType, connectionString, type, parametersType, s_typeHash, gridIndex)
{}
internal Identity(string sql, CommandType? commandType, IDbConnection connection, Type type, Type parametersType, int gridIndex = 0)
: base(sql, commandType, connection.ConnectionString, type, parametersType, s_typeHash, gridIndex)
{ }
static int CountNonTrivial(out int hashCode)
{
int hashCodeLocal = 0;
int count = 0;
bool Map<T>()
{
if(typeof(T) != typeof(DontMap))
{
count++;
hashCodeLocal = (hashCodeLocal * 23) + (typeof(T).GetHashCode());
return true;
}
return false;
}
_ = Map<TFirst>() && Map<TSecond>() && Map<TThird>()
&& Map<TFourth>() && Map<TFifth>() && Map<TSixth>()
&& Map<TSeventh>();
hashCode = hashCodeLocal;
return count;
}
internal override int TypeCount => s_typeCount;
internal override Type GetType(int index)
{
switch (index)
{
case 0: return typeof(TFirst);
case 1: return typeof(TSecond);
case 2: return typeof(TThird);
case 3: return typeof(TFourth);
case 4: return typeof(TFifth);
case 5: return typeof(TSixth);
case 6: return typeof(TSeventh);
default: return base.GetType(index);
}
}
}
internal sealed class IdentityWithTypes : Identity
{
private readonly Type[] _types;
internal IdentityWithTypes(string sql, CommandType? commandType, string connectionString, Type type, Type parametersType, Type[] otherTypes, int gridIndex = 0)
: base(sql, commandType, connectionString, type, parametersType, HashTypes(otherTypes), gridIndex)
{
_types = otherTypes ?? Type.EmptyTypes;
}
internal IdentityWithTypes(string sql, CommandType? commandType, IDbConnection connection, Type type, Type parametersType, Type[] otherTypes, int gridIndex = 0)
: base(sql, commandType, connection.ConnectionString, type, parametersType, HashTypes(otherTypes), gridIndex)
{
_types = otherTypes ?? Type.EmptyTypes;
}
internal override int TypeCount => _types.Length;
internal override Type GetType(int index) => _types[index];
static int HashTypes(Type[] types)
{
var hashCode = 0;
if (types != null)
{
foreach (var t in types)
{
hashCode = (hashCode * 23) + (t?.GetHashCode() ?? 0);
}
}
return hashCode;
}
}
/// <summary>
/// Identity of a cached query in Dapper, used for extensibility.
/// </summary>
public class Identity : IEquatable<Identity>
{
internal virtual int TypeCount => 0;
internal virtual Type GetType(int index) => throw new IndexOutOfRangeException(nameof(index));
internal Identity ForGrid<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh>(Type primaryType, int gridIndex) =>
new Identity<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh>(sql, commandType, connectionString, primaryType, parametersType, gridIndex);
internal Identity ForGrid(Type primaryType, int gridIndex) =>
new Identity(sql, commandType, connectionString, primaryType, parametersType, 0, gridIndex);
internal Identity ForGrid(Type primaryType, Type[] otherTypes, int gridIndex) =>
(otherTypes == null || otherTypes.Length == 0)
? new Identity(sql, commandType, connectionString, primaryType, parametersType, 0, gridIndex)
: new IdentityWithTypes(sql, commandType, connectionString, primaryType, parametersType, otherTypes, gridIndex);
/// <summary>
/// Create an identity for use with DynamicParameters, internal use only.
/// </summary>
/// <param name="type">The parameters type to create an <see cref="Identity"/> for.</param>
/// <returns></returns>
public Identity ForDynamicParameters(Type type) =>
new Identity(sql, commandType, connectionString, this.type, type, 0, -1);
internal Identity(string sql, CommandType? commandType, IDbConnection connection, Type type, Type parametersType)
: this(sql, commandType, connection.ConnectionString, type, parametersType, 0, 0) { /* base call */ }
private protected Identity(string sql, CommandType? commandType, string connectionString, Type type, Type parametersType, int otherTypesHash, int gridIndex)
{
this.sql = sql;
this.commandType = commandType;
this.connectionString = connectionString;
this.type = type;
this.parametersType = parametersType;
this.gridIndex = gridIndex;
unchecked
{
hashCode = 17; // we *know* we are using this in a dictionary, so pre-compute this
hashCode = (hashCode * 23) + commandType.GetHashCode();
hashCode = (hashCode * 23) + gridIndex.GetHashCode();
hashCode = (hashCode * 23) + (sql?.GetHashCode() ?? 0);
hashCode = (hashCode * 23) + (type?.GetHashCode() ?? 0);
hashCode = (hashCode * 23) + otherTypesHash;
hashCode = (hashCode * 23) + (connectionString == null ? 0 : connectionStringComparer.GetHashCode(connectionString));
hashCode = (hashCode * 23) + (parametersType?.GetHashCode() ?? 0);
}
}
/// <summary>
/// Whether this <see cref="Identity"/> equals another.
/// </summary>
/// <param name="obj">The other <see cref="object"/> to compare to.</param>
public override bool Equals(object obj) => Equals(obj as Identity);
/// <summary>
/// The raw SQL command.
/// </summary>
public readonly string sql;
/// <summary>
/// The SQL command type.
/// </summary>
public readonly CommandType? commandType;
/// <summary>
/// The hash code of this Identity.
/// </summary>
public readonly int hashCode;
/// <summary>
/// The grid index (position in the reader) of this Identity.
/// </summary>
public readonly int gridIndex;
/// <summary>
/// This <see cref="Type"/> of this Identity.
/// </summary>
public readonly Type type;
/// <summary>
/// The connection string for this Identity.
/// </summary>
public readonly string connectionString;
/// <summary>
/// The type of the parameters object for this Identity.
/// </summary>
public readonly Type parametersType;
/// <summary>
/// Gets the hash code for this identity.
/// </summary>
/// <returns></returns>
public override int GetHashCode() => hashCode;
/// <summary>
/// See object.ToString()
/// </summary>
public override string ToString() => sql;
/// <summary>
/// Compare 2 Identity objects
/// </summary>
/// <param name="other">The other <see cref="Identity"/> object to compare.</param>
/// <returns>Whether the two are equal</returns>
public bool Equals(Identity other)
{
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(other, null)) return false;
int typeCount;
return gridIndex == other.gridIndex
&& type == other.type
&& sql == other.sql
&& commandType == other.commandType
&& connectionStringComparer.Equals(connectionString, other.connectionString)
&& parametersType == other.parametersType
&& (typeCount = TypeCount) == other.TypeCount
&& (typeCount == 0 || TypesEqual(this, other, typeCount));
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool TypesEqual(Identity x, Identity y, int count)
{
if (y.TypeCount != count) return false;
for(int i = 0; i < count; i++)
{
if (x.GetType(i) != y.GetType(i))
return false;
}
return true;
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityClient.cs.tt
namespace Microsoft.Graph
{
/// <summary>
/// The type GraphServiceClient.
/// </summary>
public partial class GraphServiceClient : BaseClient, IGraphServiceClient
{
/// <summary>
/// Instantiates a new GraphServiceClient.
/// </summary>
/// <param name="authenticationProvider">The <see cref="IAuthenticationProvider"/> for authenticating request messages.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending requests.</param>
public GraphServiceClient(
IAuthenticationProvider authenticationProvider,
IHttpProvider httpProvider = null)
: this("https://graph.microsoft.com/v1.0", authenticationProvider, httpProvider)
{
}
/// <summary>
/// Instantiates a new GraphServiceClient.
/// </summary>
/// <param name="baseUrl">The base service URL. For example, "https://graph.microsoft.com/v1.0".</param>
/// <param name="authenticationProvider">The <see cref="IAuthenticationProvider"/> for authenticating request messages.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending requests.</param>
public GraphServiceClient(
string baseUrl,
IAuthenticationProvider authenticationProvider,
IHttpProvider httpProvider = null)
: base(baseUrl, authenticationProvider, httpProvider)
{
}
/// <summary>
/// Gets the GraphServiceDirectoryObjects request builder.
/// </summary>
public IGraphServiceDirectoryObjectsCollectionRequestBuilder DirectoryObjects
{
get
{
return new GraphServiceDirectoryObjectsCollectionRequestBuilder(this.BaseUrl + "/directoryObjects", this);
}
}
/// <summary>
/// Gets the GraphServiceDevices request builder.
/// </summary>
public IGraphServiceDevicesCollectionRequestBuilder Devices
{
get
{
return new GraphServiceDevicesCollectionRequestBuilder(this.BaseUrl + "/devices", this);
}
}
/// <summary>
/// Gets the GraphServiceDomains request builder.
/// </summary>
public IGraphServiceDomainsCollectionRequestBuilder Domains
{
get
{
return new GraphServiceDomainsCollectionRequestBuilder(this.BaseUrl + "/domains", this);
}
}
/// <summary>
/// Gets the GraphServiceDomainDnsRecords request builder.
/// </summary>
public IGraphServiceDomainDnsRecordsCollectionRequestBuilder DomainDnsRecords
{
get
{
return new GraphServiceDomainDnsRecordsCollectionRequestBuilder(this.BaseUrl + "/domainDnsRecords", this);
}
}
/// <summary>
/// Gets the GraphServiceGroups request builder.
/// </summary>
public IGraphServiceGroupsCollectionRequestBuilder Groups
{
get
{
return new GraphServiceGroupsCollectionRequestBuilder(this.BaseUrl + "/groups", this);
}
}
/// <summary>
/// Gets the GraphServiceDirectoryRoles request builder.
/// </summary>
public IGraphServiceDirectoryRolesCollectionRequestBuilder DirectoryRoles
{
get
{
return new GraphServiceDirectoryRolesCollectionRequestBuilder(this.BaseUrl + "/directoryRoles", this);
}
}
/// <summary>
/// Gets the GraphServiceDirectoryRoleTemplates request builder.
/// </summary>
public IGraphServiceDirectoryRoleTemplatesCollectionRequestBuilder DirectoryRoleTemplates
{
get
{
return new GraphServiceDirectoryRoleTemplatesCollectionRequestBuilder(this.BaseUrl + "/directoryRoleTemplates", this);
}
}
/// <summary>
/// Gets the GraphServiceOrganization request builder.
/// </summary>
public IGraphServiceOrganizationCollectionRequestBuilder Organization
{
get
{
return new GraphServiceOrganizationCollectionRequestBuilder(this.BaseUrl + "/organization", this);
}
}
/// <summary>
/// Gets the GraphServiceGroupSettings request builder.
/// </summary>
public IGraphServiceGroupSettingsCollectionRequestBuilder GroupSettings
{
get
{
return new GraphServiceGroupSettingsCollectionRequestBuilder(this.BaseUrl + "/groupSettings", this);
}
}
/// <summary>
/// Gets the GraphServiceGroupSettingTemplates request builder.
/// </summary>
public IGraphServiceGroupSettingTemplatesCollectionRequestBuilder GroupSettingTemplates
{
get
{
return new GraphServiceGroupSettingTemplatesCollectionRequestBuilder(this.BaseUrl + "/groupSettingTemplates", this);
}
}
/// <summary>
/// Gets the GraphServiceSubscribedSkus request builder.
/// </summary>
public IGraphServiceSubscribedSkusCollectionRequestBuilder SubscribedSkus
{
get
{
return new GraphServiceSubscribedSkusCollectionRequestBuilder(this.BaseUrl + "/subscribedSkus", this);
}
}
/// <summary>
/// Gets the GraphServiceUsers request builder.
/// </summary>
public IGraphServiceUsersCollectionRequestBuilder Users
{
get
{
return new GraphServiceUsersCollectionRequestBuilder(this.BaseUrl + "/users", this);
}
}
/// <summary>
/// Gets the GraphServiceContracts request builder.
/// </summary>
public IGraphServiceContractsCollectionRequestBuilder Contracts
{
get
{
return new GraphServiceContractsCollectionRequestBuilder(this.BaseUrl + "/contracts", this);
}
}
/// <summary>
/// Gets the GraphServiceSchemaExtensions request builder.
/// </summary>
public IGraphServiceSchemaExtensionsCollectionRequestBuilder SchemaExtensions
{
get
{
return new GraphServiceSchemaExtensionsCollectionRequestBuilder(this.BaseUrl + "/schemaExtensions", this);
}
}
/// <summary>
/// Gets the GraphServiceDrives request builder.
/// </summary>
public IGraphServiceDrivesCollectionRequestBuilder Drives
{
get
{
return new GraphServiceDrivesCollectionRequestBuilder(this.BaseUrl + "/drives", this);
}
}
/// <summary>
/// Gets the GraphServiceShares request builder.
/// </summary>
public IGraphServiceSharesCollectionRequestBuilder Shares
{
get
{
return new GraphServiceSharesCollectionRequestBuilder(this.BaseUrl + "/shares", this);
}
}
/// <summary>
/// Gets the GraphServiceSites request builder.
/// </summary>
public IGraphServiceSitesCollectionRequestBuilder Sites
{
get
{
return new GraphServiceSitesCollectionRequestBuilder(this.BaseUrl + "/sites", this);
}
}
/// <summary>
/// Gets the GraphServiceWorkbooks request builder.
/// </summary>
public IGraphServiceWorkbooksCollectionRequestBuilder Workbooks
{
get
{
return new GraphServiceWorkbooksCollectionRequestBuilder(this.BaseUrl + "/workbooks", this);
}
}
/// <summary>
/// Gets the GraphServiceSubscriptions request builder.
/// </summary>
public IGraphServiceSubscriptionsCollectionRequestBuilder Subscriptions
{
get
{
return new GraphServiceSubscriptionsCollectionRequestBuilder(this.BaseUrl + "/subscriptions", this);
}
}
/// <summary>
/// Gets the GraphServiceInvitations request builder.
/// </summary>
public IGraphServiceInvitationsCollectionRequestBuilder Invitations
{
get
{
return new GraphServiceInvitationsCollectionRequestBuilder(this.BaseUrl + "/invitations", this);
}
}
/// <summary>
/// Gets the GraphServiceMe request builder.
/// </summary>
public IUserRequestBuilder Me
{
get
{
return new UserRequestBuilder(this.BaseUrl + "/me", this);
}
}
/// <summary>
/// Gets the GraphServiceDrive request builder.
/// </summary>
public IDriveRequestBuilder Drive
{
get
{
return new DriveRequestBuilder(this.BaseUrl + "/drive", this);
}
}
/// <summary>
/// Gets the GraphServicePlanner request builder.
/// </summary>
public IPlannerRequestBuilder Planner
{
get
{
return new PlannerRequestBuilder(this.BaseUrl + "/planner", this);
}
}
}
}
| |
// 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.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
// is actually recognized by the JIT, but both are here for simplicity.
public partial struct Vector3
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
/// <summary>
/// The Z component of the vector.
/// </summary>
public Single Z;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[JitIntrinsic]
public Vector3(Single value) : this(value, value, value) { }
/// <summary>
/// Constructs a Vector3 from the given Vector2 and a third value.
/// </summary>
/// <param name="value">The Vector to extract X and Y components from.</param>
/// <param name="z">The Z component.</param>
public Vector3(Vector2 value, float z) : this(value.X, value.Y, z) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param>
[JitIntrinsic]
public Vector3(Single x, Single y, Single z)
{
X = x;
Y = y;
Z = z;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array.</exception>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 3)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
array[index + 2] = Z;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector3 is equal to this Vector3 instance.
/// </summary>
/// <param name="other">The Vector3 to compare this instance to.</param>
/// <returns>True if the other Vector3 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector3 other)
{
return X == other.X &&
Y == other.Y &&
Z == other.Z;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector3 vector1, Vector3 vector2)
{
return vector1.X * vector2.X +
vector1.Y * vector2.Y +
vector1.Z * vector2.Z;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[JitIntrinsic]
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y,
(value1.Z < value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The maximized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y,
(value1.Z > value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Abs(Vector3 value)
{
return new Vector3(Math.Abs(value.X), Math.Abs(value.Y), Math.Abs(value.Z));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 SquareRoot(Vector3 value)
{
return new Vector3((Single)Math.Sqrt(value.X), (Single)Math.Sqrt(value.Y), (Single)Math.Sqrt(value.Z));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator +(Vector3 left, Vector3 right)
{
return new Vector3(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 left, Vector3 right)
{
return new Vector3(left.X - right.X, left.Y - right.Y, left.Z - right.Z);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Vector3 right)
{
return new Vector3(left.X * right.X, left.Y * right.Y, left.Z * right.Z);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Single right)
{
return left * new Vector3(right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Single left, Vector3 right)
{
return new Vector3(left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 left, Vector3 right)
{
return new Vector3(left.X / right.X, left.Y / right.Y, left.Z / right.Z);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector3(
value1.X * invDiv,
value1.Y * invDiv,
value1.Z * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector3 left, Vector3 right)
{
return (left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector3 left, Vector3 right)
{
return (left.X != right.X ||
left.Y != right.Y ||
left.Z != right.Z);
}
#endregion Public Static Operators
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
namespace io.swagger.client {
public class ApiInvoker {
private static readonly ApiInvoker _instance = new ApiInvoker();
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
public static ApiInvoker GetInstance() {
return _instance;
}
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
public void addDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value);
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
public string escapeString(string str) {
return str;
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format, otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
public string ParameterToString(object obj)
{
return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj);
}
/// <summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="json"> JSON string
/// <param name="type"> Object type
/// <returns>Object representation of the JSON string</returns>
public static object deserialize(string json, Type type) {
try
{
return JsonConvert.DeserializeObject(json, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
public static string serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
}
public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[];
}
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) {
var b = new StringBuilder();
foreach (var queryParamItem in queryParams)
{
var value = queryParamItem.Value;
if (value == null) continue;
b.Append(b.ToString().Length == 0 ? "?" : "&");
b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value));
}
var querystring = b.ToString();
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
var client = WebRequest.Create(host + path + querystring);
client.Method = method;
byte[] formData = null;
if (formParams.Count > 0)
{
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
formData = GetMultipartFormData(formParams, formDataBoundary);
client.ContentLength = formData.Length;
}
else
{
client.ContentType = "application/json";
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key)))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
switch (method)
{
case "GET":
break;
case "POST":
case "PATCH":
case "PUT":
case "DELETE":
using (Stream requestStream = client.GetRequestStream())
{
if (formData != null)
{
requestStream.Write(formData, 0, formData.Length);
}
var swRequestWriter = new StreamWriter(requestStream);
swRequestWriter.Write(serialize(body));
swRequestWriter.Close();
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
try
{
var webResponse = (HttpWebResponse)client.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
webResponse.Close();
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
}
if (binaryResponse)
{
using (var memoryStream = new MemoryStream())
{
webResponse.GetResponseStream().CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
else
{
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
{
var responseData = responseReader.ReadToEnd();
return responseData;
}
}
}
catch(WebException ex)
{
var response = ex.Response as HttpWebResponse;
int statusCode = 0;
if (response != null)
{
statusCode = (int)response.StatusCode;
response.Close();
}
throw new ApiException(statusCode, ex.Message);
}
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
needsCLRF = true;
if (param.Value is byte[])
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
boundary,
param.Key,
"application/octet-stream");
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnusedVariable
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable UnusedAutoPropertyAccessor.Local
namespace Apache.Ignite.Core.Tests
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Resource;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
/// <summary>
/// Tests for Apache.Ignite.exe.
/// </summary>
[Category(TestUtils.CategoryIntensive)]
public class ExecutableTest
{
/** Spring configuration path. */
private const string SpringCfgPath = "config\\compute\\compute-standalone.xml";
/** Min memory Java task. */
private const string MinMemTask = "org.apache.ignite.platform.PlatformMinMemoryTask";
/** Max memory Java task. */
private const string MaxMemTask = "org.apache.ignite.platform.PlatformMaxMemoryTask";
/** Grid. */
private IIgnite _grid;
/** Temp dir for assemblies. */
private string _tempDir;
/// <summary>
/// Set-up routine.
/// </summary>
[SetUp]
public void SetUp()
{
_tempDir = PathUtils.GetTempDirectoryName();
TestUtils.KillProcesses();
_grid = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(RemoteConfiguration)),
new BinaryTypeConfiguration(typeof(RemoteConfigurationClosure))
}
},
SpringConfigUrl = SpringCfgPath
});
Assert.IsTrue(_grid.WaitTopology(1));
IgniteProcess.SaveConfigurationBackup();
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
TestUtils.KillProcesses();
IgniteProcess.RestoreConfigurationBackup();
Directory.Delete(_tempDir, true);
}
/// <summary>
/// Test data pass through configuration file.
/// </summary>
[Test]
public void TestConfig()
{
IgniteProcess.ReplaceConfiguration("config\\Apache.Ignite.exe.config.test");
GenerateDll("test-1.dll");
GenerateDll("test-2.dll");
var proc = new IgniteProcess();
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var cfg = RemoteConfig();
Assert.AreEqual(SpringCfgPath, cfg.SpringConfigUrl);
Assert.AreEqual(602, cfg.JvmInitialMemoryMb);
Assert.AreEqual(702, cfg.JvmMaxMemoryMb);
CollectionAssert.Contains(cfg.LoadedAssemblies, "test-1");
CollectionAssert.Contains(cfg.LoadedAssemblies, "test-2");
Assert.Null(cfg.Assemblies);
CollectionAssert.Contains(cfg.JvmOptions, "-DOPT1");
CollectionAssert.Contains(cfg.JvmOptions, "-DOPT2");
}
/// <summary>
/// Test assemblies passing through command-line.
/// </summary>
[Test]
public void TestAssemblyCmd()
{
var dll1 = GenerateDll("test-1.dll", true);
var dll2 = GenerateDll("test-2.dll", true);
var proc = new IgniteProcess(
"-springConfigUrl=" + SpringCfgPath,
"-assembly=" + dll1,
"-assembly=" + dll2);
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var cfg = RemoteConfig();
CollectionAssert.Contains(cfg.LoadedAssemblies, "test-1");
CollectionAssert.Contains(cfg.LoadedAssemblies, "test-2");
}
/// <summary>
/// Test JVM options passing through command-line.
/// </summary>
[Test]
public void TestJvmOptsCmd()
{
var proc = new IgniteProcess(
"-springConfigUrl=" + SpringCfgPath,
"-J-DOPT1",
"-J-DOPT2"
);
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var cfg = RemoteConfig();
Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2"));
}
/// <summary>
/// Test JVM memory options passing through command-line: raw java options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdRaw()
{
var proc = new IgniteProcess(
"-springConfigUrl=" + SpringCfgPath,
"-J-Xms506m",
"-J-Xmx607m"
);
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 506*1024*1024, minMem);
var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 607*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing through command-line: custom options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdCustom()
{
var proc = new IgniteProcess(
"-springConfigUrl=" + SpringCfgPath,
"-JvmInitialMemoryMB=616",
"-JvmMaxMemoryMB=866"
);
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 616*1024*1024, minMem);
var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 866*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing from application configuration.
/// </summary>
[Test]
public void TestJvmMemoryOptsAppConfig(
[Values("config\\Apache.Ignite.exe.config.test", "config\\Apache.Ignite.exe.config.test2")] string config)
{
IgniteProcess.ReplaceConfiguration(config);
GenerateDll("test-1.dll");
GenerateDll("test-2.dll");
var proc = new IgniteProcess();
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 602*1024*1024, minMem);
var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 702*1024*1024, maxMem);
proc.Kill();
Assert.IsTrue(_grid.WaitTopology(1));
// Command line options overwrite config file options
// ReSharper disable once RedundantAssignment
proc = new IgniteProcess("-J-Xms606m", "-J-Xmx706m");
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 606*1024*1024, minMem);
maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 706*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing through command-line: custom options + raw options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdCombined()
{
var proc = new IgniteProcess(
"-springConfigUrl=" + SpringCfgPath,
"-J-Xms556m",
"-J-Xmx666m",
"-JvmInitialMemoryMB=128",
"-JvmMaxMemoryMB=256"
);
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
// Raw JVM options (Xms/Xmx) should override custom options
var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 556*1024*1024, minMem);
var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 666*1024*1024, maxMem);
}
/// <summary>
/// Tests the .NET XML configuration specified in app.config.
/// </summary>
[Test]
public void TestXmlConfigurationAppConfig()
{
IgniteProcess.ReplaceConfiguration("config\\Apache.Ignite.exe.config.test3");
var proc = new IgniteProcess();
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var remoteCfg = RemoteConfig();
Assert.IsTrue(remoteCfg.JvmOptions.Contains("-DOPT25"));
proc.Kill();
Assert.IsTrue(_grid.WaitTopology(1));
}
/// <summary>
/// Tests the .NET XML configuration specified in command line.
/// </summary>
[Test]
public void TestXmlConfigurationCmd()
{
var proc = new IgniteProcess("-configFileName=config\\ignite-dotnet-cfg.xml");
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var remoteCfg = RemoteConfig();
Assert.IsTrue(remoteCfg.JvmOptions.Contains("-DOPT25"));
proc.Kill();
Assert.IsTrue(_grid.WaitTopology(1));
}
/// <summary>
/// Tests invalid command arguments.
/// </summary>
[Test]
public void TestInvalidCmdArgs()
{
var ignoredWarns = new[]
{
"WARNING: An illegal reflective access operation has occurred",
"WARNING: Illegal reflective access by org.apache.ignite.internal.util.GridUnsafe$2 " +
"(file:/C:/w/incubator-ignite/modules/core/target/classes/) to field java.nio.Buffer.address",
"WARNING: Please consider reporting this to the maintainers of org.apache.ignite.internal.util." +
"GridUnsafe$2",
"WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations",
"WARNING: All illegal access operations will be denied in a future release"
};
Action<string, string> checkError = (args, err) =>
{
var reader = new ListDataReader();
var proc = new IgniteProcess(reader, args);
int exitCode;
Assert.IsTrue(proc.Join(30000, out exitCode));
Assert.AreEqual(-1, exitCode);
Assert.AreEqual(err, reader.GetOutput()
.Except(ignoredWarns)
.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)));
};
checkError("blabla", "ERROR: Apache.Ignite.Core.Common.IgniteException: Missing argument value: " +
"'blabla'. See 'Apache.Ignite.exe /help'");
checkError("blabla=foo", "ERROR: Apache.Ignite.Core.Common.IgniteException: " +
"Unknown argument: 'blabla'. See 'Apache.Ignite.exe /help'");
checkError("assembly=", "ERROR: Apache.Ignite.Core.Common.IgniteException: Missing argument value: " +
"'assembly'. See 'Apache.Ignite.exe /help'");
checkError("assembly=x.dll", "ERROR: Apache.Ignite.Core.Common.IgniteException: " +
"Failed to load assembly: x.dll");
checkError("configFileName=wrong.config", "ERROR: System.Configuration.ConfigurationErrorsException: " +
"Specified config file does not exist: wrong.config");
checkError("configSectionName=wrongSection", "ERROR: System.Configuration.ConfigurationErrorsException: " +
"Could not find IgniteConfigurationSection " +
"in current application configuration");
checkError("JvmInitialMemoryMB=A_LOT", "ERROR: System.InvalidOperationException: Failed to configure " +
"Ignite: property 'JvmInitialMemoryMB' has value 'A_LOT', " +
"which is not an integer.");
checkError("JvmMaxMemoryMB=ALL_OF_IT", "ERROR: System.InvalidOperationException: Failed to configure " +
"Ignite: property 'JvmMaxMemoryMB' has value 'ALL_OF_IT', " +
"which is not an integer.");
}
/// <summary>
/// Tests a scenario where XML config has references to types from dynamically loaded assemblies.
/// </summary>
[Test]
public void TestXmlConfigurationReferencesTypesFromDynamicallyLoadedAssemblies()
{
const string code = @"
using System;
using Apache.Ignite.Core.Log;
namespace CustomNs {
class CustomLogger : ILogger {
public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider,
string category, string nativeErrorInfo, Exception ex) {}
public bool IsEnabled(LogLevel level) { return true; }
} }";
var dllPath = GenerateDll("CustomAsm.dll", true, code);
var proc = new IgniteProcess(
"-configFileName=config\\ignite-dotnet-cfg-logger.xml",
"-assembly=" + dllPath);
Assert.IsTrue(proc.Alive);
Assert.IsTrue(_grid.WaitTopology(2));
var remoteCfg = RemoteConfig();
Assert.AreEqual("CustomNs.CustomLogger", remoteCfg.LoggerTypeName);
}
/// <summary>
/// Get remote node configuration.
/// </summary>
/// <returns>Configuration.</returns>
private RemoteConfiguration RemoteConfig()
{
return _grid.GetCluster().ForRemotes().GetCompute().Call(new RemoteConfigurationClosure());
}
/// <summary>
/// Generates a DLL dynamically.
/// </summary>
/// <param name="outputPath">Target path.</param>
/// <param name="randomPath">Whether to use random path.</param>
/// <param name="code">Code to compile.</param>
private string GenerateDll(string outputPath, bool randomPath = false, string code = null)
{
// Put resulting DLLs to the random temp dir to make sure they are not resolved from current dir.
var resPath = randomPath ? Path.Combine(_tempDir, outputPath) : outputPath;
var parameters = new CompilerParameters
{
GenerateExecutable = false,
OutputAssembly = resPath,
ReferencedAssemblies = { typeof(IIgnite).Assembly.Location }
};
var src = code ?? "namespace Apache.Ignite.Client.Test { public class Foo {}}";
var results = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, src);
Assert.False(
results.Errors.HasErrors,
string.Join(Environment.NewLine, results.Errors.Cast<CompilerError>().Select(e => e.ToString())));
return resPath;
}
/// <summary>
/// Asserts that JVM maximum memory corresponds to Xmx parameter value.
/// </summary>
private static void AssertJvmMaxMemory(long expected, long actual)
{
// allow 20% tolerance because max memory in Java is not exactly equal to Xmx parameter value
Assert.LessOrEqual(actual, expected / 4 * 5);
Assert.Greater(actual, expected / 5 * 4);
}
/// <summary>
/// Closure which extracts configuration and passes it back.
/// </summary>
private class RemoteConfigurationClosure : IComputeFunc<RemoteConfiguration>
{
#pragma warning disable 0649
/** Grid. */
[InstanceResource] private IIgnite _grid;
#pragma warning restore 0649
/** <inheritDoc /> */
public RemoteConfiguration Invoke()
{
var grid0 = (Ignite) _grid;
var cfg = grid0.Configuration;
var res = new RemoteConfiguration
{
IgniteHome = cfg.IgniteHome,
SpringConfigUrl = cfg.SpringConfigUrl,
JvmDll = cfg.JvmDllPath,
JvmClasspath = cfg.JvmClasspath,
JvmOptions = cfg.JvmOptions,
Assemblies = cfg.Assemblies,
LoadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name).ToArray(),
JvmInitialMemoryMb = cfg.JvmInitialMemoryMb,
JvmMaxMemoryMb = cfg.JvmMaxMemoryMb,
LoggerTypeName = cfg.Logger == null ? null : cfg.Logger.GetType().FullName
};
Console.WriteLine("RETURNING CFG: " + cfg);
return res;
}
}
/// <summary>
/// Configuration.
/// </summary>
private class RemoteConfiguration
{
/// <summary>
/// GG home.
/// </summary>
public string IgniteHome { get; set; }
/// <summary>
/// Spring config URL.
/// </summary>
public string SpringConfigUrl { get; set; }
/// <summary>
/// JVM DLL.
/// </summary>
public string JvmDll { get; set; }
/// <summary>
/// JVM classpath.
/// </summary>
public string JvmClasspath { get; set; }
/// <summary>
/// JVM options.
/// </summary>
public ICollection<string> JvmOptions { get; set; }
/// <summary>
/// Assemblies.
/// </summary>
public ICollection<string> Assemblies { get; set; }
/// <summary>
/// Assemblies.
/// </summary>
public ICollection<string> LoadedAssemblies { get; set; }
/// <summary>
/// Minimum JVM memory (Xms).
/// </summary>
public int JvmInitialMemoryMb { get; set; }
/// <summary>
/// Maximum JVM memory (Xms).
/// </summary>
public int JvmMaxMemoryMb { get; set; }
/// <summary>
/// Logger type name.
/// </summary>
public string LoggerTypeName { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using Outlander.Core.Client.Scripting;
namespace Outlander.Core.Client
{
public class TokenDefinitionRegistry
{
private List<TokenDefinition> _definitions = new List<TokenDefinition>();
public void Add(TokenDefinition token)
{
_definitions.Add(token);
}
public IEnumerable<TokenDefinition> Definitions()
{
return _definitions;
}
public void New(Action<TokenDefinition> configure)
{
var def = new TokenDefinition();
configure(def);
_definitions.Add(def);
}
public static TokenDefinitionRegistry ClientCommands()
{
var registry = new TokenDefinitionRegistry();
registry.New(d => {
d.Type = "script";
d.Pattern = "^\\.(\\w+)";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Groups[1].Index, source.Length - match.Groups[1].Index);
var args = source.Substring(match.Groups[1].Index + match.Groups[1].Length, source.Length - (match.Groups[1].Index + match.Groups[1].Length));
var splitArgs = Regex
.Matches(args, RegexPatterns.Arguments)
.Cast<Match>()
.Select(m => m.Groups["match"].Value.Trim('"'))
.ToArray();
var token = new ScriptToken
{
Id = Guid.NewGuid().ToString(),
Name = match.Groups[1].Value,
Text = source,
Type = def.Type,
Value = value,
Args = splitArgs
};
return token;
};
});
registry.New(d => {
d.Type = "scriptcommand";
d.Pattern = "^#script";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "send";
d.Pattern = "^#send";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "globalvar";
d.Pattern = "^#var";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "parse";
d.Pattern = "^#parse";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
return registry;
}
public static TokenDefinitionRegistry Default()
{
var registry = new TokenDefinitionRegistry();
registry.New(d => {
d.Type = "exit";
d.Pattern = "^exit";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = match.Value
};
return token;
};
});
registry.New(d => {
d.Type = "comment";
d.Pattern = "^#.*";
d.Ignore = true;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = match.Value
};
return token;
};
});
registry.New(d => {
d.Type = "label";
d.Pattern = RegexPatterns.Label;
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = match.Groups[1].Value
};
return token;
};
});
registry.New(d => {
d.Type = "goto";
d.Pattern = "^goto";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "waitfor";
d.Pattern = "^waitfor\\b";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "waitforre";
d.Pattern = "^waitforre\\b";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "match";
d.Pattern = "^match\\b";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
const string Goto_Regex = "^match\\b\\s([\\w\\.-]+)\\s(.*)";
var gotoMatch = Regex.Match(source, Goto_Regex, RegexOptions.IgnoreCase);
var token = new MatchToken
{
Text = source,
Type = def.Type,
IsRegex = false,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim(),
Goto = gotoMatch.Groups[1].Value,
Pattern = gotoMatch.Groups[2].Value.Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "matchre";
d.Pattern = "^matchre\\b";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
const string Goto_Regex = "^matchre\\b\\s([\\w\\.-]+)\\s(.*)";
var gotoMatch = Regex.Match(source, Goto_Regex, RegexOptions.IgnoreCase);
var token = new MatchToken
{
Text = source,
Type = def.Type,
IsRegex = true,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim(),
Goto = gotoMatch.Groups[1].Value,
Pattern = gotoMatch.Groups[2].Value.Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "matchwait";
d.Pattern = "^matchwait";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "pause";
d.Pattern = "^pause";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "put";
d.Pattern = "^put";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "echo";
d.Pattern = "^echo";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
if(token.Value == null || token.Value.Length == 0 || !token.Value.EndsWith("\n")) {
token.Value += "\n";
}
return token;
};
});
registry.New(d => {
d.Type = "var";
d.Pattern = "^var";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "var";
d.Pattern = "^setvariable";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "unvar";
d.Pattern = "^unvar\\b";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "hasvar";
d.Pattern = "^hasvar\\b";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "save";
d.Pattern = "^save";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "if";
d.Pattern = "^if\\b";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new IfToken
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "if_";
d.Pattern = "^if_(\\d+)";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new IfToken
{
Text = source,
Type = def.Type,
Value = match.Value,
ReplaceBlocks = false,
Blocks = new IfBlocks
{
IfEval = match.Groups[1].Value,
IfBlock = value
}
};
return token;
};
});
registry.New(d => {
d.Type = "move";
d.Pattern = "^move";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "nextroom";
d.Pattern = "^nextroom";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "action";
d.Pattern = "^action\\b(.*)\\bwhen\\b(.*)";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new ActionToken
{
Text = source,
Type = def.Type,
Value = value,
Action = match.Groups[1].Value.Trim(),
When = match.Groups[2].Value.Trim()
};
return token;
};
});
registry.New(d => {
d.Type = "send";
d.Pattern = "^send";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "debuglevel";
d.Pattern = "^debuglevel";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "parse";
d.Pattern = "^parse";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "containsre";
d.Pattern = "^containsre";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var token = new Token
{
Text = source,
Type = def.Type,
Value = value
};
return token;
};
});
registry.New(d => {
d.Type = "gosub";
d.Pattern = "^gosub";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var value = source.Substring(match.Index + match.Length, source.Length - (match.Index + match.Length)).Trim();
var labelMatch = Regex.Match(value, RegexPatterns.Gosub);
var splitArgs = Regex
.Matches(value, RegexPatterns.Arguments)
.Cast<Match>()
.Select(m => m.Groups["match"].Value.Trim('"'))
.Skip(1)
.ToArray();
var token = new GotoToken
{
Text = source,
Type = def.Type,
Value = value,
Label = labelMatch.Groups["label"].Value,
Args = splitArgs
};
return token;
};
});
registry.New(d => {
d.Type = "return";
d.Pattern = "^return";
d.Ignore = false;
d.BuildToken = (source, match, def)=> {
var token = new Token
{
Text = source,
Type = def.Type,
Value = "return"
};
return token;
};
});
return registry;
}
}
public class IfToken : Token
{
public IfToken()
{
ReplaceBlocks = true;
}
public bool ReplaceBlocks { get; set; }
public IfBlocks Blocks { get; set; }
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using AlephNote.Plugins.Evernote.Thrift.Collections;
using AlephNote.Plugins.Evernote.Thrift.Protocol;
using AlephNote.Plugins.Evernote.Thrift.Transport;
namespace AlephNote.Plugins.Evernote.Thrift.Server
{
/// <summary>
/// Server that uses C# threads (as opposed to the ThreadPool) when handling requests
/// </summary>
public class TThreadedServer : TServer
{
private const int DEFAULT_MAX_THREADS = 100;
private volatile bool stop = false;
private readonly int maxThreads;
private Queue<TTransport> clientQueue;
private THashSet<Thread> clientThreads;
private object clientLock;
private Thread workerThread;
public TThreadedServer(TProcessor processor, TServerTransport serverTransport)
: this(processor, serverTransport,
new TTransportFactory(), new TTransportFactory(),
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadedServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate)
: this(processor, serverTransport,
new TTransportFactory(), new TTransportFactory(),
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
DEFAULT_MAX_THREADS, logDelegate)
{
}
public TThreadedServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(processor, serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadedServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
int maxThreads, LogDelegate logDel)
: base(processor, serverTransport, inputTransportFactory, outputTransportFactory,
inputProtocolFactory, outputProtocolFactory, logDel)
{
this.maxThreads = maxThreads;
clientQueue = new Queue<TTransport>();
clientLock = new object();
clientThreads = new THashSet<Thread>();
}
/// <summary>
/// Use new Thread for each new client connection. block until numConnections < maxThreads
/// </summary>
public override void Serve()
{
try
{
//start worker thread
workerThread = new Thread(new ThreadStart(Execute));
workerThread.Start();
serverTransport.Listen();
}
catch (TTransportException ttx)
{
logDelegate("Error, could not listen on ServerTransport: " + ttx);
return;
}
while (!stop)
{
int failureCount = 0;
try
{
TTransport client = serverTransport.Accept();
lock (clientLock)
{
clientQueue.Enqueue(client);
Monitor.Pulse(clientLock);
}
}
catch (TTransportException ttx)
{
if (stop)
{
logDelegate("TThreadPoolServer was shutting down, caught " + ttx);
}
else
{
++failureCount;
logDelegate(ttx.ToString());
}
}
}
if (stop)
{
try
{
serverTransport.Close();
}
catch (TTransportException ttx)
{
logDelegate("TServeTransport failed on close: " + ttx.Message);
}
stop = false;
}
}
/// <summary>
/// Loops on processing a client forever
/// threadContext will be a TTransport instance
/// </summary>
/// <param name="threadContext"></param>
private void Execute()
{
while (!stop)
{
TTransport client;
Thread t;
lock (clientLock)
{
//don't dequeue if too many connections
while (clientThreads.Count >= maxThreads)
{
Monitor.Wait(clientLock);
}
while (clientQueue.Count == 0)
{
Monitor.Wait(clientLock);
}
client = clientQueue.Dequeue();
t = new Thread(new ParameterizedThreadStart(ClientWorker));
clientThreads.Add(t);
}
//start processing requests from client on new thread
t.Start(client);
}
}
private void ClientWorker(Object context)
{
TTransport client = (TTransport)context;
TTransport inputTransport = null;
TTransport outputTransport = null;
TProtocol inputProtocol = null;
TProtocol outputProtocol = null;
try
{
inputTransport = inputTransportFactory.GetTransport(client);
outputTransport = outputTransportFactory.GetTransport(client);
inputProtocol = inputProtocolFactory.GetProtocol(inputTransport);
outputProtocol = outputProtocolFactory.GetProtocol(outputTransport);
while (processor.Process(inputProtocol, outputProtocol))
{
//keep processing requests until client disconnects
}
}
catch (TTransportException)
{
}
catch (Exception x)
{
logDelegate("Error: " + x);
}
if (inputTransport != null)
{
inputTransport.Close();
}
if (outputTransport != null)
{
outputTransport.Close();
}
lock (clientLock)
{
clientThreads.Remove(Thread.CurrentThread);
Monitor.Pulse(clientLock);
}
return;
}
public override void Stop()
{
throw new NotImplementedException(); // can't abort Thread in Net Standard (?)
}
}
}
| |
// F#: The CodeDOM provider ignores type constructors (static constructors),
// but this is handled because test suite checks for "Supports" flags
//
// Next issue is that F# generates properties instead of fields (modified lookup in the test)
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
using Microsoft.Samples.CodeDomTestSuite;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using Microsoft.JScript;
public class SubsetAttributesTest : CodeDomTestTree {
public override TestTypes TestType {
get {
return TestTypes.Subset;
}
}
public override string Name {
get {
return "SubsetAttributesTest";
}
}
public override string Description {
get {
return "Tests metadata attributes while staying in the subset.";
}
}
public override bool ShouldCompile {
get {
return true;
}
}
public override bool ShouldVerify {
get {
return true;
}
}
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
// GENERATES (C#):
// [assembly: System.Reflection.AssemblyTitle("MyAssembly")]
// [assembly: System.Reflection.AssemblyVersion("1.0.6.2")]
// [assembly: System.CLSCompliantAttribute(false)]
//
// namespace MyNamespace {
// using System;
// using System.Drawing;
// using System.Windows.Forms;
// using System.ComponentModel;
//
CodeNamespace ns = new CodeNamespace ();
ns.Name = "MyNamespace";
ns.Imports.Add (new CodeNamespaceImport ("System"));
ns.Imports.Add (new CodeNamespaceImport ("System.Drawing"));
ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms"));
ns.Imports.Add (new CodeNamespaceImport ("System.ComponentModel"));
cu.Namespaces.Add (ns);
cu.ReferencedAssemblies.Add ("System.Xml.dll");
cu.ReferencedAssemblies.Add ("System.Drawing.dll");
cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll");
// Assembly Attributes
if (Supports (provider, GeneratorSupport.AssemblyAttributes)) {
AddScenario ("CheckAssemblyAttributes", "Check that assembly attributes get generated properly.");
CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyTitle", new
CodeAttributeArgument (new CodePrimitiveExpression ("MyAssembly"))));
attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyVersion", new
CodeAttributeArgument (new CodePrimitiveExpression ("1.0.6.2"))));
attrs.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new
CodeAttributeArgument (new CodePrimitiveExpression (false))));
}
// GENERATES (C#):
// [System.Serializable()]
// [System.Obsolete("Don\'t use this Class")]
// [System.Windows.Forms.AxHost.ClsidAttribute("Class.ID")]
// public class MyClass {
//
#if !WHIDBEY
if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider))
AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly.");
#else
AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly.");
#endif
CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
class1.Name = "MyClass";
class1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Serializable"));
class1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Class"))));
class1.CustomAttributes.Add (new
CodeAttributeDeclaration (typeof (System.Windows.Forms.AxHost.ClsidAttribute).FullName,
new CodeAttributeArgument (new CodePrimitiveExpression ("Class.ID"))));
ns.Types.Add (class1);
// GENERATES (C#):
// [System.Obsolete("Don\'t use this Method")]
// [System.ComponentModel.Editor("This", "That")]
// public void MyMethod(string blah, int[] arrayit) {
// }
AddScenario ("CheckMyMethodAttributes", "Check that attributes are generated properly on MyMethod().");
CodeMemberMethod method1 = new CodeMemberMethod ();
method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
method1.Name = "MyMethod";
method1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Method"))));
method1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.ComponentModel.Editor", new
CodeAttributeArgument (new CodePrimitiveExpression ("This")), new CodeAttributeArgument (new
CodePrimitiveExpression ("That"))));
CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression (typeof (string), "blah");
method1.Parameters.Add (param1);
CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression (typeof (int[]), "arrayit");
method1.Parameters.Add (param2);
class1.Members.Add (method1);
// GENERATES (C#):
// [System.Xml.Serialization.XmlElementAttribute()]
// private string myField = "hi!";
//
AddScenario ("CheckMyFieldAttributes", "Check that attributes are generated properly on MyField.");
CodeMemberField field1 = new CodeMemberField ();
field1.Name = "myField";
field1.Attributes = MemberAttributes.Public;
field1.Type = new CodeTypeReference (typeof (string));
field1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlElementAttribute"));
field1.InitExpression = new CodePrimitiveExpression ("hi!");
class1.Members.Add (field1);
// GENERATES (C#):
// [System.Obsolete("Don\'t use this Property")]
// public string MyProperty {
// get {
// return this.myField;
// }
// }
AddScenario ("CheckMyPropertyAttributes", "Check that attributes are generated properly on MyProperty.");
CodeMemberProperty prop1 = new CodeMemberProperty ();
prop1.Attributes = MemberAttributes.Public;
prop1.Name = "MyProperty";
prop1.Type = new CodeTypeReference (typeof (string));
prop1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Property"))));
prop1.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "myField")));
class1.Members.Add (prop1);
// GENERATES (C#):
// [System.Obsolete("Don\'t use this Constructor")]
// public MyClass() {
// }
// }
if (!(provider is JScriptCodeProvider))
AddScenario ("CheckConstructorAttributes", "Check that attributes are generated properly on the constructor.");
CodeConstructor const1 = new CodeConstructor ();
const1.Attributes = MemberAttributes.Public;
const1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Constructor"))));
class1.Members.Add (const1);
if (Supports (provider, GeneratorSupport.DeclareEvents)) {
// GENERATES (C#):
// public class Test : Form {
//
// private Button b = new Button();
//
//
AddScenario ("CheckEventAttributes", "test attributes on an event");
class1 = new CodeTypeDeclaration ("Test");
class1.IsClass = true;
class1.BaseTypes.Add (new CodeTypeReference ("Form"));
ns.Types.Add (class1);
CodeMemberField mfield = new CodeMemberField (new CodeTypeReference ("Button"), "b");
mfield.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("Button"));
class1.Members.Add (mfield);
// GENERATES (C#):
// public Test() {
// this.Size = new Size(600, 600);
// b.Text = "Test";
// b.TabIndex = 0;
// b.Location = new Point(400, 525);
// this.MyEvent += new EventHandler(this.b_Click);
// }
//
CodeConstructor ctor = new CodeConstructor ();
ctor.Attributes = MemberAttributes.Public;
ctor.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (),
"Size"), new CodeObjectCreateExpression (new CodeTypeReference ("Size"),
new CodePrimitiveExpression (600), new CodePrimitiveExpression (600))));
ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
"Text"), new CodePrimitiveExpression ("Test")));
ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
"TabIndex"), new CodePrimitiveExpression (0)));
ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
"Location"), new CodeObjectCreateExpression (new CodeTypeReference ("Point"),
new CodePrimitiveExpression (400), new CodePrimitiveExpression (525))));
ctor.Statements.Add (new CodeAttachEventStatement (new CodeEventReferenceExpression (new
CodeThisReferenceExpression (), "MyEvent"), new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler")
, new CodeThisReferenceExpression (), "b_Click")));
class1.Members.Add (ctor);
// GENERATES (C#):
// [System.CLSCompliantAttribute(false)]
// public event System.EventHandler MyEvent;
CodeMemberEvent evt = new CodeMemberEvent ();
evt.Name = "MyEvent";
evt.Type = new CodeTypeReference ("System.EventHandler");
evt.Attributes = MemberAttributes.Public;
evt.CustomAttributes.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false))));
class1.Members.Add (evt);
// GENERATES (C#):
// private void b_Click(object sender, System.EventArgs e) {
// }
// }
// }
//
CodeMemberMethod cmm = new CodeMemberMethod ();
cmm.Name = "b_Click";
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
class1.Members.Add (cmm);
}
}
public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) {
Type genType;
// Verifying Assembly Attributes
if (Supports (provider, GeneratorSupport.AssemblyAttributes)) {
object[] attributes = asm.GetCustomAttributes (true);
bool verifiedAssemblyAttributes = VerifyAttribute (attributes, typeof (AssemblyTitleAttribute), "Title", "MyAssembly");
verifiedAssemblyAttributes &=
VerifyAttribute (attributes, typeof (AssemblyVersionAttribute), "Version", "1.0.6.2") ||
asm.GetName ().Version.Equals (new Version (1, 0, 6, 2));
if (verifiedAssemblyAttributes) {
VerifyScenario ("CheckAssemblyAttributes");
}
}
object[] customAttributes;
object[] customAttributes2;
object[] customAttributesAll;
if (FindType ("MyNamespace.MyClass", asm, out genType)) {
customAttributes = genType.GetCustomAttributes (typeof (System.ObsoleteAttribute), true);
customAttributes2 = genType.GetCustomAttributes (typeof (System.SerializableAttribute), true);
customAttributesAll = genType.GetCustomAttributes (true);
#if !WHIDBEY
if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) {
#endif
if (customAttributes.GetLength (0) == 1 &&
customAttributes2.GetLength (0) >= 1 &&
customAttributesAll.GetLength (0) >= 3) {
VerifyScenario ("CheckClassAttributes");
}
#if !WHIDBEY
}
#endif
// verify method attributes
MethodInfo methodInfo = genType.GetMethod ("MyMethod");
if (methodInfo != null &&
methodInfo.GetCustomAttributes (typeof (System.ObsoleteAttribute), true).GetLength (0) > 0 &&
methodInfo.GetCustomAttributes (typeof (System.ComponentModel.EditorAttribute), true).GetLength (0) > 0) {
VerifyScenario ("CheckMyMethodAttributes");
}
// verify property attributes
PropertyInfo propertyInfo = genType.GetProperty ("MyProperty");
if (propertyInfo != null &&
propertyInfo.GetCustomAttributes (typeof (System.ObsoleteAttribute), true).GetLength (0) > 0) {
VerifyScenario ("CheckMyPropertyAttributes");
}
// verify constructor attributes
ConstructorInfo[] constructorInfo = genType.GetConstructors ();
if (constructorInfo != null && constructorInfo.Length > 0 && !(provider is JScriptCodeProvider) &&
constructorInfo[0].GetCustomAttributes (typeof (System.ObsoleteAttribute), true).GetLength (0) > 0) {
VerifyScenario ("CheckConstructorAttributes");
}
// verify field attributes
FieldInfo fieldInfo = genType.GetField("myField");
if (fieldInfo != null &&
fieldInfo.GetCustomAttributes (typeof (System.Xml.Serialization.XmlElementAttribute), true).GetLength (0) > 0) {
VerifyScenario ("CheckMyFieldAttributes");
}
}
// verify event attributes
if (Supports (provider, GeneratorSupport.DeclareEvents) && FindType ("MyNamespace.Test", asm, out genType)) {
EventInfo eventInfo = genType.GetEvent ("MyEvent");
if (eventInfo != null &&
eventInfo.GetCustomAttributes (typeof (System.CLSCompliantAttribute), true).GetLength (0) > 0) {
VerifyScenario ("CheckEventAttributes");
}
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
using MLifter.Classes;
using System.Runtime.Remoting;
using MLifter.BusinessLayer;
using MLifter.DAL.Interfaces;
using MLifter.DAL;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Lifetime;
namespace MLifterRemoting
{
/// <summary>
/// Provides services for remotely accessing MemoryLifter functions.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public class Remoting : IDisposable
{
//IPC connection data
private static string UniqueChannelName = string.Empty;
private static string UniqueChannelPortName = string.Empty;
private static string ClientURL = string.Empty;
private static string ServiceURL = string.Empty;
GlobalDictionaryLoader loader = null;
/// <summary>
/// Initializes a new instance of the <see cref="Remoting"/> class and connects to MemoryLifter.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-26</remarks>
/// <exception cref="MLCouldNotBeStartedException">Occurs when MemoryLifter did not start or did not react to connection attempts.</exception>
/// <exception cref="MLNotReadyException">Occurs when MemoryLifter is not ready for being remote controlled.</exception>
public Remoting()
{
LifetimeServices.LeaseManagerPollTime = TimeSpan.FromSeconds(3);
Connect();
}
/// <summary>
/// Connects this instance.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-26</remarks>
/// <exception cref="MLCouldNotBeStartedException">Occurs when MemoryLifter did not start or did not react to connection attempts.</exception>
/// <exception cref="MLNotReadyException">Occurs when MemoryLifter is not ready for being remote controlled.</exception>
private void Connect()
{
Debug.WriteLine("Connecting to MemoryLifter...");
MLifter.Program.GetIPCData(out UniqueChannelName, out UniqueChannelPortName, out ClientURL, out ServiceURL);
loader = (GlobalDictionaryLoader)RemotingServices.Connect(typeof(GlobalDictionaryLoader), ClientURL);
int tries;
try
{
tries = 20;
while (!loader.IsMLReady())
{
Thread.Sleep(50);
if (tries-- < 0)
throw new MLNotReadyException();
}
}
catch (RemotingException)
{
StartML();
Thread.Sleep(200);
try
{
tries = 100;
while (!loader.IsMLReady())
{
Thread.Sleep(50);
if (tries-- < 0)
throw new MLNotReadyException();
}
}
catch (RemotingException)
{
throw;
}
}
return;
}
/// <summary>
/// Opens the learning module (or schedules it for opening).
/// </summary>
/// <param name="configFilePath">The config file path.</param>
/// <param name="LmId">The lm id.</param>
/// <param name="LmName">Name of the lm.</param>
/// <param name="UserId">The user id.</param>
/// <param name="UserName">Name of the user.</param>
/// <param name="UserPassword">The user password (needed for FormsAuthentication, else empty).</param>
/// <remarks>Documented by Dev02, 2009-06-26</remarks>
/// <exception cref="MLHasOpenFormsException">Occurs when settings or the learning module could not be changed because MemoryLifter has other forms/windows open.</exception>
/// <exception cref="ConfigFileParseException">Occurs when the supplied config file could not be parsed properly or does not contain a valid connection.</exception>
/// <exception cref="MLCouldNotBeStartedException">Occurs when MemoryLifter did not start or did not react to connection attempts.</exception>
public void OpenLearningModule(string configFilePath, int LmId, string LmName, int UserId, string UserName, string UserPassword)
{
ConnectionStringHandler csHandler = new ConnectionStringHandler(configFilePath);
if (csHandler.ConnectionStrings.Count < 1)
throw new ConfigFileParseException();
Debug.WriteLine(string.Format("Config file parsed ({0}), building connection...", configFilePath));
IConnectionString connectionString = csHandler.ConnectionStrings[0];
ConnectionStringStruct css = new ConnectionStringStruct();
css.LmId = LmId;
css.Typ = connectionString.ConnectionType;
css.ConnectionString = connectionString.ConnectionString;
if (connectionString is UncConnectionStringBuilder)
{
css.ConnectionString = Path.Combine(css.ConnectionString, LmName + Helper.EmbeddedDbExtension);
css.Typ = DatabaseType.MsSqlCe;
}
if (connectionString is ISyncableConnectionString)
{
ISyncableConnectionString syncConnectionString = (ISyncableConnectionString)connectionString;
css.LearningModuleFolder = syncConnectionString.MediaURI;
css.ExtensionURI = syncConnectionString.ExtensionURI;
css.SyncType = syncConnectionString.SyncType;
}
LearningModulesIndexEntry entry = new LearningModulesIndexEntry(css);
entry.User = new DummyUser(UserId, UserName);
((DummyUser)entry.User).Password = UserPassword;
entry.UserName = UserName;
entry.UserId = UserId;
entry.Connection = connectionString;
entry.DisplayName = LmName;
entry.SyncedPath = LmName + Helper.SyncedEmbeddedDbExtension;
Debug.WriteLine("Opening learning module...");
try
{
loader.LoadDictionary(entry);
}
catch (MLifter.Classes.FormsOpenException)
{
throw new MLHasOpenFormsException();
}
}
/// <summary>
/// Selects the learning chapters (or schedules them for being selected).
/// </summary>
/// <param name="chapterIds">The chapter ids.</param>
/// <remarks>Documented by Dev02, 2009-06-26</remarks>
/// <exception cref="MLHasOpenFormsException">Occurs when settings or the learning module could not be changed because MemoryLifter has other forms/windows open.</exception>
/// <exception cref="MLCouldNotBeStartedException">Occurs when MemoryLifter did not start or did not react to connection attempts.</exception>
public void SelectLearningChapters(int[] chapterIds)
{
Debug.WriteLine("Selecting learning chapters...");
try
{
loader.SelectLearningChapters(chapterIds);
}
catch (MLifter.Classes.FormsOpenException)
{
throw new MLHasOpenFormsException();
}
}
/// <summary>
/// Starts the MemoryLifter process.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-26</remarks>
/// <exception cref="MLCouldNotBeStartedException">Occurs when MemoryLifter did not start or did not react to connection attempts.</exception>
private void StartML()
{
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = MLifter.Program.GetAssemblyPath(true);
si.WorkingDirectory = Path.GetDirectoryName(si.FileName);
si.UseShellExecute = true;
Debug.WriteLine(string.Format("Starting MemoryLifter program ({0})", si.FileName));
try
{
Process ml = Process.Start(si);
ml.WaitForInputIdle();
if (ml.HasExited)
{
Debug.WriteLine("ML did not start successfully.");
throw new MLCouldNotBeStartedException("MemoryLifter exited immediately.");
}
}
catch (System.ComponentModel.Win32Exception e)
{
throw new MLCouldNotBeStartedException("Error launching the MemoryLifter process.", e);
}
return;
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public void Dispose()
{
if (loader != null)
loader = null;
}
#endregion
}
/// <summary>
/// Occurs when settings or the learning module could not be changed because MemoryLifter has other forms/windows open.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-26</remarks>
[global::System.Serializable]
public class MLHasOpenFormsException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="MLHasOpenFormsException"/> class.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLHasOpenFormsException() { }
/// <summary>
/// Initializes a new instance of the <see cref="MLHasOpenFormsException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLHasOpenFormsException(string message) : base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="MLHasOpenFormsException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLHasOpenFormsException(string message, Exception inner) : base(message, inner) { }
/// <summary>
/// Initializes a new instance of the <see cref="MLHasOpenFormsException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="info"/> parameter is null.
/// </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">
/// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0).
/// </exception>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
protected MLHasOpenFormsException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
/// <summary>
/// Occurs when the supplied config file could not be parsed properly or does not contain a valid connection.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
[global::System.Serializable]
public class ConfigFileParseException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="ConfigFileParseException"/> class.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public ConfigFileParseException() { }
/// <summary>
/// Initializes a new instance of the <see cref="ConfigFileParseException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public ConfigFileParseException(string message) : base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConfigFileParseException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public ConfigFileParseException(string message, Exception inner) : base(message, inner) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConfigFileParseException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="info"/> parameter is null.
/// </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">
/// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0).
/// </exception>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
protected ConfigFileParseException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
/// <summary>
/// Occurs when MemoryLifter did not start properly.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
[global::System.Serializable]
public class MLCouldNotBeStartedException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="MLCouldNotBeStartedException"/> class.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLCouldNotBeStartedException() { }
/// <summary>
/// Initializes a new instance of the <see cref="MLCouldNotBeStartedException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLCouldNotBeStartedException(string message) : base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="MLCouldNotBeStartedException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLCouldNotBeStartedException(string message, Exception inner) : base(message, inner) { }
/// <summary>
/// Initializes a new instance of the <see cref="MLCouldNotBeStartedException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="info"/> parameter is null.
/// </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">
/// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0).
/// </exception>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
protected MLCouldNotBeStartedException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
/// <summary>
/// Occurs when MemoryLifter is not ready for being remote controlled.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
[global::System.Serializable]
public class MLNotReadyException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="MLNotReadyException"/> class.
/// </summary>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLNotReadyException() { }
/// <summary>
/// Initializes a new instance of the <see cref="MLNotReadyException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLNotReadyException(string message) : base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="MLNotReadyException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
public MLNotReadyException(string message, Exception inner) : base(message, inner) { }
/// <summary>
/// Initializes a new instance of the <see cref="MLNotReadyException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="info"/> parameter is null.
/// </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">
/// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0).
/// </exception>
/// <remarks>Documented by Dev02, 2009-06-29</remarks>
protected MLNotReadyException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
| |
// 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 BlendVariableInt64()
{
var test = new SimpleTernaryOpTest__BlendVariableInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__BlendVariableInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] inArray3, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int64, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int64> _fld1;
public Vector256<Int64> _fld2;
public Vector256<Int64> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt64("0xFFFFFFFFFFFFFFFF", 16) : (long)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableInt64 testClass)
{
var result = Avx2.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableInt64 testClass)
{
fixed (Vector256<Int64>* pFld1 = &_fld1)
fixed (Vector256<Int64>* pFld2 = &_fld2)
fixed (Vector256<Int64>* pFld3 = &_fld3)
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int64*)(pFld1)),
Avx.LoadVector256((Int64*)(pFld2)),
Avx.LoadVector256((Int64*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Int64[] _data3 = new Int64[Op3ElementCount];
private static Vector256<Int64> _clsVar1;
private static Vector256<Int64> _clsVar2;
private static Vector256<Int64> _clsVar3;
private Vector256<Int64> _fld1;
private Vector256<Int64> _fld2;
private Vector256<Int64> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__BlendVariableInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt64("0xFFFFFFFFFFFFFFFF", 16) : (long)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
}
public SimpleTernaryOpTest__BlendVariableInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt64("0xFFFFFFFFFFFFFFFF", 16) : (long)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt64("0xFFFFFFFFFFFFFFFF", 16) : (long)0); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.BlendVariable(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.BlendVariable(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int64>* pClsVar2 = &_clsVar2)
fixed (Vector256<Int64>* pClsVar3 = &_clsVar3)
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int64*)(pClsVar1)),
Avx.LoadVector256((Int64*)(pClsVar2)),
Avx.LoadVector256((Int64*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray3Ptr);
var result = Avx2.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadVector256((Int64*)(_dataTable.inArray3Ptr));
var result = Avx2.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray3Ptr));
var result = Avx2.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__BlendVariableInt64();
var result = Avx2.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__BlendVariableInt64();
fixed (Vector256<Int64>* pFld1 = &test._fld1)
fixed (Vector256<Int64>* pFld2 = &test._fld2)
fixed (Vector256<Int64>* pFld3 = &test._fld3)
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int64*)(pFld1)),
Avx.LoadVector256((Int64*)(pFld2)),
Avx.LoadVector256((Int64*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int64>* pFld1 = &_fld1)
fixed (Vector256<Int64>* pFld2 = &_fld2)
fixed (Vector256<Int64>* pFld3 = &_fld3)
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int64*)(pFld1)),
Avx.LoadVector256((Int64*)(pFld2)),
Avx.LoadVector256((Int64*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int64*)(&test._fld1)),
Avx.LoadVector256((Int64*)(&test._fld2)),
Avx.LoadVector256((Int64*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int64> op1, Vector256<Int64> op2, Vector256<Int64> op3, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] inArray3 = new Int64[Op3ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] inArray3 = new Int64[Op3ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] secondOp, Int64[] thirdOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((thirdOp[0] != 0) ? secondOp[0] != result[0] : firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((thirdOp[i] != 0) ? secondOp[i] != result[i] : firstOp[i] != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.BlendVariable)}<Int64>(Vector256<Int64>, Vector256<Int64>, Vector256<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
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.
namespace System.Xml.Xsl
{
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml.XPath;
using System.Xml.Xsl.XsltOld;
using System.Xml.Xsl.XsltOld.Debugger;
public sealed class XslTransform
{
private XmlResolver _documentResolver = null;
private bool _isDocumentResolverSet = false;
private XmlResolver _DocumentResolver
{
get
{
if (_isDocumentResolverSet)
return _documentResolver;
else
{
return CreateDefaultResolver();
}
}
}
//
// Compiled stylesheet state
//
private Stylesheet _CompiledStylesheet;
private List<TheQuery> _QueryStore;
private RootAction _RootAction;
private IXsltDebugger _debugger;
public XslTransform() { }
public XmlResolver XmlResolver
{
set
{
_documentResolver = value;
_isDocumentResolverSet = true;
}
}
public void Load(XmlReader stylesheet)
{
Load(stylesheet, CreateDefaultResolver());
}
public void Load(XmlReader stylesheet, XmlResolver resolver)
{
if (stylesheet == null)
{
throw new ArgumentNullException(nameof(stylesheet));
}
Load(new XPathDocument(stylesheet, XmlSpace.Preserve), resolver);
}
public void Load(IXPathNavigable stylesheet)
{
Load(stylesheet, CreateDefaultResolver());
}
public void Load(IXPathNavigable stylesheet, XmlResolver resolver)
{
if (stylesheet == null)
{
throw new ArgumentNullException(nameof(stylesheet));
}
Load(stylesheet.CreateNavigator(), resolver);
}
public void Load(XPathNavigator stylesheet)
{
if (stylesheet == null)
{
throw new ArgumentNullException(nameof(stylesheet));
}
Load(stylesheet, CreateDefaultResolver());
}
public void Load(XPathNavigator stylesheet, XmlResolver resolver)
{
if (stylesheet == null)
{
throw new ArgumentNullException(nameof(stylesheet));
}
Compile(stylesheet, resolver);
}
public void Load(string url)
{
XmlTextReaderImpl tr = new XmlTextReaderImpl(url);
Compile(Compiler.LoadDocument(tr).CreateNavigator(), CreateDefaultResolver());
}
public void Load(string url, XmlResolver resolver)
{
XmlTextReaderImpl tr = new XmlTextReaderImpl(url);
{
tr.XmlResolver = resolver;
}
Compile(Compiler.LoadDocument(tr).CreateNavigator(), resolver);
}
// ------------------------------------ Transform() ------------------------------------ //
private void CheckCommand()
{
if (_CompiledStylesheet == null)
{
throw new InvalidOperationException(SR.Xslt_NoStylesheetLoaded);
}
}
public XmlReader Transform(XPathNavigator input, XsltArgumentList args, XmlResolver resolver)
{
CheckCommand();
Processor processor = new Processor(input, args, resolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger);
return processor.StartReader();
}
public XmlReader Transform(XPathNavigator input, XsltArgumentList args)
{
return Transform(input, args, _DocumentResolver);
}
public void Transform(XPathNavigator input, XsltArgumentList args, XmlWriter output, XmlResolver resolver)
{
CheckCommand();
Processor processor = new Processor(input, args, resolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger);
processor.Execute(output);
}
public void Transform(XPathNavigator input, XsltArgumentList args, XmlWriter output)
{
Transform(input, args, output, _DocumentResolver);
}
public void Transform(XPathNavigator input, XsltArgumentList args, Stream output, XmlResolver resolver)
{
CheckCommand();
Processor processor = new Processor(input, args, resolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger);
processor.Execute(output);
}
public void Transform(XPathNavigator input, XsltArgumentList args, Stream output)
{
Transform(input, args, output, _DocumentResolver);
}
public void Transform(XPathNavigator input, XsltArgumentList args, TextWriter output, XmlResolver resolver)
{
CheckCommand();
Processor processor = new Processor(input, args, resolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger);
processor.Execute(output);
}
public void Transform(XPathNavigator input, XsltArgumentList args, TextWriter output)
{
CheckCommand();
Processor processor = new Processor(input, args, _DocumentResolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger);
processor.Execute(output);
}
public XmlReader Transform(IXPathNavigable input, XsltArgumentList args, XmlResolver resolver)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
return Transform(input.CreateNavigator(), args, resolver);
}
public XmlReader Transform(IXPathNavigable input, XsltArgumentList args)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
return Transform(input.CreateNavigator(), args, _DocumentResolver);
}
public void Transform(IXPathNavigable input, XsltArgumentList args, TextWriter output, XmlResolver resolver)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Transform(input.CreateNavigator(), args, output, resolver);
}
public void Transform(IXPathNavigable input, XsltArgumentList args, TextWriter output)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Transform(input.CreateNavigator(), args, output, _DocumentResolver);
}
public void Transform(IXPathNavigable input, XsltArgumentList args, Stream output, XmlResolver resolver)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Transform(input.CreateNavigator(), args, output, resolver);
}
public void Transform(IXPathNavigable input, XsltArgumentList args, Stream output)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Transform(input.CreateNavigator(), args, output, _DocumentResolver);
}
public void Transform(IXPathNavigable input, XsltArgumentList args, XmlWriter output, XmlResolver resolver)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Transform(input.CreateNavigator(), args, output, resolver);
}
public void Transform(IXPathNavigable input, XsltArgumentList args, XmlWriter output)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Transform(input.CreateNavigator(), args, output, _DocumentResolver);
}
public void Transform(string inputfile, string outputfile, XmlResolver resolver)
{
FileStream fs = null;
try
{
// We should read doc before creating output file in case they are the same
XPathDocument doc = new XPathDocument(inputfile);
fs = new FileStream(outputfile, FileMode.Create, FileAccess.ReadWrite);
Transform(doc, /*args:*/null, fs, resolver);
}
finally
{
if (fs != null)
{
fs.Dispose();
}
}
}
public void Transform(string inputfile, string outputfile)
{
Transform(inputfile, outputfile, _DocumentResolver);
}
// Implementation
private void Compile(XPathNavigator stylesheet, XmlResolver resolver)
{
Debug.Assert(stylesheet != null);
Compiler compiler = (Debugger == null) ? new Compiler() : new DbgCompiler(this.Debugger);
NavigatorInput input = new NavigatorInput(stylesheet);
compiler.Compile(input, resolver ?? XmlNullResolver.Singleton);
Debug.Assert(compiler.CompiledStylesheet != null);
Debug.Assert(compiler.QueryStore != null);
Debug.Assert(compiler.QueryStore != null);
_CompiledStylesheet = compiler.CompiledStylesheet;
_QueryStore = compiler.QueryStore;
_RootAction = compiler.RootAction;
}
internal IXsltDebugger Debugger
{
get { return _debugger; }
}
private static XmlResolver CreateDefaultResolver()
{
if (LocalAppContextSwitches.AllowDefaultResolver)
{
return new XmlUrlResolver();
}
else
{
return XmlNullResolver.Singleton;
}
}
}
}
| |
#region Copyright
//
// Nini Configuration Project.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.IO;
using Nini.Config;
using NUnit.Framework;
namespace Nini.Test.Config
{
[TestFixture]
public class ConfigBaseTests
{
[Test]
public void GetConfig ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Pets]");
writer.WriteLine (" cat = muffy");
writer.WriteLine (" dog = rover");
writer.WriteLine (" bird = tweety");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["Pets"];
Assert.AreEqual ("Pets", config.Name);
Assert.AreEqual (3, config.GetKeys ().Length);
Assert.AreEqual (source, config.ConfigSource);
}
[Test]
public void GetString ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" cat = muffy");
writer.WriteLine (" dog = rover");
writer.WriteLine (" bird = tweety");
IniConfigSource source =
new IniConfigSource (new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
Assert.AreEqual ("muffy", config.Get ("cat"));
Assert.AreEqual ("rover", config.Get ("dog"));
Assert.AreEqual ("muffy", config.GetString ("cat"));
Assert.AreEqual ("rover", config.GetString ("dog"));
Assert.AreEqual ("my default", config.Get ("Not Here", "my default"));
Assert.IsNull (config.Get ("Not Here 2"));
}
[Test]
public void GetInt ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" value 1 = 49588");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
Assert.AreEqual (49588, config.GetInt ("value 1"));
Assert.AreEqual (12345, config.GetInt ("Not Here", 12345));
try
{
config.GetInt ("Not Here Also");
Assert.Fail ();
}
catch
{
}
}
[Test]
public void GetLong ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" value 1 = 4000000000");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
Assert.AreEqual (4000000000, config.GetLong ("value 1"));
Assert.AreEqual (5000000000, config.GetLong ("Not Here", 5000000000));
try
{
config.GetLong ("Not Here Also");
Assert.Fail ();
}
catch
{
}
}
[Test]
public void GetFloat ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" value 1 = 494.59");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
Assert.AreEqual (494.59, config.GetFloat ("value 1"));
Assert.AreEqual ((float)5656.2853,
config.GetFloat ("Not Here", (float)5656.2853));
}
[Test]
public void BooleanAlias ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" bool 1 = TrUe");
writer.WriteLine (" bool 2 = FalSe");
writer.WriteLine (" bool 3 = ON");
writer.WriteLine (" bool 4 = OfF");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
config.Alias.AddAlias ("true", true);
config.Alias.AddAlias ("false", false);
config.Alias.AddAlias ("on", true);
config.Alias.AddAlias ("off", false);
Assert.IsTrue (config.GetBoolean ("bool 1"));
Assert.IsFalse (config.GetBoolean ("bool 2"));
Assert.IsTrue (config.GetBoolean ("bool 3"));
Assert.IsFalse (config.GetBoolean ("bool 4"));
Assert.IsTrue (config.GetBoolean ("Not Here", true));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void BooleanAliasNoDefault ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" bool 1 = TrUe");
writer.WriteLine (" bool 2 = FalSe");
IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
config.Alias.AddAlias ("true", true);
config.Alias.AddAlias ("false", false);
Assert.IsTrue (config.GetBoolean ("Not Here", true));
Assert.IsFalse (config.GetBoolean ("Not Here Also"));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void NonBooleanParameter ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" bool 1 = not boolean");
IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
config.Alias.AddAlias ("true", true);
config.Alias.AddAlias ("false", false);
Assert.IsTrue (config.GetBoolean ("bool 1"));
}
[Test]
public void GetIntAlias ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" node type = TEXT");
writer.WriteLine (" error code = WARN");
IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ()));
const int WARN = 100, ERROR = 200;
IConfig config = source.Configs["Test"];
config.Alias.AddAlias ("error code", "waRn", WARN);
config.Alias.AddAlias ("error code", "eRRor", ERROR);
config.Alias.AddAlias ("node type", new System.Xml.XmlNodeType ());
config.Alias.AddAlias ("default", "age", 31);
Assert.AreEqual (WARN, config.GetInt ("error code", true));
Assert.AreEqual ((int)System.Xml.XmlNodeType.Text,
config.GetInt ("node type", true));
Assert.AreEqual (31, config.GetInt ("default", 31, true));
}
[Test]
public void GetKeys ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" bool 1 = TrUe");
writer.WriteLine (" bool 2 = FalSe");
writer.WriteLine (" bool 3 = ON");
IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
Assert.AreEqual (3, config.GetKeys ().Length);
Assert.AreEqual ("bool 1", config.GetKeys ()[0]);
Assert.AreEqual ("bool 2", config.GetKeys ()[1]);
Assert.AreEqual ("bool 3", config.GetKeys ()[2]);
}
[Test]
public void GetValues ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" key 1 = value 1");
writer.WriteLine (" key 2 = value 2");
writer.WriteLine (" key 3 = value 3");
IniConfigSource source =
new IniConfigSource (new StringReader (writer.ToString ()));
IConfig config = source.Configs["Test"];
Assert.AreEqual (3, config.GetValues ().Length);
Assert.AreEqual ("value 1", config.GetValues ()[0]);
Assert.AreEqual ("value 2", config.GetValues ()[1]);
Assert.AreEqual ("value 3", config.GetValues ()[2]);
}
[Test]
public void SetAndRemove ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Pets]");
writer.WriteLine (" cat = muffy");
writer.WriteLine (" dog = rover");
writer.WriteLine (" bird = tweety");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["Pets"];
Assert.AreEqual ("Pets", config.Name);
Assert.AreEqual (3, config.GetKeys ().Length);
config.Set ("snake", "cobra");
Assert.AreEqual (4, config.GetKeys ().Length);
// Test removing
Assert.IsNotNull (config.Get ("dog"));
config.Remove ("dog");
Assert.AreEqual (3, config.GetKeys ().Length);
Assert.IsNull (config.Get ("dog"));
Assert.IsNotNull (config.Get ("snake"));
}
[Test]
public void Rename ()
{
IniConfigSource source = new IniConfigSource ();
IConfig config = source.AddConfig ("Pets");
config.Set ("cat", "Muffy");
config.Set ("dog", "Rover");
config.Name = "MyPets";
Assert.AreEqual ("MyPets", config.Name);
Assert.IsNull (source.Configs["Pets"]);
IConfig newConfig = source.Configs["MyPets"];
Assert.AreEqual (config, newConfig);
Assert.AreEqual (2, newConfig.GetKeys ().Length);
}
[Test]
public void Contains ()
{
IniConfigSource source = new IniConfigSource ();
IConfig config = source.AddConfig ("Pets");
config.Set ("cat", "Muffy");
config.Set ("dog", "Rover");
Assert.IsTrue (config.Contains ("cat"));
Assert.IsTrue (config.Contains ("dog"));
config.Remove ("cat");
Assert.IsFalse (config.Contains ("cat"));
Assert.IsTrue (config.Contains ("dog"));
}
[Test]
public void ExpandString ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[web]");
writer.WriteLine (" apache = Apache implements ${protocol}");
writer.WriteLine (" protocol = http");
writer.WriteLine ("[server]");
writer.WriteLine (" domain = ${web|protocol}://nini.sf.net/");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["web"];
Assert.AreEqual ("http", config.Get ("protocol"));
Assert.AreEqual ("Apache implements ${protocol}", config.Get ("apache"));
Assert.AreEqual ("Apache implements http", config.GetExpanded ("apache"));
Assert.AreEqual ("Apache implements ${protocol}", config.Get ("apache"));
config = source.Configs["server"];
Assert.AreEqual ("http://nini.sf.net/", config.GetExpanded ("domain"));
Assert.AreEqual ("${web|protocol}://nini.sf.net/", config.Get ("domain"));
}
[Test]
public void ExpandWithEndBracket ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[web]");
writer.WriteLine (" apache = } Apache implements ${protocol}");
writer.WriteLine (" protocol = http");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["web"];
Assert.AreEqual ("} Apache implements http", config.GetExpanded ("apache"));
}
[Test]
public void ExpandBackToBack ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[web]");
writer.WriteLine (" apache = Protocol: ${protocol}${version}");
writer.WriteLine (" protocol = http");
writer.WriteLine (" version = 1.1");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["web"];
Assert.AreEqual ("Protocol: http1.1", config.GetExpanded ("apache"));
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using EnsureThat;
using EnsureThat.Internals;
using Xunit;
namespace UnitTests
{
using System.Collections.Generic;
public class EnsureComparableParamTests : UnitTestBase
{
[Fact]
public void IsLt_When_value_is_gt_than_limit_It_throws_ArgumentException()
{
var spec = When_value_is_gt_than_limit();
AssertIsLtScenario(spec.Value, spec.Limit,
() => Ensure.Comparable.IsLt(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsLt(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsLt(spec.Limit));
}
[Fact]
public void IsLt_When_value_is_equal_to_limit_It_throws_ArgumentException()
{
var spec = When_value_is_equal_to_limit();
AssertIsLtScenario(spec.Value, spec.Limit,
() => Ensure.Comparable.IsLt(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsLt(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsLt(spec.Limit));
}
[Fact]
public void IsLt_When_value_is_lt_than_limit_It_should_not_throw()
{
var spec = When_value_is_lt_than_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsLt(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsLt(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsLt(spec.Limit));
}
[Fact]
public void IsLt_Comparer_arg_is_used()
{
// Sp < sa when case sensitive (S < s), but Sp > sa case insensitive (p > a)
var Sp = "Sp";
var sa = "sa";
IComparer<string> ordinal = StringComparer.Ordinal;
ShouldNotThrow(
() => Ensure.Comparable.IsLt(Sp, sa, ordinal, ParamName),
() => EnsureArg.IsLt(Sp, sa, ordinal, ParamName),
() => Ensure.String.IsLt(Sp, sa, StringComparison.Ordinal, ParamName),
() => Ensure.That(Sp, ParamName).IsLt(sa, StringComparison.Ordinal));
// Validate with comparer (order is reversed)
IComparer<string> ignoreCase = StringComparer.OrdinalIgnoreCase;
ShouldNotThrow(
() => Ensure.Comparable.IsLt(sa, Sp, ignoreCase, ParamName),
() => EnsureArg.IsLt(sa, Sp, ignoreCase, ParamName),
() => Ensure.String.IsLt(sa, Sp, StringComparison.OrdinalIgnoreCase, ParamName),
() => Ensure.That(sa, ParamName).IsLt(Sp, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void IsGt_When_value_is_equal_to_limit_It_throws_ArgumentException()
{
var spec = When_value_is_equal_to_limit();
AssertIsGtScenario(spec.Value, spec.Limit,
() => Ensure.Comparable.IsGt(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsGt(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsGt(spec.Limit));
}
[Fact]
public void IsGt_When_value_is_lt_than_limit_It_throws_ArgumentException()
{
var spec = When_value_is_lt_than_limit();
AssertIsGtScenario(spec.Value, spec.Limit,
() => Ensure.Comparable.IsGt(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsGt(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsGt(spec.Limit));
}
[Fact]
public void IsGt_When_value_is_gt_than_limit_It_should_not_throw()
{
var spec = When_value_is_gt_than_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsGt(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsGt(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsGt(spec.Limit));
}
[Fact]
public void IsGt_Comparer_arg_is_used()
{
// sa > Sp when case sensitive (s > S), but sa < Sp case insensitive (a < p)
var sa = "sa";
var Sp = "Sp";
IComparer<string> ordinal = StringComparer.Ordinal;
ShouldNotThrow(
() => Ensure.Comparable.IsGt(sa, Sp, ordinal, ParamName),
() => EnsureArg.IsGt(sa, Sp, ordinal, ParamName),
() => Ensure.String.IsGt(sa, Sp, StringComparison.Ordinal, ParamName),
() => Ensure.That(sa, ParamName).IsGt(Sp, StringComparison.Ordinal));
// Validate with comparer (order is reversed)
IComparer<string> ignoreCase = StringComparer.OrdinalIgnoreCase;
ShouldNotThrow(
() => Ensure.Comparable.IsGt(Sp, sa, ignoreCase, ParamName),
() => EnsureArg.IsGt(Sp, sa, ignoreCase, ParamName),
() => Ensure.String.IsGt(Sp, sa, StringComparison.OrdinalIgnoreCase, ParamName),
() => Ensure.That(Sp, ParamName).IsGt(sa, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void IsLte_When_value_is_equal_to_limit_It_should_not_throw()
{
var spec = When_value_is_equal_to_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsLte(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsLte(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsLte(spec.Limit));
}
[Fact]
public void IsLte_When_value_is_gt_than_limit_It_throws_ArgumentException()
{
var spec = When_value_is_gt_than_limit();
AssertIsLteScenario(spec.Value, spec.Limit,
() => Ensure.Comparable.IsLte(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsLte(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsLte(spec.Limit));
}
[Fact]
public void IsLte_When_value_is_lt_than_limit_It_should_not_throw()
{
var spec = When_value_is_lt_than_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsLte(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsLte(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsLte(spec.Limit));
}
[Fact]
public void IsLte_Comparer_arg_is_used()
{
// sa > Sa when case sensitive, but sa == Sp when case insensitive
var sa = "sa";
var Sa = "Sa";
IComparer<string> ordinal = StringComparer.Ordinal;
AssertIsLteScenario(sa, Sa,
() => Ensure.Comparable.IsLte(sa, Sa, ordinal, ParamName),
() => EnsureArg.IsLte(sa, Sa, ordinal, ParamName),
() => Ensure.String.IsLte(sa, Sa, StringComparison.Ordinal, ParamName),
() => Ensure.That(sa, ParamName).IsLte(Sa, StringComparison.Ordinal));
// Validate with comparer (order is reversed)
IComparer<string> ignoreCase = StringComparer.OrdinalIgnoreCase;
ShouldNotThrow(
() => Ensure.Comparable.IsLte(sa, Sa, ignoreCase, ParamName),
() => EnsureArg.IsLte(sa, Sa, ignoreCase, ParamName),
() => Ensure.String.IsLte(sa, Sa, StringComparison.OrdinalIgnoreCase, ParamName),
() => Ensure.That(sa, ParamName).IsLte(Sa, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void IsGte_When_value_is_equal_to_limit_It_should_not_throw()
{
var spec = When_value_is_equal_to_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsGte(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsGte(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsGte(spec.Limit));
}
[Fact]
public void IsGte_When_value_is_lt_than_limit_It_throws_ArgumentException()
{
var spec = When_value_is_lt_than_limit();
AssertIsGteScenario(spec.Value, spec.Limit,
() => Ensure.Comparable.IsGte(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsGte(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsGte(spec.Limit));
}
[Fact]
public void IsGte_When_value_is_gt_than_limit_It_should_not_throw()
{
var spec = When_value_is_gt_than_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsGte(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsGte(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsGte(spec.Limit));
}
[Fact]
public void IsGte_Comparer_arg_is_used()
{
// Sa < sa when case sensitive, but Sa == sa when case insensitive
var Sa = "Sa";
var sa = "sa";
IComparer<string> ordinal = StringComparer.Ordinal;
AssertIsGteScenario(Sa, sa,
() => Ensure.Comparable.IsGte(Sa, sa, ordinal, ParamName),
() => EnsureArg.IsGte(Sa, sa, ordinal, ParamName),
() => Ensure.String.IsGte(Sa, sa, StringComparison.Ordinal, ParamName),
() => Ensure.That(Sa, ParamName).IsGte(sa, StringComparison.Ordinal));
// Validate with comparer (order is reversed)
IComparer<string> ignoreCase = StringComparer.OrdinalIgnoreCase;
ShouldNotThrow(
() => Ensure.Comparable.IsGte(Sa, sa, ignoreCase, ParamName),
() => EnsureArg.IsGte(Sa, sa, ignoreCase, ParamName),
() => Ensure.String.IsGte(Sa, sa, StringComparison.OrdinalIgnoreCase, ParamName),
() => Ensure.That(Sa, ParamName).IsGte(sa, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void IsInRange_When_value_is_lower_limit_It_should_not_throw()
{
var spec = When_value_is_lower_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => EnsureArg.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsInRange(spec.LowerLimit, spec.UpperLimit));
}
[Fact]
public void IsInRange_When_value_is_upper_limit_It_should_not_throw()
{
var spec = When_value_is_upper_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => EnsureArg.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsInRange(spec.LowerLimit, spec.UpperLimit));
}
[Fact]
public void IsInRange_When_value_is_between_limits_It_should_not_throw()
{
var spec = When_value_is_between_limits();
ShouldNotThrow(
() => Ensure.Comparable.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => EnsureArg.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsInRange(spec.LowerLimit, spec.UpperLimit));
}
[Fact]
public void IsInRange_When_value_is_lower_than_lower_limit_It_throws_ArgumentException()
{
var spec = When_value_is_lower_than_lower_limit();
AssertIsRangeToLowScenario(spec.Value, spec.LowerLimit,
() => Ensure.Comparable.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => EnsureArg.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsInRange(spec.LowerLimit, spec.UpperLimit));
}
[Fact]
public void IsInRange_When_value_is_greater_than_upper_limit_It_throws_ArgumentException()
{
var spec = When_value_is_greater_than_upper_limit();
AssertIsRangeToHighScenario(spec.Value, spec.UpperLimit,
() => Ensure.Comparable.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => EnsureArg.IsInRange(spec.Value, spec.LowerLimit, spec.UpperLimit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsInRange(spec.LowerLimit, spec.UpperLimit));
}
[Fact]
public void IsInRange_Comparer_arg_is_used()
{
// sa < Sb < sc when case sensitive, but not when case insensitive
var sa = "sa";
var Sb = "Sb";
var sc = "sc";
IComparer<string> ordinal = StringComparer.Ordinal;
AssertIsRangeToLowScenario(Sb, sa,
() => Ensure.Comparable.IsInRange(Sb, sa, sc, ordinal, ParamName),
() => EnsureArg.IsInRange(Sb, sa, sc, ordinal, ParamName),
() => Ensure.String.IsInRange(Sb, sa, sc, StringComparison.Ordinal, ParamName),
() => Ensure.That(Sb, ParamName).IsInRange(sa, sc, StringComparison.Ordinal));
// Validate with comparer (order is reversed)
IComparer<string> ignoreCase = StringComparer.OrdinalIgnoreCase;
ShouldNotThrow(
() => Ensure.Comparable.IsInRange(Sb, sa, sc, ignoreCase, ParamName),
() => EnsureArg.IsInRange(Sb, sa, sc, ignoreCase, ParamName),
() => Ensure.String.IsInRange(Sb, sa, sc, StringComparison.OrdinalIgnoreCase, ParamName),
() => Ensure.That(Sb, ParamName).IsInRange(sa, sc, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void Is_When_same_values_It_should_not_throw()
{
var spec = When_value_is_equal_to_limit();
ShouldNotThrow(
() => Ensure.Comparable.Is(spec.Value, spec.Limit, ParamName),
() => EnsureArg.Is(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).Is(spec.Limit));
}
[Fact]
public void Is_When_different_values_It_throws_ArgumentException()
{
var spec = When_value_is_lt_than_limit();
ShouldThrow<ArgumentException>(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_Is_Failed, spec.Value, spec.Limit),
() => Ensure.Comparable.Is(spec.Value, spec.Limit, ParamName),
() => EnsureArg.Is(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).Is(spec.Limit));
}
[Fact]
public void Is_Comparer_arg_is_used()
{
// sa < Sb < sc when case sensitive, but not when case insensitive
var sa = "sa";
var Sa = "Sa";
IComparer<string> ordinal = StringComparer.Ordinal;
ShouldThrow<ArgumentException>(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_Is_Failed, sa, Sa),
() => Ensure.Comparable.Is(sa, Sa, ordinal, ParamName),
() => EnsureArg.Is(sa, Sa, ordinal, ParamName),
() => Ensure.String.IsEqualTo(sa, Sa, StringComparison.Ordinal, ParamName),
() => Ensure.That(sa, ParamName).IsEqualTo(Sa, StringComparison.Ordinal));
// Validate with comparer (order is reversed)
IComparer<string> ignoreCase = StringComparer.OrdinalIgnoreCase;
ShouldNotThrow(
() => Ensure.Comparable.Is(sa, Sa, ignoreCase, ParamName),
() => EnsureArg.Is(sa, Sa, ignoreCase, ParamName),
() => Ensure.String.IsEqualTo(sa, Sa, StringComparison.OrdinalIgnoreCase, ParamName),
() => Ensure.That(sa, ParamName).IsEqualTo(Sa, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void IsNot_When_different_values_It_should_not_throw()
{
var spec = When_value_is_lt_than_limit();
ShouldNotThrow(
() => Ensure.Comparable.IsNot(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsNot(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsNot(spec.Limit));
}
[Fact]
public void IsNot_When_same_values_It_throws_ArgumentException()
{
var spec = When_value_is_equal_to_limit();
ShouldThrow<ArgumentException>(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNot_Failed, spec.Value, spec.Limit),
() => Ensure.Comparable.IsNot(spec.Value, spec.Limit, ParamName),
() => EnsureArg.IsNot(spec.Value, spec.Limit, ParamName),
() => Ensure.That(spec.Value, ParamName).IsNot(spec.Limit));
}
[Fact]
public void IsNot_Comparer_arg_is_used()
{
// sa < Sb < sc when case sensitive, but not when case insensitive
var sa = "sa";
var Sa = "Sa";
IComparer<string> ordinal = StringComparer.Ordinal;
ShouldNotThrow(
() => Ensure.Comparable.IsNot(sa, Sa, ordinal, ParamName),
() => EnsureArg.IsNot(sa, Sa, ordinal, ParamName),
() => Ensure.String.IsNotEqualTo(sa, Sa, StringComparison.Ordinal, ParamName),
() => Ensure.That(sa, ParamName).IsNotEqualTo(Sa, StringComparison.Ordinal));
// Validate with comparer (order is reversed)
IComparer<string> ignoreCase = StringComparer.OrdinalIgnoreCase;
ShouldThrow<ArgumentException>(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNot_Failed, sa, Sa),
() => Ensure.Comparable.IsNot(sa, Sa, ignoreCase, ParamName),
() => EnsureArg.IsNot(sa, Sa, ignoreCase, ParamName),
() => Ensure.String.IsNotEqualTo(sa, Sa, StringComparison.OrdinalIgnoreCase, ParamName),
() => Ensure.That(sa, ParamName).IsNotEqualTo(Sa, StringComparison.OrdinalIgnoreCase));
}
private CompareParamTestSpec When_value_is_gt_than_limit() => new CompareParamTestSpec
{
Limit = 42,
Value = 43
};
private CompareParamTestSpec When_value_is_equal_to_limit()
{
return new CompareParamTestSpec { Limit = 42, Value = 42 };
}
private CompareParamTestSpec When_value_is_lt_than_limit()
{
return new CompareParamTestSpec { Limit = 42, Value = 41 };
}
private CompareParamTestSpec When_value_is_lower_limit()
{
return new CompareParamTestSpec { LowerLimit = 42, UpperLimit = 50, Value = 42 };
}
private CompareParamTestSpec When_value_is_upper_limit()
{
return new CompareParamTestSpec { LowerLimit = 42, UpperLimit = 50, Value = 50 };
}
private CompareParamTestSpec When_value_is_between_limits()
{
return new CompareParamTestSpec { LowerLimit = 40, UpperLimit = 50, Value = 45 };
}
private CompareParamTestSpec When_value_is_lower_than_lower_limit()
{
return new CompareParamTestSpec { LowerLimit = 40, UpperLimit = 50, Value = 39 };
}
private CompareParamTestSpec When_value_is_greater_than_upper_limit()
{
return new CompareParamTestSpec { LowerLimit = 40, UpperLimit = 50, Value = 51 };
}
private static void AssertIsLtScenario<T>(T value, T limit, params Action[] actions)
=> ShouldThrow<ArgumentOutOfRangeException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotLt, value, limit), actions);
private static void AssertIsGtScenario<T>(T value, T limit, params Action[] actions)
=> ShouldThrow<ArgumentOutOfRangeException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotGt, value, limit), actions);
private static void AssertIsLteScenario<T>(T value, T limit, params Action[] actions)
=> ShouldThrow<ArgumentOutOfRangeException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotLte, value, limit), actions);
private static void AssertIsGteScenario<T>(T value, T limit, params Action[] actions)
=> ShouldThrow<ArgumentOutOfRangeException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotGte, value, limit), actions);
private static void AssertIsRangeToLowScenario<T>(T value, T limit, params Action[] actions)
=> ShouldThrow<ArgumentOutOfRangeException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotInRange_ToLow, value, limit), actions);
private static void AssertIsRangeToHighScenario<T>(T value, T limit, params Action[] actions)
=> ShouldThrow<ArgumentOutOfRangeException>(string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotInRange_ToHigh, value, limit), actions);
[SuppressMessage("Design", "CA1036:Override methods on comparable types")]
public class CustomComparable : IComparable<CustomComparable>
{
private readonly int _value;
public CustomComparable(int value)
{
_value = value;
}
public int CompareTo(CustomComparable other)
{
var x = _value;
var y = other._value;
return x.CompareTo(y);
}
public static implicit operator CustomComparable(int value) => new CustomComparable(value);
public override string ToString() => _value.ToString(DefaultFormatProvider.Strings);
}
public class CompareParamTestSpec
{
public CustomComparable Limit { get; set; }
public CustomComparable LowerLimit { get; set; }
public CustomComparable UpperLimit { get; set; }
public CustomComparable Value { get; set; }
}
}
}
| |
// 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\GameSession.h:27
namespace UnrealEngine
{
[ManageType("ManageGameSession")]
public partial class ManageGameSession : AGameSession, IManageWrapper
{
public ManageGameSession(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_DumpSessionState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_HandleMatchHasEnded(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_HandleMatchHasStarted(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_HandleMatchIsWaitingToStart(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostSeamlessTravel(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_RegisterServer(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_RegisterServerFailed(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_Restart(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_ReturnToMainMenuHost(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_ClearCrossLevelReferences(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_Destroyed(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_ForceNetRelevant(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_ForceNetUpdate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_GatherCurrentMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_K2_DestroyActor(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_LifeSpanExpired(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_MarkComponentsAsPendingKill(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_NotifyActorBeginCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_NotifyActorEndCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_OnRep_AttachmentReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_OnRep_Instigator(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_OnRep_Owner(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_OnRep_ReplicatedMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_OnRep_ReplicateMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_OutsideWorldBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostActorCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostNetInit(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostNetReceiveLocationAndRotation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostNetReceivePhysicState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostNetReceiveRole(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostUnregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PreInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PreRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_RegisterActorTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_RegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_ReregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_RerunConstructionScripts(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_Reset(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_RewindForReplay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_SetActorHiddenInGame(IntPtr self, bool bNewHidden);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_SetLifeSpan(IntPtr self, float inLifespan);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_SetReplicateMovement(IntPtr self, bool bInReplicateMovement);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_TearOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_TeleportSucceeded(IntPtr self, bool bIsATest);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_Tick(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_TornOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_UnregisterAllComponents(IntPtr self, bool bForReregister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameSession_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Dump session info to log for debugging.
/// </summary>
public override void DumpSessionState()
=> E__Supper__AGameSession_DumpSessionState(this);
/// <summary>
/// Handle when the match has completed
/// </summary>
public override void HandleMatchHasEnded()
=> E__Supper__AGameSession_HandleMatchHasEnded(this);
/// <summary>
/// Handle when the match has started
/// </summary>
public override void HandleMatchHasStarted()
=> E__Supper__AGameSession_HandleMatchHasStarted(this);
/// <summary>
/// Handle when the match enters waiting to start
/// </summary>
public override void HandleMatchIsWaitingToStart()
=> E__Supper__AGameSession_HandleMatchIsWaitingToStart(this);
/// <summary>
/// called after a seamless level transition has been completed on the *new* GameMode
/// <para>used to reinitialize players already in the game as they won't have *Login() called on them </para>
/// </summary>
public override void PostSeamlessTravel()
=> E__Supper__AGameSession_PostSeamlessTravel(this);
/// <summary>
/// Allow a dedicated server a chance to register itself with an online service
/// </summary>
public override void RegisterServer()
=> E__Supper__AGameSession_RegisterServer(this);
/// <summary>
/// Callback when autologin was expected but failed
/// </summary>
public override void RegisterServerFailed()
=> E__Supper__AGameSession_RegisterServerFailed(this);
/// <summary>
/// Restart the session
/// </summary>
public override void Restart()
=> E__Supper__AGameSession_Restart(this);
/// <summary>
/// Gracefully tell all clients then local players to return to lobby
/// </summary>
public override void ReturnToMainMenuHost()
=> E__Supper__AGameSession_ReturnToMainMenuHost(this);
/// <summary>
/// Overridable native event for when play begins for this actor.
/// </summary>
protected override void BeginPlay()
=> E__Supper__AGameSession_BeginPlay(this);
/// <summary>
/// Do anything needed to clear out cross level references; Called from ULevel::PreSave
/// </summary>
public override void ClearCrossLevelReferences()
=> E__Supper__AGameSession_ClearCrossLevelReferences(this);
/// <summary>
/// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending
/// </summary>
public override void Destroyed()
=> E__Supper__AGameSession_Destroyed(this);
/// <summary>
/// Forces this actor to be net relevant if it is not already by default
/// </summary>
public override void ForceNetRelevant()
=> E__Supper__AGameSession_ForceNetRelevant(this);
/// <summary>
/// Force actor to be updated to clients/demo net drivers
/// </summary>
public override void ForceNetUpdate()
=> E__Supper__AGameSession_ForceNetUpdate(this);
/// <summary>
/// Fills ReplicatedMovement property
/// </summary>
public override void GatherCurrentMovement()
=> E__Supper__AGameSession_GatherCurrentMovement(this);
/// <summary>
/// Invalidates anything produced by the last lighting build.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bTranslationOnly)
=> E__Supper__AGameSession_InvalidateLightingCacheDetailed(this, bTranslationOnly);
/// <summary>
/// Destroy the actor
/// </summary>
public override void DestroyActor()
=> E__Supper__AGameSession_K2_DestroyActor(this);
/// <summary>
/// Called when the lifespan of an actor expires (if he has one).
/// </summary>
public override void LifeSpanExpired()
=> E__Supper__AGameSession_LifeSpanExpired(this);
/// <summary>
/// Called to mark all components as pending kill when the actor is being destroyed
/// </summary>
public override void MarkComponentsAsPendingKill()
=> E__Supper__AGameSession_MarkComponentsAsPendingKill(this);
/// <summary>
/// Event when this actor has the mouse moved over it with the clickable interface.
/// </summary>
public override void NotifyActorBeginCursorOver()
=> E__Supper__AGameSession_NotifyActorBeginCursorOver(this);
/// <summary>
/// Event when this actor has the mouse moved off of it with the clickable interface.
/// </summary>
public override void NotifyActorEndCursorOver()
=> E__Supper__AGameSession_NotifyActorEndCursorOver(this);
public override void OnRep_AttachmentReplication()
=> E__Supper__AGameSession_OnRep_AttachmentReplication(this);
public override void OnRep_Instigator()
=> E__Supper__AGameSession_OnRep_Instigator(this);
protected override void OnRep_Owner()
=> E__Supper__AGameSession_OnRep_Owner(this);
public override void OnRep_ReplicatedMovement()
=> E__Supper__AGameSession_OnRep_ReplicatedMovement(this);
public override void OnRep_ReplicateMovement()
=> E__Supper__AGameSession_OnRep_ReplicateMovement(this);
/// <summary>
/// Called on the client when the replication paused value is changed
/// </summary>
public override void OnReplicationPausedChanged(bool bIsReplicationPaused)
=> E__Supper__AGameSession_OnReplicationPausedChanged(this, bIsReplicationPaused);
/// <summary>
/// Called when the Actor is outside the hard limit on world bounds
/// </summary>
public override void OutsideWorldBounds()
=> E__Supper__AGameSession_OutsideWorldBounds(this);
/// <summary>
/// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay
/// <para>For actors with a root component, the location and rotation will have already been set. </para>
/// This is called before calling construction scripts, but after native components have been created
/// </summary>
public override void PostActorCreated()
=> E__Supper__AGameSession_PostActorCreated(this);
/// <summary>
/// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay
/// </summary>
public override void PostInitializeComponents()
=> E__Supper__AGameSession_PostInitializeComponents(this);
/// <summary>
/// Always called immediately after spawning and reading in replicated properties
/// </summary>
public override void PostNetInit()
=> E__Supper__AGameSession_PostNetInit(this);
/// <summary>
/// Update location and rotation from ReplicatedMovement. Not called for simulated physics!
/// </summary>
public override void PostNetReceiveLocationAndRotation()
=> E__Supper__AGameSession_PostNetReceiveLocationAndRotation(this);
/// <summary>
/// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity()
/// </summary>
public override void PostNetReceivePhysicState()
=> E__Supper__AGameSession_PostNetReceivePhysicState(this);
/// <summary>
/// Always called immediately after a new Role is received from the remote.
/// </summary>
public override void PostNetReceiveRole()
=> E__Supper__AGameSession_PostNetReceiveRole(this);
/// <summary>
/// Called after all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PostRegisterAllComponents()
=> E__Supper__AGameSession_PostRegisterAllComponents(this);
/// <summary>
/// Called after all currently registered components are cleared
/// </summary>
public override void PostUnregisterAllComponents()
=> E__Supper__AGameSession_PostUnregisterAllComponents(this);
/// <summary>
/// Called right before components are initialized, only called during gameplay
/// </summary>
public override void PreInitializeComponents()
=> E__Supper__AGameSession_PreInitializeComponents(this);
/// <summary>
/// Called before all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PreRegisterAllComponents()
=> E__Supper__AGameSession_PreRegisterAllComponents(this);
/// <summary>
/// Calls PrestreamTextures() for all the actor's meshcomponents.
/// </summary>
/// <param name="seconds">Number of seconds to force all mip-levels to be resident</param>
/// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param>
/// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param>
public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups)
=> E__Supper__AGameSession_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups);
/// <summary>
/// Virtual call chain to register all tick functions for the actor class hierarchy
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterActorTickFunctions(bool bRegister)
=> E__Supper__AGameSession_RegisterActorTickFunctions(this, bRegister);
/// <summary>
/// Ensure that all the components in the Components array are registered
/// </summary>
public override void RegisterAllComponents()
=> E__Supper__AGameSession_RegisterAllComponents(this);
/// <summary>
/// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty.
/// </summary>
public override void ReregisterAllComponents()
=> E__Supper__AGameSession_ReregisterAllComponents(this);
/// <summary>
/// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location.
/// </summary>
public override void RerunConstructionScripts()
=> E__Supper__AGameSession_RerunConstructionScripts(this);
/// <summary>
/// Reset actor to initial state - used when restarting level without reloading.
/// </summary>
public override void Reset()
=> E__Supper__AGameSession_Reset(this);
/// <summary>
/// Called on the actor before checkpoint data is applied during a replay.
/// <para>Only called if bReplayRewindable is set. </para>
/// </summary>
public override void RewindForReplay()
=> E__Supper__AGameSession_RewindForReplay(this);
/// <summary>
/// Sets the actor to be hidden in the game
/// </summary>
/// <param name="bNewHidden">Whether or not to hide the actor and all its components</param>
public override void SetActorHiddenInGame(bool bNewHidden)
=> E__Supper__AGameSession_SetActorHiddenInGame(this, bNewHidden);
/// <summary>
/// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed.
/// </summary>
public override void SetLifeSpan(float inLifespan)
=> E__Supper__AGameSession_SetLifeSpan(this, inLifespan);
/// <summary>
/// Set whether this actor's movement replicates to network clients.
/// </summary>
/// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param>
public override void SetReplicateMovement(bool bInReplicateMovement)
=> E__Supper__AGameSession_SetReplicateMovement(this, bInReplicateMovement);
/// <summary>
/// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true.
/// </summary>
public override void TearOff()
=> E__Supper__AGameSession_TearOff(this);
/// <summary>
/// Called from TeleportTo() when teleport succeeds
/// </summary>
public override void TeleportSucceeded(bool bIsATest)
=> E__Supper__AGameSession_TeleportSucceeded(this, bIsATest);
/// <summary>
/// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame.
/// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para>
/// </summary>
/// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param>
public override void Tick(float deltaSeconds)
=> E__Supper__AGameSession_Tick(this, deltaSeconds);
/// <summary>
/// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients.
/// <para>@see bTearOff </para>
/// </summary>
public override void TornOff()
=> E__Supper__AGameSession_TornOff(this);
/// <summary>
/// Unregister all currently registered components
/// </summary>
/// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param>
public override void UnregisterAllComponents(bool bForReregister)
=> E__Supper__AGameSession_UnregisterAllComponents(this, bForReregister);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__AGameSession_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__AGameSession_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__AGameSession_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__AGameSession_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__AGameSession_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__AGameSession_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__AGameSession_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__AGameSession_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__AGameSession_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__AGameSession_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__AGameSession_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__AGameSession_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__AGameSession_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__AGameSession_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__AGameSession_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageGameSession self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageGameSession(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageGameSession>(PtrDesc);
}
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Codecs
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Lucene.Net.Util.BytesRef;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = Lucene.Net.Index.DocsEnum;
using IndexOptions = Lucene.Net.Index.IndexOptions;
using FieldInfo = Lucene.Net.Index.FieldInfo; // javadocs
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using MergeState = Lucene.Net.Index.MergeState;
using MultiDocsAndPositionsEnum = Lucene.Net.Index.MultiDocsAndPositionsEnum;
using MultiDocsEnum = Lucene.Net.Index.MultiDocsEnum;
using TermsEnum = Lucene.Net.Index.TermsEnum;
/// <summary>
/// Abstract API that consumes terms for an individual field.
/// <para/>
/// The lifecycle is:
/// <list type="number">
/// <item><description>TermsConsumer is returned for each field
/// by <see cref="FieldsConsumer.AddField(FieldInfo)"/>.</description></item>
/// <item><description>TermsConsumer returns a <see cref="PostingsConsumer"/> for
/// each term in <see cref="StartTerm(BytesRef)"/>.</description></item>
/// <item><description>When the producer (e.g. IndexWriter)
/// is done adding documents for the term, it calls
/// <see cref="FinishTerm(BytesRef, TermStats)"/>, passing in
/// the accumulated term statistics.</description></item>
/// <item><description>Producer calls <see cref="Finish(long, long, int)"/> with
/// the accumulated collection statistics when it is finished
/// adding terms to the field.</description></item>
/// </list>
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class TermsConsumer
{
/// <summary>
/// Sole constructor. (For invocation by subclass
/// constructors, typically implicit.)
/// </summary>
protected internal TermsConsumer()
{
}
/// <summary>
/// Starts a new term in this field; this may be called
/// with no corresponding call to finish if the term had
/// no docs.
/// </summary>
public abstract PostingsConsumer StartTerm(BytesRef text);
/// <summary>
/// Finishes the current term; numDocs must be > 0.
/// <c>stats.TotalTermFreq</c> will be -1 when term
/// frequencies are omitted for the field.
/// </summary>
public abstract void FinishTerm(BytesRef text, TermStats stats);
/// <summary>
/// Called when we are done adding terms to this field.
/// <paramref name="sumTotalTermFreq"/> will be -1 when term
/// frequencies are omitted for the field.
/// </summary>
public abstract void Finish(long sumTotalTermFreq, long sumDocFreq, int docCount);
/// <summary>
/// Gets the <see cref="T:IComparer{BytesRef}"/> used to sort terms
/// before feeding to this API.
/// </summary>
public abstract IComparer<BytesRef> Comparer { get; }
private MappingMultiDocsEnum docsEnum;
private MappingMultiDocsEnum docsAndFreqsEnum;
private MappingMultiDocsAndPositionsEnum postingsEnum;
/// <summary>
/// Default merge impl. </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public virtual void Merge(MergeState mergeState, IndexOptions indexOptions, TermsEnum termsEnum)
{
BytesRef term;
if (Debugging.AssertsEnabled) Debugging.Assert(termsEnum != null);
long sumTotalTermFreq = 0;
long sumDocFreq = 0;
long sumDFsinceLastAbortCheck = 0;
FixedBitSet visitedDocs = new FixedBitSet(mergeState.SegmentInfo.DocCount);
if (indexOptions == IndexOptions.DOCS_ONLY)
{
if (docsEnum == null)
{
docsEnum = new MappingMultiDocsEnum();
}
docsEnum.MergeState = mergeState;
MultiDocsEnum docsEnumIn = null;
while (termsEnum.MoveNext())
{
term = termsEnum.Term;
// We can pass null for liveDocs, because the
// mapping enum will skip the non-live docs:
docsEnumIn = (MultiDocsEnum)termsEnum.Docs(null, docsEnumIn, DocsFlags.NONE);
if (docsEnumIn != null)
{
docsEnum.Reset(docsEnumIn);
PostingsConsumer postingsConsumer = StartTerm(term);
TermStats stats = postingsConsumer.Merge(mergeState, indexOptions, docsEnum, visitedDocs);
if (stats.DocFreq > 0)
{
FinishTerm(term, stats);
sumTotalTermFreq += stats.DocFreq;
sumDFsinceLastAbortCheck += stats.DocFreq;
sumDocFreq += stats.DocFreq;
if (sumDFsinceLastAbortCheck > 60000)
{
mergeState.CheckAbort.Work(sumDFsinceLastAbortCheck / 5.0);
sumDFsinceLastAbortCheck = 0;
}
}
}
}
}
else if (indexOptions == IndexOptions.DOCS_AND_FREQS)
{
if (docsAndFreqsEnum == null)
{
docsAndFreqsEnum = new MappingMultiDocsEnum();
}
docsAndFreqsEnum.MergeState = mergeState;
MultiDocsEnum docsAndFreqsEnumIn = null;
while (termsEnum.MoveNext())
{
term = termsEnum.Term;
// We can pass null for liveDocs, because the
// mapping enum will skip the non-live docs:
docsAndFreqsEnumIn = (MultiDocsEnum)termsEnum.Docs(null, docsAndFreqsEnumIn);
if (Debugging.AssertsEnabled) Debugging.Assert(docsAndFreqsEnumIn != null);
docsAndFreqsEnum.Reset(docsAndFreqsEnumIn);
PostingsConsumer postingsConsumer = StartTerm(term);
TermStats stats = postingsConsumer.Merge(mergeState, indexOptions, docsAndFreqsEnum, visitedDocs);
if (stats.DocFreq > 0)
{
FinishTerm(term, stats);
sumTotalTermFreq += stats.TotalTermFreq;
sumDFsinceLastAbortCheck += stats.DocFreq;
sumDocFreq += stats.DocFreq;
if (sumDFsinceLastAbortCheck > 60000)
{
mergeState.CheckAbort.Work(sumDFsinceLastAbortCheck / 5.0);
sumDFsinceLastAbortCheck = 0;
}
}
}
}
else if (indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS)
{
if (postingsEnum == null)
{
postingsEnum = new MappingMultiDocsAndPositionsEnum();
}
postingsEnum.MergeState = mergeState;
MultiDocsAndPositionsEnum postingsEnumIn = null;
while (termsEnum.MoveNext())
{
term = termsEnum.Term;
// We can pass null for liveDocs, because the
// mapping enum will skip the non-live docs:
postingsEnumIn = (MultiDocsAndPositionsEnum)termsEnum.DocsAndPositions(null, postingsEnumIn, DocsAndPositionsFlags.PAYLOADS);
if (Debugging.AssertsEnabled) Debugging.Assert(postingsEnumIn != null);
postingsEnum.Reset(postingsEnumIn);
PostingsConsumer postingsConsumer = StartTerm(term);
TermStats stats = postingsConsumer.Merge(mergeState, indexOptions, postingsEnum, visitedDocs);
if (stats.DocFreq > 0)
{
FinishTerm(term, stats);
sumTotalTermFreq += stats.TotalTermFreq;
sumDFsinceLastAbortCheck += stats.DocFreq;
sumDocFreq += stats.DocFreq;
if (sumDFsinceLastAbortCheck > 60000)
{
mergeState.CheckAbort.Work(sumDFsinceLastAbortCheck / 5.0);
sumDFsinceLastAbortCheck = 0;
}
}
}
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (postingsEnum == null)
{
postingsEnum = new MappingMultiDocsAndPositionsEnum();
}
postingsEnum.MergeState = mergeState;
MultiDocsAndPositionsEnum postingsEnumIn = null;
while (termsEnum.MoveNext())
{
term = termsEnum.Term;
// We can pass null for liveDocs, because the
// mapping enum will skip the non-live docs:
postingsEnumIn = (MultiDocsAndPositionsEnum)termsEnum.DocsAndPositions(null, postingsEnumIn);
if (Debugging.AssertsEnabled) Debugging.Assert(postingsEnumIn != null);
postingsEnum.Reset(postingsEnumIn);
PostingsConsumer postingsConsumer = StartTerm(term);
TermStats stats = postingsConsumer.Merge(mergeState, indexOptions, postingsEnum, visitedDocs);
if (stats.DocFreq > 0)
{
FinishTerm(term, stats);
sumTotalTermFreq += stats.TotalTermFreq;
sumDFsinceLastAbortCheck += stats.DocFreq;
sumDocFreq += stats.DocFreq;
if (sumDFsinceLastAbortCheck > 60000)
{
mergeState.CheckAbort.Work(sumDFsinceLastAbortCheck / 5.0);
sumDFsinceLastAbortCheck = 0;
}
}
}
}
Finish(indexOptions == IndexOptions.DOCS_ONLY ? -1 : sumTotalTermFreq, sumDocFreq, visitedDocs.Cardinality());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Reflection;
using System.Collections.Generic;
#pragma warning disable 0067
namespace System.Reflection.Tests
{
public class EventInfoMethodTests
{
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler1()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(obj, myhandler);
}
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler2()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublicStatic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
ei.AddEventHandler(null, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(null, myhandler);
}
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler3()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublicVirtual");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(obj, myhandler);
}
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler4()
{
EventInfo ei = GetEventInfo(typeof(SubClass), "EventPublicNew");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
SubClass obj = new SubClass();
ei.AddEventHandler(obj, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(obj, myhandler);
}
// Verify AddEventHandler and RemoveEventHandler for EventInfo
[Fact]
public void VerifyAddRemoveEventHandler5()
{
EventInfo ei = GetEventInfo(typeof(SubClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
SubClass obj = new SubClass();
ei.AddEventHandler(obj, myhandler);
//Try to remove event Handler and Verify that no exception is thrown.
ei.RemoveEventHandler(obj, myhandler);
}
//Negative Tests
// Target null for AddEventHandler
[Fact]
public void VerifyAddRemoveEventHandler6()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
//Target is null and event is not static
// Win8P throws generic Exception
try
{
ei.AddEventHandler(null, myhandler);
Assert.False(true, "Exception expected.");
}
catch (Exception) { }
}
// Target null for RemoveEventHandler
[Fact]
public void VerifyAddRemoveEventHandler7()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
//Target is null and event is not static
// Win8P throws generic Exception
try
{
ei.RemoveEventHandler(null, myhandler);
Assert.False(true, "Exception expected.");
}
catch (Exception) { }
}
// EventHandler null for AddEventHandler
[Fact]
public void VerifyAddRemoveEventHandler8()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
SomeDelegate d1 = new SomeDelegate(SomeHandler);
//Handler is not correct.
Assert.Throws<ArgumentException>(() =>
{
ei.AddEventHandler(obj, d1);
});
}
// EventHandler null for RemoveEventHandler
[Fact]
public void VerifyAddRemoveEventHandler9()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
SomeDelegate d1 = new SomeDelegate(SomeHandler);
//Handler is not correct.
// Win8P throws generic Exception
Assert.Throws<ArgumentException>(() =>
{
ei.RemoveEventHandler(obj, d1);
});
}
// Wrong Target for AddEventHandler
[Fact]
public void VerifyAddRemoveEventHandler10()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
String obj = "hello";
//Target is wrong.
// Win8P throws generic Exception
try
{
ei.AddEventHandler(obj, myhandler);
Assert.False(true, "Exception expected.");
}
catch (Exception) { }
}
// Target null for RemoveEventHandler
[Fact]
public void VerifyAddRemoveEventHandler11()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
EventHandler myhandler = new EventHandler(MyEventHandler);
BaseClass obj = new BaseClass();
ei.AddEventHandler(obj, myhandler);
//Target is wrong.
// Win8P throws generic Exception
try
{
ei.RemoveEventHandler((Object)"hello", myhandler);
Assert.False(true, "Exception expected.");
}
catch (Exception) { }
}
// Test for Equals Method
[Fact]
public void VerifyEqualsMethod1()
{
EventInfo ei1 = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei1);
EventInfo ei2 = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei2);
Assert.Equal(ei1, ei2);
}
// Test for Equals Method
[Fact]
public void VerifyEqualsMethod2()
{
EventInfo ei1 = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei1);
EventInfo ei2 = GetEventInfo(typeof(SubClass), "EventPublic");
Assert.NotNull(ei2);
Assert.NotEqual(ei1, ei2);
}
// Test for Equals Method
[Fact]
public void VerifyEqualsMethod3()
{
EventInfo ei1 = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei1);
EventInfo ei2 = GetEventInfo(typeof(BaseClass), "EventPublicStatic");
Assert.NotNull(ei2);
Assert.NotEqual(ei1, ei2);
}
// Test for GetHashCode Method
[Fact]
public void VerifyGetHashCode()
{
EventInfo ei = GetEventInfo(typeof(BaseClass), "EventPublic");
Assert.NotNull(ei);
int hcode = ei.GetHashCode();
Assert.False(hcode <= 0);
}
//private helper methods
private static EventInfo GetEventInfo(Type t, string eventName)
{
TypeInfo ti = t.GetTypeInfo();
IEnumerator<EventInfo> allevents = ti.DeclaredEvents.GetEnumerator();
EventInfo eventFound = null;
while (allevents.MoveNext())
{
if (eventName.Equals(allevents.Current.Name))
{
eventFound = allevents.Current;
break;
}
}
return eventFound;
}
//Event Handler for Testing
private static void MyEventHandler(Object o, EventArgs e)
{
}
//Event Handler for Testing
private static void SomeHandler(Object o)
{
}
public delegate void SomeDelegate(Object o);
}
// Metadata for Reflection
public class BaseClass
{
public event EventHandler EventPublic; // inherited
public static event EventHandler EventPublicStatic;
public virtual event EventHandler EventPublicVirtual;
}
public class SubClass : BaseClass
{
public new event EventHandler EventPublic; //overrides event
public event EventHandler EventPublicNew; // new event
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using DiscUtils.Streams;
namespace DiscUtils.PowerShell.VirtualDiskProvider
{
internal sealed class OnDemandVirtualDisk : VirtualDisk
{
private DiscFileSystem _fileSystem;
private string _path;
private FileAccess _access;
public OnDemandVirtualDisk(string path, FileAccess access)
{
_path = path;
_access = access;
}
public OnDemandVirtualDisk(DiscFileSystem fileSystem, string path, FileAccess access)
{
_fileSystem = fileSystem;
_path = path;
_access = access;
}
public bool IsValid
{
get
{
try
{
using (VirtualDisk disk = OpenDisk())
{
return disk != null;
}
}
catch (IOException)
{
return false;
}
}
}
public override Geometry Geometry
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return disk.Geometry;
}
}
}
public override VirtualDiskClass DiskClass
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return disk.DiskClass;
}
}
}
public override long Capacity
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return disk.Capacity;
}
}
}
public override VirtualDiskParameters Parameters
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return disk.Parameters;
}
}
}
public override SparseStream Content
{
get { return new StreamWrapper(_fileSystem, _path, _access); }
}
public override IEnumerable<VirtualDiskLayer> Layers
{
get { throw new NotSupportedException("Access to virtual disk layers is not implemented for on-demand disks"); }
}
public override VirtualDiskTypeInfo DiskTypeInfo
{
get {
using (VirtualDisk disk = OpenDisk())
{
return disk.DiskTypeInfo;
}
}
}
public override VirtualDisk CreateDifferencingDisk(DiscFileSystem fileSystem, string path)
{
using (VirtualDisk disk = OpenDisk())
{
return disk.CreateDifferencingDisk(fileSystem, path);
}
}
public override VirtualDisk CreateDifferencingDisk(string path)
{
using (VirtualDisk disk = OpenDisk())
{
return disk.CreateDifferencingDisk(path);
}
}
private VirtualDisk OpenDisk()
{
return VirtualDisk.OpenDisk(_fileSystem, _path, _access);
}
private class StreamWrapper : SparseStream
{
private DiscFileSystem _fileSystem;
private string _path;
private FileAccess _access;
private long _position;
public StreamWrapper(DiscFileSystem fileSystem, string path, FileAccess access)
{
_fileSystem = fileSystem;
_path = path;
_access = access;
}
public override IEnumerable<StreamExtent> Extents
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return new List<StreamExtent>(disk.Content.Extents);
}
}
}
public override bool CanRead
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return disk.Content.CanRead;
}
}
}
public override bool CanSeek
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return disk.Content.CanSeek;
}
}
}
public override bool CanWrite
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return disk.Content.CanWrite;
}
}
}
public override void Flush()
{
}
public override long Length
{
get
{
using (VirtualDisk disk = OpenDisk())
{
return disk.Content.Length;
}
}
}
public override long Position
{
get
{
return _position;
}
set
{
_position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
using (VirtualDisk disk = OpenDisk())
{
disk.Content.Position = _position;
return disk.Content.Read(buffer, offset, count);
}
}
public override long Seek(long offset, SeekOrigin origin)
{
long effectiveOffset = offset;
if (origin == SeekOrigin.Current)
{
effectiveOffset += _position;
}
else if (origin == SeekOrigin.End)
{
effectiveOffset += Length;
}
if (effectiveOffset < 0)
{
throw new IOException("Attempt to move before beginning of disk");
}
else
{
_position = effectiveOffset;
return _position;
}
}
public override void SetLength(long value)
{
using (VirtualDisk disk = OpenDisk())
{
disk.Content.SetLength(value);
}
}
public override void Write(byte[] buffer, int offset, int count)
{
using (VirtualDisk disk = OpenDisk())
{
disk.Content.Position = _position;
disk.Content.Write(buffer, offset, count);
}
}
private VirtualDisk OpenDisk()
{
return VirtualDisk.OpenDisk(_fileSystem, _path, _access);
}
}
}
}
| |
using net.authorize.sample.MobileInappTransactions;
using net.authorize.sample.PaymentTransactions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using net.authorize.sample.CustomerProfiles;
namespace net.authorize.sample
{
//===============================================================================================
//
// NOTE: If you add a new sample update the following methods here:
//
// ShowMethods() - Add the method name
// RunMethod(String methodName) - Update the switch statement to run the method
//
//===============================================================================================
class SampleCode
{
static void Main(string[] args)
{
if (args.Length == 0)
{
SelectMethod();
}
else if (args.Length == 1)
{
RunMethod(args[0]);
return;
}
else
{
ShowUsage();
}
Console.WriteLine("");
Console.Write("Press <Return> to finish ...");
Console.ReadLine();
}
private static void ShowUsage()
{
Console.WriteLine("Usage : SampleCode [CodeSampleName]");
Console.WriteLine("");
Console.WriteLine("Run with no parameter to select a method. Otherwise pass a method name.");
Console.WriteLine("");
Console.WriteLine("Code Sample Names: ");
ShowMethods();
Console.WriteLine("Code Sample Names: ");
}
private static void SelectMethod()
{
Console.WriteLine("Code Sample Names: ");
Console.WriteLine("");
ShowMethods();
Console.WriteLine("");
Console.Write("Type a sample name & then press <Return> : ");
RunMethod(Console.ReadLine());
}
private static void ShowMethods()
{
Console.WriteLine(" ChargeCreditCard");
Console.WriteLine(" AuthorizeCreditCard");
Console.WriteLine(" CapturePreviouslyAuthorizedAmount");
Console.WriteLine(" CaptureFundsAuthorizedThroughAnotherChannel");
Console.WriteLine(" Refund");
Console.WriteLine(" Void");
Console.WriteLine(" DebitBankAccount");
Console.WriteLine(" CreditBankAccount");
Console.WriteLine(" ChargeCustomerProfile");
Console.WriteLine(" ChargeTokenizedCard");
Console.WriteLine(" ChargeEncryptedTrackData");
Console.WriteLine(" ChargeTrackData");
Console.WriteLine(" CreateAnApplePayTransaction");
Console.WriteLine(" CreateAnAndroidPayTransaction");
Console.WriteLine(" CreateAnAcceptTransaction");
Console.WriteLine(" DecryptVisaCheckoutData");
Console.WriteLine(" CreateVisaCheckoutTransaction");
Console.WriteLine(" PayPalVoid");
Console.WriteLine(" PayPalAuthorizeCapture");
Console.WriteLine(" PayPalAuthorizeCaptureContinue");
Console.WriteLine(" PayPalAuthorizeOnly");
Console.WriteLine(" PayPalCredit");
Console.WriteLine(" PayPalGetDetails");
Console.WriteLine(" PayPalPriorAuthorizationCapture");
Console.WriteLine(" CancelSubscription");
Console.WriteLine(" CreateSubscription");
Console.WriteLine(" CreateSubscriptionFromCustomerProfile");
Console.WriteLine(" GetListOfSubscriptions");
Console.WriteLine(" GetSubscriptionStatus");
Console.WriteLine(" GetSubscription");
Console.WriteLine(" GetUnsettledTransactionList");
Console.WriteLine(" UpdateSubscription");
Console.WriteLine(" CreateCustomerProfile");
Console.WriteLine(" CreateCustomerPaymentProfile");
Console.WriteLine(" CreateCustomerShippingAddress");
Console.WriteLine(" DeleteCustomerProfile");
Console.WriteLine(" DeleteCustomerPaymentProfile");
Console.WriteLine(" DeleteCustomerShippingAddress");
Console.WriteLine(" ValidateCustomerPaymentProfile");
Console.WriteLine(" UpdateCustomerShippingAddress");
Console.WriteLine(" UpdateCustomerProfile");
Console.WriteLine(" UpdateCustomerPaymentProfile");
Console.WriteLine(" GetCustomerShippingAddress");
Console.WriteLine(" GetCustomerProfileId");
Console.WriteLine(" GetCustomerProfile");
Console.WriteLine(" GetAcceptCustomerProfilePage");
Console.WriteLine(" GetCustomerPaymentProfile");
Console.WriteLine(" GetCustomerPaymentProfileList");
Console.WriteLine(" DeleteCustomerShippingAddress");
Console.WriteLine(" DeleteCustomerProfile");
Console.WriteLine(" DeleteCustomerPaymentProfile");
Console.WriteLine(" CreateCustomerShippingAddress");
Console.WriteLine(" CreateCustomerProfileFromTransaction");
Console.WriteLine(" GetBatchStatistics");
Console.WriteLine(" GetSettledBatchList");
Console.WriteLine(" GetTransactionDetails");
Console.WriteLine(" GetTransactionList");
Console.WriteLine(" UpdateSplitTenderGroup");
Console.WriteLine(" GetHostedPaymentPage");
}
private static void RunMethod(String methodName)
{
// These are default transaction keys.
// You can create your own keys in seconds by signing up for a sandbox account here: https://developer.authorize.net/sandbox/
const string apiLoginId = "5KP3u95bQpv";
const string transactionKey = "346HZ32z3fP4hTG2";
//Update TransactionID for which you want to run the sample code
const string transactionId = "2249735976";
//Update PayerID for which you want to run the sample code
const string payerId = "M8R9JRNJ3R28Y";
const string customerProfileId = "213213";
const string customerPaymentProfileId = "2132345";
const string shippingAddressId = "1223213";
const decimal amount = 12.34m;
const string subscriptionId = "1223213";
const short day = 45;
const string emailId = "test@test.com";
switch (methodName)
{
case "ValidateCustomerPaymentProfile":
ValidateCustomerPaymentProfile.Run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId);
break;
case "UpdateCustomerShippingAddress":
UpdateCustomerShippingAddress.Run(apiLoginId, transactionKey, customerProfileId, shippingAddressId);
break;
case "UpdateCustomerProfile":
UpdateCustomerProfile.Run(apiLoginId, transactionKey, customerProfileId);
break;
case "UpdateCustomerPaymentProfile":
UpdateCustomerPaymentProfile.Run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId);
break;
case "GetCustomerShippingAddress":
GetCustomerShippingAddress.Run(apiLoginId, transactionKey, customerProfileId, shippingAddressId);
break;
case "GetCustomerProfileIds":
GetCustomerProfileIds.Run(apiLoginId, transactionKey);
break;
case "GetCustomerProfile":
GetCustomerProfile.Run(apiLoginId, transactionKey, customerProfileId);
break;
case "GetAcceptCustomerProfilePage":
GetAcceptCustomerProfilePage.Run(apiLoginId, transactionKey, customerProfileId);
break;
case "GetCustomerPaymentProfile":
GetCustomerPaymentProfile.Run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId);
break;
case "GetCustomerPaymentProfileList":
GetCustomerPaymentProfileList.Run(apiLoginId, transactionKey);
break;
case "DeleteCustomerShippingAddress":
DeleteCustomerShippingAddress.Run(apiLoginId, transactionKey, customerProfileId, shippingAddressId);
break;
case "DeleteCustomerProfile":
DeleteCustomerProfile.Run(apiLoginId, transactionKey, customerProfileId);
break;
case "DeleteCustomerPaymentProfile":
DeleteCustomerPaymentProfile.Run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId);
break;
case "CreateCustomerShippingAddress":
CreateCustomerShippingAddress.Run(apiLoginId, transactionKey, customerProfileId);
break;
case "CreateCustomerProfileFromTransaction":
CreateCustomerProfileFromTransaction.Run(apiLoginId, transactionKey, transactionId);
break;
case "GetTransactionDetails":
GetTransactionDetails.Run(apiLoginId, transactionKey, transactionId);
break;
case "GetTransactionList":
GetTransactionList.Run(apiLoginId, transactionKey);
break;
case "CreateAnApplePayTransaction":
CreateAnApplePayTransaction.Run(apiLoginId, transactionKey, 12.23m);
break;
case "CreateAnAndroidPayTransaction":
CreateAnAndroidPayTransaction.Run(apiLoginId, transactionKey, 12.23m);
break;
case "CreateAnAcceptTransaction":
CreateAnAcceptTransaction.Run(apiLoginId, transactionKey, 12.23m);
break;
case "DecryptVisaCheckoutData":
DecryptVisaCheckoutData.Run(apiLoginId, transactionKey);
break;
case "CreateVisaCheckoutTransaction":
CreateVisaCheckoutTransaction.Run(apiLoginId, transactionKey);
break;
case "ChargeCreditCard":
ChargeCreditCard.Run(apiLoginId, transactionKey, amount);
break;
case "ChargeEncryptedTrackData":
ChargeEncryptedTrackData.Run(apiLoginId, transactionKey, amount);
break;
case "ChargeTrackData":
ChargeTrackData.Run(apiLoginId, transactionKey, amount);
break;
case "CapturePreviouslyAuthorizedAmount":
CapturePreviouslyAuthorizedAmount.Run(apiLoginId, transactionKey, amount, transactionId);
break;
case "CaptureFundsAuthorizedThroughAnotherChannel":
CaptureFundsAuthorizedThroughAnotherChannel.Run(apiLoginId, transactionKey, amount);
break;
case "AuthorizeCreditCard":
AuthorizeCreditCard.Run(apiLoginId, transactionKey, amount);
break;
case "Refund":
RefundTransaction.Run(apiLoginId, transactionKey, amount, transactionId);
break;
case "Void":
VoidTransaction.Run(apiLoginId, transactionKey, transactionId);
break;
case "DebitBankAccount":
DebitBankAccount.Run(apiLoginId, transactionKey, amount);
break;
case "CreditBankAccount":
CreditBankAccount.Run(apiLoginId, transactionKey, transactionId);
break;
case "ChargeCustomerProfile":
ChargeCustomerProfile.Run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId, amount);
break;
case "ChargeTokenizedCard":
ChargeTokenizedCreditCard.Run(apiLoginId, transactionKey);
break;
case "PayPalVoid":
PayPalVoid.Run(apiLoginId, transactionKey, transactionId);
break;
case "PayPalAuthorizeCapture":
PayPalAuthorizeCapture.Run(apiLoginId, transactionKey, amount);
break;
case "PayPalAuthorizeCaptureContinue":
PayPalAuthorizeCaptureContinue.Run(apiLoginId, transactionKey, transactionId, payerId);
break;
case "PayPalAuthorizeOnly":
PayPalAuthorizeOnly.Run(apiLoginId, transactionKey, amount);
break;
case "PayPalAuthorizeOnlyContinue":
PayPalAuthorizeOnlyContinue.Run(apiLoginId, transactionKey, transactionId, payerId);
break;
case "PayPalCredit":
PayPalCredit.Run(apiLoginId, transactionKey, transactionId);
break;
case "PayPalGetDetails":
PayPalGetDetails.Run(apiLoginId, transactionKey, transactionId);
break;
case "PayPalPriorAuthorizationCapture":
PayPalPriorAuthorizationCapture.Run(apiLoginId, transactionKey, transactionId);
break;
case "CancelSubscription":
CancelSubscription.Run(apiLoginId, transactionKey, subscriptionId);
break;
case "CreateSubscription":
CreateSubscription.Run(apiLoginId, transactionKey, day);
break;
case "CreateSubscriptionFromCustomerProfile":
CreateSubscriptionFromCustomerProfile.Run(apiLoginId, transactionKey, day, "12322","232321","123232");
break;
case "GetListOfSubscriptions":
GetListOfSubscriptions.Run(apiLoginId, transactionKey);
break;
case "GetSubscriptionStatus":
GetSubscriptionStatus.Run(apiLoginId, transactionKey, subscriptionId);
break;
case "GetSubscription":
GetSubscription.Run(apiLoginId, transactionKey, subscriptionId);
break;
case "UpdateSubscription":
UpdateSubscription.Run(apiLoginId, transactionKey, subscriptionId);
break;
case "CreateCustomerProfile":
CreateCustomerProfile.Run(apiLoginId, transactionKey, emailId);
break;
case "CreateCustomerPaymentProfile":
CreateCustomerPaymentProfile.Run(apiLoginId, transactionKey, customerProfileId);
break;
case "GetUnsettledTransactionList":
GetUnsettledTransactionList.Run(apiLoginId, transactionKey);
break;
case "GetBatchStatistics":
GetBatchStatistics.Run(apiLoginId, transactionKey);
break;
case "GetSettledBatchList":
GetSettledBatchList.Run(apiLoginId,transactionKey);
break;
case "UpdateSplitTenderGroup":
UpdateSplitTenderGroup.Run(apiLoginId, transactionKey);
break;
case "GetHostedPaymentPage":
GetHostedPaymentPage.Run(apiLoginId, transactionKey, 12.23m);
break;
default:
ShowUsage();
break;
}
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Substance Sample", "Textures", "Samples a procedural material", KeyCode.None, true, 0, int.MaxValue, typeof( SubstanceArchive ), typeof( ProceduralMaterial ) )]
public sealed class SubstanceSamplerNode : PropertyNode
{
private const string GlobalVarDecStr = "uniform sampler2D {0};";
private const string PropertyDecStr = "{0}(\"{0}\", 2D) = \"white\"";
private const string AutoNormalStr = "Auto-Normal";
private const string SubstanceStr = "Substance";
private float TexturePreviewSizeX = 128;
private float TexturePreviewSizeY = 128;
private float PickerPreviewSizeX = 128;
private float PickerPreviewSizeY = 17;
private float PickerPreviewWidthAdjust = 18;
private CacheNodeConnections m_cacheNodeConnections;
[SerializeField]
private int m_firstOutputConnected = 0;
[SerializeField]
private ProceduralMaterial m_proceduralMaterial;
[SerializeField]
private int m_textureCoordSet = 0;
[SerializeField]
private ProceduralOutputType[] m_textureTypes;
[SerializeField]
private bool m_autoNormal = true;
private System.Type m_type;
private List<int> m_outputConns = new List<int>();
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddInputPort( WirePortDataType.FLOAT2, false, "UV" );
AddOutputPort( WirePortDataType.COLOR, Constants.EmptyPortValue );
m_insideSize.Set( TexturePreviewSizeX + PickerPreviewWidthAdjust, TexturePreviewSizeY + PickerPreviewSizeY + 5 );
m_type = typeof( ProceduralMaterial );
m_currentParameterType = PropertyType.Property;
m_freeType = false;
m_freeName = false;
m_autoWrapProperties = true;
m_customPrefix = "Substance Sample ";
m_drawPrecisionUI = false;
m_showPreview = true;
m_selectedLocation = PreviewLocation.TopCenter;
m_cacheNodeConnections = new CacheNodeConnections();
}
public override void OnOutputPortConnected( int portId, int otherNodeId, int otherPortId )
{
base.OnOutputPortConnected( portId, otherNodeId, otherPortId );
m_firstOutputConnected = -1;
}
public override void OnOutputPortDisconnected( int portId )
{
base.OnOutputPortDisconnected( portId );
m_firstOutputConnected = -1;
}
void CalculateFirstOutputConnected()
{
m_outputConns.Clear();
int count = m_outputPorts.Count;
for ( int i = 0; i < count; i++ )
{
if ( m_outputPorts[ i ].IsConnected )
{
if ( m_firstOutputConnected < 0 )
m_firstOutputConnected = i;
m_outputConns.Add( i );
}
}
if ( m_firstOutputConnected < 0 )
m_firstOutputConnected = 0;
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
Rect previewArea = m_remainingBox;
previewArea.width = TexturePreviewSizeX * drawInfo.InvertedZoom;
previewArea.height = TexturePreviewSizeY * drawInfo.InvertedZoom;
previewArea.x += 0.5f * m_remainingBox.width - 0.5f * previewArea.width;
GUI.Box( previewArea, string.Empty, UIUtils.ObjectFieldThumb );
Rect pickerArea = previewArea;
pickerArea.width = PickerPreviewSizeX * drawInfo.InvertedZoom;
pickerArea.height = PickerPreviewSizeY * drawInfo.InvertedZoom;
pickerArea.y += previewArea.height;
Texture[] textures = m_proceduralMaterial != null ? m_proceduralMaterial.GetGeneratedTextures() : null;
if ( textures != null )
{
if ( m_firstOutputConnected < 0 )
{
CalculateFirstOutputConnected();
}
else if ( textures.Length != m_textureTypes.Length )
{
OnNewSubstanceSelected( textures );
}
int texCount = m_outputConns.Count;
previewArea.height /= texCount;
for ( int i = 0; i < texCount; i++ )
{
EditorGUI.DrawPreviewTexture( previewArea, textures[ m_outputConns[ i ] ], null, ScaleMode.ScaleAndCrop );
previewArea.y += previewArea.height;
}
}
EditorGUI.BeginChangeCheck();
m_proceduralMaterial = EditorGUIObjectField( pickerArea, m_proceduralMaterial, m_type, false ) as ProceduralMaterial;
if ( EditorGUI.EndChangeCheck() )
{
textures = m_proceduralMaterial != null ? m_proceduralMaterial.GetGeneratedTextures() : null;
OnNewSubstanceSelected( textures );
}
}
void OnNewSubstanceSelected( Texture[] textures )
{
CacheCurrentSettings();
ConfigPortsFromMaterial( true, textures );
ConnectFromCache();
m_requireMaterialUpdate = true;
CalculateFirstOutputConnected();
ContainerGraph.ParentWindow.RequestRepaint();
}
public override void DrawProperties()
{
base.DrawProperties();
EditorGUI.BeginChangeCheck();
m_proceduralMaterial = EditorGUILayoutObjectField( SubstanceStr, m_proceduralMaterial, m_type, false ) as ProceduralMaterial ;
if ( EditorGUI.EndChangeCheck() )
{
Texture[] textures = m_proceduralMaterial != null ? m_proceduralMaterial.GetGeneratedTextures() : null;
if ( textures != null )
{
OnNewSubstanceSelected( textures );
}
}
m_textureCoordSet = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordSet, Constants.AvailableUVSetsStr, Constants.AvailableUVSets );
EditorGUI.BeginChangeCheck();
m_autoNormal = EditorGUILayoutToggle( AutoNormalStr, m_autoNormal );
if ( EditorGUI.EndChangeCheck() )
{
for ( int i = 0; i < m_textureTypes.Length; i++ )
{
WirePortDataType portType = ( m_autoNormal && m_textureTypes[ i ] == ProceduralOutputType.Normal ) ? WirePortDataType.FLOAT3 : WirePortDataType.COLOR;
if ( m_outputPorts[ i ].DataType != portType )
{
m_outputPorts[ i ].ChangeType( portType, false );
}
}
}
}
private void CacheCurrentSettings()
{
m_cacheNodeConnections.Clear();
for ( int portId = 0; portId < m_outputPorts.Count; portId++ )
{
if ( m_outputPorts[ portId ].IsConnected )
{
int connCount = m_outputPorts[ portId ].ConnectionCount;
for ( int connIdx = 0; connIdx < connCount; connIdx++ )
{
WireReference connection = m_outputPorts[ portId ].GetConnection( connIdx );
m_cacheNodeConnections.Add( m_outputPorts[ portId ].Name, new NodeCache( connection.NodeId, connection.PortId ) );
}
}
}
}
private void ConnectFromCache()
{
for ( int i = 0; i < m_outputPorts.Count; i++ )
{
List<NodeCache> connections = m_cacheNodeConnections.GetList( m_outputPorts[ i ].Name );
if ( connections != null )
{
int count = connections.Count;
for ( int connIdx = 0; connIdx < count; connIdx++ )
{
UIUtils.SetConnection( connections[ connIdx ].TargetNodeId, connections[ connIdx ].TargetPortId, UniqueId, i );
}
}
}
}
private void ConfigPortsFromMaterial( bool invalidateConnections = false, Texture[] newTextures = null )
{
//PreviewSizeX = ( m_proceduralMaterial != null ) ? UIUtils.ObjectField.CalcSize( new GUIContent( m_proceduralMaterial.name ) ).x + 15 : 110;
m_insideSize.x = TexturePreviewSizeX + 5;
SetAdditonalTitleText( ( m_proceduralMaterial != null ) ? string.Format( Constants.PropertyValueLabel, m_proceduralMaterial.name ) : string.Empty );
Texture[] textures = newTextures != null ? newTextures : ( ( m_proceduralMaterial != null ) ? m_proceduralMaterial.GetGeneratedTextures() : null );
if ( textures != null )
{
string nameToRemove = m_proceduralMaterial.name + "_";
m_textureTypes = new ProceduralOutputType[ textures.Length ];
for ( int i = 0; i < textures.Length; i++ )
{
ProceduralTexture procTex = textures[ i ] as ProceduralTexture;
m_textureTypes[ i ] = procTex.GetProceduralOutputType();
WirePortDataType portType = ( m_autoNormal && m_textureTypes[ i ] == ProceduralOutputType.Normal ) ? WirePortDataType.FLOAT3 : WirePortDataType.COLOR;
string newName = textures[ i ].name.Replace( nameToRemove, string.Empty );
char firstLetter = Char.ToUpper( newName[ 0 ] );
newName = firstLetter.ToString() + newName.Substring( 1 );
if ( i < m_outputPorts.Count )
{
m_outputPorts[ i ].ChangeProperties( newName, portType, false );
if ( invalidateConnections )
{
m_outputPorts[ i ].FullDeleteConnections();
}
}
else
{
AddOutputPort( portType, newName );
}
}
if ( textures.Length < m_outputPorts.Count )
{
int itemsToRemove = m_outputPorts.Count - textures.Length;
for ( int i = 0; i < itemsToRemove; i++ )
{
int idx = m_outputPorts.Count - 1;
if ( m_outputPorts[ idx ].IsConnected )
{
m_outputPorts[ idx ].ForceClearConnection();
}
RemoveOutputPort( idx );
}
}
}
else
{
int itemsToRemove = m_outputPorts.Count - 1;
m_outputPorts[ 0 ].ChangeProperties( Constants.EmptyPortValue, WirePortDataType.COLOR, false );
m_outputPorts[ 0 ].ForceClearConnection();
for ( int i = 0; i < itemsToRemove; i++ )
{
int idx = m_outputPorts.Count - 1;
if ( m_outputPorts[ idx ].IsConnected )
{
m_outputPorts[ idx ].ForceClearConnection();
}
RemoveOutputPort( idx );
}
}
m_sizeIsDirty = true;
m_isDirty = true;
Event.current.Use();
}
private void ConfigFromObject( UnityEngine.Object obj )
{
ProceduralMaterial newMat = AssetDatabase.LoadAssetAtPath<ProceduralMaterial>( AssetDatabase.GetAssetPath( obj ) );
if ( newMat != null )
{
m_proceduralMaterial = newMat;
ConfigPortsFromMaterial();
}
}
public override void OnObjectDropped( UnityEngine.Object obj )
{
ConfigFromObject( obj );
}
public override void SetupFromCastObject( UnityEngine.Object obj )
{
ConfigFromObject( obj );
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if ( m_proceduralMaterial == null )
{
return "(0).xxxx";
}
if ( m_outputPorts[ outputId ].IsLocalValue )
{
return m_outputPorts[ outputId ].LocalValue;
}
Texture[] textures = m_proceduralMaterial.GetGeneratedTextures();
string uvPropertyName = string.Empty;
for ( int i = 0; i < m_outputPorts.Count; i++ )
{
if ( m_outputPorts[ i ].IsConnected )
{
uvPropertyName = textures[ i ].name;
break;
}
}
string name = textures[ outputId ].name + OutputId;
dataCollector.AddToUniforms( UniqueId, string.Format( GlobalVarDecStr, textures[ outputId ].name ) );
dataCollector.AddToProperties( UniqueId, string.Format( PropertyDecStr, textures[ outputId ].name ) + "{}", -1 );
bool isVertex = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation );
string value = string.Format( "tex2D{0}( {1}, {2})", ( isVertex ? "lod" : string.Empty ), textures[ outputId ].name, GetUVCoords( ref dataCollector, ignoreLocalvar, uvPropertyName ) );
if ( m_autoNormal && m_textureTypes[ outputId ] == ProceduralOutputType.Normal )
{
value = string.Format( Constants.UnpackNormal, value );
}
dataCollector.AddPropertyNode( this );
RegisterLocalVariable( outputId, value, ref dataCollector, name );
return m_outputPorts[ outputId ].LocalValue;
}
public string GetUVCoords( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar, string propertyName )
{
bool isVertex = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation );
if ( m_inputPorts[ 0 ].IsConnected )
{
return m_inputPorts[ 0 ].GenerateShaderForOutput( ref dataCollector, isVertex ? WirePortDataType.FLOAT4 : WirePortDataType.FLOAT2, ignoreLocalVar, true );
}
else
{
string vertexCoords = Constants.VertexShaderInputStr + ".texcoord";
if ( m_textureCoordSet > 0 )
{
vertexCoords += m_textureCoordSet.ToString();
}
string uvChannelName = IOUtils.GetUVChannelName( propertyName, m_textureCoordSet );
string dummyPropUV = "_texcoord" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" );
string dummyUV = "uv" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ) + dummyPropUV;
dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;" );
dataCollector.AddToProperties( UniqueId, "[HideInInspector] " + dummyPropUV + "( \"\", 2D ) = \"white\" {}", 100 );
dataCollector.AddToInput( UniqueId, "float2 " + dummyUV, true );
if ( isVertex )
{
dataCollector.AddToVertexLocalVariables( UniqueId, "float4 " + uvChannelName + " = float4(" + vertexCoords + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw, 0 ,0);" );
return uvChannelName;
}
else
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw" );
return uvChannelName;
}
}
public override void UpdateMaterial( Material mat )
{
base.UpdateMaterial( mat );
if ( m_proceduralMaterial != null )
{
Texture[] textures = m_proceduralMaterial.GetGeneratedTextures();
for ( int i = 0; i < textures.Length; i++ )
{
if ( mat.HasProperty( textures[ i ].name ) )
{
mat.SetTexture( textures[ i ].name, textures[ i ] );
}
}
}
}
public override bool UpdateShaderDefaults( ref Shader shader, ref TextureDefaultsDataColector defaultCol )
{
if ( m_proceduralMaterial != null )
{
Texture[] textures = m_proceduralMaterial.GetGeneratedTextures();
for ( int i = 0; i < textures.Length; i++ )
{
defaultCol.AddValue( textures[ i ].name, textures[ i ] );
}
}
return true;
}
public override void Destroy()
{
base.Destroy();
m_proceduralMaterial = null;
m_cacheNodeConnections.Clear();
m_cacheNodeConnections = null;
m_outputConns.Clear();
m_outputConns = null;
}
public override string GetPropertyValStr()
{
return m_proceduralMaterial ? m_proceduralMaterial.name : string.Empty;
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
string guid = GetCurrentParam( ref nodeParams );
m_textureCoordSet = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
m_autoNormal = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
if ( guid.Length > 1 )
{
m_proceduralMaterial = AssetDatabase.LoadAssetAtPath<ProceduralMaterial>( AssetDatabase.GUIDToAssetPath( guid ) );
if ( m_proceduralMaterial != null )
{
ConfigPortsFromMaterial();
}
else
{
UIUtils.ShowMessage( "Substance not found ", MessageSeverity.Error );
}
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
string guid = ( m_proceduralMaterial != null ) ? AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath( m_proceduralMaterial ) ) : "0";
IOUtils.AddFieldValueToString( ref nodeInfo, guid );
IOUtils.AddFieldValueToString( ref nodeInfo, m_textureCoordSet );
IOUtils.AddFieldValueToString( ref nodeInfo, m_autoNormal );
}
}
}
| |
// ===========================================================
// Copyright (c) 2014-2015, Enrico Da Ros/kendar.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.
//
// * 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.Collections.ObjectModel;
using System.Diagnostics;
using ConcurrencyHelpers.Containers;
using ConcurrencyHelpers.Containers.Asyncs;
using ConcurrencyHelpers.Interfaces;
using ConcurrencyHelpers.Utils;
namespace ConcurrencyHelpers.Monitor
{
public static class PerfMon
{
private static Dictionary<string, BaseMetric> _beforeStart = new Dictionary<string, BaseMetric>();
private static bool _started = false;
private static LockFreeItem<ReadOnlyCollection<BaseMetric>> _accessibleData;
private static CollectedPerfDataEventHandler _onDataCollected;
public const string PERFMON_RUNS = "PerfMon.Runs";
private static SystemTimer _timer;
private static readonly AsyncLockFreeDictionary<string, BaseMetric> _perfData;
private static bool _overlapping = false;
private static readonly Stopwatch _stopWatch;
private static int _periodRun;
private static void ShareData(List<BaseMetric> perfData)
{
if (!_started) return;
_accessibleData.Data = new ReadOnlyCollection<BaseMetric>(perfData);
if (_onDataCollected != null)
{
_onDataCollected(null, new CollectedPerfDataEventArgs(_accessibleData.Data));
}
}
public static ReadOnlyCollection<BaseMetric> Data
{
get
{
if (!_started) return null;
return _accessibleData.Data;
}
}
public static event CollectedPerfDataEventHandler OnDataCollected
{
add
{
_onDataCollected += value;
}
remove
{
if (_onDataCollected != null)
{
// ReSharper disable once DelegateSubtraction
_onDataCollected -= value;
}
}
}
/*public static void AddRunCountMonitor(string id)
{
_perfData.TryAdd(id.ToLowerInvariant(), new BaseMetric(true, false, _periodRun));
}
public static void AddDurationMonitor(string id)
{
_perfData.TryAdd(id.ToLowerInvariant(), new BaseMetric(false, true, _periodRun));
}
public static void AddMonitor(string id)
{
_perfData.TryAdd(id.ToLowerInvariant(), new BaseMetric(true, true, _periodRun));
}
public static void AddStatusMonitor(string id, object baseStatus)
{
_perfData.TryAdd(id.ToLowerInvariant(), new BaseMetric(false, false, _periodRun, baseStatus));
}*/
static PerfMon()
{
_accessibleData = new LockFreeItem<ReadOnlyCollection<BaseMetric>>(new ReadOnlyCollection<BaseMetric>(new List<BaseMetric>()));
_perfData = new AsyncLockFreeDictionary<string, BaseMetric>();
_stopWatch = new Stopwatch();
}
static void OnElapsed(object sender, ElapsedTimerEventArgs e)
{
if (!_started) return;
if (_overlapping) return;
_overlapping = true;
_stopWatch.Reset();
_stopWatch.Start();
WriteAllData();
SetElapsedAndRun(PERFMON_RUNS, _stopWatch.ElapsedMilliseconds);
_overlapping = false;
}
public static void Start(int periodRun = 1000)
{
_started = true;
_overlapping = false;
_periodRun = periodRun;
_timer = new SystemTimer(periodRun, 0);
_timer.Elapsed += OnElapsed;
foreach (var item in _beforeStart)
{
AddMonitor(item.Key, item.Value);
}
AddMonitor(PERFMON_RUNS, new RunAndExcutionCounterMetric());
_timer.Start();
}
public static void Reset()
{
}
static void WriteAllData()
{
if (!_started) return;
var listOfData = new List<BaseMetric>();
var now = DateTime.UtcNow;
foreach (var item in _perfData)
{
item.Value.DoCalculation(now);
listOfData.Add(item.Value);
}
ShareData(listOfData);
}
public static void AddMonitor(string id, BaseMetric metric)
{
if (!_started)
{
if (!_beforeStart.ContainsKey(id))
{
_beforeStart.Add(id, metric);
}
}
else
{
metric.Initialize(_periodRun, id.ToLowerInvariant());
_perfData.TryAdd(id.ToLowerInvariant(), metric);
}
}
public static bool SetElapsedAndRun(string id, long elapsedMs, int runs = 1)
{
if (!_started) return true;
if(!_perfData.ContainsKey(id.ToLowerInvariant())) return false;
var item = _perfData[id.ToLowerInvariant()] as RunAndExcutionCounterMetric;
if (item == null) return false;
item.InternalElapsedCount.SetValue(elapsedMs);
item.InternalRunCount.SetValue(runs);
return true;
}
public static bool SetMetric(string id, long value)
{
if (!_started) return true;
if (!_perfData.ContainsKey(id.ToLowerInvariant())) return false;
var item = _perfData[id.ToLowerInvariant()] as ValueCounterMetric;
if (item == null) return false;
item.InternalRunCount.SetValue(value);
return true;
}
public static bool SetStatus(string id, object status)
{
if (!_started) return true;
if (!_perfData.ContainsKey(id.ToLowerInvariant())) return false;
var item = _perfData[id.ToLowerInvariant()] as StatusMetric;
if (item == null) return false;
item.InternalStatus.SetValue(status);
return true;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace Northwind
{
/// <summary>
/// Strongly-typed collection for the Customer class.
/// </summary>
[Serializable]
public partial class CustomerCollection : ActiveList<Customer, CustomerCollection>
{
public CustomerCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>CustomerCollection</returns>
public CustomerCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Customer o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Customers table.
/// </summary>
[Serializable]
public partial class Customer : ActiveRecord<Customer>, IActiveRecord
{
#region .ctors and Default Settings
public Customer()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Customer(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public Customer(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public Customer(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Customers", TableType.Table, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.String;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = false;
colvarCustomerID.IsPrimaryKey = true;
colvarCustomerID.IsForeignKey = false;
colvarCustomerID.IsReadOnly = false;
colvarCustomerID.DefaultSetting = @"";
colvarCustomerID.ForeignKeyTableName = "";
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema);
colvarCompanyName.ColumnName = "CompanyName";
colvarCompanyName.DataType = DbType.String;
colvarCompanyName.MaxLength = 40;
colvarCompanyName.AutoIncrement = false;
colvarCompanyName.IsNullable = false;
colvarCompanyName.IsPrimaryKey = false;
colvarCompanyName.IsForeignKey = false;
colvarCompanyName.IsReadOnly = false;
colvarCompanyName.DefaultSetting = @"";
colvarCompanyName.ForeignKeyTableName = "";
schema.Columns.Add(colvarCompanyName);
TableSchema.TableColumn colvarContactName = new TableSchema.TableColumn(schema);
colvarContactName.ColumnName = "ContactName";
colvarContactName.DataType = DbType.String;
colvarContactName.MaxLength = 30;
colvarContactName.AutoIncrement = false;
colvarContactName.IsNullable = true;
colvarContactName.IsPrimaryKey = false;
colvarContactName.IsForeignKey = false;
colvarContactName.IsReadOnly = false;
colvarContactName.DefaultSetting = @"";
colvarContactName.ForeignKeyTableName = "";
schema.Columns.Add(colvarContactName);
TableSchema.TableColumn colvarContactTitle = new TableSchema.TableColumn(schema);
colvarContactTitle.ColumnName = "ContactTitle";
colvarContactTitle.DataType = DbType.String;
colvarContactTitle.MaxLength = 30;
colvarContactTitle.AutoIncrement = false;
colvarContactTitle.IsNullable = true;
colvarContactTitle.IsPrimaryKey = false;
colvarContactTitle.IsForeignKey = false;
colvarContactTitle.IsReadOnly = false;
colvarContactTitle.DefaultSetting = @"";
colvarContactTitle.ForeignKeyTableName = "";
schema.Columns.Add(colvarContactTitle);
TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema);
colvarAddress.ColumnName = "Address";
colvarAddress.DataType = DbType.String;
colvarAddress.MaxLength = 60;
colvarAddress.AutoIncrement = false;
colvarAddress.IsNullable = true;
colvarAddress.IsPrimaryKey = false;
colvarAddress.IsForeignKey = false;
colvarAddress.IsReadOnly = false;
colvarAddress.DefaultSetting = @"";
colvarAddress.ForeignKeyTableName = "";
schema.Columns.Add(colvarAddress);
TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema);
colvarCity.ColumnName = "City";
colvarCity.DataType = DbType.String;
colvarCity.MaxLength = 15;
colvarCity.AutoIncrement = false;
colvarCity.IsNullable = true;
colvarCity.IsPrimaryKey = false;
colvarCity.IsForeignKey = false;
colvarCity.IsReadOnly = false;
colvarCity.DefaultSetting = @"";
colvarCity.ForeignKeyTableName = "";
schema.Columns.Add(colvarCity);
TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema);
colvarRegion.ColumnName = "Region";
colvarRegion.DataType = DbType.String;
colvarRegion.MaxLength = 15;
colvarRegion.AutoIncrement = false;
colvarRegion.IsNullable = true;
colvarRegion.IsPrimaryKey = false;
colvarRegion.IsForeignKey = false;
colvarRegion.IsReadOnly = false;
colvarRegion.DefaultSetting = @"";
colvarRegion.ForeignKeyTableName = "";
schema.Columns.Add(colvarRegion);
TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema);
colvarPostalCode.ColumnName = "PostalCode";
colvarPostalCode.DataType = DbType.String;
colvarPostalCode.MaxLength = 10;
colvarPostalCode.AutoIncrement = false;
colvarPostalCode.IsNullable = true;
colvarPostalCode.IsPrimaryKey = false;
colvarPostalCode.IsForeignKey = false;
colvarPostalCode.IsReadOnly = false;
colvarPostalCode.DefaultSetting = @"";
colvarPostalCode.ForeignKeyTableName = "";
schema.Columns.Add(colvarPostalCode);
TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema);
colvarCountry.ColumnName = "Country";
colvarCountry.DataType = DbType.String;
colvarCountry.MaxLength = 15;
colvarCountry.AutoIncrement = false;
colvarCountry.IsNullable = true;
colvarCountry.IsPrimaryKey = false;
colvarCountry.IsForeignKey = false;
colvarCountry.IsReadOnly = false;
colvarCountry.DefaultSetting = @"";
colvarCountry.ForeignKeyTableName = "";
schema.Columns.Add(colvarCountry);
TableSchema.TableColumn colvarPhone = new TableSchema.TableColumn(schema);
colvarPhone.ColumnName = "Phone";
colvarPhone.DataType = DbType.String;
colvarPhone.MaxLength = 24;
colvarPhone.AutoIncrement = false;
colvarPhone.IsNullable = true;
colvarPhone.IsPrimaryKey = false;
colvarPhone.IsForeignKey = false;
colvarPhone.IsReadOnly = false;
colvarPhone.DefaultSetting = @"";
colvarPhone.ForeignKeyTableName = "";
schema.Columns.Add(colvarPhone);
TableSchema.TableColumn colvarFax = new TableSchema.TableColumn(schema);
colvarFax.ColumnName = "Fax";
colvarFax.DataType = DbType.String;
colvarFax.MaxLength = 24;
colvarFax.AutoIncrement = false;
colvarFax.IsNullable = true;
colvarFax.IsPrimaryKey = false;
colvarFax.IsForeignKey = false;
colvarFax.IsReadOnly = false;
colvarFax.DefaultSetting = @"";
colvarFax.ForeignKeyTableName = "";
schema.Columns.Add(colvarFax);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Customers",schema);
}
}
#endregion
#region Props
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get { return GetColumnValue<string>(Columns.CustomerID); }
set { SetColumnValue(Columns.CustomerID, value); }
}
[XmlAttribute("CompanyName")]
[Bindable(true)]
public string CompanyName
{
get { return GetColumnValue<string>(Columns.CompanyName); }
set { SetColumnValue(Columns.CompanyName, value); }
}
[XmlAttribute("ContactName")]
[Bindable(true)]
public string ContactName
{
get { return GetColumnValue<string>(Columns.ContactName); }
set { SetColumnValue(Columns.ContactName, value); }
}
[XmlAttribute("ContactTitle")]
[Bindable(true)]
public string ContactTitle
{
get { return GetColumnValue<string>(Columns.ContactTitle); }
set { SetColumnValue(Columns.ContactTitle, value); }
}
[XmlAttribute("Address")]
[Bindable(true)]
public string Address
{
get { return GetColumnValue<string>(Columns.Address); }
set { SetColumnValue(Columns.Address, value); }
}
[XmlAttribute("City")]
[Bindable(true)]
public string City
{
get { return GetColumnValue<string>(Columns.City); }
set { SetColumnValue(Columns.City, value); }
}
[XmlAttribute("Region")]
[Bindable(true)]
public string Region
{
get { return GetColumnValue<string>(Columns.Region); }
set { SetColumnValue(Columns.Region, value); }
}
[XmlAttribute("PostalCode")]
[Bindable(true)]
public string PostalCode
{
get { return GetColumnValue<string>(Columns.PostalCode); }
set { SetColumnValue(Columns.PostalCode, value); }
}
[XmlAttribute("Country")]
[Bindable(true)]
public string Country
{
get { return GetColumnValue<string>(Columns.Country); }
set { SetColumnValue(Columns.Country, value); }
}
[XmlAttribute("Phone")]
[Bindable(true)]
public string Phone
{
get { return GetColumnValue<string>(Columns.Phone); }
set { SetColumnValue(Columns.Phone, value); }
}
[XmlAttribute("Fax")]
[Bindable(true)]
public string Fax
{
get { return GetColumnValue<string>(Columns.Fax); }
set { SetColumnValue(Columns.Fax, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
public Northwind.CustomerCustomerDemoCollection CustomerCustomerDemoRecords()
{
return new Northwind.CustomerCustomerDemoCollection().Where(CustomerCustomerDemo.Columns.CustomerID, CustomerID).Load();
}
public Northwind.OrderCollection Orders()
{
return new Northwind.OrderCollection().Where(Order.Columns.CustomerID, CustomerID).Load();
}
#endregion
//no foreign key tables defined (0)
#region Many To Many Helpers
public Northwind.CustomerDemographicCollection GetCustomerDemographicCollection() { return Customer.GetCustomerDemographicCollection(this.CustomerID); }
public static Northwind.CustomerDemographicCollection GetCustomerDemographicCollection(string varCustomerID)
{
SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [dbo].[CustomerDemographics] INNER JOIN [CustomerCustomerDemo] ON [CustomerDemographics].[CustomerTypeID] = [CustomerCustomerDemo].[CustomerTypeID] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmd.AddParameter("@CustomerID", varCustomerID, DbType.String);
IDataReader rdr = SubSonic.DataService.GetReader(cmd);
CustomerDemographicCollection coll = new CustomerDemographicCollection();
coll.LoadAndCloseReader(rdr);
return coll;
}
public static void SaveCustomerDemographicMap(string varCustomerID, CustomerDemographicCollection items)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmdDel.AddParameter("@CustomerID", varCustomerID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (CustomerDemographic item in items)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerID", varCustomerID);
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", item.GetPrimaryKeyValue());
varCustomerCustomerDemo.Save();
}
}
public static void SaveCustomerDemographicMap(string varCustomerID, System.Web.UI.WebControls.ListItemCollection itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmdDel.AddParameter("@CustomerID", varCustomerID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (System.Web.UI.WebControls.ListItem l in itemList)
{
if (l.Selected)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerID", varCustomerID);
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", l.Value);
varCustomerCustomerDemo.Save();
}
}
}
public static void SaveCustomerDemographicMap(string varCustomerID , string[] itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmdDel.AddParameter("@CustomerID", varCustomerID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (string item in itemList)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerID", varCustomerID);
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", item);
varCustomerCustomerDemo.Save();
}
}
public static void DeleteCustomerDemographicMap(string varCustomerID)
{
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmdDel.AddParameter("@CustomerID", varCustomerID, DbType.String);
DataService.ExecuteQuery(cmdDel);
}
#endregion
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCustomerID,string varCompanyName,string varContactName,string varContactTitle,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varPhone,string varFax)
{
Customer item = new Customer();
item.CustomerID = varCustomerID;
item.CompanyName = varCompanyName;
item.ContactName = varContactName;
item.ContactTitle = varContactTitle;
item.Address = varAddress;
item.City = varCity;
item.Region = varRegion;
item.PostalCode = varPostalCode;
item.Country = varCountry;
item.Phone = varPhone;
item.Fax = varFax;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(string varCustomerID,string varCompanyName,string varContactName,string varContactTitle,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varPhone,string varFax)
{
Customer item = new Customer();
item.CustomerID = varCustomerID;
item.CompanyName = varCompanyName;
item.ContactName = varContactName;
item.ContactTitle = varContactTitle;
item.Address = varAddress;
item.City = varCity;
item.Region = varRegion;
item.PostalCode = varPostalCode;
item.Country = varCountry;
item.Phone = varPhone;
item.Fax = varFax;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn CustomerIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CompanyNameColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn ContactNameColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn ContactTitleColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn AddressColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn CityColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn RegionColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn PostalCodeColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn CountryColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn PhoneColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn FaxColumn
{
get { return Schema.Columns[10]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CustomerID = @"CustomerID";
public static string CompanyName = @"CompanyName";
public static string ContactName = @"ContactName";
public static string ContactTitle = @"ContactTitle";
public static string Address = @"Address";
public static string City = @"City";
public static string Region = @"Region";
public static string PostalCode = @"PostalCode";
public static string Country = @"Country";
public static string Phone = @"Phone";
public static string Fax = @"Fax";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
}
#endregion
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Text;
using NodaTime.Text.Patterns;
using NUnit.Framework;
namespace NodaTime.Test.Text.Patterns
{
[TestFixture, Category("Formatting"), Category("Format"), Category("Parse")]
public class PatternCursorTest : TextCursorTestBase
{
internal override TextCursor MakeCursor(string value)
{
return new PatternCursor(value);
}
[Test]
public void TestGetQuotedString_EscapeAtEnd()
{
var cursor = new PatternCursor("'abc\\");
Assert.AreEqual('\'', GetNextCharacter(cursor));
Assert.Throws<InvalidPatternException>(() => cursor.GetQuotedString('\''));
}
[Test]
public void TestGetQuotedString()
{
var cursor = new PatternCursor("'abc'");
Assert.AreEqual('\'', GetNextCharacter(cursor));
string actual = cursor.GetQuotedString('\'');
Assert.AreEqual("abc", actual);
Assert.IsFalse(cursor.MoveNext());
}
[Test]
public void TestGetQuotedString_Empty()
{
var cursor = new PatternCursor("''");
char openQuote = GetNextCharacter(cursor);
string actual = cursor.GetQuotedString(openQuote);
Assert.AreEqual(string.Empty, actual);
Assert.IsFalse(cursor.MoveNext());
}
[Test]
public void TestGetQuotedString_HandlesDoubleQuote()
{
var cursor = new PatternCursor("\"abc\"");
char openQuote = GetNextCharacter(cursor);
string actual = cursor.GetQuotedString(openQuote);
Assert.AreEqual("abc", actual);
Assert.IsFalse(cursor.MoveNext());
}
[Test]
public void TestGetQuotedString_HandlesEscape()
{
var cursor = new PatternCursor("'ab\\c'");
char openQuote = GetNextCharacter(cursor);
string actual = cursor.GetQuotedString(openQuote);
Assert.AreEqual("abc", actual);
Assert.IsFalse(cursor.MoveNext());
}
[Test]
public void TestGetQuotedString_HandlesEscapedCloseQuote()
{
var cursor = new PatternCursor("'ab\\'c'");
char openQuote = GetNextCharacter(cursor);
string actual = cursor.GetQuotedString(openQuote);
Assert.AreEqual("ab'c", actual);
Assert.IsFalse(cursor.MoveNext());
}
[Test]
public void TestGetQuotedString_HandlesOtherQuote()
{
var cursor = new PatternCursor("[abc]");
GetNextCharacter(cursor);
string actual = cursor.GetQuotedString(']');
Assert.AreEqual("abc", actual);
Assert.IsFalse(cursor.MoveNext());
}
[Test]
public void TestGetQuotedString_MissingCloseQuote()
{
var cursor = new PatternCursor("'abc");
char openQuote = GetNextCharacter(cursor);
Assert.Throws<InvalidPatternException>(() => cursor.GetQuotedString(openQuote));
}
[Test]
public void TestGetQuotedString_NotAtEnd()
{
var cursor = new PatternCursor("'abc'more");
char openQuote = GetNextCharacter(cursor);
string actual = cursor.GetQuotedString(openQuote);
Assert.AreEqual("abc", actual);
ValidateCurrentCharacter(cursor, 4, '\'');
Assert.AreEqual('m', GetNextCharacter(cursor));
}
[Test]
public void TestGetQuotedString_Simple()
{
var cursor = new PatternCursor("'abc'");
char openQuote = GetNextCharacter(cursor);
string actual = cursor.GetQuotedString(openQuote);
Assert.AreEqual("abc", actual);
Assert.IsFalse(cursor.MoveNext());
}
[Test]
public void TestGetRepeatCount_Current()
{
var cursor = new PatternCursor("aaa");
GetNextCharacter(cursor);
int actual = cursor.GetRepeatCount(10);
Assert.AreEqual(3, actual);
ValidateCurrentCharacter(cursor, 2, 'a');
}
[Test]
public void TestGetRepeatCount_ExceedsMax()
{
var cursor = new PatternCursor("aaa");
Assert.IsTrue(cursor.MoveNext());
Assert.Throws<InvalidPatternException>(() => cursor.GetRepeatCount(2));
}
[Test]
public void TestGetRepeatCount_One()
{
var cursor = new PatternCursor("a");
Assert.IsTrue(cursor.MoveNext());
int actual = cursor.GetRepeatCount(10);
Assert.AreEqual(1, actual);
ValidateCurrentCharacter(cursor, 0, 'a');
}
[Test]
public void TestGetRepeatCount_StopsOnNonMatch()
{
var cursor = new PatternCursor("aaadaa");
Assert.IsTrue(cursor.MoveNext());
int actual = cursor.GetRepeatCount(10);
Assert.AreEqual(3, actual);
ValidateCurrentCharacter(cursor, 2, 'a');
}
[Test]
public void TestGetRepeatCount_Three()
{
var cursor = new PatternCursor("aaa");
Assert.IsTrue(cursor.MoveNext());
int actual = cursor.GetRepeatCount(10);
Assert.AreEqual(3, actual);
ValidateCurrentCharacter(cursor, 2, 'a');
}
[Test]
public void TestGetEmbeddedPattern_Valid()
{
var cursor = new PatternCursor("x<HH:mm>y");
cursor.MoveNext();
string embedded = cursor.GetEmbeddedPattern('<', '>');
Assert.AreEqual("HH:mm", embedded);
ValidateCurrentCharacter(cursor, 7, '>');
}
[Test]
public void TestGetEmbeddedPattern_Valid_WithQuoting()
{
var cursor = new PatternCursor("x<HH:'T'mm>y");
cursor.MoveNext();
string embedded = cursor.GetEmbeddedPattern('<', '>');
Assert.AreEqual("HH:'T'mm", embedded);
Assert.AreEqual('>', cursor.Current);
}
[Test]
public void TestGetEmbeddedPattern_Valid_WithEscaping()
{
var cursor = new PatternCursor(@"x<HH:\Tmm>y");
cursor.MoveNext();
string embedded = cursor.GetEmbeddedPattern('<', '>');
Assert.AreEqual(@"HH:\Tmm", embedded);
Assert.AreEqual('>', cursor.Current);
}
[Test]
public void TestGetEmbeddedPattern_WrongOpenCharacter()
{
var cursor = new PatternCursor("x(oops)");
cursor.MoveNext();
Assert.Throws<InvalidPatternException>(() => cursor.GetEmbeddedPattern('<', '>'));
}
[Test]
public void TestGetEmbeddedPattern_NoCloseCharacter()
{
var cursor = new PatternCursor("x<oops)");
cursor.MoveNext();
Assert.Throws<InvalidPatternException>(() => cursor.GetEmbeddedPattern('<', '>'));
}
[Test]
public void TestGetEmbeddedPattern_EscapedCloseCharacter()
{
var cursor = new PatternCursor(@"x<oops\>");
cursor.MoveNext();
Assert.Throws<InvalidPatternException>(() => cursor.GetEmbeddedPattern('<', '>'));
}
[Test]
public void TestGetEmbeddedPattern_QuotedCloseCharacter()
{
var cursor = new PatternCursor("x<oops'>'");
cursor.MoveNext();
Assert.Throws<InvalidPatternException>(() => cursor.GetEmbeddedPattern('<', '>'));
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski 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.IO;
namespace NLog.UnitTests.Config
{
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System;
using System.Globalization;
using System.Text;
using Xunit;
public class TargetConfigurationTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Single(l.Renderers);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
}
[Fact]
public void SimpleElementSyntaxTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target type='Debug'>
<name>d</name>
<layout>${message}</layout>
</target>
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Single(l.Renderers);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
}
[Fact]
public void NestedXmlConfigElementTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<extensions>
<add type='" + typeof(StructuredDebugTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='StructuredDebugTarget'>
<name>structuredTgt</name>
<layout>${message}</layout>
<config platform='any'>
<parameter name='param1' />
</config>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("structuredTgt") as StructuredDebugTarget;
Assert.NotNull(t);
Assert.Equal("any", t.Config.Platform);
Assert.Equal("param1", t.Config.Parameter.Name);
}
[Fact]
public void ArrayParameterTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter name='p1' layout='${message}' />
<parameter name='p2' layout='${level}' />
<parameter name='p3' layout='${logger}' />
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
Assert.Equal("'${level}'", t.Parameters[1].Layout.ToString());
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Fact]
public void ArrayElementParameterTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter>
<name>p1</name>
<layout>${message}</layout>
</parameter>
<parameter>
<name>p2</name>
<layout type='CsvLayout'>
<column name='x' layout='${message}' />
<column name='y' layout='${level}' />
</layout>
</parameter>
<parameter>
<name>p3</name>
<layout>${logger}</layout>
</parameter>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout;
Assert.NotNull(csvLayout);
Assert.Equal(2, csvLayout.Columns.Count);
Assert.Equal("x", csvLayout.Columns[0].Name);
Assert.Equal("y", csvLayout.Columns[1].Name);
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Fact]
public void SimpleTest2()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message} ${level}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message} ${level}", l.Text);
Assert.NotNull(l);
Assert.Equal(3, l.Renderers.Count);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
Assert.IsType<LiteralLayoutRenderer>(l.Renderers[1]);
Assert.IsType<LevelLayoutRenderer>(l.Renderers[2]);
Assert.Equal(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text);
}
[Fact]
public void WrapperTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper name='a' type='AsyncWrapper'>
<target name='c' type='Debug' layout='${message}' />
</wrapper>
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b"));
Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a"));
Assert.IsType<DebugTarget>(c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void WrapperRefTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='c' type='Debug' layout='${message}' />
<wrapper name='a' type='AsyncWrapper'>
<target-ref name='c' />
</wrapper>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper-target-ref name='a' />
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b"));
Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a"));
Assert.IsType<DebugTarget>(c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void CompoundTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<compound-target name='rr' type='RoundRobinGroup'>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d1"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d2"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d3"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text);
Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text);
Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text);
Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text);
}
[Fact]
public void CompoundRefTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
<compound-target name='rr' type='RoundRobinGroup'>
<target-ref name='d1' />
<target-ref name='d2' />
<target-ref name='d3' />
<target-ref name='d4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d1"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d2"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d3"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text);
Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text);
Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text);
Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text);
}
[Fact]
public void AsyncWrappersTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets async='true'>
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
var wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d_wrapped", wrappedTarget.Name);
t = c.FindTargetByName("d2") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal("d2", t.Name);
wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d2_wrapped", wrappedTarget.Name);
}
[Fact]
public void DefaultTargetParametersTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<default-target-parameters type='Debug' layout='x${message}x' />
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
t = c.FindTargetByName("d2") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
}
[Fact]
public void DefaultTargetParametersOnWrappedTargetTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<default-target-parameters type='Debug' layout='x${message}x' />
<target type='BufferingWrapper' name='buf1'>
<target type='Debug' name='d1' />
</target>
</targets>
</nlog>");
var wrap = c.FindTargetByName("buf1") as BufferingTargetWrapper;
Assert.NotNull(wrap);
Assert.NotNull(wrap.WrappedTarget);
var t = wrap.WrappedTarget as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
}
[Fact]
public void DefaultWrapperTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<default-wrapper type='BufferingWrapper'>
<wrapper type='RetryingWrapper' />
</default-wrapper>
<target type='Debug' name='d' layout='${level}' />
<target type='Debug' name='d2' layout='${level}' />
</targets>
</nlog>");
var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper;
Assert.NotNull(bufferingTargetWrapper);
var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper;
Assert.NotNull(retryingTargetWrapper);
Assert.Null(retryingTargetWrapper.Name);
var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget;
Assert.NotNull(debugTarget);
Assert.Equal("d_wrapped", debugTarget.Name);
Assert.Equal("'${level}'", debugTarget.Layout.ToString());
}
[Fact]
public void DontThrowExceptionWhenArchiveEverySetByDefaultParameters()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<targets>
<default-target-parameters
type='File'
concurrentWrites='true'
keepFileOpen='true'
maxArchiveFiles='5'
archiveNumbering='Rolling'
archiveEvery='Day' />
<target fileName='" + Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + @".log'
name = 'file'
type = 'File'
layout = '${message}' />
</targets>
<rules>
<logger name='*' writeTo='file'/>
</rules>
</nlog> ");
LogManager.Configuration = configuration;
LogManager.GetLogger("TestLogger").Info("DefaultFileTargetParametersTests.DontThrowExceptionWhenArchiveEverySetByDefaultParameters is true");
}
[Fact]
public void DataTypesTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<extensions>
<add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
uriProperty='http://nlog-project.org'
lineEndingModeProperty='default'
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.True(myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
Assert.Equal(new Uri("http://nlog-project.org"), myTarget.UriProperty);
Assert.Equal(LineEndingMode.Default, myTarget.LineEndingModeProperty);
}
[Fact]
public void NullableDataTypesTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<extensions>
<add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyNullableTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.True(myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
}
[Target("MyTarget")]
public class MyTarget : Target
{
public byte ByteProperty { get; set; }
public short Int16Property { get; set; }
public int Int32Property { get; set; }
public long Int64Property { get; set; }
public string StringProperty { get; set; }
public bool BoolProperty { get; set; }
public double DoubleProperty { get; set; }
public float FloatProperty { get; set; }
public MyEnum EnumProperty { get; set; }
public MyFlagsEnum FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
public Uri UriProperty { get; set; }
public LineEndingMode LineEndingModeProperty { get; set; }
public MyTarget() : base()
{
}
public MyTarget(string name) : this()
{
Name = name;
}
}
[Target("MyNullableTarget")]
public class MyNullableTarget : Target
{
public byte? ByteProperty { get; set; }
public short? Int16Property { get; set; }
public int? Int32Property { get; set; }
public long? Int64Property { get; set; }
public string StringProperty { get; set; }
public bool? BoolProperty { get; set; }
public double? DoubleProperty { get; set; }
public float? FloatProperty { get; set; }
public MyEnum? EnumProperty { get; set; }
public MyFlagsEnum? FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
public MyNullableTarget() : base()
{
}
public MyNullableTarget(string name) : this()
{
Name = name;
}
}
public enum MyEnum
{
Value1,
Value2,
Value3,
}
[Flags]
public enum MyFlagsEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
}
[Target("StructuredDebugTarget")]
public class StructuredDebugTarget : TargetWithLayout
{
public StructuredDebugTargetConfig Config { get; set; }
public StructuredDebugTarget()
{
Config = new StructuredDebugTargetConfig();
}
}
public class StructuredDebugTargetConfig
{
public string Platform { get; set; }
public StructuredDebugTargetParameter Parameter { get; set; }
public StructuredDebugTargetConfig()
{
Parameter = new StructuredDebugTargetParameter();
}
}
public class StructuredDebugTargetParameter
{
public string Name { get; set; }
}
}
}
| |
using System;
using System.Security.Cryptography;
using System.Text;
using Sodium.Exceptions;
namespace Sodium
{
/// <summary>Create and Open Boxes.</summary>
public static class PublicKeyBox
{
public const int PublicKeyBytes = 32;
public const int SecretKeyBytes = 32;
private const int NONCE_BYTES = 24;
private const int MAC_BYTES = 16;
/// <summary>Creates a new key pair based on a random seed.</summary>
/// <returns>A KeyPair.</returns>
public static KeyPair GenerateKeyPair()
{
var publicKey = new byte[PublicKeyBytes];
var privateKey = new byte[SecretKeyBytes];
SodiumLibrary.crypto_box_keypair(publicKey, privateKey);
return new KeyPair(publicKey, privateKey);
}
/// <summary>Creates a new key pair based on the provided private key.</summary>
/// <param name="privateKey">The private key.</param>
/// <returns>A KeyPair.</returns>
/// <exception cref="SeedOutOfRangeException"></exception>
public static KeyPair GenerateKeyPair(byte[] privateKey)
{
//validate the length of the seed
if (privateKey == null || privateKey.Length != SecretKeyBytes)
throw new SeedOutOfRangeException("privateKey", (privateKey == null) ? 0 : privateKey.Length,
string.Format("privateKey must be {0} bytes in length.", SecretKeyBytes));
var publicKey = ScalarMult.Base(privateKey);
return new KeyPair(publicKey, privateKey);
}
/// <summary>Creates a new key pair based on the provided seed.</summary>
/// <param name="seed">Seed data.</param>
/// <returns>A KeyPair.</returns>
/// <exception cref="SeedOutOfRangeException"></exception>
public static KeyPair GenerateSeededKeyPair(byte[] seed)
{
var publicKey = new byte[PublicKeyBytes];
var privateKey = new byte[SecretKeyBytes];
// Expected length of the keypair seed
int seedBytes = SodiumLibrary.crypto_box_seedbytes();
//validate the length of the seed
if (seed == null || seed.Length != seedBytes)
throw new SeedOutOfRangeException("seed", (seed == null) ? 0 : seed.Length,
string.Format("Key seed must be {0} bytes in length.", SecretKeyBytes));
SodiumLibrary.crypto_box_seed_keypair(publicKey, privateKey, seed);
return new KeyPair(publicKey, privateKey);
}
/// <summary>Generates a random 24 byte nonce.</summary>
/// <returns>Returns a byte array with 24 random bytes</returns>
public static byte[] GenerateNonce()
{
return SodiumCore.GetRandomBytes(NONCE_BYTES);
}
/// <summary>Creates a Box</summary>
/// <param name="message">The message.</param>
/// <param name="nonce">The 24 byte nonce.</param>
/// <param name="secretKey">The secret key to sign message with.</param>
/// <param name="publicKey">The recipient's public key.</param>
/// <returns>The encrypted message.</returns>
/// <exception cref="KeyOutOfRangeException"></exception>
/// <exception cref="NonceOutOfRangeException"></exception>
/// <exception cref="CryptographicException"></exception>
public static byte[] Create(string message, byte[] nonce, byte[] secretKey, byte[] publicKey)
{
return Create(Encoding.UTF8.GetBytes(message), nonce, secretKey, publicKey);
}
/// <summary>Creates a Box</summary>
/// <param name="message">The message.</param>
/// <param name="nonce">The 24 byte nonce.</param>
/// <param name="secretKey">The secret key to sign message with.</param>
/// <param name="publicKey">The recipient's public key.</param>
/// <returns>The encrypted message.</returns>
/// <exception cref="KeyOutOfRangeException"></exception>
/// <exception cref="NonceOutOfRangeException"></exception>
/// <exception cref="CryptographicException"></exception>
public static byte[] Create(byte[] message, byte[] nonce, byte[] secretKey, byte[] publicKey)
{
//validate the length of the secret key
if (secretKey == null || secretKey.Length != SecretKeyBytes)
throw new KeyOutOfRangeException("secretKey", (secretKey == null) ? 0 : secretKey.Length,
string.Format("key must be {0} bytes in length.", SecretKeyBytes));
//validate the length of the public key
if (publicKey == null || publicKey.Length != PublicKeyBytes)
throw new KeyOutOfRangeException("publicKey", (publicKey == null) ? 0 : publicKey.Length,
string.Format("key must be {0} bytes in length.", PublicKeyBytes));
//validate the length of the nonce
if (nonce == null || nonce.Length != NONCE_BYTES)
throw new NonceOutOfRangeException("nonce", (nonce == null) ? 0 : nonce.Length,
string.Format("nonce must be {0} bytes in length.", NONCE_BYTES));
var buffer = new byte[message.Length + MAC_BYTES];
var ret = SodiumLibrary.crypto_box_easy(buffer, message, message.Length, nonce, publicKey, secretKey);
if (ret != 0)
throw new CryptographicException("Failed to create PublicKeyBox");
return buffer;
}
/// <summary>Creates detached a Box</summary>
/// <param name="message">The message.</param>
/// <param name="nonce">The 24 byte nonce.</param>
/// <param name="secretKey">The secret key to sign message with.</param>
/// <param name="publicKey">The recipient's public key.</param>
/// <returns>A detached object with a cipher and a mac.</returns>
/// <exception cref="KeyOutOfRangeException"></exception>
/// <exception cref="NonceOutOfRangeException"></exception>
/// <exception cref="CryptographicException"></exception>
public static DetachedBox CreateDetached(string message, byte[] nonce, byte[] secretKey, byte[] publicKey)
{
return CreateDetached(Encoding.UTF8.GetBytes(message), nonce, secretKey, publicKey);
}
/// <summary>Creates a detached Box</summary>
/// <param name="message">The message.</param>
/// <param name="nonce">The 24 byte nonce.</param>
/// <param name="secretKey">The secret key to sign message with.</param>
/// <param name="publicKey">The recipient's public key.</param>
/// <returns>A detached object with a cipher and a mac.</returns>
/// <exception cref="KeyOutOfRangeException"></exception>
/// <exception cref="NonceOutOfRangeException"></exception>
/// <exception cref="CryptographicException"></exception>
public static DetachedBox CreateDetached(byte[] message, byte[] nonce, byte[] secretKey, byte[] publicKey)
{
//validate the length of the secret key
if (secretKey == null || secretKey.Length != SecretKeyBytes)
throw new KeyOutOfRangeException("secretKey", (secretKey == null) ? 0 : secretKey.Length,
string.Format("key must be {0} bytes in length.", SecretKeyBytes));
//validate the length of the public key
if (publicKey == null || publicKey.Length != PublicKeyBytes)
throw new KeyOutOfRangeException("publicKey", (publicKey == null) ? 0 : secretKey.Length,
string.Format("key must be {0} bytes in length.", PublicKeyBytes));
//validate the length of the nonce
if (nonce == null || nonce.Length != NONCE_BYTES)
throw new NonceOutOfRangeException("nonce", (nonce == null) ? 0 : nonce.Length,
string.Format("nonce must be {0} bytes in length.", NONCE_BYTES));
var cipher = new byte[message.Length];
var mac = new byte[MAC_BYTES];
var ret = SodiumLibrary.crypto_box_detached(cipher, mac, message, message.Length, nonce, secretKey, publicKey);
if (ret != 0)
throw new CryptographicException("Failed to create public detached Box");
return new DetachedBox(cipher, mac);
}
/// <summary>Opens a Box</summary>
/// <param name="cipherText"></param>
/// <param name="nonce">The 24 byte nonce.</param>
/// <param name="secretKey">The recipient's secret key.</param>
/// <param name="publicKey">The sender's public key.</param>
/// <returns>The decrypted message.</returns>
/// <exception cref="KeyOutOfRangeException"></exception>
/// <exception cref="NonceOutOfRangeException"></exception>
/// <exception cref="CryptographicException"></exception>
public static byte[] Open(byte[] cipherText, byte[] nonce, byte[] secretKey, byte[] publicKey)
{
//validate the length of the secret key
if (secretKey == null || secretKey.Length != SecretKeyBytes)
throw new KeyOutOfRangeException("secretKey", (secretKey == null) ? 0 : secretKey.Length,
string.Format("key must be {0} bytes in length.", SecretKeyBytes));
//validate the length of the public key
if (publicKey == null || publicKey.Length != PublicKeyBytes)
throw new KeyOutOfRangeException("publicKey", (publicKey == null) ? 0 : secretKey.Length,
string.Format("key must be {0} bytes in length.", PublicKeyBytes));
//validate the length of the nonce
if (nonce == null || nonce.Length != NONCE_BYTES)
throw new NonceOutOfRangeException("nonce", (nonce == null) ? 0 : nonce.Length,
string.Format("nonce must be {0} bytes in length.", NONCE_BYTES));
//check to see if there are MAC_BYTES of leading nulls, if so, trim.
//this is required due to an error in older versions.
if (cipherText[0] == 0)
{
//check to see if trim is needed
var trim = true;
for (var i = 0; i < MAC_BYTES - 1; i++)
{
if (cipherText[i] != 0)
{
trim = false;
break;
}
}
//if the leading MAC_BYTES are null, trim it off before going on.
if (trim)
{
var temp = new byte[cipherText.Length - MAC_BYTES];
Array.Copy(cipherText, MAC_BYTES, temp, 0, cipherText.Length - MAC_BYTES);
cipherText = temp;
}
}
var buffer = new byte[cipherText.Length - MAC_BYTES];
var ret = SodiumLibrary.crypto_box_open_easy(buffer, cipherText, cipherText.Length, nonce, publicKey, secretKey);
if (ret != 0)
throw new CryptographicException("Failed to open PublicKeyBox");
return buffer;
}
/// <summary>Opens a detached Box</summary>
/// <param name="cipherText">Hex-encoded string to be opened.</param>
/// <param name="mac">The 16 byte mac.</param>
/// <param name="nonce">The 24 byte nonce.</param>
/// <param name="secretKey">The recipient's secret key.</param>
/// <param name="publicKey">The sender's public key.</param>
/// <returns>The decrypted message.</returns>
/// <exception cref="KeyOutOfRangeException"></exception>
/// <exception cref="MacOutOfRangeException"></exception>
/// <exception cref="NonceOutOfRangeException"></exception>
/// <exception cref="CryptographicException"></exception>
public static byte[] OpenDetached(string cipherText, byte[] mac, byte[] nonce, byte[] secretKey, byte[] publicKey)
{
return OpenDetached(Utilities.HexToBinary(cipherText), mac, nonce, secretKey, publicKey);
}
/// <summary>Opens a detached Box</summary>
/// <param name="detached">A detached object.</param>
/// <param name="nonce">The 24 byte nonce.</param>
/// <param name="secretKey">The recipient's secret key.</param>
/// <param name="publicKey">The sender's public key.</param>
/// <returns>The decrypted message.</returns>
/// <exception cref="KeyOutOfRangeException"></exception>
/// <exception cref="MacOutOfRangeException"></exception>
/// <exception cref="NonceOutOfRangeException"></exception>
/// <exception cref="CryptographicException"></exception>
public static byte[] OpenDetached(DetachedBox detached, byte[] nonce, byte[] secretKey, byte[] publicKey)
{
return OpenDetached(detached.CipherText, detached.Mac, nonce, secretKey, publicKey);
}
/// <summary>Opens a detached Box</summary>
/// <param name="cipherText">The cipherText.</param>
/// <param name="mac">The 16 byte mac.</param>
/// <param name="nonce">The 24 byte nonce.</param>
/// <param name="secretKey">The recipient's secret key.</param>
/// <param name="publicKey">The sender's public key.</param>
/// <returns>The decrypted message.</returns>
/// <exception cref="KeyOutOfRangeException"></exception>
/// <exception cref="MacOutOfRangeException"></exception>
/// <exception cref="NonceOutOfRangeException"></exception>
/// <exception cref="CryptographicException"></exception>
public static byte[] OpenDetached(byte[] cipherText, byte[] mac, byte[] nonce, byte[] secretKey, byte[] publicKey)
{
//validate the length of the secret key
if (secretKey == null || secretKey.Length != SecretKeyBytes)
throw new KeyOutOfRangeException("secretKey", (secretKey == null) ? 0 : secretKey.Length,
string.Format("key must be {0} bytes in length.", SecretKeyBytes));
//validate the length of the public key
if (publicKey == null || publicKey.Length != PublicKeyBytes)
throw new KeyOutOfRangeException("publicKey", (publicKey == null) ? 0 : secretKey.Length,
string.Format("key must be {0} bytes in length.", PublicKeyBytes));
//validate the length of the mac
if (mac == null || mac.Length != MAC_BYTES)
throw new MacOutOfRangeException("mac", (mac == null) ? 0 : mac.Length,
string.Format("mac must be {0} bytes in length.", MAC_BYTES));
//validate the length of the nonce
if (nonce == null || nonce.Length != NONCE_BYTES)
throw new NonceOutOfRangeException("nonce", (nonce == null) ? 0 : nonce.Length,
string.Format("nonce must be {0} bytes in length.", NONCE_BYTES));
var buffer = new byte[cipherText.Length];
var ret = SodiumLibrary.crypto_box_open_detached(buffer, cipherText, mac, cipherText.Length, nonce, secretKey, publicKey);
if (ret != 0)
throw new CryptographicException("Failed to open public detached Box");
return buffer;
}
}
}
| |
// Copyright (C) 2015 Luca Piccioni
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace BindingsGen.GLSpecs
{
/// <summary>
/// Registry command parameter.
/// </summary>
[DebuggerDisplay("CommandParameter: Name={Name} Group={Group} Length={Length} Type={Type}")]
public class CommandParameter : ICommandParameter
{
#region Constructors
/// <summary>
/// Parameterless constructor.
/// </summary>
public CommandParameter()
{
}
/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="otherParam">
/// Another CommandParameter to be copied.
/// </param>
public CommandParameter(CommandParameter otherParam)
{
if (otherParam == null)
throw new ArgumentNullException(nameof(otherParam));
Group = otherParam.Group;
Length = otherParam.Length;
Type = otherParam.Type;
TypeDecorators = new List<string>(otherParam.TypeDecorators);
Name = otherParam.Name;
ParentCommand = otherParam.ParentCommand;
OverridenParameter = otherParam;
}
#endregion
#region Specification
/// <summary>
/// Group name, an arbitrary string
/// </summary>
[XmlAttribute("group")]
public String Group;
/// <summary>
/// The parameter length, either an integer specifying the number of elements of the parameter <ptype>, or a
/// complex string expression with poorly defined syntax, usually representing a length that is computed as a
/// combination of other command parameter values, and possibly current GL state as well.
/// </summary>
[XmlAttribute("len")]
public String Length;
/// <summary>
/// The Type is optional, and contains text which is a valid type name found in Type, and indicates that this
/// type must be previously defined for the definition of the command to succeed. Builtin C types, and any derived
/// types which are expected to be found in other header files, should not be wrapped in Type.
/// </summary>
[XmlElement("ptype")]
public String Type;
/// <summary>
///
/// </summary>
[XmlText()]
public List<String> TypeDecorators = new List<String>();
/// <summary>
///
/// </summary>
public String TypeDecorator
{
get
{
if (TypeDecorators.Count > 0)
return (TypeDecorators[TypeDecorators.Count - 1].Trim());
return (null);
}
}
/// <summary>
/// The name is required, and contains the parameter name being described.
/// </summary>
[XmlElement("name")]
public String Name;
/// <summary>
/// Overriden parameter.
/// </summary>
[XmlIgnore()]
public CommandParameter OverridenParameter;
#endregion
#region Length Management
/// <summary>
/// Get the length mode for this parameter.
/// </summary>
public CommandParameterLengthMode LengthMode
{
get
{
// No length information
if (String.IsNullOrEmpty(Length))
return (CommandParameterLengthMode.None);
// Constant length?
uint constLength;
if (UInt32.TryParse(Length, out constLength))
return (CommandParameterLengthMode.Constant);
// Argument?
if (ParentCommand.Parameters.Exists(delegate(CommandParameter item) { return (item.Name == Length); }))
return (CommandParameterLengthMode.ArgumentReference);
// Argument multiple?
Match argumentMultipleMatch = Regex.Match(Length, @"(?<Arg>\w[\w\d_]*)\*(\d+)");
if (argumentMultipleMatch.Success) {
string argumentMultipleName = argumentMultipleMatch.Groups["Arg"].Value;
if (ParentCommand.Parameters.Exists(delegate(CommandParameter item) { return (item.Name == argumentMultipleName); }))
return (CommandParameterLengthMode.ArgumentMultiple);
}
return (CommandParameterLengthMode.Complex);
}
}
public uint LengthConstant
{
get
{
uint constLength;
if (UInt32.TryParse(Length, out constLength))
return (constLength);
throw new InvalidOperationException("not a const-length constraint");
}
}
public string LengthArgument
{
get
{
Match argumentMultipleMatch = Regex.Match(Length, @"(?<Arg>\w[\w\d_]*)\*(?<Mul>\d+)");
if (argumentMultipleMatch.Success)
return (argumentMultipleMatch.Groups["Arg"].Value);
throw new InvalidOperationException("not a multiple-length constraint");
}
}
public uint LengthMultiple
{
get
{
Match argumentMultipleMatch = Regex.Match(Length, @"(?<Arg>\w[\w\d_]*)\*(?<Mul>\d+)");
if (argumentMultipleMatch.Success) {
string argumentMultipleValue = argumentMultipleMatch.Groups["Mul"].Value;
return (UInt32.Parse(argumentMultipleValue));
}
throw new InvalidOperationException("not a multiple-length constraint");
}
}
#endregion
#region Code Generation - Implementation
/// <summary>
/// Determine whether this CommandParameter can be used in a safe context.
/// </summary>
internal bool IsSafe
{
get
{
string importType = ImportType;
if (importType.EndsWith("*") || (importType == "IntPtr"))
return (false);
return (true);
}
}
/// <summary>
/// Determine whether this CommandParameter can be used in a safe context when marshalling argument.
/// </summary>
internal bool IsSafeMarshal(Command parentCommand)
{
if ((GetManagedImplementationType(parentCommand) == "IntPtr") && (GetImportType(parentCommand) != "IntPtr"))
return (true);
return (false);
}
/// <summary>
/// Determine whether this CommandParameter must be used in a fixed context.
/// </summary>
/// <param name="ctx"></param>
/// <param name="parentCommand"></param>
/// <returns></returns>
internal virtual bool IsFixed(RegistryContext ctx, Command parentCommand)
{
string modifier = CommandFlagsDatabase.GetCommandArgumentModifier(parentCommand, this);
if (modifier == "ref" || modifier == "out")
return (false);
string implementationType = GetManagedImplementationType(parentCommand);
string importType = GetImportType(parentCommand);
if (Regex.IsMatch(implementationType.ToLower(), @"(string|bool)\[\]"))
return (Regex.IsMatch(importType.ToLower(), @"(string|bool)\*"));
if (implementationType.EndsWith("[]"))
return (true);
return (false);
}
/// <summary>
/// Determine whether this CommandParameter must be used in a pinned context.
/// </summary>
/// <param name="ctx"></param>
/// <param name="parentCommand"></param>
/// <returns></returns>
internal bool IsPinned(RegistryContext ctx, Command parentCommand)
{
return (Type == "object");
}
/// <summary>
///
/// </summary>
/// <param name="ctx"></param>
/// <param name="parentCommand"></param>
/// <returns></returns>
/// <remarks>
/// <para>
/// In the generale case, the implementation type corresponds to <see cref="ManagedImplementationType"/>.
/// </para>
/// <para>
/// In the case the implementation type is a managed array, but the specification assert a length equals to
/// 1, and <paramref name="parentCommand"/> is a "Get" implementation, the implementation type is converted
/// to a basic type, with an "out" modifier.
/// </para>
/// </remarks>
public virtual string GetImplementationType(RegistryContext ctx, Command parentCommand)
{
string modifier = CommandFlagsDatabase.GetCommandArgumentModifier(parentCommand, this);
string implementationType = GetManagedImplementationType(parentCommand);
// Type[] + Length=1 -> out Type
if ((IsConstant == false) && implementationType.EndsWith("[]") && (Length == "1") && ((parentCommand.IsGetImplementation(ctx) || ((parentCommand.Flags & CommandFlags.OutParam) != 0))))
implementationType = implementationType.Substring(0, implementationType.Length - 2);
// String + Length!=null && !IsConst -> [Out] StringBuilder (in Get commands)
if ((IsConstant == false) && (implementationType == "string") && (Length != null) && ((parentCommand.IsGetImplementation(ctx) || ((parentCommand.Flags & CommandFlags.OutParam) != 0))))
implementationType = "StringBuilder";
// Support 'ref' argument
if ((modifier == "ref" || modifier == "out") && implementationType.EndsWith("[]"))
implementationType = modifier + " " + implementationType.Substring(0, implementationType.Length - 2);
return (implementationType);
}
public string GetImplementationTypeModifier(RegistryContext ctx, Command parentCommand)
{
// Support ref argument
if (ModifierOverride != null)
return (ModifierOverride);
string implementationType = GetManagedImplementationType(parentCommand);
// Type[] + Length=1 -> out Type
if ((IsConstant == false) && implementationType.EndsWith("[]") && (Length == "1") && (parentCommand.IsGetImplementation(ctx)))
return ("out");
// Type[] + Length=1 -> out Type
if ((IsConstant == false) && implementationType.EndsWith("[]") && (Length == "1") && ((parentCommand.Flags & CommandFlags.OutParam) != 0))
return ("out");
return (null);
}
public string ModifierOverride;
public string GetImplementationTypeAttributes(RegistryContext ctx, Command parentCommand)
{
string implementationType = GetManagedImplementationType(parentCommand);
string implementationMod = GetImplementationTypeModifier(ctx, parentCommand);
string attribute = null;
// String + Length!=null && !IsConst -> [Out] StringBuilder (in Get commands)
if ((IsConstant == false) && (implementationType == "String") && (Length != null) && ((parentCommand.IsGetImplementation(ctx) || ((parentCommand.Flags & CommandFlags.OutParam) != 0))))
attribute = "[Out]";
// Array && !IsConst -> [Out] T[] (in Get commands)
if ((IsConstant == false) && (implementationType.EndsWith("[]")) && ((implementationMod != "out") && (implementationMod != "ref")) && ((parentCommand.IsGetImplementation(ctx) || ((parentCommand.Flags & CommandFlags.OutParam) != 0))))
attribute = "[Out]";
return (attribute);
}
/// <summary>
/// Get the parameter type for managed implementation.
/// </summary>
/// <remarks>
/// <para>
/// The parameter type for managed implementation is <see cref="ImportType"/> for basic (value) types. In
/// the case the type is a pointer type (reference), translate the type to a managed array.
/// </para>
/// <para>
/// In the case the <see cref="InputType"/> is a <code>void*</code>, is will be translated into <see cref="IntPtr"/>.
/// </para>
/// </remarks>
public string GetManagedImplementationType(Command parentCommand)
{
string implementationType = GetImportType(parentCommand);
implementationType = implementationType.Replace("*", "[]");
// void* > IntPtr
if (implementationType == "void[]")
implementationType = "IntPtr";
return (implementationType);
}
/// <summary>
/// Get the command parameter name, without altering it for language conformance (i.e. the '@' escaping character).
/// </summary>
public string ImplementationNameRaw
{
get
{
if (ParentCommand != null) {
string alternativeName = CommandFlagsDatabase.GetCommandArgumentAlternativeName(ParentCommand, this);
return (alternativeName ?? Name);
} else
return (Name);
}
}
/// <summary>
/// Get the command parameter name.
/// </summary>
public string ImplementationName
{
get
{
string rawName = ImplementationNameRaw;
return (TypeMap.IsCsKeyword(rawName) ? "@" + rawName : rawName);
}
}
public string FixedLocalVarName
{
get
{
string fixedName = String.Format("p_{0}", Name);
return (TypeMap.IsCsKeyword(fixedName) ? "@" + fixedName : fixedName);
}
}
public virtual string GetDelegateCallVarName(Command parentCommand)
{
string delegateVarName = ImplementationName;
if ((GetManagedImplementationType(parentCommand) == "IntPtr") && (GetImportType(parentCommand) != "IntPtr"))
delegateVarName = String.Format("{0}.ToPointer()", ImplementationName);
return (delegateVarName);
}
#endregion
#region Code Generation - Delegate
public string GetDelegateType(RegistryContext ctx, Command parentCommand)
{
string modifier = CommandFlagsDatabase.GetCommandArgumentModifier(parentCommand, this);
string implementationType = GetImportType(parentCommand);
// String + Length!=null -> [Out] StringBuilder
if ((IsConstant == false) && (implementationType == "string") && (Length != null) && ((parentCommand.IsGetImplementation(ctx) || ((parentCommand.Flags & CommandFlags.OutParam) != 0))))
implementationType = "StringBuilder";
// Support 'ref' argument
if ((modifier == "ref" || modifier == "out") && implementationType.EndsWith("*"))
implementationType = modifier + " " + implementationType.Substring(0, implementationType.Length - 1);
return (implementationType.Trim());
}
public string GetDelegateTypeModifier(RegistryContext ctx, Command parentCommand)
{
return (null);
}
public string GetDelegateTypeAttributes(RegistryContext ctx, Command parentCommand)
{
string implementationType = GetManagedImplementationType(parentCommand);
string attribute = null;
// String + Length!=null -> [Out] StringBuilder
if ((IsConstant == false) && (implementationType == "String") && (Length != null) && ((parentCommand.IsGetImplementation(ctx) || ((parentCommand.Flags & CommandFlags.OutParam) != 0))))
attribute = "[Out]";
switch (SpecificationType) {
case "GLboolean": // bool
attribute = (attribute ?? String.Empty) + "[MarshalAs(UnmanagedType.I1)]";
break;
// Note: MarshalAsAttribute not applicable to bool*!
//case "GLboolean*": // bool[]
// attribute = (attribute ?? String.Empty) + "[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1)]";
// break;
}
return (attribute);
}
#endregion
#region Code Generation - Import
public string GetImportType()
{
if (ParentCommand == null)
throw new InvalidOperationException("no parent command");
return (GetImportType(ParentCommand));
}
public string GetImportType(Command parentCommand)
{
string retype = CommandFlagsDatabase.GetCommandArgumentAlternativeType(parentCommand, this);
if (retype != null)
return (TypeMap.CsTypeMap.MapType(retype));
return (ImportType);
}
private string SpecificationType
{
get
{
string typeDecorator = TypeDecorator != null ? TypeDecorator.Trim() : null;
string type = Type != null ? Type.Trim() : null;
if (typeDecorator != null) {
// glPathGlyphIndexRangeNV: <param><ptype>GLuint</ptype> <name>baseAndCount</name>[2]</param>
if (Regex.Match(typeDecorator, @"\[\d+\]").Success)
typeDecorator = "*";
}
if (type != null && type.StartsWith("const ")) {
// Remove any const modifier at the beginning of the type
// does .NET can take advantage of this information? AFAIK no
type = type.Substring(5); // .Replace("const", String.Empty);
}
string importType = "IntPtr";
if ((type != null) && (typeDecorator != null))
importType = type + typeDecorator;
else if (type != null)
importType = type;
else if (typeDecorator != null)
importType = typeDecorator;
return (importType);
}
}
private string ImportType
{
get
{
string specificationType = SpecificationType;
// Special type handling for GLboolean arrays as arguments: they are marshaled as bytes!
switch (specificationType) {
case "GLboolean*":
specificationType = "byte*";
break;
}
return (TypeMap.CsTypeMap.MapType(specificationType));
}
}
public string ImportName
{
get { return (TypeMap.IsCsKeyword(Name) ? "@" + Name : Name); }
}
#endregion
#region Code Generation - Common
public bool IsManagedArray(RegistryContext ctx, Command parentCommand)
{
return (GetImplementationType(ctx, parentCommand).EndsWith("[]"));
}
public bool IsConstant
{
get
{
if (TypeDecorators.FindIndex(delegate(string item) { return (item.Trim() == "const"); }) >= 0)
return (true);
if ((TypeDecorators.Count == 1) && (TypeDecorators[0].StartsWith("const")))
return (true);
return (false);
}
}
public bool IsEnum
{
get
{
CommandFlagsDatabase.CommandItem.ParameterItemFlags paramFlags = CommandFlagsDatabase.GetCommandParameterFlags(ParentCommand, this);
if ((paramFlags & CommandFlagsDatabase.CommandItem.ParameterItemFlags.LogAsEnum) != 0)
return (true);
switch (Type) {
case "GLenum":
case "EGLenum":
return (true);
default:
return (false);
}
}
}
#endregion
#region Information Linkage
public int GetCommandIndex(Command parentCommand)
{
return (parentCommand.Parameters.IndexOf(this));
}
/// <summary>
/// The parent command which this command parameter belongs to.
/// </summary>
[XmlIgnore()]
public Command ParentCommand;
#endregion
#region ICommandParameter Implementation
public virtual bool IsImplicit(RegistryContext ctx, Command parentCommand) { return (false); }
public virtual void WriteDebugAssertion(SourceStreamWriter sw, RegistryContext ctx, Command parentCommand)
{
switch (LengthMode) {
case CommandParameterLengthMode.Constant:
// Note:
// - The argument must be an Array instance
if (IsManagedArray(ctx, parentCommand))
sw.WriteLine("Debug.Assert({0}.Length >= {1});", ImplementationName, LengthConstant);
break;
case CommandParameterLengthMode.ArgumentMultiple:
uint multiple = LengthMultiple;
// Note:
// - The array must provide 'n' elements for each unit in counter parameter
if (IsManagedArray(ctx, parentCommand) && multiple > 1)
sw.WriteLine("Debug.Assert({0}.Length > 0 && ({0}.Length % {1}) == 0, \"empty or not multiple of {1}\");", ImplementationName, multiple);
break;
}
}
public virtual void WriteFixedStatement(SourceStreamWriter sw, RegistryContext ctx, Command parentCommand)
{
if (IsFixed(ctx, parentCommand) == false)
return;
string dereference = String.Empty;
switch (GetImplementationTypeModifier(ctx, parentCommand)) {
case "out":
case "ref":
dereference = "&";
break;
}
sw.WriteLine("fixed ({0} {1} = {2}{3})", GetImportType(parentCommand), FixedLocalVarName, dereference, ImplementationName);
}
public virtual void WriteImplementationParam(SourceStreamWriter sw, RegistryContext ctx, Command parentCommand)
{
sw.Write(GetDelegateCallVarName(parentCommand));
}
public virtual void WriteDelegateParam(SourceStreamWriter sw, RegistryContext ctx, Command parentCommand)
{
if (IsFixed(ctx, parentCommand) == false) {
string modifier = CommandFlagsDatabase.GetCommandArgumentModifier(parentCommand, this);
if (modifier != null)
sw.Write(modifier + " ");
sw.Write(GetDelegateCallVarName(parentCommand));
} else
sw.Write(FixedLocalVarName);
}
public virtual void WriteCallLogFormatParam(SourceStreamWriter sw, RegistryContext ctx, Command parentCommand, int paramIndex)
{
string implementationType = GetImplementationType(ctx, parentCommand);
bool safeImplementationType = !implementationType.EndsWith("*") && implementationType != "IntPtr";
if (safeImplementationType == false)
sw.Write("0x{{{0}}}", paramIndex);
else
sw.Write("{{{0}}}", paramIndex);
}
public virtual void WriteCallLogArgParam(SourceStreamWriter sw, RegistryContext ctx, Command parentCommand)
{
CommandFlagsDatabase.CommandItem.ParameterItemFlags parameterFlags = CommandFlagsDatabase.GetCommandParameterFlags(parentCommand, this);
//if (((Type != null) && (Type == "GLenum")) || ((parameterFlags & CommandFlagsDatabase.CommandItem.ParameterItemFlags.LogAsEnum) != 0))
// sw.Write("LogEnumName({0})", ImplementationName);
//else if (IsManagedArray && GetImplementationTypeModifier(ctx, parentCommand) != "out")
// sw.Write("LogValue({0})", ImplementationName);
//else
WriteCallLogArgParam(sw, ImplementationName, GetImplementationType(ctx, parentCommand));
}
public static void WriteCallLogArgParam(SourceStreamWriter sw, string implementationName, string implementationType)
{
if (implementationType.EndsWith("*"))
sw.Write("new IntPtr({0})", implementationName);
//else if (implementationType == "IntPtr")
// sw.Write("{0}.ToString(\"X8\")", implementationName);
else
sw.Write("{0}", implementationName);
}
public virtual void WritePinnedVariable(SourceStreamWriter sw, RegistryContext ctx, Command parentCommand)
{
// No code for common parameter
}
public virtual void WriteUnpinCommand(SourceStreamWriter sw, RegistryContext ctx, Command parentCommand)
{
// No code for common parameter
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using Microsoft.PythonTools.Editor.Core;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.PythonTools.Editor {
/// <summary>
/// Provides highlighting of matching braces in a text view.
/// </summary>
class BraceMatcher {
private readonly ITextView _textView;
private readonly PythonEditorServices _editorServices;
private ITextBuffer _markedBuffer;
private static TextMarkerTag _tag = new TextMarkerTag("Brace Matching (Rectangle)");
/// <summary>
/// Starts watching the provided text view for brace matching. When new braces are inserted
/// in the text or when the cursor moves to a brace the matching braces are highlighted.
/// </summary>
public static void WatchBraceHighlights(PythonEditorServices editorServices, ITextView view) {
var matcher = new BraceMatcher(editorServices, view);
// position changed only fires when the caret is explicitly moved, not from normal text edits,
// so we track both changes and position changed.
view.Caret.PositionChanged += matcher.CaretPositionChanged;
view.TextBuffer.Changed += matcher.TextBufferChanged;
view.Closed += matcher.TextViewClosed;
}
public BraceMatcher(PythonEditorServices editorServices, ITextView view) {
_textView = view;
_editorServices = editorServices;
}
private void TextViewClosed(object sender, EventArgs e) {
_textView.Caret.PositionChanged -= CaretPositionChanged;
_textView.TextBuffer.Changed -= TextBufferChanged;
_textView.Closed -= TextViewClosed;
}
private void CaretPositionChanged(object sender, CaretPositionChangedEventArgs e) {
RemoveExistingHighlights();
UpdateBraceMatching(e.NewPosition.BufferPosition.Position);
}
private void TextBufferChanged(object sender, TextContentChangedEventArgs changed) {
RemoveExistingHighlights();
if (changed.Changes.Count == 1) {
var newText = changed.Changes[0].NewText;
if (newText == ")" || newText == "}" || newText == "]") {
UpdateBraceMatching(changed.Changes[0].NewPosition + 1);
}
}
}
private bool HasTags {
get {
return _markedBuffer != null;
}
}
private void RemoveExistingHighlights() {
if (HasTags) {
RemoveExistingHighlights(_markedBuffer);
_markedBuffer = null;
}
}
private void UpdateBraceMatching(int pos) {
if (pos != 0) {
var prevCharText = _textView.TextBuffer.CurrentSnapshot.GetText(pos - 1, 1);
if (prevCharText == ")" || prevCharText == "]" || prevCharText == "}") {
if (HighlightBrace(GetBraceKind(prevCharText), pos, -1)) {
return;
}
}
}
if (pos != _textView.TextBuffer.CurrentSnapshot.Length) {
var nextCharText = _textView.TextBuffer.CurrentSnapshot.GetText(pos, 1);
if (nextCharText == "(" || nextCharText == "[" || nextCharText == "{") {
HighlightBrace(GetBraceKind(nextCharText), pos + 1, 1);
}
}
}
private void RemoveExistingHighlights(ITextBuffer buffer) {
if (HasTags) {
GetTextMarker(buffer).RemoveTagSpans(x => true);
}
}
private SimpleTagger<TextMarkerTag> GetTextMarker(ITextBuffer buffer) {
return _editorServices.TextMarkerProviderFactory.GetTextMarkerTagger(buffer);
}
private bool HighlightBrace(BraceKind brace, int position, int direction) {
var pt = _textView.BufferGraph.MapDownToInsertionPoint(
new SnapshotPoint(_textView.TextBuffer.CurrentSnapshot, position),
PointTrackingMode.Positive,
EditorExtensions.IsPythonContent
);
if (pt == null) {
return false;
}
return HighlightBrace(brace, pt.Value, direction);
}
private bool HighlightBrace(BraceKind brace, SnapshotPoint position, int direction) {
var buffer = _editorServices.GetBufferInfo(position.Snapshot.TextBuffer);
if (buffer == null) {
return false;
}
var snapshot = position.Snapshot;
var span = new SnapshotSpan(snapshot, position.Position - 1, 1);
var originalSpan = span;
if (!(buffer.GetTokenAtPoint(position)?.Trigger ?? Parsing.TokenTriggers.None).HasFlag(Parsing.TokenTriggers.MatchBraces)) {
return false;
}
int depth = 0;
foreach (var token in (direction > 0 ? buffer.GetTokensForwardFromPoint(position) : buffer.GetTokensInReverseFromPoint(position - 1))) {
if (!token.Trigger.HasFlag(Parsing.TokenTriggers.MatchBraces)) {
continue;
}
var tspan = token.ToSnapshotSpan(snapshot);
var txt = tspan.GetText();
try {
if (IsSameBraceKind(txt, brace)) {
if (txt.IsCloseGrouping()) {
depth -= direction;
} else {
depth += direction;
}
}
} catch (InvalidOperationException) {
return false;
}
if (depth == 0) {
RemoveExistingHighlights();
_markedBuffer = snapshot.TextBuffer;
// left brace
GetTextMarker(snapshot.TextBuffer).CreateTagSpan(snapshot.CreateTrackingSpan(tspan, SpanTrackingMode.EdgeExclusive), _tag);
// right brace
GetTextMarker(snapshot.TextBuffer).CreateTagSpan(snapshot.CreateTrackingSpan(new SnapshotSpan(snapshot, position - 1, 1), SpanTrackingMode.EdgeExclusive), _tag);
return true;
}
}
return false;
}
private enum BraceKind {
Bracket,
Paren,
Brace
}
private static bool IsSameBraceKind(string brace, BraceKind kind) {
return GetBraceKind(brace) == kind;
}
private static BraceKind GetBraceKind(string brace) {
if (string.IsNullOrEmpty(brace)) {
throw new InvalidOperationException();
}
switch (brace[0]) {
case '[':
case ']': return BraceKind.Bracket;
case '(':
case ')': return BraceKind.Paren;
case '{':
case '}': return BraceKind.Bracket;
default: throw new InvalidOperationException();
}
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// An in-memory representation of a JSON Schema.
/// </summary>
public class JsonSchema
{
/// <summary>
/// Gets or sets the id.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets whether the object is required.
/// </summary>
public bool? Required { get; set; }
/// <summary>
/// Gets or sets whether the object is read only.
/// </summary>
public bool? ReadOnly { get; set; }
/// <summary>
/// Gets or sets whether the object is visible to users.
/// </summary>
public bool? Hidden { get; set; }
/// <summary>
/// Gets or sets whether the object is transient.
/// </summary>
public bool? Transient { get; set; }
/// <summary>
/// Gets or sets the description of the object.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the types of values allowed by the object.
/// </summary>
/// <value>The type.</value>
public JsonSchemaType? Type { get; set; }
/// <summary>
/// Gets or sets the pattern.
/// </summary>
/// <value>The pattern.</value>
public string Pattern { get; set; }
/// <summary>
/// Gets or sets the minimum length.
/// </summary>
/// <value>The minimum length.</value>
public int? MinimumLength { get; set; }
/// <summary>
/// Gets or sets the maximum length.
/// </summary>
/// <value>The maximum length.</value>
public int? MaximumLength { get; set; }
/// <summary>
/// Gets or sets a number that the value should be divisble by.
/// </summary>
/// <value>A number that the value should be divisble by.</value>
public double? DivisibleBy { get; set; }
/// <summary>
/// Gets or sets the minimum.
/// </summary>
/// <value>The minimum.</value>
public double? Minimum { get; set; }
/// <summary>
/// Gets or sets the maximum.
/// </summary>
/// <value>The maximum.</value>
public double? Maximum { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether the value can not equal the number defined by the "minimum" attribute.
/// </summary>
/// <value>A flag indicating whether the value can not equal the number defined by the "minimum" attribute.</value>
public bool? ExclusiveMinimum { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether the value can not equal the number defined by the "maximum" attribute.
/// </summary>
/// <value>A flag indicating whether the value can not equal the number defined by the "maximum" attribute.</value>
public bool? ExclusiveMaximum { get; set; }
/// <summary>
/// Gets or sets the minimum number of items.
/// </summary>
/// <value>The minimum number of items.</value>
public int? MinimumItems { get; set; }
/// <summary>
/// Gets or sets the maximum number of items.
/// </summary>
/// <value>The maximum number of items.</value>
public int? MaximumItems { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of items.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of items.</value>
public IList<JsonSchema> Items { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of properties.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of properties.</value>
public IDictionary<string, JsonSchema> Properties { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of additional properties.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of additional properties.</value>
public JsonSchema AdditionalProperties { get; set; }
/// <summary>
/// Gets or sets the pattern properties.
/// </summary>
/// <value>The pattern properties.</value>
public IDictionary<string, JsonSchema> PatternProperties { get; set; }
/// <summary>
/// Gets or sets a value indicating whether additional properties are allowed.
/// </summary>
/// <value>
/// <c>true</c> if additional properties are allowed; otherwise, <c>false</c>.
/// </value>
public bool AllowAdditionalProperties { get; set; }
/// <summary>
/// Gets or sets the required property if this property is present.
/// </summary>
/// <value>The required property if this property is present.</value>
public string Requires { get; set; }
/// <summary>
/// Gets or sets the identity.
/// </summary>
/// <value>The identity.</value>
public IList<string> Identity { get; set; }
/// <summary>
/// Gets or sets the a collection of valid enum values allowed.
/// </summary>
/// <value>A collection of valid enum values allowed.</value>
public IList<JToken> Enum { get; set; }
/// <summary>
/// Gets or sets a collection of options.
/// </summary>
/// <value>A collection of options.</value>
public IDictionary<JToken, string> Options { get; set; }
/// <summary>
/// Gets or sets disallowed types.
/// </summary>
/// <value>The disallow types.</value>
public JsonSchemaType? Disallow { get; set; }
/// <summary>
/// Gets or sets the default value.
/// </summary>
/// <value>The default value.</value>
public JToken Default { get; set; }
/// <summary>
/// Gets or sets the extend <see cref="JsonSchema"/>.
/// </summary>
/// <value>The extended <see cref="JsonSchema"/>.</value>
public JsonSchema Extends { get; set; }
/// <summary>
/// Gets or sets the format.
/// </summary>
/// <value>The format.</value>
public string Format { get; set; }
private readonly string _internalId = Guid.NewGuid().ToString("N");
internal string InternalId
{
get { return _internalId; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSchema"/> class.
/// </summary>
public JsonSchema()
{
AllowAdditionalProperties = true;
}
/// <summary>
/// Reads a <see cref="JsonSchema"/> from the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the JSON Schema to read.</param>
/// <returns>The <see cref="JsonSchema"/> object representing the JSON Schema.</returns>
public static JsonSchema Read(JsonReader reader)
{
return Read(reader, new JsonSchemaResolver());
}
/// <summary>
/// Reads a <see cref="JsonSchema"/> from the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the JSON Schema to read.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> to use when resolving schema references.</param>
/// <returns>The <see cref="JsonSchema"/> object representing the JSON Schema.</returns>
public static JsonSchema Read(JsonReader reader, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
JsonSchemaBuilder builder = new JsonSchemaBuilder(resolver);
return builder.Parse(reader);
}
/// <summary>
/// Load a <see cref="JsonSchema"/> from a string that contains schema JSON.
/// </summary>
/// <param name="json">A <see cref="String"/> that contains JSON.</param>
/// <returns>A <see cref="JsonSchema"/> populated from the string that contains JSON.</returns>
public static JsonSchema Parse(string json)
{
return Parse(json, new JsonSchemaResolver());
}
/// <summary>
/// Parses the specified json.
/// </summary>
/// <param name="json">The json.</param>
/// <param name="resolver">The resolver.</param>
/// <returns>A <see cref="JsonSchema"/> populated from the string that contains JSON.</returns>
public static JsonSchema Parse(string json, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(json, "json");
JsonReader reader = new JsonTextReader(new StringReader(json));
return Read(reader, resolver);
}
/// <summary>
/// Writes this schema to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
public void WriteTo(JsonWriter writer)
{
WriteTo(writer, new JsonSchemaResolver());
}
/// <summary>
/// Writes this schema to a <see cref="JsonWriter"/> using the specified <see cref="JsonSchemaResolver"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="resolver">The resolver used.</param>
public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
JsonSchemaWriter schemaWriter = new JsonSchemaWriter(writer, resolver);
schemaWriter.WriteSchema(this);
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
WriteTo(jsonWriter);
return writer.ToString();
}
}
}
#endif
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: primitive/pb_local_date.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Primitive {
/// <summary>Holder for reflection information generated from primitive/pb_local_date.proto</summary>
public static partial class PbLocalDateReflection {
#region Descriptor
/// <summary>File descriptor for primitive/pb_local_date.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PbLocalDateReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch1wcmltaXRpdmUvcGJfbG9jYWxfZGF0ZS5wcm90bxIVaG9sbXMudHlwZXMu",
"cHJpbWl0aXZlIjcKC1BiTG9jYWxEYXRlEgwKBHllYXIYASABKA0SDQoFbW9u",
"dGgYAiABKA0SCwoDZGF5GAMgASgNQiNaCXByaW1pdGl2ZaoCFUhPTE1TLlR5",
"cGVzLlByaW1pdGl2ZWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Primitive.PbLocalDate), global::HOLMS.Types.Primitive.PbLocalDate.Parser, new[]{ "Year", "Month", "Day" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PbLocalDate : pb::IMessage<PbLocalDate> {
private static readonly pb::MessageParser<PbLocalDate> _parser = new pb::MessageParser<PbLocalDate>(() => new PbLocalDate());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PbLocalDate> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PbLocalDate() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PbLocalDate(PbLocalDate other) : this() {
year_ = other.year_;
month_ = other.month_;
day_ = other.day_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PbLocalDate Clone() {
return new PbLocalDate(this);
}
/// <summary>Field number for the "year" field.</summary>
public const int YearFieldNumber = 1;
private uint year_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint Year {
get { return year_; }
set {
year_ = value;
}
}
/// <summary>Field number for the "month" field.</summary>
public const int MonthFieldNumber = 2;
private uint month_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint Month {
get { return month_; }
set {
month_ = value;
}
}
/// <summary>Field number for the "day" field.</summary>
public const int DayFieldNumber = 3;
private uint day_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint Day {
get { return day_; }
set {
day_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PbLocalDate);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PbLocalDate other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Year != other.Year) return false;
if (Month != other.Month) return false;
if (Day != other.Day) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Year != 0) hash ^= Year.GetHashCode();
if (Month != 0) hash ^= Month.GetHashCode();
if (Day != 0) hash ^= Day.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 (Year != 0) {
output.WriteRawTag(8);
output.WriteUInt32(Year);
}
if (Month != 0) {
output.WriteRawTag(16);
output.WriteUInt32(Month);
}
if (Day != 0) {
output.WriteRawTag(24);
output.WriteUInt32(Day);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Year != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Year);
}
if (Month != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Month);
}
if (Day != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Day);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PbLocalDate other) {
if (other == null) {
return;
}
if (other.Year != 0) {
Year = other.Year;
}
if (other.Month != 0) {
Month = other.Month;
}
if (other.Day != 0) {
Day = other.Day;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Year = input.ReadUInt32();
break;
}
case 16: {
Month = input.ReadUInt32();
break;
}
case 24: {
Day = input.ReadUInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Web;
using AjaxPro;
using ASC.Core;
using ASC.Core.Users;
using ASC.MessagingSystem;
using ASC.Web.Studio.Core.Notify;
using ASC.Web.Studio.Core.Users;
using ASC.Web.Studio.PublicResources;
namespace ASC.Web.Studio.Core
{
[AjaxNamespace("EmailOperationService")]
public class EmailOperationService
{
public class InvalidEmailException : Exception
{
public InvalidEmailException()
{
}
public InvalidEmailException(string message) : base(message)
{
}
}
public class AccessDeniedException : Exception
{
public AccessDeniedException()
{
}
public AccessDeniedException(string message) : base(message)
{
}
}
public class UserNotFoundException : Exception
{
public UserNotFoundException()
{
}
public UserNotFoundException(string message) : base(message)
{
}
}
public class InputException : Exception
{
public InputException()
{
}
public InputException(string message) : base(message)
{
}
}
/// <summary>
/// Sends the email activation instructions to the specified email
/// </summary>
/// <param name="userID">The ID of the user who should activate the email</param>
/// <param name="email">Email</param>
[AjaxMethod]
public string SendEmailActivationInstructions(Guid userID, string email)
{
if (userID == Guid.Empty) throw new ArgumentNullException("userID");
email = (email ?? "").Trim();
if (String.IsNullOrEmpty(email)) throw new ArgumentNullException(Resource.ErrorEmailEmpty);
if (!email.TestEmailRegex()) throw new InvalidEmailException(Resource.ErrorNotCorrectEmail);
try
{
var viewer = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
var user = CoreContext.UserManager.GetUsers(userID);
if (user == null) throw new UserNotFoundException(Resource.ErrorUserNotFound);
if (viewer == null) throw new AccessDeniedException(Resource.ErrorAccessDenied);
if (viewer.IsAdmin() || viewer.ID == user.ID)
{
var existentUser = CoreContext.UserManager.GetUserByEmail(email);
if (existentUser.ID != ASC.Core.Users.Constants.LostUser.ID && existentUser.ID != userID)
throw new InputException(CustomNamingPeople.Substitute<Resource>("ErrorEmailAlreadyExists"));
user.Email = email;
if (user.ActivationStatus == EmployeeActivationStatus.Activated)
{
user.ActivationStatus = EmployeeActivationStatus.NotActivated;
}
if (user.ActivationStatus == (EmployeeActivationStatus.AutoGenerated | EmployeeActivationStatus.Activated))
{
user.ActivationStatus = EmployeeActivationStatus.AutoGenerated;
}
CoreContext.UserManager.SaveUserInfo(user);
}
else
{
email = user.Email;
}
if (user.ActivationStatus == EmployeeActivationStatus.Pending && !user.IsLDAP())
{
if (user.IsVisitor())
{
StudioNotifyService.Instance.GuestInfoActivation(user);
}
else
{
StudioNotifyService.Instance.UserInfoActivation(user);
}
}
else
{
StudioNotifyService.Instance.SendEmailActivationInstructions(user, email);
}
MessageService.Send(HttpContext.Current.Request, MessageAction.UserSentActivationInstructions, user.DisplayUserName(false));
return String.Format(Resource.MessageEmailActivationInstuctionsSentOnEmail, "<b>" + email + "</b>");
}
catch (UserNotFoundException)
{
throw;
}
catch (AccessDeniedException)
{
throw;
}
catch (InputException)
{
throw;
}
catch (Exception)
{
throw new Exception(Resource.UnknownError);
}
}
/// <summary>
/// Sends the email change instructions to the specified email
/// </summary>
/// <param name="userID">The ID of the user who is changing the email</param>
/// <param name="email">Email</param>
[AjaxMethod]
public string SendEmailChangeInstructions(Guid userID, string email)
{
if (userID == Guid.Empty) throw new ArgumentNullException("userID");
email = (email ?? "").Trim();
if (String.IsNullOrEmpty(email)) throw new Exception(Resource.ErrorEmailEmpty);
if (!email.TestEmailRegex()) throw new Exception(Resource.ErrorNotCorrectEmail);
try
{
var viewer = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
var user = CoreContext.UserManager.GetUsers(userID);
if (user == null)
throw new UserNotFoundException(Resource.ErrorUserNotFound);
if (viewer == null || (user.IsOwner() && viewer.ID != user.ID))
throw new AccessDeniedException(Resource.ErrorAccessDenied);
var existentUser = CoreContext.UserManager.GetUserByEmail(email);
if (existentUser.ID != ASC.Core.Users.Constants.LostUser.ID)
throw new InputException(CustomNamingPeople.Substitute<Resource>("ErrorEmailAlreadyExists"));
if (!viewer.IsAdmin())
{
StudioNotifyService.Instance.SendEmailChangeInstructions(user, email);
}
else
{
if (email == user.Email)
throw new InputException(Resource.ErrorEmailsAreTheSame);
user.Email = email;
if (user.ActivationStatus.HasFlag(EmployeeActivationStatus.AutoGenerated))
{
user.ActivationStatus = EmployeeActivationStatus.AutoGenerated;
}
else
{
user.ActivationStatus = EmployeeActivationStatus.NotActivated;
}
CoreContext.UserManager.SaveUserInfo(user);
StudioNotifyService.Instance.SendEmailActivationInstructions(user, email);
}
MessageService.Send(HttpContext.Current.Request, MessageAction.UserSentEmailChangeInstructions, user.DisplayUserName(false));
return String.Format(Resource.MessageEmailChangeInstuctionsSentOnEmail, "<b>" + email + "</b>");
}
catch (AccessDeniedException)
{
throw;
}
catch (UserNotFoundException)
{
throw;
}
catch (InputException)
{
throw;
}
catch (Exception)
{
throw new Exception(Resource.UnknownError);
}
}
}
}
| |
// Copyright 2007 Google 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;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace GoogleEmailUploader {
/// <summary>
/// Enum representing the result of authentication.
/// </summary>
public enum AuthenticationResultKind {
/// <summary>
/// The login request used a username or password that is recognized.
/// </summary>
Authenticated,
/// <summary>
/// The login request used a username or password that is not
/// recognized.
/// </summary>
BadAuthentication,
/// <summary>
/// The account email address has not been verified. The user will need
/// to access their Google account directly to resolve the issue before
/// logging in using a non-Google application.
/// </summary>
NotVerified,
/// <summary>
/// The user has not agreed to terms. The user will need to access their
/// Google account directly to resolve the issue before logging in using
/// a non-Google application.
/// </summary>
TermsNotAgreed,
/// <summary>
/// A CAPTCHA is required. (A response with this error code will also
/// contain an image URL and a CAPTCHA token.)
/// </summary>
CAPTCHARequired,
/// <summary>
/// The error is unknown or unspecified; the request contained invalid
/// input or was malformed.
/// </summary>
Unknown,
/// <summary>
/// The user account has been deleted.
/// </summary>
AccountDeleted,
/// <summary>
/// The user account has been disabled.
/// </summary>
AccountDisabled,
/// <summary>
/// The user's access to the specified service has been disabled.
/// (The user account may still be valid.)
/// </summary>
ServiceDisabled,
/// <summary>
/// The service is not available; try again later.
/// </summary>
ServiceUnavailable,
/// <summary>
/// The request timed out.
/// </summary>
TimeOut,
/// <summary>
/// There was error in connecting to the service.
/// </summary>
ConnectionFailure,
/// <summary>
/// Response could not be parsed.
/// </summary>
ResponseParseError,
}
/// <summary>
/// Class representing the actual response from the Google Authentication
/// server.
/// </summary>
public class AuthenticationResponse {
/// <summary>
/// The result of the authentication.
/// </summary>
public AuthenticationResultKind AuthenticationResult {
get {
return this.authenticationResult;
}
}
AuthenticationResultKind authenticationResult;
/// <summary>
/// Helpful url if its non null.
/// </summary>
public string Url {
get {
return this.url;
}
}
string url;
/// <summary>
/// Non null only when AuthenticationResult is CAPTCHARequired.
/// </summary>
public string CAPTCHAUrl {
get {
return this.captchaUrl;
}
}
string captchaUrl;
/// <summary>
/// Use only when AuthenticationResult is CAPTCHARequired.
/// Returns null if there was error getting image.
/// </summary>
public Image CAPTCHAImage {
get {
return this.captchaImage;
}
}
Image captchaImage;
/// <summary>
/// Non null only when AuthenticationResult is CAPTCHARequired.
/// </summary>
public string CAPTCHAToken {
get {
return this.captchaToken;
}
}
string captchaToken;
/// <summary>
/// Non null only when AuthenticationResult is Authenticated.
/// </summary>
public string AuthToken {
get {
return this.authToken;
}
}
string authToken;
/// <summary>
/// Non null only when AuthenticationResult is Authenticated.
/// </summary>
public string SIDToken {
get {
return this.sidToken;
}
}
string sidToken;
/// <summary>
/// Non null only when AuthenticationResult is Authenticated.
/// </summary>
public string LSIDToken {
get {
return this.lsidToken;
}
}
string lsidToken;
/// <summary>
/// Non null only when AuthenticationResult is ConnectionFailure.
/// </summary>
public HttpException HttpException {
get {
return this.httpException;
}
}
HttpException httpException;
/// <summary>
/// Factory method for creating the response when authentication succeeds.
/// </summary>
public static AuthenticationResponse CreateAuthenticatedResponse(
string authToken,
string sidToken,
string lsidToken) {
AuthenticationResponse authenticationResponse =
new AuthenticationResponse();
authenticationResponse.authenticationResult =
AuthenticationResultKind.Authenticated;
authenticationResponse.authToken = authToken;
authenticationResponse.sidToken = sidToken;
authenticationResponse.lsidToken = lsidToken;
return authenticationResponse;
}
/// <summary>
/// Factory method for creating the response when autentication needs
/// solution for captcha challenge.
/// </summary>
public static AuthenticationResponse CreateCAPTCHAResponse(
string captchaUrl,
string captchaToken,
string url,
Image captchaImage) {
AuthenticationResponse authenticationResponse =
new AuthenticationResponse();
authenticationResponse.authenticationResult =
AuthenticationResultKind.CAPTCHARequired;
authenticationResponse.captchaUrl = captchaUrl;
authenticationResponse.captchaToken = captchaToken;
authenticationResponse.url = url;
authenticationResponse.captchaImage = captchaImage;
return authenticationResponse;
}
/// <summary>
/// Factory method for creating response when there is error connection.
/// </summary>
public static AuthenticationResponse CreateConnectionFailureResponse(
HttpException httpException) {
Debug.Assert(httpException != null);
AuthenticationResponse authenticationResponse =
new AuthenticationResponse();
authenticationResponse.authenticationResult =
AuthenticationResultKind.ConnectionFailure;
authenticationResponse.httpException = httpException;
return authenticationResponse;
}
/// <summary>
/// Factory method for creating response when the connection timed out.
/// </summary>
public static AuthenticationResponse CreateTimeoutResponse() {
AuthenticationResponse authenticationResponse =
new AuthenticationResponse();
authenticationResponse.authenticationResult =
AuthenticationResultKind.TimeOut;
return authenticationResponse;
}
/// <summary>
/// Factory method for creating response when there is error in parsing
/// server response.
/// </summary>
public static AuthenticationResponse CreateParseErrorResponse() {
AuthenticationResponse authenticationResponse =
new AuthenticationResponse();
authenticationResponse.authenticationResult =
AuthenticationResultKind.ResponseParseError;
return authenticationResponse;
}
/// <summary>
/// Factory method for creating response when there is authentication
/// failure.
/// </summary>
public static AuthenticationResponse CreateFailureResponse(
AuthenticationResultKind authenticationResultKind,
string url) {
Debug.Assert(
authenticationResultKind != AuthenticationResultKind.Authenticated &&
authenticationResultKind !=
AuthenticationResultKind.CAPTCHARequired &&
authenticationResultKind !=
AuthenticationResultKind.ConnectionFailure &&
authenticationResultKind != AuthenticationResultKind.TimeOut &&
authenticationResultKind !=
AuthenticationResultKind.ResponseParseError);
AuthenticationResponse authenticationResponse =
new AuthenticationResponse();
authenticationResponse.authenticationResult = authenticationResultKind;
authenticationResponse.url = url;
return authenticationResponse;
}
}
/// <summary>
/// Enumeration identifing kind of google account.
/// </summary>
enum AccountType {
/// <summary>
/// Authenticate as a Google account only
/// </summary>
Google,
/// <summary>
/// Authenticate as a hosted account only
/// </summary>
Hosted,
/// <summary>
/// Authenticate first as a hosted account; if attempt fails, authenticate
/// as a Google account
/// </summary>
GoogleOrHosted,
}
/// <summary>
/// Class encapsulating the authentication logic.
/// </summary>
class GoogleAuthenticator {
const string CheckPasswordTemplate =
"accountType={0}&Email={1}&Passwd={2}&source={3}";
const string CheckPasswordCAPTCHATemplate =
"accountType={0}&Email={1}&Passwd={2}&source={3}"
+ "&logintoken={4}&logincaptcha={5}";
const string AuthenticateTemplate =
"accountType={0}&Email={1}&Passwd={2}&service={3}&source={4}";
const string AuthenticationURL =
"https://www.google.com/accounts/ClientLogin";
const string CAPTCHAURLPrefix = "http://www.google.com/accounts/";
const string ApplicationURLEncoded = "application/x-www-form-urlencoded";
static readonly char[] SplitChars = new char[] {
'\r',
'\n'};
const string SID = "SID";
const string LSID = "LSID";
const string Auth = "Auth";
const string Url = "Url";
const string Error = "Error";
const string CaptchaToken = "CaptchaToken";
const string CaptchaUrl = "CaptchaUrl";
const string BadAuthentication = "BadAuthentication";
const string NotVerified = "NotVerified";
const string TermsNotAgreed = "TermsNotAgreed";
const string CaptchaRequired = "CaptchaRequired";
const string Unknown = "Unknown";
const string AccountDeleted = "AccountDeleted";
const string AccountDisabled = "AccountDisabled";
const string ServiceDisabled = "ServiceDisabled";
const string ServiceUnavailable = "ServiceUnavailable";
readonly IHttpFactory HttpFactory;
readonly string AccountTypeName;
readonly string ApplicationName;
/// <summary>
/// Constructor of GoogleAuthenticator.
/// </summary>
/// <param name="serviceName">
/// Name of service for which authentication is requested
/// </param>
/// <param name="timeout">
/// Timeout in miliseconds. Use Timeout.Infinite for no timeout.
/// </param>
internal GoogleAuthenticator(IHttpFactory httpFactory,
AccountType accountType,
string applicationName) {
this.HttpFactory = httpFactory;
switch (accountType) {
case AccountType.Google:
this.AccountTypeName = "GOOGLE";
break;
case AccountType.Hosted:
this.AccountTypeName = "HOSTED";
break;
case AccountType.GoogleOrHosted:
this.AccountTypeName = "HOSTED_OR_GOOGLE";
break;
}
this.ApplicationName = applicationName;
}
Image DownloadCAPTCHAImage(string captchaUrl) {
IHttpRequest httpRequest = this.HttpFactory.CreateGetRequest(captchaUrl);
IHttpResponse httpResponse = null;
try {
httpResponse = httpRequest.GetResponse();
} catch (HttpException) {
return null;
}
Image retImage = null;
using (Stream respStream = httpResponse.GetResponseStream()) {
try {
retImage = Image.FromStream(respStream);
} catch (ArgumentException) {
return null;
}
}
httpResponse.Close();
return retImage;
}
AuthenticationResponse ScanAndCreateResponse(string response) {
if (response == null || response.Length == 0) {
return AuthenticationResponse.CreateParseErrorResponse();
}
string[] splits = response.Split(GoogleAuthenticator.SplitChars);
string sidValue = null;
string lsidValue = null;
string authValue = null;
string urlValue = null;
string errorValue = null;
string captchaToken = null;
string captchaUrlSuffix = null;
for (int i = 0; i < splits.Length; ++i) {
string split = splits[i];
if (split.StartsWith(GoogleAuthenticator.SID)) {
sidValue = split.Substring(GoogleAuthenticator.SID.Length + 1);
} else if (split.StartsWith(GoogleAuthenticator.LSID)) {
lsidValue = split.Substring(GoogleAuthenticator.LSID.Length + 1);
} else if (split.StartsWith(GoogleAuthenticator.Auth)) {
authValue = split.Substring(GoogleAuthenticator.Auth.Length + 1);
} else if (split.StartsWith(GoogleAuthenticator.Url)) {
urlValue = split.Substring(GoogleAuthenticator.Url.Length + 1);
} else if (split.StartsWith(GoogleAuthenticator.Error)) {
errorValue = split.Substring(GoogleAuthenticator.Error.Length + 1);
} else if (split.StartsWith(GoogleAuthenticator.CaptchaToken)) {
captchaToken = split.Substring(
GoogleAuthenticator.CaptchaToken.Length + 1);
} else if (split.StartsWith(GoogleAuthenticator.CaptchaUrl)) {
captchaUrlSuffix = split.Substring(
GoogleAuthenticator.CaptchaUrl.Length + 1);
}
}
if (errorValue != null) {
switch (errorValue) {
case GoogleAuthenticator.BadAuthentication:
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.BadAuthentication, urlValue);
case GoogleAuthenticator.NotVerified:
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.NotVerified, urlValue);
case GoogleAuthenticator.TermsNotAgreed:
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.TermsNotAgreed, urlValue);
case GoogleAuthenticator.CaptchaRequired: {
Debug.Assert(captchaUrlSuffix != null && captchaToken != null);
if (captchaUrlSuffix == null || captchaToken == null) {
goto case GoogleAuthenticator.Unknown;
}
string captchaUrl =
GoogleAuthenticator.CAPTCHAURLPrefix + captchaUrlSuffix;
return AuthenticationResponse.CreateCAPTCHAResponse(
captchaUrl,
captchaToken,
urlValue,
this.DownloadCAPTCHAImage(captchaUrl));
}
case GoogleAuthenticator.Unknown:
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.Unknown, urlValue);
case GoogleAuthenticator.AccountDeleted:
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.AccountDeleted, urlValue);
case GoogleAuthenticator.AccountDisabled:
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.AccountDisabled, urlValue);
case GoogleAuthenticator.ServiceDisabled:
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.ServiceDisabled, urlValue);
case GoogleAuthenticator.ServiceUnavailable:
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.ServiceUnavailable, urlValue);
}
} else if (lsidValue != null) {
// Since google services do not use sid and lsid,
// we can ignore the case where sidValue and lsidValue are null.
Debug.Assert(sidValue != null);
return AuthenticationResponse.CreateAuthenticatedResponse(
authValue,
sidValue,
lsidValue);
}
return AuthenticationResponse.CreateParseErrorResponse();
}
/// <summary>
/// Autenticate with email and password for particular service
/// </summary>
internal AuthenticationResponse AuthenticateForService(string emailId,
string password,
string serviceName) {
int atIndex = emailId.IndexOf('@');
if (atIndex == -1 || atIndex >= emailId.Length) {
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.BadAuthentication,
null);
}
string requestString =
string.Format(
GoogleAuthenticator.AuthenticateTemplate,
this.AccountTypeName,
emailId,
password,
serviceName,
this.ApplicationName);
return this.AuthenticateAndParseResponse(requestString);
}
/// <summary>
/// Check email and password
/// </summary>
internal AuthenticationResponse CheckPassword(string emailId,
string password) {
int atIndex = emailId.IndexOf('@');
if (atIndex == -1 || atIndex >= emailId.Length) {
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.BadAuthentication,
null);
}
string requestString =
string.Format(
GoogleAuthenticator.CheckPasswordTemplate,
this.AccountTypeName,
emailId,
password,
this.ApplicationName);
return this.AuthenticateAndParseResponse(requestString);
}
/// <summary>
/// Check email and password with CAPTCHA solution
/// </summary>
internal AuthenticationResponse CheckPasswordCAPTCHA(
string emailId,
string password,
string captchaToken,
string captchaSolution) {
int atIndex = emailId.IndexOf('@');
if (atIndex == -1 || atIndex >= emailId.Length) {
return AuthenticationResponse.CreateFailureResponse(
AuthenticationResultKind.BadAuthentication,
null);
}
string requestString =
string.Format(
GoogleAuthenticator.CheckPasswordCAPTCHATemplate,
this.AccountTypeName,
emailId,
password,
this.ApplicationName,
captchaToken,
captchaSolution);
return this.AuthenticateAndParseResponse(requestString);
}
private AuthenticationResponse AuthenticateAndParseResponse(
string requestString) {
try {
GoogleEmailUploaderTrace.EnteringMethod(
"GoogleAuthenticator.AuthenticateAndParseResponse");
IHttpResponse httpResponse = null;
try {
IHttpRequest httpRequest =
this.HttpFactory.CreatePostRequest(
GoogleAuthenticator.AuthenticationURL);
httpRequest.ContentType = GoogleAuthenticator.ApplicationURLEncoded;
using (Stream newStream = httpRequest.GetRequestStream()) {
byte[] data = Encoding.UTF8.GetBytes(requestString);
newStream.Write(data, 0, data.Length);
}
httpResponse = httpRequest.GetResponse();
} catch (HttpException httpException) {
GoogleEmailUploaderTrace.WriteLine(httpException.Message);
if (httpException.Status == HttpExceptionStatus.Forbidden) {
httpResponse = httpException.Response;
} else {
return AuthenticationResponse.CreateConnectionFailureResponse(
httpException);
}
}
Debug.Assert(httpResponse != null);
string responseString = null;
using (Stream respStream = httpResponse.GetResponseStream()) {
using (StreamReader readStream =
new StreamReader(respStream, Encoding.UTF8)) {
responseString = readStream.ReadToEnd();
}
}
httpResponse.Close();
AuthenticationResponse authenticationResponse =
this.ScanAndCreateResponse(responseString);
GoogleEmailUploaderTrace.WriteLine("Authentication result: {0}",
authenticationResponse.AuthenticationResult);
return authenticationResponse;
} finally {
GoogleEmailUploaderTrace.ExitingMethod(
"GoogleAuthenticator.AuthenticateAndParseResponse");
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
namespace Lucene.Net.Codecs.Lucene40
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using Directory = Lucene.Net.Store.Directory;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
using StoredFieldVisitor = Lucene.Net.Index.StoredFieldVisitor;
/// <summary>
/// Class responsible for access to stored document fields.
/// <para/>
/// It uses <segment>.fdt and <segment>.fdx; files.
/// <para/>
/// @lucene.internal
/// </summary>
/// <seealso cref="Lucene40StoredFieldsFormat"/>
public sealed class Lucene40StoredFieldsReader : StoredFieldsReader, IDisposable
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private readonly FieldInfos fieldInfos;
private readonly IndexInput fieldsStream;
private readonly IndexInput indexStream;
private int numTotalDocs;
private int size;
private bool closed;
/// <summary>
/// Returns a cloned FieldsReader that shares open
/// <see cref="IndexInput"/>s with the original one. It is the caller's
/// job not to dispose the original FieldsReader until all
/// clones are called (eg, currently <see cref="Index.SegmentReader"/> manages
/// this logic).
/// </summary>
public override object Clone()
{
EnsureOpen();
return new Lucene40StoredFieldsReader(fieldInfos, numTotalDocs, size, (IndexInput)fieldsStream.Clone(), (IndexInput)indexStream.Clone());
}
/// <summary>
/// Used only by clone. </summary>
private Lucene40StoredFieldsReader(FieldInfos fieldInfos, int numTotalDocs, int size, IndexInput fieldsStream, IndexInput indexStream)
{
this.fieldInfos = fieldInfos;
this.numTotalDocs = numTotalDocs;
this.size = size;
this.fieldsStream = fieldsStream;
this.indexStream = indexStream;
}
/// <summary>
/// Sole constructor. </summary>
public Lucene40StoredFieldsReader(Directory d, SegmentInfo si, FieldInfos fn, IOContext context)
{
string segment = si.Name;
bool success = false;
fieldInfos = fn;
try
{
fieldsStream = d.OpenInput(IndexFileNames.SegmentFileName(segment, "", Lucene40StoredFieldsWriter.FIELDS_EXTENSION), context);
string indexStreamFN = IndexFileNames.SegmentFileName(segment, "", Lucene40StoredFieldsWriter.FIELDS_INDEX_EXTENSION);
indexStream = d.OpenInput(indexStreamFN, context);
CodecUtil.CheckHeader(indexStream, Lucene40StoredFieldsWriter.CODEC_NAME_IDX, Lucene40StoredFieldsWriter.VERSION_START, Lucene40StoredFieldsWriter.VERSION_CURRENT);
CodecUtil.CheckHeader(fieldsStream, Lucene40StoredFieldsWriter.CODEC_NAME_DAT, Lucene40StoredFieldsWriter.VERSION_START, Lucene40StoredFieldsWriter.VERSION_CURRENT);
Debug.Assert(Lucene40StoredFieldsWriter.HEADER_LENGTH_DAT == fieldsStream.GetFilePointer());
Debug.Assert(Lucene40StoredFieldsWriter.HEADER_LENGTH_IDX == indexStream.GetFilePointer());
long indexSize = indexStream.Length - Lucene40StoredFieldsWriter.HEADER_LENGTH_IDX;
this.size = (int)(indexSize >> 3);
// Verify two sources of "maxDoc" agree:
if (this.size != si.DocCount)
{
throw new CorruptIndexException("doc counts differ for segment " + segment + ": fieldsReader shows " + this.size + " but segmentInfo shows " + si.DocCount);
}
numTotalDocs = (int)(indexSize >> 3);
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
try
{
Dispose();
} // ensure we throw our original exception
catch (Exception)
{
}
}
}
}
/// <exception cref="ObjectDisposedException"> if this FieldsReader is disposed. </exception>
private void EnsureOpen()
{
if (closed)
{
throw new ObjectDisposedException(this.GetType().FullName, "this FieldsReader is closed");
}
}
/// <summary>
/// Closes the underlying <see cref="Lucene.Net.Store.IndexInput"/> streams.
/// This means that the <see cref="Index.Fields"/> values will not be accessible.
/// </summary>
/// <exception cref="IOException"> If an I/O error occurs. </exception>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (!closed)
{
IOUtils.Dispose(fieldsStream, indexStream);
closed = true;
}
}
}
/// <summary>
/// Returns number of documents.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
public int Count => size;
private void SeekIndex(int docID)
{
indexStream.Seek(Lucene40StoredFieldsWriter.HEADER_LENGTH_IDX + docID * 8L);
}
public override void VisitDocument(int n, StoredFieldVisitor visitor)
{
SeekIndex(n);
fieldsStream.Seek(indexStream.ReadInt64());
int numFields = fieldsStream.ReadVInt32();
for (int fieldIDX = 0; fieldIDX < numFields; fieldIDX++)
{
int fieldNumber = fieldsStream.ReadVInt32();
FieldInfo fieldInfo = fieldInfos.FieldInfo(fieldNumber);
int bits = fieldsStream.ReadByte() & 0xFF;
Debug.Assert(bits <= (Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_MASK | Lucene40StoredFieldsWriter.FIELD_IS_BINARY), "bits=" + bits.ToString("x"));
switch (visitor.NeedsField(fieldInfo))
{
case StoredFieldVisitor.Status.YES:
ReadField(visitor, fieldInfo, bits);
break;
case StoredFieldVisitor.Status.NO:
SkipField(bits);
break;
case StoredFieldVisitor.Status.STOP:
return;
}
}
}
private void ReadField(StoredFieldVisitor visitor, FieldInfo info, int bits)
{
int numeric = bits & Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_MASK;
if (numeric != 0)
{
switch (numeric)
{
case Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_INT:
visitor.Int32Field(info, fieldsStream.ReadInt32());
return;
case Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_LONG:
visitor.Int64Field(info, fieldsStream.ReadInt64());
return;
case Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_FLOAT:
visitor.SingleField(info, J2N.BitConversion.Int32BitsToSingle(fieldsStream.ReadInt32()));
return;
case Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_DOUBLE:
visitor.DoubleField(info, J2N.BitConversion.Int64BitsToDouble(fieldsStream.ReadInt64()));
return;
default:
throw new CorruptIndexException("Invalid numeric type: " + numeric.ToString("x"));
}
}
else
{
int length = fieldsStream.ReadVInt32();
var bytes = new byte[length];
fieldsStream.ReadBytes(bytes, 0, length);
if ((bits & Lucene40StoredFieldsWriter.FIELD_IS_BINARY) != 0)
{
visitor.BinaryField(info, bytes);
}
else
{
#pragma warning disable 612, 618
visitor.StringField(info, IOUtils.CHARSET_UTF_8.GetString(bytes));
#pragma warning restore 612, 618
}
}
}
private void SkipField(int bits)
{
int numeric = bits & Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_MASK;
if (numeric != 0)
{
switch (numeric)
{
case Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_INT:
case Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_FLOAT:
fieldsStream.ReadInt32();
return;
case Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_LONG:
case Lucene40StoredFieldsWriter.FIELD_IS_NUMERIC_DOUBLE:
fieldsStream.ReadInt64();
return;
default:
throw new CorruptIndexException("Invalid numeric type: " + numeric.ToString("x"));
}
}
else
{
int length = fieldsStream.ReadVInt32();
fieldsStream.Seek(fieldsStream.GetFilePointer() + length);
}
}
/// <summary>
/// Returns the length in bytes of each raw document in a
/// contiguous range of length <paramref name="numDocs"/> starting with
/// <paramref name="startDocID"/>. Returns the <see cref="IndexInput"/> (the fieldStream),
/// already seeked to the starting point for <paramref name="startDocID"/>.
/// </summary>
public IndexInput RawDocs(int[] lengths, int startDocID, int numDocs)
{
SeekIndex(startDocID);
long startOffset = indexStream.ReadInt64();
long lastOffset = startOffset;
int count = 0;
while (count < numDocs)
{
long offset;
int docID = startDocID + count + 1;
Debug.Assert(docID <= numTotalDocs);
if (docID < numTotalDocs)
{
offset = indexStream.ReadInt64();
}
else
{
offset = fieldsStream.Length;
}
lengths[count++] = (int)(offset - lastOffset);
lastOffset = offset;
}
fieldsStream.Seek(startOffset);
return fieldsStream;
}
public override long RamBytesUsed()
{
return 0;
}
public override void CheckIntegrity()
{
}
}
}
| |
//
// Mono.Cxxi.CppType.cs: Abstracts a C++ type declaration
//
// Author:
// Alexander Corrado (alexander.corrado@gmail.com)
// Andreia Gaita (shana@spoiledcat.net)
//
// Copyright (C) 2010-2011 Alexander Corrado
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Collections.Generic;
using Mono.Cxxi.Util;
namespace Mono.Cxxi {
// These can be used anywhere a CppType could be used.
public enum CppTypes {
Unknown,
Class,
Struct,
Enum,
Union,
Void,
Bool,
Char,
Int,
Float,
Double,
WChar_T,
// for template type parameters
Typename
}
public struct CppType {
// FIXME: Passing these as delegates allows for the flexibility of doing processing on the
// type (i.e. to correctly mangle the function pointer arguments if the managed type is a delegate),
// however this does not make it very easy to override the default mappings at runtime.
public static List<Func<CppType,Type>> CppTypeToManagedMap = new List<Func<CppType, Type>> () {
(t) => (t.ElementType == CppTypes.Class ||
t.ElementType == CppTypes.Struct ||
(t.ElementType == CppTypes.Unknown && t.ElementTypeName != null)) &&
(t.Modifiers.Count (m => m == CppModifiers.Pointer) == 1 ||
t.Modifiers.Contains (CppModifiers.Reference))? typeof (ICppObject) : null,
// void* gets IntPtr
(t) => t.ElementType == CppTypes.Void && t.Modifiers.Contains (CppModifiers.Pointer)? typeof (IntPtr) : null,
// single pointer to char gets string
// same with wchar_t (needs marshaling attribute though!)
(t) => (t.ElementType == CppTypes.Char || t.ElementType == CppTypes.WChar_T) && t.Modifiers.Count (m => m == CppModifiers.Pointer) == 1? typeof (string) : null,
// pointer to pointer to char gets string[]
(t) => t.ElementType == CppTypes.Char && t.Modifiers.Count (m => m == CppModifiers.Pointer) == 2? typeof (string).MakeArrayType () : null,
// arrays
(t) => t.Modifiers.Contains (CppModifiers.Array) && (t.Subtract (CppModifiers.Array).ToManagedType () != null)? t.Subtract (CppModifiers.Array).ToManagedType ().MakeArrayType () : null,
// convert single pointers to primatives to managed byref
(t) => t.Modifiers.Count (m => m == CppModifiers.Pointer) == 1 && (t.Subtract (CppModifiers.Pointer).ToManagedType () != null)? t.Subtract (CppModifiers.Pointer).ToManagedType ().MakeByRefType () : null,
// more than one level of indirection gets IntPtr type
(t) => t.Modifiers.Contains (CppModifiers.Pointer)? typeof (IntPtr) : null,
(t) => t.Modifiers.Contains (CppModifiers.Reference) && (t.Subtract (CppModifiers.Reference).ToManagedType () != null)? t.Subtract (CppModifiers.Reference).ToManagedType ().MakeByRefType () : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Contains (CppModifiers.Short) && t.Modifiers.Contains (CppModifiers.Unsigned)? typeof (ushort) : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Count (m => m == CppModifiers.Long) == 2 && t.Modifiers.Contains (CppModifiers.Unsigned)? typeof (ulong) : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Contains (CppModifiers.Short)? typeof (short) : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Count (m => m == CppModifiers.Long) == 2? typeof (long) : null,
(t) => t.ElementType == CppTypes.Int && t.Modifiers.Contains (CppModifiers.Unsigned)? typeof (uint) : null,
(t) => t.ElementType == CppTypes.Void? typeof (void) : null,
(t) => t.ElementType == CppTypes.Bool? typeof (bool) : null,
(t) => t.ElementType == CppTypes.Char? typeof (char) : null,
(t) => t.ElementType == CppTypes.Int? typeof (int) : null,
(t) => t.ElementType == CppTypes.Float? typeof (float) : null,
(t) => t.ElementType == CppTypes.Double? typeof (double) : null
};
public static List<Func<Type,CppType>> ManagedToCppTypeMap = new List<Func<Type,CppType>> () {
(t) => typeof (void).Equals (t) ? CppTypes.Void : CppTypes.Unknown,
(t) => typeof (bool).Equals (t) ? CppTypes.Bool : CppTypes.Unknown,
(t) => typeof (char).Equals (t) ? CppTypes.Char : CppTypes.Unknown,
(t) => typeof (int).Equals (t) ? CppTypes.Int : CppTypes.Unknown,
(t) => typeof (float).Equals (t) ? CppTypes.Float : CppTypes.Unknown,
(t) => typeof (double).Equals (t)? CppTypes.Double : CppTypes.Unknown,
(t) => typeof (short).Equals (t) ? new CppType (CppModifiers.Short, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (long).Equals (t) ? new CppType (CppModifiers.Long, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (uint).Equals (t) ? new CppType (CppModifiers.Unsigned, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (ushort).Equals (t)? new CppType (CppModifiers.Unsigned, CppModifiers.Short, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (ulong).Equals (t)? new CppType (CppModifiers.Unsigned, CppModifiers.Long, CppTypes.Int) : CppTypes.Unknown,
(t) => typeof (IntPtr).Equals (t)? new CppType (CppTypes.Void, CppModifiers.Pointer) : CppTypes.Unknown,
(t) => typeof (UIntPtr).Equals(t)? new CppType (CppTypes.Void, CppModifiers.Pointer) : CppTypes.Unknown,
// strings mangle as "const char*" by default
(t) => typeof (string).Equals (t)? new CppType (CppModifiers.Const, CppTypes.Char, CppModifiers.Pointer) : CppTypes.Unknown,
// StringBuilder gets "char*"
(t) => typeof (StringBuilder).Equals (t)? new CppType (CppTypes.Char, CppModifiers.Pointer) : CppTypes.Unknown,
// delegate types get special treatment
(t) => typeof (Delegate).IsAssignableFrom (t)? CppType.ForDelegate (t) : CppTypes.Unknown,
// ... and of course ICppObjects do too!
// FIXME: We assume c++ class not struct. There should probably be an attribute
// we can apply to managed wrappers to indicate if the underlying C++ type is actually declared struct
(t) => typeof (ICppObject).IsAssignableFrom (t)? new CppType (CppTypes.Class, Regex.Replace (t.Name, "`\\d\\d?$", ""), CppModifiers.Pointer) : CppTypes.Unknown,
// value types or interface (ICppClass) that don't fit the above categories...
(t) => t.IsValueType || t.IsInterface? new CppType (CppTypes.Class, Regex.Replace (t.Name, "`\\d\\d?$", "")) : CppTypes.Unknown,
// convert managed type modifiers to C++ type modifiers like so:
// ref types to C++ references
// pointer types to C++ pointers
// array types to C++ arrays
(t) => {
var cppType = CppType.ForManagedType (t.GetElementType () ?? (t.IsGenericType? t.GetGenericTypeDefinition () : null));
if (t.IsByRef) cppType.Modifiers.Add (CppModifiers.Reference);
if (t.IsPointer) cppType.Modifiers.Add (CppModifiers.Pointer);
if (t.IsArray) cppType.Modifiers.Add (CppModifiers.Array);
if (t.IsGenericType) cppType.Modifiers.Add (new CppModifiers.TemplateModifier (t.GetGenericArguments ().Select (g => CppType.ForManagedType (g)).ToArray ()));
return cppType;
}
};
public CppTypes ElementType { get; set; }
// if the ElementType is Union, Struct, Class, or Enum
// this will contain the name of said type
public string ElementTypeName { get; set; }
// may be null, and will certainly be null if ElementTypeName is null
public string [] Namespaces { get; set; }
// this is initialized lazily to avoid unnecessary heap
// allocations if possible
private List<CppModifiers> internalModifiers;
public List<CppModifiers> Modifiers {
get {
if (internalModifiers == null)
internalModifiers = new List<CppModifiers> ();
return internalModifiers;
}
}
// here, you can pass in things like "const char*" or "const Foo * const"
// DISCLAIMER: this is really just for convenience for now, and is not meant to be able
// to parse even moderately complex C++ type declarations.
public CppType (string type) : this (Regex.Split (type, "\\s+(?![^\\>]*\\>|[^\\[\\]]*\\])"))
{
}
public CppType (params object[] cppTypeSpec) : this ()
{
ElementType = CppTypes.Unknown;
ElementTypeName = null;
Namespaces = null;
internalModifiers = null;
Parse (cppTypeSpec);
}
// FIXME: This makes no attempt to actually verify that the parts compose a valid C++ type.
private void Parse (object [] parts)
{
foreach (object part in parts) {
if (part is CppModifiers) {
Modifiers.Add ((CppModifiers)part);
continue;
}
if (part is CppModifiers [] || part is IEnumerable<CppModifiers>) {
Modifiers.AddRange ((IEnumerable<CppModifiers>)part);
continue;
}
if (part is CppTypes) {
ElementType = (CppTypes)part;
continue;
}
Type managedType = part as Type;
if (managedType != null) {
CppType mapped = CppType.ForManagedType (managedType);
CopyTypeFrom (mapped);
continue;
}
string strPart = part as string;
if (strPart != null) {
var parsed = CppModifiers.Parse (strPart);
if (parsed.Count > 0) {
if (internalModifiers == null)
internalModifiers = parsed;
else
internalModifiers.AddRange (parsed);
strPart = CppModifiers.Remove (strPart);
}
// if we have something left, it must be a type name
strPart = strPart.Trim ();
if (strPart != "") {
string [] qualifiedName = strPart.Split (new string [] { "::" }, StringSplitOptions.RemoveEmptyEntries);
int numNamespaces = qualifiedName.Length - 1;
if (numNamespaces > 0) {
Namespaces = new string [numNamespaces];
for (int i = 0; i < numNamespaces; i++)
Namespaces [i] = qualifiedName [i];
}
strPart = qualifiedName [numNamespaces];
// FIXME: Fix this mess
switch (strPart) {
case "void":
ElementType = CppTypes.Void;
break;
case "bool":
ElementType = CppTypes.Bool;
break;
case "char":
ElementType = CppTypes.Char;
break;
case "int":
ElementType = CppTypes.Int;
break;
case "float":
ElementType = CppTypes.Float;
break;
case "double":
ElementType = CppTypes.Double;
break;
default:
// otherwise it is the element type name...
ElementTypeName = strPart;
break;
}
}
}
}
}
// Applies the element type of the passed instance
// and combines its modifiers into this instance.
// Use when THIS instance may have attributes you want,
// but want the element type of the passed instance.
public CppType CopyTypeFrom (CppType type)
{
ElementType = type.ElementType;
ElementTypeName = type.ElementTypeName;
Namespaces = type.Namespaces;
List<CppModifiers> oldModifiers = internalModifiers;
internalModifiers = type.internalModifiers;
if (oldModifiers != null)
Modifiers.AddRange (oldModifiers);
return this;
}
// Removes the modifiers on the passed instance from this instance
public CppType Subtract (CppType type)
{
if (internalModifiers == null)
return this;
CppType current = this;
foreach (var modifier in ((IEnumerable<CppModifiers>)type.Modifiers).Reverse ())
current = current.Subtract (modifier);
return current;
}
public CppType Subtract (CppModifiers modifier)
{
CppType newType = this;
newType.internalModifiers = new List<CppModifiers> (((IEnumerable<CppModifiers>)newType.Modifiers).Reverse ().WithoutFirst (modifier));
return newType;
}
// note: this adds modifiers "backwards" (it is mainly used by the generator)
public CppType Modify (CppModifiers modifier)
{
CppType newType = this;
var newModifier = new CppModifiers [] { modifier };
if (newType.internalModifiers != null)
newType.internalModifiers.AddFirst (newModifier);
else
newType.internalModifiers = new List<CppModifiers> (newModifier);
return newType;
}
public override bool Equals (object obj)
{
if (obj == null)
return false;
if (obj.GetType () == typeof (CppTypes))
return Equals (new CppType (obj));
if (obj.GetType () != typeof (CppType))
return false;
CppType other = (CppType)obj;
return (((internalModifiers == null || !internalModifiers.Any ()) &&
(other.internalModifiers == null || !other.internalModifiers.Any ())) ||
(internalModifiers != null && other.internalModifiers != null &&
CppModifiers.NormalizeOrder (internalModifiers).SequenceEqual (CppModifiers.NormalizeOrder (other.internalModifiers)))) &&
(((Namespaces == null || !Namespaces.Any ()) &&
(other.Namespaces == null || !other.Namespaces.Any ())) ||
(Namespaces != null && other.Namespaces != null &&
Namespaces.SequenceEqual (other.Namespaces))) &&
ElementType == other.ElementType &&
ElementTypeName == other.ElementTypeName;
}
public override int GetHashCode ()
{
unchecked {
return (internalModifiers != null? internalModifiers.SequenceHashCode () : 0) ^
ElementType.GetHashCode () ^
(Namespaces != null? Namespaces.SequenceHashCode () : 0) ^
(ElementTypeName != null? ElementTypeName.GetHashCode () : 0);
}
}
public override string ToString ()
{
StringBuilder cppTypeString = new StringBuilder ();
if (ElementType != CppTypes.Unknown && ElementType != CppTypes.Typename)
cppTypeString.Append (Enum.GetName (typeof (CppTypes), ElementType).ToLower ()).Append (' ');
if (Namespaces != null) {
foreach (var ns in Namespaces)
cppTypeString.Append (ns).Append ("::");
}
if (ElementTypeName != null && ElementType != CppTypes.Typename)
cppTypeString.Append (ElementTypeName);
if (internalModifiers != null) {
foreach (var modifier in internalModifiers)
cppTypeString.Append (' ').Append (modifier.ToString ());
}
return cppTypeString.ToString ().Trim ();
}
public Type ToManagedType ()
{
CppType me = this;
Type mappedType = (from checkType in CppTypeToManagedMap
where checkType (me) != null
select checkType (me)).FirstOrDefault ();
return mappedType;
}
public static CppType ForManagedType (Type type)
{
CppType mappedType = (from checkType in ManagedToCppTypeMap
where checkType (type).ElementType != CppTypes.Unknown
select checkType (type)).FirstOrDefault ();
return mappedType;
}
public static CppType ForDelegate (Type delType)
{
if (!typeof (Delegate).IsAssignableFrom (delType))
throw new ArgumentException ("Argument must be a delegate type");
throw new NotImplementedException ();
}
public static implicit operator CppType (CppTypes type) {
return new CppType (type);
}
}
}
| |
/*
* Created by Alexandre Rocha Lima e Marcondes
* User: Administrator
* Date: 13/08/2005
* Time: 16:13
*
* Description: An SQL Builder, Object Interface to Database Tables
* Its based on DataObjects from php PEAR
* 1. Builds SQL statements based on the objects vars and the builder methods.
* 2. acts as a datastore for a table row.
* The core class is designed to be extended for each of your tables so that you put the
* data logic inside the data classes.
* included is a Generator to make your configuration files and your base classes.
*
* CSharp DataObject
* Copyright (c) 2005, Alessandro de Oliveira Binhara
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the <ORGANIZATION> 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;
using System.Data;
using System.Data.OleDb;
using NUnit.Framework;
using CsDO.Lib;
namespace CsDO.Tests {
public class MockDbConnection : IDbConnection
{
private string connectionString;
private string database;
private ConnectionState state;
public string ConnectionString { get { return connectionString; } set { connectionString = value; } }
public int ConnectionTimeout { get { return 95248447; } }
public string Database { get { return database; } }
public ConnectionState State { get { return state; } }
public void Dispose() { }
public void Open() { state = ConnectionState.Open; }
public void Close() { state = ConnectionState.Closed; }
public IDbCommand CreateCommand() { return new MockDbCommand(); }
public void ChangeDatabase(string databaseName) { database = databaseName; }
public IDbTransaction BeginTransaction() { return new MockDbTransaction(); }
public IDbTransaction BeginTransaction(IsolationLevel il) { return BeginTransaction(); }
}
public class MockDbCommand : IDbCommand
{
private string commandText;
private string[] commands;
private int commandTimeout;
private CommandType commandType;
private IDbConnection connection;
private IDataParameterCollection parameters;
private IDbTransaction transaction;
private UpdateRowSource updatedRowSource;
public string CommandText
{
get { return commandText; }
set
{
commands = commandText.Split(' ');
commandText = value;
}
}
public int CommandTimeout { get { return commandTimeout; } set { commandTimeout = value; } }
public CommandType CommandType { get { return commandType; } set { commandType = value; } }
public IDbConnection Connection { get { return connection; } set { connection = value; } }
public IDataParameterCollection Parameters { get { return parameters; } set { parameters = value; } }
public IDbTransaction Transaction { get { return transaction; } set { transaction = value; } }
public UpdateRowSource UpdatedRowSource { get { return updatedRowSource; } set { updatedRowSource = value; } }
public MockDbCommand()
{
commandText = "";
connection = null;
}
public MockDbCommand(string sql, IDbConnection conn)
{
commandText = sql;
commands = commandText.Split(' ');
connection = conn;
}
public void Dispose() { }
public void Cancel() { }
public void Prepare() { }
public object ExecuteScalar() { return (String) "First Column"; }
public IDataReader ExecuteReader()
{
for(int i = 0; i < commands.Length; i++) {
if (commands[i].ToUpper().Equals("FROM")) {
return new MockDataReader(commands[i+1]);
}
}
return null;
}
public IDataReader ExecuteReader(CommandBehavior behavior) { return this.ExecuteReader(); }
public int ExecuteNonQuery()
{
commands = commandText.Split(' ');
if (commandText.ToUpper().StartsWith("INSERT")) {
return 1;
} else if (commandText.ToUpper().StartsWith("UPDATE")) {
if (commandText.ToUpper().IndexOf("WHERE") > -1)
return 1;
else
return 99248446;
} else if (commandText.ToUpper().StartsWith("DELETE")) {
if (commandText.ToUpper().IndexOf("WHERE") > -1)
return 1;
else
return 99248446;
} else if (commandText.ToUpper().StartsWith("CREATE")) {
return 1;
} else if (commandText.ToUpper().StartsWith("DROP")) {
return 1;
} else
return 0;
}
public IDbDataParameter CreateParameter()
{
IDbDataParameter result = new OleDbParameter();
if (parameters != null)
parameters.Add(result);
return result;
}
}
public class MockDbTransaction : IDbTransaction
{
public IDbConnection Connection { get { return new MockDbConnection(); } }
public IsolationLevel IsolationLevel { get { return IsolationLevel.Unspecified; } }
public void Dispose() { }
public void Commit() { }
public void Rollback() { }
}
public class MockDataReader : IDataReader
{
private MockDriver driver = (MockDriver) Conf.Driver;
private string tableName = "";
private DataTable table = null;
private int row = -1;
private bool isClosed = true;
public int Depth { get { return 95248447; } }
public bool IsClosed {get { return isClosed; } }
public int RecordsAffected { get { return 95248447; } }
public int FieldCount { get { return driver.getColumnCount(tableName); } }
public object this[string s] { get { return GetValue(GetOrdinal(s)); } }
public object this[int i] { get { return GetValue(i); } }
public MockDataReader(string table) {
isClosed = false;
tableName = table;
this.table = driver.dataset.Tables[table];
}
public void Dispose() { }
public void Close() { isClosed = true; }
public DataTable GetSchemaTable() { return null; }
public bool NextResult()
{
if (!isClosed && (row < table.Rows.Count)) {
row++;
return true;
}
return false;
}
public bool Read() { return NextResult(); }
public bool GetBoolean(int i) { return (bool) table.Rows[row].ItemArray[i]; }
public byte GetByte(int i) { return (byte) table.Rows[row].ItemArray[i]; }
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { return fieldOffset - 1; }
public char GetChar(int i) { return (char) table.Rows[row].ItemArray[i]; }
public long GetChars(int i, long fieldOffset, char[] buffer, int bufferoffset, int length) { return fieldOffset - 1; }
public IDataReader GetData(int i) { return this; }
public string GetDataTypeName(int i) { return (String) table.Columns[i].DataType.Name; }
public DateTime GetDateTime(int i) { return(DateTime) table.Rows[row].ItemArray[i]; }
public decimal GetDecimal(int i) { return (decimal) table.Rows[row].ItemArray[i]; }
public double GetDouble(int i) { return (double) table.Rows[row].ItemArray[i]; }
public Type GetFieldType(int i) { return table.Columns[i].DataType; }
public float GetFloat(int i) { return (float) table.Rows[row].ItemArray[i]; }
public Guid GetGuid(int i) { return (Guid) table.Rows[row].ItemArray[i]; }
public short GetInt16(int i) { return (short) table.Rows[row].ItemArray[i]; }
public int GetInt32(int i) { return (int) table.Rows[row].ItemArray[i]; }
public long GetInt64(int i) { return (long) table.Rows[row].ItemArray[i]; }
public string GetName(int i) { return table.Columns[i].ColumnName; }
public int GetOrdinal(string name) { return table.Columns.IndexOf(name); }
public string GetString(int i) { return (String) table.Rows[row].ItemArray[i]; }
public object GetValue(int i) { return table.Rows[row].ItemArray[i]; }
public bool IsDBNull(int i) { return table.Rows[row].IsNull(i); }
public int GetValues(object[] values)
{
int length = table.Rows[row].ItemArray.Length;
table.Rows[row].ItemArray.CopyTo(values, length);
return length;
}
}
public class MockDriver : IDataBase
{
private MockDbConnection conn = null;
private MockDbCommand prevCommand = null;
public IDataAdapter getDataAdapter(IDbCommand command)
{
return null;
}
protected internal System.Data.DataSet dataset = new DataSet("MockData");
public void addColumn(string table, string name, Type type) {
addColumn(table, name, type, false, false);
}
public void addTable(string name) {
DataTable table = new DataTable(name);
dataset.Tables.Add(table);
}
public void clearTables() {
dataset.Tables.Clear();
}
public void addColumn(string table, string name, Type type, bool unique, bool readOnly) {
DataColumn column = new DataColumn();
column.DataType = type;
column.ColumnName = name;
column.ReadOnly = readOnly;
column.Unique = unique;
dataset.Tables[table].Columns.Add(column);
}
public void addRow(string table, DataRow row) {
dataset.Tables[table].Rows.Add(row);
}
public DataRow newRow(string table) {
return dataset.Tables[table].NewRow();
}
public DataColumn getColumn(string table, int index) {
return dataset.Tables[table].Columns[index];
}
public int getColumnCount(string table) {
return dataset.Tables[table].Columns.Count;
}
public int getColumnIndex(string table, string name) {
return dataset.Tables[table].Columns.IndexOf(name);
}
public void clearTable(string table) {
dataset.Tables[table].Columns.Clear();
dataset.Tables[table].Rows.Clear();
}
public void setPrimaryKey(string table, string name) {
if (name != null) {
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = dataset.Tables[table].Columns["id"];
dataset.Tables[table].PrimaryKey = PrimaryKeyColumns;
} else {
dataset.Tables[table].PrimaryKey = null;
}
}
public MockDriver() { }
public MockDbCommand getPreviousCommand() {
return prevCommand;
}
public MockDbConnection getPreviousConnection() {
return conn;
}
public IDbCommand getCommand(String sql)
{
prevCommand = new MockDbCommand(sql, getConnection());
return prevCommand;
}
public IDbCommand getSystemCommand(String sql)
{
prevCommand = new MockDbCommand(sql, getSystemConnection());
return prevCommand;
}
protected IDbConnection getConnection()
{
if (conn == null)
conn = new MockDbConnection();
return conn;
}
protected IDbConnection getSystemConnection() { return getConnection(); }
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if PLATFORM_DETECTION
using System;
using System.Collections;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Summary description for PlatformHelperTests.
/// </summary>
[TestFixture]
public class PlatformDetectionTests
{
private static readonly PlatformHelper win95Helper = new PlatformHelper(
new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ),
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );
private static readonly PlatformHelper winXPHelper = new PlatformHelper(
new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ),
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );
private void CheckOSPlatforms( OSPlatform os,
string expectedPlatforms )
{
Assert.That(expectedPlatforms, Is.SubsetOf(PlatformHelper.OSPlatforms).IgnoreCase,
"Error in test: one or more expected platforms is not a valid OSPlatform.");
CheckPlatforms(
new PlatformHelper( os, RuntimeFramework.CurrentFramework ),
expectedPlatforms,
PlatformHelper.OSPlatforms );
}
private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework,
string expectedPlatforms )
{
CheckPlatforms(
new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ),
expectedPlatforms,
PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,NET-3.0,NET-3.5,NET-4.0,NET-4.5,MONO-1.0,MONO-2.0,MONO-3.0,MONO-3.5,MONO-4.0,MONOTOUCH" );
}
private void CheckPlatforms( PlatformHelper helper,
string expectedPlatforms, string checkPlatforms )
{
string[] expected = expectedPlatforms.Split( new char[] { ',' } );
string[] check = checkPlatforms.Split( new char[] { ',' } );
foreach( string testPlatform in check )
{
bool shouldPass = false;
foreach( string platform in expected )
if ( shouldPass = platform.ToLower() == testPlatform.ToLower() )
break;
bool didPass = helper.IsPlatformSupported( testPlatform );
if ( shouldPass && !didPass )
Assert.Fail( "Failed to detect {0}", testPlatform );
else if ( didPass && !shouldPass )
Assert.Fail( "False positive on {0}", testPlatform );
else if ( !shouldPass && !didPass )
Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason );
}
}
[Test]
public void DetectWin95()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ),
"Win95,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWin98()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ),
"Win98,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWinMe()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ),
"WinMe,Win32Windows,Win32,Win" );
}
[Test]
public void DetectNT3()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ),
"NT3,Win32NT,Win32,Win" );
}
[Test]
public void DetectNT4()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ),
"NT4,Win32NT,Win32,Win" );
}
[Test]
public void DetectWin2K()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ),
"Win2K,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWinXP()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ),
"WinXP,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWinXPProfessionalX64()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ),
"WinXP,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWin2003Server()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server),
"Win2003Server,NT5,Win32NT,Win32,Win");
}
[Test]
public void DetectVista()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation),
"Vista,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWin2008ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server),
"Win2008Server,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWin2008ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server),
"Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows7()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation),
"Win7,Windows7,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows2012ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.Server),
"Win2012Server,Win2012ServerR1,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows2012ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.Server),
"Win2012Server,Win2012ServerR2,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows8()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.WorkStation),
"Win8,Windows8,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows81()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.WorkStation),
"Win8.1,Windows8.1,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows10()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.WorkStation),
"Win10,Windows10,Win32NT,Win32,Win");
}
[Test]
public void DetectWindowsServer()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.Server),
"WindowsServer10,Win32NT,Win32,Win");
}
[Test]
public void DetectUnixUnderMicrosoftDotNet()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version(0,0)),
"UNIX,Linux");
}
[Test]
public void DetectUnixUnderMono()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version(0,0)),
"UNIX,Linux");
}
[Test]
public void DetectXbox()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Xbox, new Version(0, 0)),
"Xbox");
}
[Test]
public void DetectMacOSX()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.MacOSX, new Version(0, 0)),
"MacOSX");
}
[Test]
public void DetectNet10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 1, 0, 3705, 0 ) ),
"NET,NET-1.0" );
}
[Test]
public void DetectNet11()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ),
"NET,NET-1.1" );
}
[Test]
public void DetectNet20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 2, 0, 50727, 0 ) ),
"Net,Net-2.0" );
}
[Test]
public void DetectNet30()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(3, 0)),
"Net,Net-2.0,Net-3.0");
}
[Test]
public void DetectNet35()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(3, 5)),
"Net,Net-2.0,Net-3.0,Net-3.5");
}
[Test]
public void DetectNet40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(4, 0, 30319, 0)),
"Net,Net-4.0");
}
[Test]
public void DetectSSCLI()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ),
"SSCLI,Rotor" );
}
[Test]
public void DetectMono10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ),
"Mono,Mono-1.0" );
}
[Test]
public void DetectMono20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 2, 0, 50727, 0 ) ),
"Mono,Mono-2.0" );
}
[Test]
public void DetectMono30()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(3, 0)),
"Mono,Mono-2.0,Mono-3.0");
}
[Test]
public void DetectMono35()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(3, 5)),
"Mono,Mono-2.0,Mono-3.0,Mono-3.5");
}
[Test]
public void DetectMono40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)),
"Mono,Mono-4.0");
}
[Test]
public void DetectMonoTouch()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.MonoTouch, new Version(4, 0, 30319)),
"MonoTouch");
}
[Test]
public void DetectExactVersion()
{
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) );
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) );
}
[Test]
public void ArrayOfPlatforms()
{
string[] platforms = new string[] { "NT4", "Win2K", "WinXP" };
Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) );
}
[Test]
public void PlatformAttribute_Include()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason);
}
[Test]
public void PlatformAttribute_Exclude()
{
PlatformAttribute attr = new PlatformAttribute();
attr.Exclude = "Win2K,WinXP,NT4";
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason );
Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) );
}
[Test]
public void PlatformAttribute_IncludeAndExclude()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
attr.Exclude = "Mono";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
attr.Exclude = "Net";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Net", winXPHelper.Reason );
}
[Test]
public void PlatformAttribute_InvalidPlatform()
{
PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" );
Assert.Throws<InvalidPlatformException>(
() => winXPHelper.IsPlatformSupported(attr),
"Invalid platform name Net11");
}
[Test]
public void PlatformAttribute_ProcessBitNess()
{
PlatformAttribute attr32 = new PlatformAttribute("32-Bit");
PlatformAttribute attr64 = new PlatformAttribute("64-Bit");
PlatformHelper helper = new PlatformHelper();
// This test verifies that the two labels are known,
// do not cause an error and return consistent results.
bool is32BitProcess = helper.IsPlatformSupported(attr32);
bool is64BitProcess = helper.IsPlatformSupported(attr64);
Assert.False(is32BitProcess & is64BitProcess, "Process cannot be both 32 and 64 bit");
#if ASYNC
// For .NET 4.0 and 4.5, we can check further
Assert.That(is64BitProcess, Is.EqualTo(Environment.Is64BitProcess));
#endif
}
#if ASYNC
[Test]
public void PlatformAttribute_OperatingSystemBitNess()
{
PlatformAttribute attr32 = new PlatformAttribute("32-Bit-OS");
PlatformAttribute attr64 = new PlatformAttribute("64-Bit-OS");
PlatformHelper helper = new PlatformHelper();
bool is64BitOS = Environment.Is64BitOperatingSystem;
Assert.That(helper.IsPlatformSupported(attr32), Is.Not.EqualTo(is64BitOS));
Assert.That(helper.IsPlatformSupported(attr64), Is.EqualTo(is64BitOS));
}
#endif
}
}
#endif
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Microsoft.VisualStudio.Debugger.Metadata;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class TypeImpl : Type
{
internal readonly System.Type Type;
private TypeImpl(System.Type type)
{
Debug.Assert(type != null);
this.Type = type;
}
public static explicit operator TypeImpl(System.Type type)
{
return type == null ? null : new TypeImpl(type);
}
public override Assembly Assembly
{
get { return new AssemblyImpl(this.Type.Assembly); }
}
public override string AssemblyQualifiedName
{
get { throw new NotImplementedException(); }
}
public override Type BaseType
{
get { return (TypeImpl)this.Type.BaseType; }
}
public override bool ContainsGenericParameters
{
get { throw new NotImplementedException(); }
}
public override Type DeclaringType
{
get { return (TypeImpl)this.Type.DeclaringType; }
}
public override bool IsEquivalentTo(MemberInfo other)
{
throw new NotImplementedException();
}
public override string FullName
{
get { return this.Type.FullName; }
}
public override Guid GUID
{
get { throw new NotImplementedException(); }
}
public override System.Reflection.MemberTypes MemberType
{
get
{
return this.Type.MemberType;
}
}
public override int MetadataToken
{
get { throw new NotImplementedException(); }
}
public override Module Module
{
get { return new ModuleImpl(this.Type.Module); }
}
public override string Name
{
get { return Type.Name; }
}
public override string Namespace
{
get { return Type.Namespace; }
}
public override Type ReflectedType
{
get { throw new NotImplementedException(); }
}
public override Type UnderlyingSystemType
{
get { return (TypeImpl)Type.UnderlyingSystemType; }
}
public override bool Equals(Type o)
{
return o != null && o.GetType() == this.GetType() && ((TypeImpl)o).Type == this.Type;
}
public override bool Equals(object objOther)
{
return Equals(objOther as Type);
}
public override int GetHashCode()
{
return Type.GetHashCode();
}
public override int GetArrayRank()
{
return Type.GetArrayRank();
}
public override ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr)
{
return Type.GetConstructors(bindingAttr).Select(c => new ConstructorInfoImpl(c)).ToArray();
}
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotImplementedException();
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return Type.GetCustomAttributesData().Select(a => new CustomAttributeDataImpl(a)).ToArray();
}
public override Type GetElementType()
{
return (TypeImpl)(Type.GetElementType());
}
public override EventInfo GetEvent(string name, System.Reflection.BindingFlags flags)
{
throw new NotImplementedException();
}
public override EventInfo[] GetEvents(System.Reflection.BindingFlags flags)
{
throw new NotImplementedException();
}
public override FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr)
{
return new FieldInfoImpl(Type.GetField(name, bindingAttr));
}
public override FieldInfo[] GetFields(System.Reflection.BindingFlags flags)
{
return Type.GetFields(flags).Select(f => new FieldInfoImpl(f)).ToArray();
}
public override Type GetGenericTypeDefinition()
{
return (TypeImpl)this.Type.GetGenericTypeDefinition();
}
public override Type[] GetGenericArguments()
{
return Type.GetGenericArguments().Select(t => new TypeImpl(t)).ToArray();
}
public override Type GetInterface(string name, bool ignoreCase)
{
throw new NotImplementedException();
}
public override Type[] GetInterfaces()
{
return Type.GetInterfaces().Select(i => new TypeImpl(i)).ToArray();
}
public override System.Reflection.InterfaceMapping GetInterfaceMap(Type interfaceType)
{
throw new NotImplementedException();
}
public override MemberInfo[] GetMember(string name, System.Reflection.BindingFlags bindingAttr)
{
return Type.GetMember(name, bindingAttr).Select(GetMember).ToArray();
}
public override MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr)
{
return Type.GetMembers(bindingAttr).Select(GetMember).ToArray();
}
private static MemberInfo GetMember(System.Reflection.MemberInfo member)
{
switch (member.MemberType)
{
case System.Reflection.MemberTypes.Constructor:
return new ConstructorInfoImpl((System.Reflection.ConstructorInfo)member);
case System.Reflection.MemberTypes.Event:
return new EventInfoImpl((System.Reflection.EventInfo)member);
case System.Reflection.MemberTypes.Field:
return new FieldInfoImpl((System.Reflection.FieldInfo)member);
case System.Reflection.MemberTypes.Method:
return new MethodInfoImpl((System.Reflection.MethodInfo)member);
case System.Reflection.MemberTypes.NestedType:
return new TypeImpl((System.Reflection.TypeInfo)member);
case System.Reflection.MemberTypes.Property:
return new PropertyInfoImpl((System.Reflection.PropertyInfo)member);
default:
throw new NotImplementedException(member.MemberType.ToString());
}
}
public override MethodInfo[] GetMethods(System.Reflection.BindingFlags flags)
{
return this.Type.GetMethods(flags).Select(m => new MethodInfoImpl(m)).ToArray();
}
public override Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override PropertyInfo[] GetProperties(System.Reflection.BindingFlags flags)
{
throw new NotImplementedException();
}
public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
{
throw new NotImplementedException();
}
public override bool IsAssignableFrom(Type c)
{
throw new NotImplementedException();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override bool IsEnum
{
get { return this.Type.IsEnum; }
}
public override bool IsGenericParameter
{
get { return Type.IsGenericParameter; }
}
public override bool IsGenericType
{
get { return Type.IsGenericType; }
}
public override bool IsGenericTypeDefinition
{
get { return Type.IsGenericTypeDefinition; }
}
public override int GenericParameterPosition
{
get { return Type.GenericParameterPosition; }
}
public override ExplicitInterfaceInfo[] GetExplicitInterfaceImplementations()
{
var interfaceMaps = Type.GetInterfaces().Select(i => Type.GetInterfaceMap(i));
// A dot is neither necessary nor sufficient for determining whether a member explicitly
// implements an interface member, but it does characterize the set of members we're
// interested in displaying differently. For example, if the property is from VB, it will
// be an explicit interface implementation, but will not have a dot. Therefore, this is
// good enough for our mock implementation.
var infos = interfaceMaps.SelectMany(map =>
map.InterfaceMethods.Zip(map.TargetMethods, (interfaceMethod, implementingMethod) =>
implementingMethod.Name.Contains(".")
? MakeExplicitInterfaceInfo(interfaceMethod, implementingMethod)
: null));
return infos.Where(i => i != null).ToArray();
}
private static ExplicitInterfaceInfo MakeExplicitInterfaceInfo(System.Reflection.MethodInfo interfaceMethod, System.Reflection.MethodInfo implementingMethod)
{
return (ExplicitInterfaceInfo)typeof(ExplicitInterfaceInfo).Instantiate(
new MethodInfoImpl(interfaceMethod), new MethodInfoImpl(implementingMethod));
}
public override bool IsInstanceOfType(object o)
{
throw new NotImplementedException();
}
public override bool IsSubclassOf(Type c)
{
throw new NotImplementedException();
}
public override Type MakeArrayType()
{
return (TypeImpl)this.Type.MakeArrayType();
}
public override Type MakeArrayType(int rank)
{
return (TypeImpl)this.Type.MakeArrayType(rank);
}
public override Type MakeByRefType()
{
throw new NotImplementedException();
}
public override Type MakeGenericType(params Type[] argTypes)
{
return (TypeImpl)this.Type.MakeGenericType(argTypes.Select(t => ((TypeImpl)t).Type).ToArray());
}
public override Type MakePointerType()
{
return (TypeImpl)this.Type.MakePointerType();
}
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl()
{
System.Reflection.TypeAttributes result = 0;
if (this.Type.IsClass)
{
result |= System.Reflection.TypeAttributes.Class;
}
if (this.Type.IsInterface)
{
result |= System.Reflection.TypeAttributes.Interface;
}
if (this.Type.IsAbstract)
{
result |= System.Reflection.TypeAttributes.Abstract;
}
if (this.Type.IsSealed)
{
result |= System.Reflection.TypeAttributes.Sealed;
}
return result;
}
protected override bool IsValueTypeImpl()
{
return this.Type.IsValueType;
}
protected override ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
protected override MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
protected override PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
Debug.Assert(binder == null, "NYI");
Debug.Assert(returnType == null, "NYI");
Debug.Assert(types == null, "NYI");
return new PropertyInfoImpl(Type.GetProperty(name, bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: modifiers));
}
protected override TypeCode GetTypeCodeImpl()
{
return System.Type.GetTypeCode(this.Type);
}
protected override bool HasElementTypeImpl()
{
throw new NotImplementedException();
}
protected override bool IsArrayImpl()
{
return Type.IsArray;
}
protected override bool IsByRefImpl()
{
throw new NotImplementedException();
}
protected override bool IsCOMObjectImpl()
{
throw new NotImplementedException();
}
protected override bool IsContextfulImpl()
{
throw new NotImplementedException();
}
protected override bool IsMarshalByRefImpl()
{
throw new NotImplementedException();
}
protected override bool IsPointerImpl()
{
return Type.IsPointer;
}
protected override bool IsPrimitiveImpl()
{
throw new NotImplementedException();
}
public override string ToString()
{
return this.Type.ToString();
}
public override Type[] GetInterfacesOnType()
{
var t = this.Type;
var builder = ArrayBuilder<Type>.GetInstance();
foreach (var @interface in t.GetInterfaces())
{
var map = t.GetInterfaceMap(@interface);
if (map.TargetMethods.Any(m => m.DeclaringType == t))
{
builder.Add((TypeImpl)@interface);
}
}
return builder.ToArrayAndFree();
}
}
}
| |
//
// StationSource.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Threading;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Data.Sqlite;
using Lastfm;
using ConnectionState = Lastfm.ConnectionState;
using Banshee.Base;
using Banshee.Widgets;
using Banshee.Database;
using Banshee.Sources;
using Banshee.Metadata;
using Banshee.MediaEngine;
using Banshee.Collection;
using Banshee.ServiceStack;
using Banshee.PlaybackController;
using Banshee.Lastfm;
namespace Banshee.LastfmStreaming.Radio
{
public class StationSource : Source, ITrackModelSource, IUnmapableSource, IDisposable, IBasicPlaybackController
{
private static string generic_name = Catalog.GetString ("Last.fm Station");
public static StationSource CreateFromUrl (LastfmSource lastfm, string url)
{
foreach (StationType type in StationType.Types) {
string regex = Regex.Escape (type.GetStationFor ("XXX")).Replace ("XXX", "([^\\/]+)");
Match match = Regex.Match (url, regex);
if (match.Groups.Count == 2 && match.Groups[0].Captures.Count > 0) {
Log.DebugFormat ("Creating last.fm station from url {0}", url);
string arg = match.Groups[1].Captures[0].Value;
StationSource station = new StationSource (lastfm, arg, type.Name, arg);
lastfm.AddChildSource (station);
station.NotifyUser ();
}
}
return null;
}
private MemoryTrackListModel track_model;
private LastfmSource lastfm;
public LastfmSource LastfmSource {
get { return lastfm; }
}
private string station;
public string Station {
get { return station; }
protected set { station = value; }
}
private StationType type;
public StationType Type {
get { return type; }
set {
type = value;
if (type.IconName != null)
Properties.SetString ("Icon.Name", type.IconName);
}
}
public override string TypeName {
get { return Type.Name; }
}
private string arg;
public string Arg {
get { return arg; }
set { arg = value; }
}
private int play_count;
public int PlayCount {
get { return play_count; }
set { play_count = value; }
}
private int dbid;
// For StationSources that already exist in the db
protected StationSource (LastfmSource lastfm, int dbId, string name, string type, string arg, int playCount) : base (generic_name, name, 150, dbId.ToString ())
{
this.lastfm = lastfm;
dbid = dbId;
Type = StationType.FindByName (type);
Arg = arg;
PlayCount = playCount;
Station = Type.GetStationFor (arg);
StationInitialize ();
}
public StationSource (LastfmSource lastfm, string name, string type, string arg) : base (generic_name, name, 150)
{
this.lastfm = lastfm;
Type = StationType.FindByName (type);
Arg = arg;
Station = Type.GetStationFor (arg);
Save ();
StationInitialize ();
}
private void StationInitialize ()
{
track_model = new MemoryTrackListModel ();
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StateChange);
lastfm.Connection.StateChanged += HandleConnectionStateChanged;
Properties.SetString ("GtkActionPath", "/LastfmStationSourcePopup");
Properties.SetString ("SourcePropertiesActionLabel", Catalog.GetString ("Edit Last.fm Station"));
Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Delete Last.fm Station"));
UpdateUI (lastfm.Connection.State);
}
public void Dispose ()
{
ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);
lastfm.Connection.StateChanged -= HandleConnectionStateChanged;
}
public virtual void Save ()
{
if (dbid <= 0)
Create ();
else
Update ();
OnUpdated ();
}
private void Create ()
{
HyenaSqliteCommand command = new HyenaSqliteCommand (
@"INSERT INTO LastfmStations (Creator, Name, Type, Arg, PlayCount)
VALUES (?, ?, ?, ?, ?)",
lastfm.Account.UserName, Name,
Type.ToString (), Arg, PlayCount
);
dbid = ServiceManager.DbConnection.Execute (command);
TypeUniqueId = dbid.ToString ();
}
private void Update ()
{
HyenaSqliteCommand command = new HyenaSqliteCommand (
@"UPDATE LastfmStations
SET Name = ?, Type = ?, Arg = ?, PlayCount = ?
WHERE StationID = ?",
Name, Type.ToString (), Arg, PlayCount, dbid
);
ServiceManager.DbConnection.Execute (command);
Station = Type.GetStationFor (Arg);
OnUpdated ();
}
//private bool shuffle;
public override void Activate ()
{
base.Activate ();
//action_service.GlobalActions ["PreviousAction"].Sensitive = false;
// We lazy load the Last.fm connection, so if we're not already connected, do it
if (lastfm.Connection.State == ConnectionState.Connected)
TuneAndLoad ();
else if (lastfm.Connection.State == ConnectionState.Disconnected)
lastfm.Connection.Connect ();
}
private void TuneAndLoad ()
{
ThreadPool.QueueUserWorkItem (delegate {
if (ChangeToThisStation ()) {
Thread.Sleep (250); // sleep for a bit to try to avoid Last.fm timeouts
if (TracksLeft < 2)
Refresh ();
else
HideStatus ();
}
});
}
public override void Deactivate ()
{
//Globals.ActionManager["PreviousAction"].Sensitive = true;
}
// Last.fm requires you to 'tune' to a station before requesting a track list/playing it
public bool ChangeToThisStation ()
{
if (lastfm.Connection.Station == Station)
return false;
Log.Debug (String.Format ("Tuning Last.fm to {0}", Name), null);
SetStatus (Catalog.GetString ("Tuning Last.fm to {0}."), false);
StationError error = lastfm.Connection.ChangeStationTo (Station);
if (error == StationError.None) {
Log.Debug (String.Format ("Successfully tuned Last.fm to {0}", station), null);
return true;
} else {
Log.Debug (String.Format ("Failed to tune Last.fm to {0}", Name), RadioConnection.ErrorMessageFor (error));
SetStatus (String.Format (
// Translators: {0} is an error message sentence from RadioConnection.cs.
Catalog.GetString ("Failed to tune in station. {0}"), RadioConnection.ErrorMessageFor (error)), true
);
return false;
}
}
public override void SetStatus (string message, bool error)
{
base.SetStatus (message, error);
//LastfmSource.SetStatus (status_message, error, ConnectionState.Connected);
}
public void SetStatus (string message, bool error, ConnectionState state)
{
base.SetStatus (message, error);
//LastfmSource.SetStatus (status_message, error, state);
}
/*public override void ShowPropertiesDialog ()
{
Editor ed = new Editor (this);
ed.RunDialog ();
}*/
/*private bool playback_requested = false;
public override void StartPlayback ()
{
if (CurrentTrack != null) {
ServiceManager.PlayerEngine.OpenPlay (CurrentTrack);
} else if (playback_requested == false) {
playback_requested = true;
Refresh ();
}
}*/
private int current_track = 0;
public TrackInfo CurrentTrack {
get { return GetTrack (current_track); }
set {
int i = track_model.IndexOf (value);
if (i != -1)
current_track = i;
}
}
#region IBasicPlaybackController
bool IBasicPlaybackController.First ()
{
return ((IBasicPlaybackController)this).Next (false, true);
}
private bool playback_requested;
bool IBasicPlaybackController.Next (bool restart, bool changeImmediately)
{
TrackInfo next = NextTrack;
if (changeImmediately) {
if (next != null) {
ServiceManager.PlayerEngine.OpenPlay (next);
} else {
playback_requested = true;
}
} else {
// We want to unconditionally SetNextTrack.
// Passing null is OK.
ServiceManager.PlayerEngine.SetNextTrack (next);
playback_requested = next == null;
}
return true;
}
bool IBasicPlaybackController.Previous (bool restart)
{
return true;
}
#endregion
public TrackInfo NextTrack {
get { return GetTrack (current_track + 1); }
}
private TrackInfo GetTrack (int track_num) {
return (track_num > track_model.Count - 1) ? null : track_model[track_num];
}
private int TracksLeft {
get {
int left = track_model.Count - current_track - 1;
return (left < 0) ? 0 : left;
}
}
public bool HasDependencies {
get { return false; }
}
private bool refreshing = false;
public void Refresh ()
{
lock (this) {
if (refreshing || lastfm.Connection.Station != Station) {
return;
}
refreshing = true;
}
if (TracksLeft == 0) {
SetStatus (Catalog.GetString ("Getting new songs for {0}."), false);
}
ThreadAssist.Spawn (delegate {
Media.Playlists.Xspf.Playlist playlist = lastfm.Connection.LoadPlaylistFor (Station);
if (playlist != null) {
if (playlist.TrackCount == 0) {
SetStatus (Catalog.GetString ("No new songs available for {0}."), true);
} else {
List<TrackInfo> new_tracks = new List<TrackInfo> ();
foreach (Media.Playlists.Xspf.Track track in playlist.Tracks) {
TrackInfo ti = new LastfmTrackInfo (track, this, track.GetExtendedValue ("trackauth"));
new_tracks.Add (ti);
lock (track_model) {
track_model.Add (ti);
}
}
HideStatus ();
ThreadAssist.ProxyToMain (delegate {
//OnTrackAdded (null, new_tracks);
track_model.Reload ();
OnUpdated ();
if (playback_requested) {
if (this == ServiceManager.PlaybackController.Source ) {
((IBasicPlaybackController)this).Next (false, true);
}
playback_requested = false;
}
});
}
} else {
SetStatus (Catalog.GetString ("Failed to get new songs for {0}."), true);
}
refreshing = false;
});
}
private void OnPlayerEvent (PlayerEventArgs args)
{
if (((PlayerEventStateChangeArgs)args).Current == PlayerState.Loaded &&
track_model.Contains (ServiceManager.PlayerEngine.CurrentTrack)) {
CurrentTrack = ServiceManager.PlayerEngine.CurrentTrack;
lock (track_model) {
// Remove all but 5 played or skipped tracks
if (current_track > 5) {
for (int i = 0; i < (current_track - 5); i++) {
track_model.Remove (track_model[0]);
}
current_track = 5;
}
// Set all previous tracks as CanPlay = false
foreach (TrackInfo track in track_model) {
if (track == CurrentTrack)
break;
if (track.CanPlay) {
track.CanPlay = false;
}
}
OnUpdated ();
}
if (TracksLeft <= 2) {
Refresh ();
}
}
}
private void HandleConnectionStateChanged (object sender, ConnectionStateChangedArgs args)
{
UpdateUI (args.State);
}
private void UpdateUI (ConnectionState state)
{
if (state == ConnectionState.Connected) {
HideStatus ();
if (this == ServiceManager.SourceManager.ActiveSource) {
TuneAndLoad ();
}
} else {
track_model.Clear ();
SetStatus (RadioConnection.MessageFor (state), state != ConnectionState.Connecting, state);
OnUpdated ();
}
}
public override string GetStatusText ()
{
return String.Format (
Catalog.GetPluralString ("{0} song played", "{0} songs played", PlayCount), PlayCount
);
}
public override bool CanRename {
get { return true; }
}
#region ITrackModelSource Implementation
public TrackListModel TrackModel {
get { return track_model; }
}
public AlbumListModel AlbumModel {
get { return null; }
}
public ArtistListModel ArtistModel {
get { return null; }
}
public void Reload ()
{
track_model.Reload ();
}
public void RemoveSelectedTracks ()
{
}
public void DeleteSelectedTracks ()
{
throw new Exception ("Should not call DeleteSelectedTracks on StationSource");
}
public bool CanAddTracks {
get { return false; }
}
public bool CanRemoveTracks {
get { return false; }
}
public bool CanDeleteTracks {
get { return false; }
}
public bool ConfirmRemoveTracks {
get { return false; }
}
public virtual bool CanRepeat {
get { return false; }
}
public virtual bool CanShuffle {
get { return false; }
}
public bool ShowBrowser {
get { return false; }
}
public bool Indexable {
get { return false; }
}
#endregion
#region IUnmapableSource Implementation
public bool Unmap ()
{
ServiceManager.DbConnection.Execute (String.Format (
@"DELETE FROM LastfmStations
WHERE StationID = '{0}'",
dbid
));
Parent.RemoveChildSource (this);
ServiceManager.SourceManager.RemoveSource (this);
return true;
}
public bool CanUnmap {
get { return true; }
}
public bool ConfirmBeforeUnmap {
get { return true; }
}
#endregion
public override void Rename (string newName)
{
base.Rename (newName);
Save ();
}
public override bool HasProperties {
get { return true; }
}
public static List<StationSource> LoadAll (LastfmSource lastfm, string creator)
{
List<StationSource> stations = new List<StationSource> ();
HyenaSqliteCommand command = new HyenaSqliteCommand (
"SELECT StationID, Name, Type, Arg, PlayCount FROM LastfmStations WHERE Creator = ?",
creator
);
using (IDataReader reader = ServiceManager.DbConnection.Query (command)) {
while (reader.Read ()) {
try {
stations.Add (new StationSource (lastfm,
Convert.ToInt32 (reader[0]),
reader[1] as string,
reader[2] as string,
reader[3] as string,
Convert.ToInt32 (reader[4])
));
} catch (Exception e) {
Log.Warning ("Error Loading Last.fm Station", e.ToString (), false);
}
}
}
// Create some default stations if the user has none
if (stations.Count == 0) {
stations.Add (new StationSource (lastfm, Catalog.GetString ("Recommended"), "Recommended", creator));
stations.Add (new StationSource (lastfm, Catalog.GetString ("Personal"), "Personal", creator));
stations.Add (new StationSource (lastfm, Catalog.GetString ("Loved"), "Loved", creator));
stations.Add (new StationSource (lastfm, Catalog.GetString ("Banshee Group"), "Group", "Banshee"));
stations.Add (new StationSource (lastfm, Catalog.GetString ("Neighbors"), "Neighbor", creator));
stations.Add (new StationSource (lastfm, Catalog.GetString ("Creative Commons"), "Tag", "creative commons"));
}
return stations;
}
static StationSource ()
{
if (!ServiceManager.DbConnection.TableExists ("LastfmStations")) {
ServiceManager.DbConnection.Execute (@"
CREATE TABLE LastfmStations (
StationID INTEGER PRIMARY KEY,
Creator STRING NOT NULL,
Name STRING NOT NULL,
Type STRING NOT NULL,
Arg STRING NOT NULL,
PlayCount INTEGER NOT NULL
)
");
} else {
try {
ServiceManager.DbConnection.Query<int> ("SELECT PlayCount FROM LastfmStations LIMIT 1");
} catch {
Log.Debug ("Adding new database column", "Table: LastfmStations, Column: PlayCount INTEGER");
ServiceManager.DbConnection.Execute ("ALTER TABLE LastfmStations ADD PlayCount INTEGER");
ServiceManager.DbConnection.Execute ("UPDATE LastfmStations SET PlayCount = 0");
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Unmanaged
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
/// <summary>
/// Unmanaged thread utils.
/// </summary>
internal static class UnmanagedThread
{
/// <summary>
/// Delegate for <see cref="SetThreadExitCallback"/>.
/// </summary>
/// <param name="threadLocalValue">Value from <see cref="EnableCurrentThreadExitEvent"/></param>
public delegate void ThreadExitCallback(IntPtr threadLocalValue);
/// <summary>
/// Sets the thread exit callback, and returns an id to pass to <see cref="EnableCurrentThreadExitEvent"/>.
/// </summary>
/// <param name="callbackPtr">
/// Pointer to a callback function that matches <see cref="ThreadExitCallback"/>.
/// </param>
public static unsafe int SetThreadExitCallback(IntPtr callbackPtr)
{
Debug.Assert(callbackPtr != IntPtr.Zero);
if (Os.IsWindows)
{
var res = NativeMethodsWindows.FlsAlloc(callbackPtr);
if (res == NativeMethodsWindows.FLS_OUT_OF_INDEXES)
{
throw new InvalidOperationException("FlsAlloc failed: " + Marshal.GetLastWin32Error());
}
return res;
}
if (Os.IsMacOs)
{
int tlsIndex;
var res = NativeMethodsMacOs.pthread_key_create(new IntPtr(&tlsIndex), callbackPtr);
NativeMethodsLinux.CheckResult(res);
return tlsIndex;
}
if (Os.IsLinux)
{
int tlsIndex;
var res = Os.IsMono
? NativeMethodsMono.pthread_key_create(new IntPtr(&tlsIndex), callbackPtr)
: NativeMethodsLinux.pthread_key_create(new IntPtr(&tlsIndex), callbackPtr);
NativeMethodsLinux.CheckResult(res);
return tlsIndex;
}
throw new InvalidOperationException("Unsupported OS: " + Environment.OSVersion);
}
/// <summary>
/// Removes thread exit callback that has been set with <see cref="SetThreadExitCallback"/>.
/// NOTE: callback may be called as a result of this method call on some platforms.
/// </summary>
/// <param name="callbackId">Callback id returned from <see cref="SetThreadExitCallback"/>.</param>
public static void RemoveThreadExitCallback(int callbackId)
{
if (Os.IsWindows)
{
var res = NativeMethodsWindows.FlsFree(callbackId);
if (!res)
{
throw new InvalidOperationException("FlsFree failed: " + Marshal.GetLastWin32Error());
}
}
else if (Os.IsMacOs)
{
var res = NativeMethodsMacOs.pthread_key_delete(callbackId);
NativeMethodsLinux.CheckResult(res);
}
else if (Os.IsLinux)
{
var res = Os.IsMono
? NativeMethodsMono.pthread_key_delete(callbackId)
: NativeMethodsLinux.pthread_key_delete(callbackId);
NativeMethodsLinux.CheckResult(res);
}
else
{
throw new InvalidOperationException("Unsupported OS: " + Environment.OSVersion);
}
}
/// <summary>
/// Enables thread exit event for current thread.
/// </summary>
public static void EnableCurrentThreadExitEvent(int callbackId, IntPtr threadLocalValue)
{
Debug.Assert(threadLocalValue != IntPtr.Zero);
// Store any value so that destructor callback is fired.
if (Os.IsWindows)
{
var res = NativeMethodsWindows.FlsSetValue(callbackId, threadLocalValue);
if (!res)
{
throw new InvalidOperationException("FlsSetValue failed: " + Marshal.GetLastWin32Error());
}
}
else if (Os.IsMacOs)
{
var res = NativeMethodsMacOs.pthread_setspecific(callbackId, threadLocalValue);
NativeMethodsLinux.CheckResult(res);
}
else if (Os.IsLinux)
{
var res = Os.IsMono
? NativeMethodsMono.pthread_setspecific(callbackId, threadLocalValue)
: NativeMethodsLinux.pthread_setspecific(callbackId, threadLocalValue);
NativeMethodsLinux.CheckResult(res);
}
else
{
throw new InvalidOperationException("Unsupported OS: " + Environment.OSVersion);
}
}
/// <summary>
/// Windows imports.
/// </summary>
private static class NativeMethodsWindows
{
// ReSharper disable once InconsistentNaming
public const int FLS_OUT_OF_INDEXES = -1;
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int FlsAlloc(IntPtr destructorCallback);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FlsFree(int dwFlsIndex);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FlsSetValue(int dwFlsIndex, IntPtr lpFlsData);
}
/// <summary>
/// Linux imports.
/// </summary>
private static class NativeMethodsLinux
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("libcoreclr.so")]
public static extern int pthread_key_create(IntPtr key, IntPtr destructorCallback);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("libcoreclr.so")]
public static extern int pthread_key_delete(int key);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("libcoreclr.so")]
public static extern int pthread_setspecific(int key, IntPtr value);
/// <summary>
/// Checks native call result.
/// </summary>
public static void CheckResult(int res)
{
if (res != 0)
{
throw new InvalidOperationException("Native call failed: " + res);
}
}
}
/// <summary>
/// macOS imports.
/// </summary>
private static class NativeMethodsMacOs
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("libSystem.dylib")]
public static extern int pthread_key_create(IntPtr key, IntPtr destructorCallback);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("libSystem.dylib")]
public static extern int pthread_key_delete(int key);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("libSystem.dylib")]
public static extern int pthread_setspecific(int key, IntPtr value);
}
/// <summary>
/// Mono on Linux requires __Internal instead of libcoreclr.so.
/// </summary>
private static class NativeMethodsMono
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("__Internal")]
public static extern int pthread_key_create(IntPtr key, IntPtr destructorCallback);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("__Internal")]
public static extern int pthread_key_delete(int key);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Reviewed.")]
[DllImport("__Internal")]
public static extern int pthread_setspecific(int key, IntPtr value);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
using NUnit.Tests;
using NUnit.Tests.Assemblies;
using NUnit.TestUtilities;
using NUnit.Framework.Internal.Filters;
namespace NUnit.Framework.Api
{
// Functional tests of the TestAssemblyRunner and all subordinate classes
public class TestAssemblyRunnerTests : ITestListener
{
private const string MOCK_ASSEMBLY_FILE = "mock-assembly.dll";
#if NETCOREAPP1_1
private const string COULD_NOT_LOAD_MSG = "The system cannot find the file specified.";
#else
private const string COULD_NOT_LOAD_MSG = "Could not load";
#endif
private const string BAD_FILE = "mock-assembly.pdb";
private const string SLOW_TESTS_FILE = "slow-nunit-tests.dll";
private const string MISSING_FILE = "junk.dll";
private static readonly string MOCK_ASSEMBLY_NAME = typeof(MockAssembly).GetTypeInfo().Assembly.FullName;
private const string INVALID_FILTER_ELEMENT_MESSAGE = "Invalid filter element: {0}";
private static readonly IDictionary<string, object> EMPTY_SETTINGS = new Dictionary<string, object>();
private ITestAssemblyRunner _runner;
private int _testStartedCount;
private int _testFinishedCount;
private int _testOutputCount;
private int _successCount;
private int _failCount;
private int _skipCount;
private int _inconclusiveCount;
[SetUp]
public void CreateRunner()
{
_runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
_testStartedCount = 0;
_testFinishedCount = 0;
_testOutputCount = 0;
_successCount = 0;
_failCount = 0;
_skipCount = 0;
_inconclusiveCount = 0;
}
#region Load
[Test]
public void Load_GoodFile_ReturnsRunnableSuite()
{
var result = LoadMockAssembly();
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(MOCK_ASSEMBLY_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.Runnable));
Assert.That(result.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
}
[Test, SetUICulture("en-US")]
public void Load_FileNotFound_ReturnsNonRunnableSuite()
{
var result = _runner.Load(MISSING_FILE, EMPTY_SETTINGS);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(MISSING_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.NotRunnable));
Assert.That(result.TestCaseCount, Is.EqualTo(0));
Assert.That(result.Properties.Get(PropertyNames.SkipReason),
Does.StartWith(COULD_NOT_LOAD_MSG));
}
[Test, SetUICulture("en-US")]
public void Load_BadFile_ReturnsNonRunnableSuite()
{
var result = _runner.Load(BAD_FILE, EMPTY_SETTINGS);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(BAD_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.NotRunnable));
Assert.That(result.TestCaseCount, Is.EqualTo(0));
Assert.That(result.Properties.Get(PropertyNames.SkipReason),
Does.StartWith("Could not load").And.Contains(BAD_FILE));
}
#endregion
#region CountTestCases
[Test]
public void CountTestCases_AfterLoad_ReturnsCorrectCount()
{
LoadMockAssembly();
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(MockAssembly.Tests));
}
[Test]
public void CountTestCases_WithoutLoad_ThrowsInvalidOperation()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.CountTestCases(TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The CountTestCases method was called but no test has been loaded"));
}
[Test]
public void CountTestCases_FileNotFound_ReturnsZero()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(0));
}
[Test]
public void CountTestCases_BadFile_ReturnsZero()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(0));
}
#endregion
#region ExploreTests
[Test]
public void ExploreTests_WithoutLoad_ThrowsInvalidOperation()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.ExploreTests(TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The ExploreTests method was called but no test has been loaded"));
}
[Test]
public void ExploreTests_FileNotFound_ReturnsZeroTests()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
var explorer = _runner.ExploreTests(TestFilter.Empty);
Assert.That(explorer.TestCaseCount, Is.EqualTo(0));
}
[Test]
public void ExploreTests_BadFile_ReturnsZeroTests()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
var explorer = _runner.ExploreTests(TestFilter.Empty);
Assert.That(explorer.TestCaseCount, Is.EqualTo(0));
}
[Test]
public void ExploreTests_AfterLoad_ReturnsCorrectCount()
{
LoadMockAssembly();
var explorer = _runner.ExploreTests(TestFilter.Empty);
Assert.That(explorer.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
}
[Test]
public void ExploreTest_AfterLoad_ReturnsSameTestCount()
{
LoadMockAssembly();
var explorer = _runner.ExploreTests(TestFilter.Empty);
Assert.That(explorer.TestCaseCount, Is.EqualTo(_runner.CountTestCases(TestFilter.Empty)));
}
[Test]
public void ExploreTests_AfterLoad_WithFilter_ReturnCorrectCount()
{
LoadMockAssembly();
ITestFilter filter = new CategoryFilter("FixtureCategory");
var explorer = _runner.ExploreTests(filter);
Assert.That(explorer.TestCaseCount, Is.EqualTo(MockTestFixture.Tests));
}
[Test]
public void ExploreTests_AfterLoad_WithFilter_ReturnSameTestCount()
{
LoadMockAssembly();
ITestFilter filter = new CategoryFilter("FixtureCategory");
var explorer = _runner.ExploreTests(filter);
Assert.That(explorer.TestCaseCount, Is.EqualTo(_runner.CountTestCases(filter)));
}
#endregion
#region Run
[Test]
public void Run_AfterLoad_ReturnsRunnableSuite()
{
LoadMockAssembly();
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(result.ResultState, Is.EqualTo(ResultState.ChildFailure));
Assert.That(result.PassCount, Is.EqualTo(MockAssembly.Passed));
Assert.That(result.FailCount, Is.EqualTo(MockAssembly.Failed));
Assert.That(result.WarningCount, Is.EqualTo(MockAssembly.Warnings));
Assert.That(result.SkipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(result.InconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void Run_AfterLoad_SendsExpectedEvents()
{
LoadMockAssembly();
_runner.Run(this, TestFilter.Empty);
Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.TestStartedEvents));
Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.TestFinishedEvents));
Assert.That(_testOutputCount, Is.EqualTo(MockAssembly.TestOutputEvents));
Assert.That(_successCount, Is.EqualTo(MockAssembly.Passed));
Assert.That(_failCount, Is.EqualTo(MockAssembly.Failed));
Assert.That(_skipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_inconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void Run_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.Run(TestListener.NULL, TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test, SetUICulture("en-US")]
public void Run_FileNotFound_ReturnsNonRunnableSuite()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
Assert.That(result.Message,
Does.StartWith(COULD_NOT_LOAD_MSG));
}
[Test]
public void RunTestsAction_WithInvalidFilterElement_ThrowsArgumentException()
{
LoadMockAssembly();
var ex = Assert.Throws<ArgumentException>(() =>
{
TestFilter.FromXml("<filter><invalidElement>foo</invalidElement></filter>");
});
Assert.That(ex.Message, Does.StartWith(string.Format(INVALID_FILTER_ELEMENT_MESSAGE, "invalidElement")));
}
[Test]
public void Run_WithParameters()
{
var dict = new Dictionary<string, string>();
dict.Add("X", "5");
dict.Add("Y", "7");
var settings = new Dictionary<string, object>();
settings.Add("TestParametersDictionary", dict);
LoadMockAssembly(settings);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
CheckParameterOutput(result);
}
[Test]
public void Run_WithLegacyParameters()
{
var settings = new Dictionary<string, object>();
settings.Add("TestParameters", "X=5;Y=7");
LoadMockAssembly(settings);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
CheckParameterOutput(result);
}
[Test, SetUICulture("en-US")]
public void Run_BadFile_ReturnsNonRunnableSuite()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
Assert.That(result.Message,
Does.StartWith("Could not load"));
}
#endregion
#region RunAsync
[Test]
public void RunAsync_AfterLoad_ReturnsRunnableSuite()
{
LoadMockAssembly();
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.ChildFailure));
Assert.That(_runner.Result.PassCount, Is.EqualTo(MockAssembly.Passed));
Assert.That(_runner.Result.FailCount, Is.EqualTo(MockAssembly.Failed));
Assert.That(_runner.Result.SkipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_runner.Result.InconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void RunAsync_AfterLoad_SendsExpectedEvents()
{
LoadMockAssembly();
_runner.RunAsync(this, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.Tests - IgnoredFixture.Tests - BadFixture.Tests - ExplicitFixture.Tests));
Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_successCount, Is.EqualTo(MockAssembly.Passed));
Assert.That(_failCount, Is.EqualTo(MockAssembly.Failed));
Assert.That(_skipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_inconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void RunAsync_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.RunAsync(TestListener.NULL, TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test, SetUICulture("en-US")]
public void RunAsync_FileNotFound_ReturnsNonRunnableSuite()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
Assert.That(_runner.Result.Message,
Does.StartWith(COULD_NOT_LOAD_MSG));
}
[Test, SetUICulture("en-US")]
public void RunAsync_BadFile_ReturnsNonRunnableSuite()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
Assert.That(_runner.Result.Message,
Does.StartWith("Could not load"));
}
#endregion
#region StopRun
[Test]
public void StopRun_WhenNoTestIsRunning_Succeeds()
{
_runner.StopRun(false);
}
[Test]
public void StopRun_WhenTestIsRunning_StopsTest()
{
var tests = LoadSlowTests();
var count = tests.TestCaseCount;
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.StopRun(false);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.True(_runner.IsTestComplete, "Test is not complete");
if (_runner.Result.ResultState != ResultState.Success) // Test may have finished before we stopped it
{
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.Cancelled));
Assert.That(_runner.Result.PassCount, Is.LessThan(count));
}
}
#endregion
#region Cancel Run
[Test]
public void CancelRun_WhenNoTestIsRunning_Succeeds()
{
_runner.StopRun(true);
}
[Test]
public void CancelRun_WhenTestIsRunning_StopsTest()
{
var tests = LoadSlowTests();
var count = tests.TestCaseCount;
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.StopRun(true);
// When cancelling, the completion event may not be signalled,
// so we only wait a short time before checking.
_runner.WaitForCompletion(Timeout.Infinite);
Assert.True(_runner.IsTestComplete, "Test is not complete");
if (_runner.Result.ResultState != ResultState.Success)
{
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.Cancelled));
Assert.That(_runner.Result.PassCount, Is.LessThan(count));
}
}
#endregion
#region ITestListener Implementation
void ITestListener.TestStarted(ITest test)
{
if (!test.IsSuite)
_testStartedCount++;
}
void ITestListener.TestFinished(ITestResult result)
{
if (!result.Test.IsSuite)
{
_testFinishedCount++;
switch (result.ResultState.Status)
{
case TestStatus.Passed:
_successCount++;
break;
case TestStatus.Failed:
_failCount++;
break;
case TestStatus.Skipped:
_skipCount++;
break;
case TestStatus.Inconclusive:
_inconclusiveCount++;
break;
}
}
}
/// <summary>
/// Called when a test produces output for immediate display
/// </summary>
/// <param name="output">A TestOutput object containing the text to display</param>
public void TestOutput(TestOutput output)
{
_testOutputCount++;
}
#endregion
#region Helper Methods
private ITest LoadMockAssembly()
{
return LoadMockAssembly(EMPTY_SETTINGS);
}
private ITest LoadMockAssembly(IDictionary<string, object> settings)
{
return _runner.Load(
Path.Combine(TestContext.CurrentContext.TestDirectory, MOCK_ASSEMBLY_FILE),
settings);
}
private ITest LoadSlowTests()
{
return _runner.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, SLOW_TESTS_FILE), EMPTY_SETTINGS);
}
private void CheckParameterOutput(ITestResult result)
{
var childResult = TestFinder.Find(
"DisplayRunParameters", result, true);
Assert.That(childResult.Output, Is.EqualTo(
"Parameter X = 5" + Environment.NewLine +
"Parameter Y = 7" + Environment.NewLine));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Reflection;
#if FEATURE_COMPILE
using System.Linq.Expressions.Compiler;
#endif
namespace System.Runtime.CompilerServices
{
//
// A CallSite provides a fast mechanism for call-site caching of dynamic dispatch
// behvaior. Each site will hold onto a delegate that provides a fast-path dispatch
// based on previous types that have been seen at the call-site. This delegate will
// call UpdateAndExecute if it is called with types that it hasn't seen before.
// Updating the binding will typically create (or lookup) a new delegate
// that supports fast-paths for both the new type and for any types that
// have been seen previously.
//
// DynamicSites will generate the fast-paths specialized for sets of runtime argument
// types. However, they will generate exactly the right amount of code for the types
// that are seen in the program so that int addition will remain as fast as it would
// be with custom implementation of the addition, and the user-defined types can be
// as fast as ints because they will all have the same optimal dynamically generated
// fast-paths.
//
// DynamicSites don't encode any particular caching policy, but use their
// CallSiteBinding to encode a caching policy.
//
/// <summary>
/// A Dynamic Call Site base class. This type is used as a parameter type to the
/// dynamic site targets. The first parameter of the delegate (T) below must be
/// of this type.
/// </summary>
public class CallSite
{
// Cache of CallSite constructors for a given delegate type
private static volatile CacheDict<Type, Func<CallSiteBinder, CallSite>> s_siteCtors;
/// <summary>
/// The Binder responsible for binding operations at this call site.
/// This binder is invoked by the UpdateAndExecute below if all Level 0,
/// Level 1 and Level 2 caches experience cache miss.
/// </summary>
internal readonly CallSiteBinder _binder;
// only CallSite<T> derives from this
internal CallSite(CallSiteBinder binder)
{
_binder = binder;
}
/// <summary>
/// used by Matchmaker sites to indicate rule match.
/// </summary>
internal bool _match;
/// <summary>
/// Class responsible for binding dynamic operations on the dynamic site.
/// </summary>
public CallSiteBinder Binder
{
get { return _binder; }
}
/// <summary>
/// Creates a CallSite with the given delegate type and binder.
/// </summary>
/// <param name="delegateType">The CallSite delegate type.</param>
/// <param name="binder">The CallSite binder.</param>
/// <returns>The new CallSite.</returns>
public static CallSite Create(Type delegateType, CallSiteBinder binder)
{
ContractUtils.RequiresNotNull(delegateType, nameof(delegateType));
ContractUtils.RequiresNotNull(binder, nameof(binder));
if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
var ctors = s_siteCtors;
if (ctors == null) {
// It's okay to just set this, worst case we're just throwing away some data
s_siteCtors = ctors = new CacheDict<Type, Func<CallSiteBinder, CallSite>>(100);
}
Func<CallSiteBinder, CallSite> ctor;
MethodInfo method = null;
if (!ctors.TryGetValue(delegateType, out ctor))
{
method = typeof(CallSite<>).MakeGenericType(delegateType).GetMethod("Create");
if (TypeUtils.CanCache(delegateType))
{
ctor = (Func<CallSiteBinder, CallSite>)method.CreateDelegate(typeof(Func<CallSiteBinder, CallSite>));
ctors.Add(delegateType, ctor);
}
}
if (ctor != null)
{
return ctor(binder);
}
// slow path
return (CallSite)method.Invoke(null, new object[] { binder });
}
}
/// <summary>
/// Dynamic site type.
/// </summary>
/// <typeparam name="T">The delegate type.</typeparam>
public partial class CallSite<T> : CallSite where T : class
{
/// <summary>
/// The update delegate. Called when the dynamic site experiences cache miss.
/// </summary>
/// <returns>The update delegate.</returns>
public T Update
{
get
{
// if this site is set up for match making, then use NoMatch as an Update
if (_match)
{
Debug.Assert(s_cachedNoMatch != null, "all normal sites should have Update cached once there is an instance.");
return s_cachedNoMatch;
}
else
{
Debug.Assert(s_cachedUpdate != null, "all normal sites should have Update cached once there is an instance.");
return s_cachedUpdate;
}
}
}
/// <summary>
/// The Level 0 cache - a delegate specialized based on the site history.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
public T Target;
/// <summary>
/// The Level 1 cache - a history of the dynamic site.
/// </summary>
internal T[] Rules;
// Cached update delegate for all sites with a given T
private static T s_cachedUpdate;
// Cached noMatch delegate for all sites with a given T
private static volatile T s_cachedNoMatch;
private CallSite(CallSiteBinder binder)
: base(binder)
{
Target = GetUpdateDelegate();
}
private CallSite()
: base(null)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
internal CallSite<T> CreateMatchMaker()
{
return new CallSite<T>();
}
/// <summary>
/// Creates an instance of the dynamic call site, initialized with the binder responsible for the
/// runtime binding of the dynamic operations at this call site.
/// </summary>
/// <param name="binder">The binder responsible for the runtime binding of the dynamic operations at this call site.</param>
/// <returns>The new instance of dynamic call site.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
public static CallSite<T> Create(CallSiteBinder binder)
{
if (!typeof(T).IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
return new CallSite<T>(binder);
}
private T GetUpdateDelegate()
{
// This is intentionally non-static to speed up creation - in particular MakeUpdateDelegate
// as static generic methods are more expensive than instance methods. We call a ref helper
// so we only access the generic static field once.
return GetUpdateDelegate(ref s_cachedUpdate);
}
private T GetUpdateDelegate(ref T addr)
{
if (addr == null)
{
// reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes
// us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely
// create 2 delegates with no other harm caused.
addr = MakeUpdateDelegate();
}
return addr;
}
/// <summary>
/// Clears the rule cache ... used by the call site tests.
/// </summary>
private void ClearRuleCache()
{
// make sure it initialized/atomized etc...
Binder.GetRuleCache<T>();
var cache = Binder.Cache;
if (cache != null)
{
lock (cache)
{
cache.Clear();
}
}
}
private const int MaxRules = 10;
internal void AddRule(T newRule)
{
T[] rules = Rules;
if (rules == null)
{
Rules = new[] { newRule };
return;
}
T[] temp;
if (rules.Length < (MaxRules - 1))
{
temp = new T[rules.Length + 1];
Array.Copy(rules, 0, temp, 1, rules.Length);
}
else
{
temp = new T[MaxRules];
Array.Copy(rules, 0, temp, 1, MaxRules - 1);
}
temp[0] = newRule;
Rules = temp;
}
// moves rule +2 up.
internal void MoveRule(int i)
{
if (i > 1)
{
var rules = Rules;
var rule = rules[i];
rules[i] = rules[i - 1];
rules[i - 1] = rules[i - 2];
rules[i - 2] = rule;
}
}
internal T MakeUpdateDelegate()
{
#if !FEATURE_COMPILE
Type target = typeof(T);
MethodInfo invoke = target.GetMethod("Invoke");
s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke);
return CreateCustomUpdateDelegate(invoke);
#else
Type target = typeof(T);
Type[] args;
MethodInfo invoke = target.GetMethod("Invoke");
if (target.GetTypeInfo().IsGenericType && IsSimpleSignature(invoke, out args))
{
MethodInfo method = null;
MethodInfo noMatchMethod = null;
if (invoke.ReturnType == typeof(void))
{
if (target == DelegateHelpers.GetActionType(args.AddFirst(typeof(CallSite))))
{
method = typeof(UpdateDelegates).GetMethod("UpdateAndExecuteVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static);
noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatchVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static);
}
}
else
{
if (target == DelegateHelpers.GetFuncType(args.AddFirst(typeof(CallSite))))
{
method = typeof(UpdateDelegates).GetMethod("UpdateAndExecute" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static);
noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatch" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static);
}
}
if (method != null)
{
s_cachedNoMatch = (T)(object)CreateDelegateHelper(target, noMatchMethod.MakeGenericMethod(args));
return (T)(object)CreateDelegateHelper(target, method.MakeGenericMethod(args));
}
}
s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke);
return CreateCustomUpdateDelegate(invoke);
#endif
}
#if FEATURE_COMPILE
// This needs to be SafeCritical to allow access to
// internal types from user code as generic parameters.
//
// It's safe for a few reasons:
// 1. The internal types are coming from a lower trust level (app code)
// 2. We got the internal types from our own generic parameter: T
// 3. The UpdateAndExecute methods don't do anything with the types,
// we just want the CallSite args to be strongly typed to avoid
// casting.
// 4. Works on desktop CLR with AppDomain that has only Execute
// permission. In theory it might require RestrictedMemberAccess,
// but it's unclear because we have tests passing without RMA.
//
// When Silverlight gets RMA we may be able to remove this.
[System.Security.SecuritySafeCritical]
private static Delegate CreateDelegateHelper(Type delegateType, MethodInfo method)
{
return method.CreateDelegate(delegateType);
}
private static bool IsSimpleSignature(MethodInfo invoke, out Type[] sig)
{
ParameterInfo[] pis = invoke.GetParametersCached();
ContractUtils.Requires(pis.Length > 0 && pis[0].ParameterType == typeof(CallSite), nameof(T));
Type[] args = new Type[invoke.ReturnType != typeof(void) ? pis.Length : pis.Length - 1];
bool supported = true;
for (int i = 1; i < pis.Length; i++)
{
ParameterInfo pi = pis[i];
if (pi.IsByRefParameter())
{
supported = false;
}
args[i - 1] = pi.ParameterType;
}
if (invoke.ReturnType != typeof(void))
{
args[args.Length - 1] = invoke.ReturnType;
}
sig = args;
return supported;
}
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private T CreateCustomUpdateDelegate(MethodInfo invoke)
{
var body = new List<Expression>();
var vars = new List<ParameterExpression>();
var @params = invoke.GetParametersCached().Map(p => Expression.Parameter(p.ParameterType, p.Name));
var @return = Expression.Label(invoke.GetReturnType());
var typeArgs = new[] { typeof(T) };
var site = @params[0];
var arguments = @params.RemoveFirst();
var @this = Expression.Variable(typeof(CallSite<T>), "this");
vars.Add(@this);
body.Add(Expression.Assign(@this, Expression.Convert(site, @this.Type)));
var applicable = Expression.Variable(typeof(T[]), "applicable");
vars.Add(applicable);
var rule = Expression.Variable(typeof(T), "rule");
vars.Add(rule);
var originalRule = Expression.Variable(typeof(T), "originalRule");
vars.Add(originalRule);
body.Add(Expression.Assign(originalRule, Expression.Field(@this, "Target")));
ParameterExpression result = null;
if (@return.Type != typeof(void))
{
vars.Add(result = Expression.Variable(@return.Type, "result"));
}
var count = Expression.Variable(typeof(int), "count");
vars.Add(count);
var index = Expression.Variable(typeof(int), "index");
vars.Add(index);
body.Add(
Expression.Assign(
site,
Expression.Call(
typeof(CallSiteOps),
"CreateMatchmaker",
typeArgs,
@this
)
)
);
Expression invokeRule;
Expression getMatch = Expression.Call(
typeof(CallSiteOps).GetMethod("GetMatch"),
site
);
Expression resetMatch = Expression.Call(
typeof(CallSiteOps).GetMethod("ClearMatch"),
site
);
var onMatch = Expression.Call(
typeof(CallSiteOps),
"UpdateRules",
typeArgs,
@this,
index
);
if (@return.Type == typeof(void))
{
invokeRule = Expression.Block(
Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params)),
Expression.IfThen(
getMatch,
Expression.Block(onMatch, Expression.Return(@return))
)
);
}
else
{
invokeRule = Expression.Block(
Expression.Assign(result, Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params))),
Expression.IfThen(
getMatch,
Expression.Block(onMatch, Expression.Return(@return, result))
)
);
}
Expression getRule = Expression.Assign(rule, Expression.ArrayAccess(applicable, index));
var @break = Expression.Label();
var breakIfDone = Expression.IfThen(
Expression.Equal(index, count),
Expression.Break(@break)
);
var incrementIndex = Expression.PreIncrementAssign(index);
body.Add(
Expression.IfThen(
Expression.NotEqual(
Expression.Assign(applicable, Expression.Call(typeof(CallSiteOps), "GetRules", typeArgs, @this)),
Expression.Constant(null, applicable.Type)
),
Expression.Block(
Expression.Assign(count, Expression.ArrayLength(applicable)),
Expression.Assign(index, Expression.Constant(0)),
Expression.Loop(
Expression.Block(
breakIfDone,
getRule,
Expression.IfThen(
Expression.NotEqual(
Expression.Convert(rule, typeof(object)),
Expression.Convert(originalRule, typeof(object))
),
Expression.Block(
Expression.Assign(
Expression.Field(@this, "Target"),
rule
),
invokeRule,
resetMatch
)
),
incrementIndex
),
@break,
null
)
)
)
);
////
//// Level 2 cache lookup
////
//
////
//// Any applicable rules in level 2 cache?
////
var cache = Expression.Variable(typeof(RuleCache<T>), "cache");
vars.Add(cache);
body.Add(
Expression.Assign(
cache,
Expression.Call(typeof(CallSiteOps), "GetRuleCache", typeArgs, @this)
)
);
body.Add(
Expression.Assign(
applicable,
Expression.Call(typeof(CallSiteOps), "GetCachedRules", typeArgs, cache)
)
);
// L2 invokeRule is different (no onMatch)
if (@return.Type == typeof(void))
{
invokeRule = Expression.Block(
Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params)),
Expression.IfThen(
getMatch,
Expression.Return(@return)
)
);
}
else
{
invokeRule = Expression.Block(
Expression.Assign(result, Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params))),
Expression.IfThen(
getMatch,
Expression.Return(@return, result)
)
);
}
var tryRule = Expression.TryFinally(
invokeRule,
Expression.IfThen(
getMatch,
Expression.Block(
Expression.Call(typeof(CallSiteOps), "AddRule", typeArgs, @this, rule),
Expression.Call(typeof(CallSiteOps), "MoveRule", typeArgs, cache, rule, index)
)
)
);
getRule = Expression.Assign(
Expression.Field(@this, "Target"),
Expression.Assign(rule, Expression.ArrayAccess(applicable, index))
);
body.Add(Expression.Assign(index, Expression.Constant(0)));
body.Add(Expression.Assign(count, Expression.ArrayLength(applicable)));
body.Add(
Expression.Loop(
Expression.Block(
breakIfDone,
getRule,
tryRule,
resetMatch,
incrementIndex
),
@break,
null
)
);
////
//// Miss on Level 0, 1 and 2 caches. Create new rule
////
body.Add(Expression.Assign(rule, Expression.Constant(null, rule.Type)));
var args = Expression.Variable(typeof(object[]), "args");
vars.Add(args);
body.Add(
Expression.Assign(
args,
Expression.NewArrayInit(typeof(object), arguments.Map(p => Convert(p, typeof(object))))
)
);
Expression setOldTarget = Expression.Assign(
Expression.Field(@this, "Target"),
originalRule
);
getRule = Expression.Assign(
Expression.Field(@this, "Target"),
Expression.Assign(
rule,
Expression.Call(
typeof(CallSiteOps),
"Bind",
typeArgs,
Expression.Property(@this, "Binder"),
@this,
args
)
)
);
tryRule = Expression.TryFinally(
invokeRule,
Expression.IfThen(
getMatch,
Expression.Call(typeof(CallSiteOps), "AddRule", typeArgs, @this, rule)
)
);
body.Add(
Expression.Loop(
Expression.Block(setOldTarget, getRule, tryRule, resetMatch),
null, null
)
);
body.Add(Expression.Default(@return.Type));
var lambda = Expression.Lambda<T>(
Expression.Label(
@return,
Expression.Block(
new ReadOnlyCollection<ParameterExpression>(vars),
new ReadOnlyCollection<Expression>(body)
)
),
"CallSite.Target",
true, // always compile the rules with tail call optimization
new ReadOnlyCollection<ParameterExpression>(@params)
);
// Need to compile with forceDynamic because T could be invisible,
// or one of the argument types could be invisible
return lambda.Compile();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private T CreateCustomNoMatchDelegate(MethodInfo invoke)
{
var @params = invoke.GetParametersCached().Map(p => Expression.Parameter(p.ParameterType, p.Name));
return Expression.Lambda<T>(
Expression.Block(
Expression.Call(
typeof(CallSiteOps).GetMethod("SetNotMatched"),
@params.First()
),
Expression.Default(invoke.GetReturnType())
),
@params
).Compile();
}
private static Expression Convert(Expression arg, Type type)
{
if (TypeUtils.AreReferenceAssignable(type, arg.Type))
{
return arg;
}
return Expression.Convert(arg, type);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using YesSql.Indexes;
namespace YesSql
{
public interface IQuery
{
/// <summary>
/// Adds a filter on the document type
/// </summary>
/// <param name="filterType">If <c>false</c> the document type won't be filtered.</param>
/// <typeparam name="T">The type of document to return</typeparam>
IQuery<T> For<T>(bool filterType = true) where T : class;
/// <summary>
/// Defines what type of index should be returned
/// </summary>
/// <typeparam name="T">The type of index to return</typeparam>
IQueryIndex<T> ForIndex<T>() where T : class, IIndex;
/// <summary>
/// Returns documents from any type
/// </summary>
IQuery<object> Any();
}
/// <summary>
/// Represents a query over an entity
/// </summary>
/// <typeparam name="T">The type to return. It can be and index or an entity</typeparam>
public interface IQuery<T> where T : class
{
/// <summary>
/// Filters any predicates on newly joined indexes.
/// </summary>
IQuery<T> Any(params Func<IQuery<T>, IQuery<T>>[] predicates);
/// <summary>
/// Filters any predicates on newly joined indexes.
/// </summary>
ValueTask<IQuery<T>> AnyAsync(params Func<IQuery<T>, ValueTask<IQuery<T>>>[] predicates);
/// <summary>
/// Filters all predicates on newly joined indexes.
/// </summary>
IQuery<T> All(params Func<IQuery<T>, IQuery<T>>[] predicates);
/// <summary>
/// Filters all predicates on newly joined indexes.
/// </summary>
ValueTask<IQuery<T>> AllAsync(params Func<IQuery<T>, ValueTask<IQuery<T>>>[] predicates);
/// <summary>
/// Filters the documents with a record in the specified index.
/// </summary>
IQuery<T> With(Type indexType);
/// <summary>
/// Filters the documents with a record in the specified index.
/// </summary>
/// <typeparam name="TIndex">The index to filter on.</typeparam>
IQuery<T, TIndex> With<TIndex>() where TIndex : class, IIndex;
/// <summary>
/// Filters the documents with a constraint on the specified index.
/// </summary>
/// <typeparam name="TIndex">The index to filter on.</typeparam>
IQuery<T, TIndex> With<TIndex>(Expression<Func<TIndex, bool>> predicate) where TIndex : class, IIndex;
/// <summary>
/// Skips the specified number of document.
/// </summary>
/// <param name="count">The number of documents to skip.</param>
IQuery<T> Skip(int count);
/// <summary>
/// Limits the results to the specified number of document.
/// </summary>
/// <param name="count">The number of documents to return.</param>
IQuery<T> Take(int count);
/// <summary>
/// Executes the query and returns the first result matching the constraints.
/// </summary>
Task<T> FirstOrDefaultAsync();
/// <summary>
/// Executes the query and returns all documents matching the constraints.
/// </summary>
Task<IEnumerable<T>> ListAsync();
/// <summary>
/// Executes the query and returns all documents matching the constraints.
/// </summary>
IAsyncEnumerable<T> ToAsyncEnumerable();
/// <summary>
/// Executes a that returns the number of documents matching the constraints.
/// </summary>
Task<int> CountAsync();
/// <summary>
/// Returns the SQL alias currently used for the specified index type.
/// </summary>
string GetTypeAlias(Type t);
}
/// <summary>
/// Represents a query over an index, which can be ordered.
/// </summary>
/// <typeparam name="T">The index's type to query over.</typeparam>
public interface IQueryIndex<T> where T : IIndex
{
/// <summary>
/// Joins the document table with an index.
/// </summary>
IQueryIndex<TIndex> With<TIndex>() where TIndex : class, IIndex;
/// <summary>
/// Joins the document table with an index, and filter it with a predicate.
/// </summary>
IQueryIndex<TIndex> With<TIndex>(Expression<Func<TIndex, bool>> predicate) where TIndex : class, IIndex;
/// <summary>
/// Adds a custom Where clause to the query.
/// </summary>
IQueryIndex<T> Where(string sql);
/// <summary>
/// Adds a custom Where clause to the query using a specific dialect.
/// </summary>
IQueryIndex<T> Where(Func<ISqlDialect, string> sql);
/// <summary>
/// Adds a named parameter to the query.
/// </summary>
IQueryIndex<T> WithParameter(string name, object value);
/// <summary>
/// Adds a named parameter to the query.
/// </summary>
IQueryIndex<T> Where(Expression<Func<T, bool>> predicate);
/// <summary>
/// Sets an OrderBy clause using a custom lambda expression.
/// </summary>
IQueryIndex<T> OrderBy(Expression<Func<T, object>> keySelector);
/// <summary>
/// Sets a descending OrderBy clause using a custom lambda expression.
/// </summary>
IQueryIndex<T> OrderByDescending(Expression<Func<T, object>> keySelector);
/// <summary>
/// Adds an OrderBy clause using a custom lambda expression.
/// </summary>
IQueryIndex<T> ThenBy(Expression<Func<T, object>> keySelector);
/// <summary>
/// Adds a descending OrderBy clause using a custom lambda expression.
/// </summary>
IQueryIndex<T> ThenByDescending(Expression<Func<T, object>> keySelector);
/// <summary>
/// Skips some results.
/// </summary>
IQueryIndex<T> Skip(int count);
/// <summary>
/// Limits the number of results.
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
IQueryIndex<T> Take(int count);
/// <summary>
/// Returns the first result only, if it exists.
/// </summary>
Task<T> FirstOrDefaultAsync();
/// <summary>
/// Executes the query.
/// </summary>
Task<IEnumerable<T>> ListAsync();
/// <summary>
/// Executes the query for asynchronous iteration.
/// </summary>
/// <returns></returns>
IAsyncEnumerable<T> ToAsyncEnumerable();
/// <summary>
/// Returns the number of results only.
/// </summary>
Task<int> CountAsync();
}
/// <summary>
/// Represents a query over an index that targets a specific entity.
/// </summary>
/// <typeparam name="T">The entity's type to return.</typeparam>
/// <typeparam name="TIndex">The index's type to query over.</typeparam>
public interface IQuery<T, TIndex> : IQuery<T>
where T : class
where TIndex : IIndex
{
/// <summary>
/// Adds a custom Where clause to the query.
/// </summary>
IQuery<T, TIndex> Where(string sql);
/// <summary>
/// Adds a custom Where clause to the query using a specific dialect.
/// </summary>
IQuery<T, TIndex> Where(Func<ISqlDialect, string> sql);
/// <summary>
/// Adds a named parameter to the query.
/// </summary>
IQuery<T, TIndex> WithParameter(string name, object value);
/// <summary>
/// Adds a named parameter to the query.
/// </summary>
IQuery<T, TIndex> Where(Expression<Func<TIndex, bool>> predicate);
/// <summary>
/// Sets an OrderBy clause using a custom lambda expression.
/// </summary>
IQuery<T, TIndex> OrderBy(Expression<Func<TIndex, object>> keySelector);
/// <summary>
/// Sets an OrderBy clause using a custom SQL statement.
/// </summary>
IQuery<T, TIndex> OrderBy(string sql);
IQuery<T, TIndex> OrderByDescending(Expression<Func<TIndex, object>> keySelector);
/// <summary>
/// Sets a descending OrderBy clause using a custom SQL statement.
/// </summary>
IQuery<T, TIndex> OrderByDescending(string sql);
/// <summary>
/// Sets a random OrderBy clause.
/// </summary>
IQuery<T, TIndex> OrderByRandom();
/// <summary>
/// Adds an OrderBy clause using a custom lambda expression.
/// </summary>
IQuery<T, TIndex> ThenBy(Expression<Func<TIndex, object>> keySelector);
/// <summary>
/// Adds an OrderBy clause using a custom SQL statement.
/// </summary>
IQuery<T, TIndex> ThenBy(string sql);
/// <summary>
/// Adds a descending OrderBy clause using a custom lambda expression.
/// </summary>
IQuery<T, TIndex> ThenByDescending(Expression<Func<TIndex, object>> keySelector);
/// <summary>
/// Adds a descending OrderBy clause using a custom SQL statement.
/// </summary>
IQuery<T, TIndex> ThenByDescending(string sql);
/// <summary>
/// Adds a random OrderBy clause.
/// </summary>
IQuery<T, TIndex> ThenByRandom();
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: CircList
// ObjectType: CircList
// CSLAType: ReadOnlyCollection
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
namespace DocStore.Business.Circulations
{
/// <summary>
/// Collection of circulations of documents and folders (read only list).<br/>
/// This is a generated <see cref="CircList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="CircInfo"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class CircList : ReadOnlyBindingListBase<CircList, CircInfo>
#else
public partial class CircList : ReadOnlyListBase<CircList, CircInfo>
#endif
{
#region Collection Business Methods
/// <summary>
/// Determines whether a <see cref="CircInfo"/> item is in the collection.
/// </summary>
/// <param name="circID">The CircID of the item to search for.</param>
/// <returns><c>true</c> if the CircInfo is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int circID)
{
foreach (var circInfo in this)
{
if (circInfo.CircID == circID)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="CircList"/> collection, based on given parameters.
/// </summary>
/// <param name="docID">The DocID parameter of the CircList to fetch.</param>
/// <param name="folderID">The FolderID parameter of the CircList to fetch.</param>
/// <returns>A reference to the fetched <see cref="CircList"/> collection.</returns>
public static CircList GetCircList(int? docID, int? folderID)
{
return DataPortal.Fetch<CircList>(new CriteriaGetByObject(docID, folderID));
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="CircList"/> collection, based on given parameters.
/// </summary>
/// <param name="docID">The DocID parameter of the CircList to fetch.</param>
/// <param name="folderID">The FolderID parameter of the CircList to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetCircList(int? docID, int? folderID, EventHandler<DataPortalResult<CircList>> callback)
{
DataPortal.BeginFetch<CircList>(new CriteriaGetByObject(docID, folderID), callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="CircList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public CircList()
{
// Use factory methods and do not use direct creation.
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Nested Criteria
/// <summary>
/// CriteriaGetByObject criteria.
/// </summary>
[Serializable]
protected class CriteriaGetByObject : CriteriaBase<CriteriaGetByObject>
{
/// <summary>
/// Maintains metadata about <see cref="DocID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> DocIDProperty = RegisterProperty<int?>(p => p.DocID);
/// <summary>
/// Gets or sets the Doc ID.
/// </summary>
/// <value>The Doc ID.</value>
public int? DocID
{
get { return ReadProperty(DocIDProperty); }
set { LoadProperty(DocIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="FolderID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> FolderIDProperty = RegisterProperty<int?>(p => p.FolderID);
/// <summary>
/// Gets or sets the Folder ID.
/// </summary>
/// <value>The Folder ID.</value>
public int? FolderID
{
get { return ReadProperty(FolderIDProperty); }
set { LoadProperty(FolderIDProperty, value); }
}
/// <summary>
/// Initializes a new instance of the <see cref="CriteriaGetByObject"/> class.
/// </summary>
/// <remarks> A parameterless constructor is required by the MobileFormatter.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public CriteriaGetByObject()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CriteriaGetByObject"/> class.
/// </summary>
/// <param name="docID">The DocID.</param>
/// <param name="folderID">The FolderID.</param>
public CriteriaGetByObject(int? docID, int? folderID)
{
DocID = docID;
FolderID = folderID;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is CriteriaGetByObject)
{
var c = (CriteriaGetByObject) obj;
if (!DocID.Equals(c.DocID))
return false;
if (!FolderID.Equals(c.FolderID))
return false;
return true;
}
return false;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return string.Concat("CriteriaGetByObject", DocID.ToString(), FolderID.ToString()).GetHashCode();
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="CircList"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="crit">The fetch criteria.</param>
protected void DataPortal_Fetch(CriteriaGetByObject crit)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetCircList", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocID", crit.DocID == null ? (object)DBNull.Value : crit.DocID.Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@FolderID", crit.FolderID == null ? (object)DBNull.Value : crit.FolderID.Value).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, crit);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="CircList"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(CircInfo.GetCircInfo(dr));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*****************************************************************************************************
Rules for Multiple Nested Parent, enforce following constraints
1) At all times, only 1(ONE) FK can be NON-Null in a row.
2) NULL FK values are not associated with PARENT(x), even if PK is NULL in Parent
3) Enforce <rule 1> when
a) Any FK value is changed
b) A relation created that result in Multiple Nested Child
WriteXml
1) WriteXml will throw if <rule 1> is violated
2) if NON-Null FK has parentRow (boolean check) print as Nested, else it will get written as normal row
additional notes:
We decided to enforce the rule 1 just if Xml being persisted
******************************************************************************************************/
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Data.Common;
using System.Collections.Generic;
using System.Threading;
namespace System.Data
{
[DefaultProperty(nameof(RelationName))]
[TypeConverter(typeof(RelationshipConverter))]
public class DataRelation
{
// properties
private DataSet _dataSet = null;
internal PropertyCollection _extendedProperties = null;
internal string _relationName = string.Empty;
// state
private DataKey _childKey;
private DataKey _parentKey;
private UniqueConstraint _parentKeyConstraint = null;
private ForeignKeyConstraint _childKeyConstraint = null;
// Design time serialization
internal string[] _parentColumnNames = null;
internal string[] _childColumnNames = null;
internal string _parentTableName = null;
internal string _childTableName = null;
internal string _parentTableNamespace = null;
internal string _childTableNamespace = null;
/// <summary>
/// This stores whether the child element appears beneath the parent in the XML persisted files.
/// </summary>
internal bool _nested = false;
/// <summary>
/// This stores whether the relationship should make sure that KeyConstraints and ForeignKeyConstraints
/// exist when added to the ConstraintsCollections of the table.
/// </summary>
internal bool _createConstraints;
private bool _checkMultipleNested = true;
private static int s_objectTypeCount; // Bid counter
private readonly int _objectID = Interlocked.Increment(ref s_objectTypeCount);
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name,
/// parent, and child columns.
/// </summary>
public DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn) :
this(relationName, parentColumn, childColumn, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name, parent, and child columns, and
/// value to create constraints.
/// </summary>
public DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints)
{
DataCommonEventSource.Log.Trace("<ds.DataRelation.DataRelation|API> {0}, relationName='{1}', parentColumn={2}, childColumn={3}, createConstraints={4}",
ObjectID, relationName, (parentColumn != null) ? parentColumn.ObjectID : 0, (childColumn != null) ? childColumn.ObjectID : 0,
createConstraints);
DataColumn[] parentColumns = new DataColumn[1];
parentColumns[0] = parentColumn;
DataColumn[] childColumns = new DataColumn[1];
childColumns[0] = childColumn;
Create(relationName, parentColumns, childColumns, createConstraints);
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name
/// and matched arrays of parent and child columns.
/// </summary>
public DataRelation(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns) :
this(relationName, parentColumns, childColumns, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name, matched arrays of parent
/// and child columns, and value to create constraints.
/// </summary>
public DataRelation(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints)
{
Create(relationName, parentColumns, childColumns, createConstraints);
}
[Browsable(false)] // design-time ctor
public DataRelation(string relationName, string parentTableName, string childTableName, string[] parentColumnNames, string[] childColumnNames, bool nested)
{
_relationName = relationName;
_parentColumnNames = parentColumnNames;
_childColumnNames = childColumnNames;
_parentTableName = parentTableName;
_childTableName = childTableName;
_nested = nested;
}
[Browsable(false)] // design-time ctor
public DataRelation(string relationName, string parentTableName, string parentTableNamespace, string childTableName, string childTableNamespace, string[] parentColumnNames, string[] childColumnNames, bool nested)
{
_relationName = relationName;
_parentColumnNames = parentColumnNames;
_childColumnNames = childColumnNames;
_parentTableName = parentTableName;
_childTableName = childTableName;
_parentTableNamespace = parentTableNamespace;
_childTableNamespace = childTableNamespace;
_nested = nested;
}
/// <summary>
/// Gets the child columns of this relation.
/// </summary>
public virtual DataColumn[] ChildColumns
{
get
{
CheckStateForProperty();
return _childKey.ToArray();
}
}
internal DataColumn[] ChildColumnsReference
{
get
{
CheckStateForProperty();
return _childKey.ColumnsReference;
}
}
/// <summary>
/// The internal Key object for the child table.
/// </summary>
internal DataKey ChildKey
{
get
{
CheckStateForProperty();
return _childKey;
}
}
/// <summary>
/// Gets the child table of this relation.
/// </summary>
public virtual DataTable ChildTable
{
get
{
CheckStateForProperty();
return _childKey.Table;
}
}
/// <summary>
/// Gets the <see cref='System.Data.DataSet'/> to which the relations' collection belongs to.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public virtual DataSet DataSet
{
get
{
CheckStateForProperty();
return _dataSet;
}
}
internal string[] ParentColumnNames => _parentKey.GetColumnNames();
internal string[] ChildColumnNames => _childKey.GetColumnNames();
private static bool IsKeyNull(object[] values)
{
for (int i = 0; i < values.Length; i++)
{
if (!DataStorage.IsObjectNull(values[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the child rows for the parent row across the relation using the version given
/// </summary>
internal static DataRow[] GetChildRows(DataKey parentKey, DataKey childKey, DataRow parentRow, DataRowVersion version)
{
object[] values = parentRow.GetKeyValues(parentKey, version);
if (IsKeyNull(values))
{
return childKey.Table.NewRowArray(0);
}
Index index = childKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
return index.GetRows(values);
}
/// <summary>
/// Gets the parent rows for the given child row across the relation using the version given
/// </summary>
internal static DataRow[] GetParentRows(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version)
{
object[] values = childRow.GetKeyValues(childKey, version);
if (IsKeyNull(values))
{
return parentKey.Table.NewRowArray(0);
}
Index index = parentKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
return index.GetRows(values);
}
internal static DataRow GetParentRow(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version)
{
if (!childRow.HasVersion((version == DataRowVersion.Original) ? DataRowVersion.Original : DataRowVersion.Current))
{
if (childRow._tempRecord == -1)
{
return null;
}
}
object[] values = childRow.GetKeyValues(childKey, version);
if (IsKeyNull(values))
{
return null;
}
Index index = parentKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
Range range = index.FindRecords(values);
if (range.IsNull)
{
return null;
}
if (range.Count > 1)
{
throw ExceptionBuilder.MultipleParents();
}
return parentKey.Table._recordManager[index.GetRecord(range.Min)];
}
/// <summary>
/// Internally sets the DataSet pointer.
/// </summary>
internal void SetDataSet(DataSet dataSet)
{
if (_dataSet != dataSet)
{
_dataSet = dataSet;
}
}
internal void SetParentRowRecords(DataRow childRow, DataRow parentRow)
{
object[] parentKeyValues = parentRow.GetKeyValues(ParentKey);
if (childRow._tempRecord != -1)
{
ChildTable._recordManager.SetKeyValues(childRow._tempRecord, ChildKey, parentKeyValues);
}
if (childRow._newRecord != -1)
{
ChildTable._recordManager.SetKeyValues(childRow._newRecord, ChildKey, parentKeyValues);
}
if (childRow._oldRecord != -1)
{
ChildTable._recordManager.SetKeyValues(childRow._oldRecord, ChildKey, parentKeyValues);
}
}
/// <summary>
/// Gets the parent columns of this relation.
/// </summary>
public virtual DataColumn[] ParentColumns
{
get
{
CheckStateForProperty();
return _parentKey.ToArray();
}
}
internal DataColumn[] ParentColumnsReference => _parentKey.ColumnsReference;
/// <summary>
/// The internal constraint object for the parent table.
/// </summary>
internal DataKey ParentKey
{
get
{
CheckStateForProperty();
return _parentKey;
}
}
/// <summary>
/// Gets the parent table of this relation.
/// </summary>
public virtual DataTable ParentTable
{
get
{
CheckStateForProperty();
return _parentKey.Table;
}
}
/// <summary>
/// Gets or sets the name used to look up this relation in the parent
/// data set's <see cref='System.Data.DataRelationCollection'/>.
/// </summary>
[DefaultValue("")]
public virtual string RelationName
{
get
{
CheckStateForProperty();
return _relationName;
}
set
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRelation.set_RelationName|API> {0}, '{1}'", ObjectID, value);
try
{
if (value == null)
{
value = string.Empty;
}
CultureInfo locale = (_dataSet != null ? _dataSet.Locale : CultureInfo.CurrentCulture);
if (string.Compare(_relationName, value, true, locale) != 0)
{
if (_dataSet != null)
{
if (value.Length == 0)
{
throw ExceptionBuilder.NoRelationName();
}
_dataSet.Relations.RegisterName(value);
if (_relationName.Length != 0)
{
_dataSet.Relations.UnregisterName(_relationName);
}
}
_relationName = value;
((DataRelationCollection.DataTableRelationCollection)(ParentTable.ChildRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
((DataRelationCollection.DataTableRelationCollection)(ChildTable.ParentRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
}
else if (string.Compare(_relationName, value, false, locale) != 0)
{
_relationName = value;
((DataRelationCollection.DataTableRelationCollection)(ParentTable.ChildRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
((DataRelationCollection.DataTableRelationCollection)(ChildTable.ParentRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
}
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
}
internal void CheckNamespaceValidityForNestedRelations(string ns)
{
foreach (DataRelation rel in ChildTable.ParentRelations)
{
if (rel == this || rel.Nested)
{
if (rel.ParentTable.Namespace != ns)
{
throw ExceptionBuilder.InValidNestedRelation(ChildTable.TableName);
}
}
}
}
internal void CheckNestedRelations()
{
DataCommonEventSource.Log.Trace("<ds.DataRelation.CheckNestedRelations|INFO> {0}", ObjectID);
Debug.Assert(DataSet == null || !_nested, "this relation supposed to be not in dataset or not nested");
// 1. There is no other relation (R) that has this.ChildTable as R.ChildTable
// This is not valid for Whidbey anymore so the code has been removed
// 2. There is no loop in nested relations
if (ChildTable == ParentTable)
{
if (string.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0)
throw ExceptionBuilder.SelfnestedDatasetConflictingName(ChildTable.TableName);
return; //allow self join tables.
}
List<DataTable> list = new List<DataTable>();
list.Add(ChildTable);
// We have already checked for nested relaion UP
for (int i = 0; i < list.Count; ++i)
{
DataRelation[] relations = list[i].NestedParentRelations;
foreach (DataRelation rel in relations)
{
if (rel.ParentTable == ChildTable && rel.ChildTable != ChildTable)
{
throw ExceptionBuilder.LoopInNestedRelations(ChildTable.TableName);
}
if (!list.Contains(rel.ParentTable))
{
// check for self nested
list.Add(rel.ParentTable);
}
}
}
}
/********************
The Namespace of a table nested inside multiple parents can be
1. Explicitly specified
2. Inherited from Parent Table
3. Empty (Form = unqualified case)
However, Schema does not allow (3) to be a global element and multiple nested child has to be a global element.
Therefore we'll reduce case (3) to (2) if all parents have same namespace else throw.
********************/
/// <summary>
/// Gets or sets a value indicating whether relations are nested.
/// </summary>
[DefaultValue(false)]
public virtual bool Nested
{
get
{
CheckStateForProperty();
return _nested;
}
set
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRelation.set_Nested|API> {0}, {1}", ObjectID, value);
try
{
if (_nested != value)
{
if (_dataSet != null)
{
if (value)
{
if (ChildTable.IsNamespaceInherited())
{ // if not added to collection, don't do this check
CheckNamespaceValidityForNestedRelations(ParentTable.Namespace);
}
Debug.Assert(ChildTable != null, "On a DataSet, but not on Table. Bad state");
ForeignKeyConstraint constraint = ChildTable.Constraints.FindForeignKeyConstraint(ChildKey.ColumnsReference, ParentKey.ColumnsReference);
if (constraint != null)
{
constraint.CheckConstraint();
}
ValidateMultipleNestedRelations();
}
}
if (!value && (_parentKey.ColumnsReference[0].ColumnMapping == MappingType.Hidden))
{
throw ExceptionBuilder.RelationNestedReadOnly();
}
if (value)
{
ParentTable.Columns.RegisterColumnName(ChildTable.TableName, null);
}
else
{
ParentTable.Columns.UnregisterName(ChildTable.TableName);
}
RaisePropertyChanging(nameof(Nested));
if (value)
{
CheckNestedRelations();
if (DataSet != null)
if (ParentTable == ChildTable)
{
foreach (DataRow row in ChildTable.Rows)
{
row.CheckForLoops(this);
}
if (ChildTable.DataSet != null && (string.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0))
{
throw ExceptionBuilder.DatasetConflictingName(_dataSet.DataSetName);
}
ChildTable._fNestedInDataset = false;
}
else
{
foreach (DataRow row in ChildTable.Rows)
{
row.GetParentRow(this);
}
}
ParentTable.ElementColumnCount++;
}
else
{
ParentTable.ElementColumnCount--;
}
_nested = value;
ChildTable.CacheNestedParent();
if (value)
{
if (string.IsNullOrEmpty(ChildTable.Namespace) && ((ChildTable.NestedParentsCount > 1) ||
((ChildTable.NestedParentsCount > 0) && !(ChildTable.DataSet.Relations.Contains(RelationName)))))
{
string parentNs = null;
foreach (DataRelation rel in ChildTable.ParentRelations)
{
if (rel.Nested)
{
if (null == parentNs)
{
parentNs = rel.ParentTable.Namespace;
}
else
{
if (!string.Equals(parentNs, rel.ParentTable.Namespace, StringComparison.Ordinal))
{
_nested = false;
throw ExceptionBuilder.InvalidParentNamespaceinNestedRelation(ChildTable.TableName);
}
}
}
}
// if not already in memory , form == unqualified
if (CheckMultipleNested && ChildTable._tableNamespace != null && ChildTable._tableNamespace.Length == 0)
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
ChildTable._tableNamespace = null; // if we dont throw, then let it inherit the Namespace
}
}
}
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
}
/// <summary>
/// Gets the constraint which ensures values in a column are unique.
/// </summary>
public virtual UniqueConstraint ParentKeyConstraint
{
get
{
CheckStateForProperty();
return _parentKeyConstraint;
}
}
internal void SetParentKeyConstraint(UniqueConstraint value)
{
Debug.Assert(_parentKeyConstraint == null || value == null, "ParentKeyConstraint should not have been set already.");
_parentKeyConstraint = value;
}
/// <summary>
/// Gets the <see cref='System.Data.ForeignKeyConstraint'/> for the relation.
/// </summary>
public virtual ForeignKeyConstraint ChildKeyConstraint
{
get
{
CheckStateForProperty();
return _childKeyConstraint;
}
}
/// <summary>
/// Gets the collection of custom user information.
/// </summary>
[Browsable(false)]
public PropertyCollection ExtendedProperties => _extendedProperties ?? (_extendedProperties = new PropertyCollection());
internal bool CheckMultipleNested
{
get { return _checkMultipleNested; }
set { _checkMultipleNested = value; }
}
internal void SetChildKeyConstraint(ForeignKeyConstraint value)
{
Debug.Assert(_childKeyConstraint == null || value == null, "ChildKeyConstraint should not have been set already.");
_childKeyConstraint = value;
}
internal event PropertyChangedEventHandler PropertyChanging;
// If we're not in a dataSet relations collection, we need to verify on every property get that we're
// still a good relation object.
internal void CheckState()
{
if (_dataSet == null)
{
_parentKey.CheckState();
_childKey.CheckState();
if (_parentKey.Table.DataSet != _childKey.Table.DataSet)
{
throw ExceptionBuilder.RelationDataSetMismatch();
}
if (_childKey.ColumnsEqual(_parentKey))
{
throw ExceptionBuilder.KeyColumnsIdentical();
}
for (int i = 0; i < _parentKey.ColumnsReference.Length; i++)
{
if ((_parentKey.ColumnsReference[i].DataType != _childKey.ColumnsReference[i].DataType) ||
((_parentKey.ColumnsReference[i].DataType == typeof(DateTime)) &&
(_parentKey.ColumnsReference[i].DateTimeMode != _childKey.ColumnsReference[i].DateTimeMode) &&
((_parentKey.ColumnsReference[i].DateTimeMode & _childKey.ColumnsReference[i].DateTimeMode) != DataSetDateTime.Unspecified)))
{
// allow unspecified and unspecifiedlocal
throw ExceptionBuilder.ColumnsTypeMismatch();
}
}
}
}
/// <summary>
/// Checks to ensure the DataRelation is a valid object, even if it doesn't
/// belong to a <see cref='System.Data.DataSet'/>.
/// </summary>
protected void CheckStateForProperty()
{
try
{
CheckState();
}
catch (Exception e) when (ADP.IsCatchableExceptionType(e))
{
throw ExceptionBuilder.BadObjectPropertyAccess(e.Message);
}
}
private void Create(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRelation.Create|INFO> {0}, relationName='{1}', createConstraints={2}", ObjectID, relationName, createConstraints);
try
{
_parentKey = new DataKey(parentColumns, true);
_childKey = new DataKey(childColumns, true);
if (parentColumns.Length != childColumns.Length)
{
throw ExceptionBuilder.KeyLengthMismatch();
}
for (int i = 0; i < parentColumns.Length; i++)
{
if ((parentColumns[i].Table.DataSet == null) || (childColumns[i].Table.DataSet == null))
{
throw ExceptionBuilder.ParentOrChildColumnsDoNotHaveDataSet();
}
}
CheckState();
_relationName = (relationName == null ? "" : relationName);
_createConstraints = createConstraints;
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
internal DataRelation Clone(DataSet destination)
{
DataCommonEventSource.Log.Trace("<ds.DataRelation.Clone|INFO> {0}, destination={1}", ObjectID, (destination != null) ? destination.ObjectID : 0);
DataTable parent = destination.Tables[ParentTable.TableName, ParentTable.Namespace];
DataTable child = destination.Tables[ChildTable.TableName, ChildTable.Namespace];
int keyLength = _parentKey.ColumnsReference.Length;
DataColumn[] parentColumns = new DataColumn[keyLength];
DataColumn[] childColumns = new DataColumn[keyLength];
for (int i = 0; i < keyLength; i++)
{
parentColumns[i] = parent.Columns[ParentKey.ColumnsReference[i].ColumnName];
childColumns[i] = child.Columns[ChildKey.ColumnsReference[i].ColumnName];
}
DataRelation clone = new DataRelation(_relationName, parentColumns, childColumns, false);
clone.CheckMultipleNested = false; // disable the check in clone as it is already created
clone.Nested = Nested;
clone.CheckMultipleNested = true; // enable the check
// ...Extended Properties
if (_extendedProperties != null)
{
foreach (object key in _extendedProperties.Keys)
{
clone.ExtendedProperties[key] = _extendedProperties[key];
}
}
return clone;
}
protected internal void OnPropertyChanging(PropertyChangedEventArgs pcevent)
{
if (PropertyChanging != null)
{
DataCommonEventSource.Log.Trace("<ds.DataRelation.OnPropertyChanging|INFO> {0}", ObjectID);
PropertyChanging(this, pcevent);
}
}
protected internal void RaisePropertyChanging(string name)
{
OnPropertyChanging(new PropertyChangedEventArgs(name));
}
/// <summary>
/// </summary>
public override string ToString() => RelationName;
internal void ValidateMultipleNestedRelations()
{
// find all nested relations that this child table has
// if this relation is the only relation it has, then fine,
// otherwise check if all relations are created from XSD, without using Key/KeyRef
// check all keys to see autogenerated
if (!Nested || !CheckMultipleNested) // no need for this verification
{
return;
}
if (0 < ChildTable.NestedParentRelations.Length)
{
DataColumn[] childCols = ChildColumns;
if (childCols.Length != 1 || !IsAutoGenerated(childCols[0]))
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
if (!XmlTreeGen.AutoGenerated(this))
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
foreach (Constraint cs in ChildTable.Constraints)
{
if (cs is ForeignKeyConstraint)
{
ForeignKeyConstraint fk = (ForeignKeyConstraint)cs;
if (!XmlTreeGen.AutoGenerated(fk, true))
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
}
else
{
UniqueConstraint unique = (UniqueConstraint)cs;
if (!XmlTreeGen.AutoGenerated(unique))
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
}
}
}
}
private bool IsAutoGenerated(DataColumn col)
{
if (col.ColumnMapping != MappingType.Hidden)
{
return false;
}
if (col.DataType != typeof(int))
{
return false;
}
string generatedname = col.Table.TableName + "_Id";
if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0"))
{
return true;
}
generatedname = ParentColumnsReference[0].Table.TableName + "_Id";
if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0"))
{
return true;
}
return false;
}
internal int ObjectID => _objectID;
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using System;
using System.Collections.Generic;
using System.Linq;
using Parse.Core.Internal;
using Parse.Common.Internal;
namespace Parse {
/// <summary>
/// A ParseACL is used to control which users and roles can access or modify a particular object. Each
/// <see cref="ParseObject"/> can have its own ParseACL. You can grant read and write permissions
/// separately to specific users, to groups of users that belong to roles, or you can grant permissions
/// to "the public" so that, for example, any user could read a particular object but only a particular
/// set of users could write to that object.
/// </summary>
public class ParseACL : IJsonConvertible {
private enum AccessKind {
Read,
Write
}
private const string publicName = "*";
private readonly ICollection<string> readers = new HashSet<string>();
private readonly ICollection<string> writers = new HashSet<string>();
internal ParseACL(IDictionary<string, object> jsonObject) {
readers = new HashSet<string>(from pair in jsonObject
where ((IDictionary<string, object>)pair.Value).ContainsKey("read")
select pair.Key);
writers = new HashSet<string>(from pair in jsonObject
where ((IDictionary<string, object>)pair.Value).ContainsKey("write")
select pair.Key);
}
/// <summary>
/// Creates an ACL with no permissions granted.
/// </summary>
public ParseACL() {
}
/// <summary>
/// Creates an ACL where only the provided user has access.
/// </summary>
/// <param name="owner">The only user that can read or write objects governed by this ACL.</param>
public ParseACL(ParseUser owner) {
SetReadAccess(owner, true);
SetWriteAccess(owner, true);
}
IDictionary<string, object> IJsonConvertible.ToJSON() {
var result = new Dictionary<string, object>();
foreach (var user in readers.Union(writers)) {
var userPermissions = new Dictionary<string, object>();
if (readers.Contains(user)) {
userPermissions["read"] = true;
}
if (writers.Contains(user)) {
userPermissions["write"] = true;
}
result[user] = userPermissions;
}
return result;
}
private void SetAccess(AccessKind kind, string userId, bool allowed) {
if (userId == null) {
throw new ArgumentException("Cannot set access for an unsaved user or role.");
}
ICollection<string> target = null;
switch (kind) {
case AccessKind.Read:
target = readers;
break;
case AccessKind.Write:
target = writers;
break;
default:
throw new NotImplementedException("Unknown AccessKind");
}
if (allowed) {
target.Add(userId);
} else {
target.Remove(userId);
}
}
private bool GetAccess(AccessKind kind, string userId) {
if (userId == null) {
throw new ArgumentException("Cannot get access for an unsaved user or role.");
}
switch (kind) {
case AccessKind.Read:
return readers.Contains(userId);
case AccessKind.Write:
return writers.Contains(userId);
default:
throw new NotImplementedException("Unknown AccessKind");
}
}
/// <summary>
/// Gets or sets whether the public is allowed to read this object.
/// </summary>
public bool PublicReadAccess {
get {
return GetAccess(AccessKind.Read, publicName);
}
set {
SetAccess(AccessKind.Read, publicName, value);
}
}
/// <summary>
/// Gets or sets whether the public is allowed to write this object.
/// </summary>
public bool PublicWriteAccess {
get {
return GetAccess(AccessKind.Write, publicName);
}
set {
SetAccess(AccessKind.Write, publicName, value);
}
}
/// <summary>
/// Sets whether the given user id is allowed to read this object.
/// </summary>
/// <param name="userId">The objectId of the user.</param>
/// <param name="allowed">Whether the user has permission.</param>
public void SetReadAccess(string userId, bool allowed) {
SetAccess(AccessKind.Read, userId, allowed);
}
/// <summary>
/// Sets whether the given user is allowed to read this object.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="allowed">Whether the user has permission.</param>
public void SetReadAccess(ParseUser user, bool allowed) {
SetReadAccess(user.ObjectId, allowed);
}
/// <summary>
/// Sets whether the given user id is allowed to write this object.
/// </summary>
/// <param name="userId">The objectId of the user.</param>
/// <param name="allowed">Whether the user has permission.</param>
public void SetWriteAccess(string userId, bool allowed) {
SetAccess(AccessKind.Write, userId, allowed);
}
/// <summary>
/// Sets whether the given user is allowed to write this object.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="allowed">Whether the user has permission.</param>
public void SetWriteAccess(ParseUser user, bool allowed) {
SetWriteAccess(user.ObjectId, allowed);
}
/// <summary>
/// Gets whether the given user id is *explicitly* allowed to read this object.
/// Even if this returns false, the user may still be able to read it if
/// PublicReadAccess is true or a role that the user belongs to has read access.
/// </summary>
/// <param name="userId">The user objectId to check.</param>
/// <returns>Whether the user has access.</returns>
public bool GetReadAccess(string userId) {
return GetAccess(AccessKind.Read, userId);
}
/// <summary>
/// Gets whether the given user is *explicitly* allowed to read this object.
/// Even if this returns false, the user may still be able to read it if
/// PublicReadAccess is true or a role that the user belongs to has read access.
/// </summary>
/// <param name="user">The user to check.</param>
/// <returns>Whether the user has access.</returns>
public bool GetReadAccess(ParseUser user) {
return GetReadAccess(user.ObjectId);
}
/// <summary>
/// Gets whether the given user id is *explicitly* allowed to write this object.
/// Even if this returns false, the user may still be able to write it if
/// PublicReadAccess is true or a role that the user belongs to has write access.
/// </summary>
/// <param name="userId">The user objectId to check.</param>
/// <returns>Whether the user has access.</returns>
public bool GetWriteAccess(string userId) {
return GetAccess(AccessKind.Write, userId);
}
/// <summary>
/// Gets whether the given user is *explicitly* allowed to write this object.
/// Even if this returns false, the user may still be able to write it if
/// PublicReadAccess is true or a role that the user belongs to has write access.
/// </summary>
/// <param name="user">The user to check.</param>
/// <returns>Whether the user has access.</returns>
public bool GetWriteAccess(ParseUser user) {
return GetWriteAccess(user.ObjectId);
}
/// <summary>
/// Sets whether users belonging to the role with the given <paramref name="roleName"/>
/// are allowed to read this object.
/// </summary>
/// <param name="roleName">The name of the role.</param>
/// <param name="allowed">Whether the role has access.</param>
public void SetRoleReadAccess(string roleName, bool allowed) {
SetAccess(AccessKind.Read, "role:" + roleName, allowed);
}
/// <summary>
/// Sets whether users belonging to the given role are allowed to read this object.
/// </summary>
/// <param name="role">The role.</param>
/// <param name="allowed">Whether the role has access.</param>
public void SetRoleReadAccess(ParseRole role, bool allowed) {
SetRoleReadAccess(role.Name, allowed);
}
/// <summary>
/// Gets whether users belonging to the role with the given <paramref name="roleName"/>
/// are allowed to read this object. Even if this returns false, the role may still be
/// able to read it if a parent role has read access.
/// </summary>
/// <param name="roleName">The name of the role.</param>
/// <returns>Whether the role has access.</returns>
public bool GetRoleReadAccess(string roleName) {
return GetAccess(AccessKind.Read, "role:" + roleName);
}
/// <summary>
/// Gets whether users belonging to the role are allowed to read this object.
/// Even if this returns false, the role may still be able to read it if a
/// parent role has read access.
/// </summary>
/// <param name="role">The name of the role.</param>
/// <returns>Whether the role has access.</returns>
public bool GetRoleReadAccess(ParseRole role) {
return GetRoleReadAccess(role.Name);
}
/// <summary>
/// Sets whether users belonging to the role with the given <paramref name="roleName"/>
/// are allowed to write this object.
/// </summary>
/// <param name="roleName">The name of the role.</param>
/// <param name="allowed">Whether the role has access.</param>
public void SetRoleWriteAccess(string roleName, bool allowed) {
SetAccess(AccessKind.Write, "role:" + roleName, allowed);
}
/// <summary>
/// Sets whether users belonging to the given role are allowed to write this object.
/// </summary>
/// <param name="role">The role.</param>
/// <param name="allowed">Whether the role has access.</param>
public void SetRoleWriteAccess(ParseRole role, bool allowed) {
SetRoleWriteAccess(role.Name, allowed);
}
/// <summary>
/// Gets whether users belonging to the role with the given <paramref name="roleName"/>
/// are allowed to write this object. Even if this returns false, the role may still be
/// able to write it if a parent role has write access.
/// </summary>
/// <param name="roleName">The name of the role.</param>
/// <returns>Whether the role has access.</returns>
public bool GetRoleWriteAccess(string roleName) {
return GetAccess(AccessKind.Write, "role:" + roleName);
}
/// <summary>
/// Gets whether users belonging to the role are allowed to write this object.
/// Even if this returns false, the role may still be able to write it if a
/// parent role has write access.
/// </summary>
/// <param name="role">The name of the role.</param>
/// <returns>Whether the role has access.</returns>
public bool GetRoleWriteAccess(ParseRole role) {
return GetRoleWriteAccess(role.Name);
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Enterprise License Manager API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/google-apps/licensing/'>Enterprise License Manager API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20170213 (774)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/google-apps/licensing/'>
* https://developers.google.com/google-apps/licensing/</a>
* <tr><th>Discovery Name<td>licensing
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Enterprise License Manager API can be found at
* <a href='https://developers.google.com/google-apps/licensing/'>https://developers.google.com/google-apps/licensing/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Licensing.v1
{
/// <summary>The Licensing Service.</summary>
public class LicensingService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public LicensingService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public LicensingService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
licenseAssignments = new LicenseAssignmentsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "licensing"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/apps/licensing/v1/product/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "apps/licensing/v1/product/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Enterprise License Manager API.</summary>
public class Scope
{
/// <summary>View and manage G Suite licenses for your domain</summary>
public static string AppsLicensing = "https://www.googleapis.com/auth/apps.licensing";
}
private readonly LicenseAssignmentsResource licenseAssignments;
/// <summary>Gets the LicenseAssignments resource.</summary>
public virtual LicenseAssignmentsResource LicenseAssignments
{
get { return licenseAssignments; }
}
}
///<summary>A base abstract class for Licensing requests.</summary>
public abstract class LicensingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new LicensingBaseServiceRequest instance.</summary>
protected LicensingBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Licensing parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "licenseAssignments" collection of methods.</summary>
public class LicenseAssignmentsResource
{
private const string Resource = "licenseAssignments";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LicenseAssignmentsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Revoke License.</summary>
/// <param name="productId">Name for product</param>
/// <param name="skuId">Name for sku</param>
/// <param
/// name="userId">email id or unique Id of the user</param>
public virtual DeleteRequest Delete(string productId, string skuId, string userId)
{
return new DeleteRequest(service, productId, skuId, userId);
}
/// <summary>Revoke License.</summary>
public class DeleteRequest : LicensingBaseServiceRequest<string>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string userId)
: base(service)
{
ProductId = productId;
SkuId = skuId;
UserId = userId;
InitParameters();
}
/// <summary>Name for product</summary>
[Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProductId { get; private set; }
/// <summary>Name for sku</summary>
[Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SkuId { get; private set; }
/// <summary>email id or unique Id of the user</summary>
[Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string UserId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{productId}/sku/{skuId}/user/{userId}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"productId", new Google.Apis.Discovery.Parameter
{
Name = "productId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"skuId", new Google.Apis.Discovery.Parameter
{
Name = "skuId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userId", new Google.Apis.Discovery.Parameter
{
Name = "userId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Get license assignment of a particular product and sku for a user</summary>
/// <param name="productId">Name for product</param>
/// <param name="skuId">Name for sku</param>
/// <param
/// name="userId">email id or unique Id of the user</param>
public virtual GetRequest Get(string productId, string skuId, string userId)
{
return new GetRequest(service, productId, skuId, userId);
}
/// <summary>Get license assignment of a particular product and sku for a user</summary>
public class GetRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string userId)
: base(service)
{
ProductId = productId;
SkuId = skuId;
UserId = userId;
InitParameters();
}
/// <summary>Name for product</summary>
[Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProductId { get; private set; }
/// <summary>Name for sku</summary>
[Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SkuId { get; private set; }
/// <summary>email id or unique Id of the user</summary>
[Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string UserId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{productId}/sku/{skuId}/user/{userId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"productId", new Google.Apis.Discovery.Parameter
{
Name = "productId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"skuId", new Google.Apis.Discovery.Parameter
{
Name = "skuId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userId", new Google.Apis.Discovery.Parameter
{
Name = "userId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Assign License.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="productId">Name for product</param>
/// <param name="skuId">Name for sku</param>
public virtual InsertRequest Insert(Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert body, string productId, string skuId)
{
return new InsertRequest(service, body, productId, skuId);
}
/// <summary>Assign License.</summary>
public class InsertRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment>
{
/// <summary>Constructs a new Insert request.</summary>
public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert body, string productId, string skuId)
: base(service)
{
ProductId = productId;
SkuId = skuId;
Body = body;
InitParameters();
}
/// <summary>Name for product</summary>
[Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProductId { get; private set; }
/// <summary>Name for sku</summary>
[Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SkuId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "insert"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{productId}/sku/{skuId}/user"; }
}
/// <summary>Initializes Insert parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"productId", new Google.Apis.Discovery.Parameter
{
Name = "productId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"skuId", new Google.Apis.Discovery.Parameter
{
Name = "skuId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>List license assignments for given product of the customer.</summary>
/// <param name="productId">Name for product</param>
/// <param name="customerId">CustomerId represents the customer
/// for whom licenseassignments are queried</param>
public virtual ListForProductRequest ListForProduct(string productId, string customerId)
{
return new ListForProductRequest(service, productId, customerId);
}
/// <summary>List license assignments for given product of the customer.</summary>
public class ListForProductRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignmentList>
{
/// <summary>Constructs a new ListForProduct request.</summary>
public ListForProductRequest(Google.Apis.Services.IClientService service, string productId, string customerId)
: base(service)
{
ProductId = productId;
CustomerId = customerId;
InitParameters();
}
/// <summary>Name for product</summary>
[Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProductId { get; private set; }
/// <summary>CustomerId represents the customer for whom licenseassignments are queried</summary>
[Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CustomerId { get; private set; }
/// <summary>Maximum number of campaigns to return at one time. Must be positive. Optional. Default value is
/// 100.</summary>
/// [default: 100]
/// [minimum: 1]
/// [maximum: 1000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<long> MaxResults { get; set; }
/// <summary>Token to fetch the next page.Optional. By default server will return first page</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "listForProduct"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{productId}/users"; }
}
/// <summary>Initializes ListForProduct parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"productId", new Google.Apis.Discovery.Parameter
{
Name = "productId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"customerId", new Google.Apis.Discovery.Parameter
{
Name = "customerId",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = "100",
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>List license assignments for given product and sku of the customer.</summary>
/// <param name="productId">Name for product</param>
/// <param name="skuId">Name for sku</param>
/// <param
/// name="customerId">CustomerId represents the customer for whom licenseassignments are queried</param>
public virtual ListForProductAndSkuRequest ListForProductAndSku(string productId, string skuId, string customerId)
{
return new ListForProductAndSkuRequest(service, productId, skuId, customerId);
}
/// <summary>List license assignments for given product and sku of the customer.</summary>
public class ListForProductAndSkuRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignmentList>
{
/// <summary>Constructs a new ListForProductAndSku request.</summary>
public ListForProductAndSkuRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string customerId)
: base(service)
{
ProductId = productId;
SkuId = skuId;
CustomerId = customerId;
InitParameters();
}
/// <summary>Name for product</summary>
[Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProductId { get; private set; }
/// <summary>Name for sku</summary>
[Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SkuId { get; private set; }
/// <summary>CustomerId represents the customer for whom licenseassignments are queried</summary>
[Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CustomerId { get; private set; }
/// <summary>Maximum number of campaigns to return at one time. Must be positive. Optional. Default value is
/// 100.</summary>
/// [default: 100]
/// [minimum: 1]
/// [maximum: 1000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<long> MaxResults { get; set; }
/// <summary>Token to fetch the next page.Optional. By default server will return first page</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "listForProductAndSku"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{productId}/sku/{skuId}/users"; }
}
/// <summary>Initializes ListForProductAndSku parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"productId", new Google.Apis.Discovery.Parameter
{
Name = "productId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"skuId", new Google.Apis.Discovery.Parameter
{
Name = "skuId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"customerId", new Google.Apis.Discovery.Parameter
{
Name = "customerId",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = "100",
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Assign License. This method supports patch semantics.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="productId">Name for product</param>
/// <param name="skuId">Name for sku for which license would be
/// revoked</param>
/// <param name="userId">email id or unique Id of the user</param>
public virtual PatchRequest Patch(Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId)
{
return new PatchRequest(service, body, productId, skuId, userId);
}
/// <summary>Assign License. This method supports patch semantics.</summary>
public class PatchRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId)
: base(service)
{
ProductId = productId;
SkuId = skuId;
UserId = userId;
Body = body;
InitParameters();
}
/// <summary>Name for product</summary>
[Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProductId { get; private set; }
/// <summary>Name for sku for which license would be revoked</summary>
[Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SkuId { get; private set; }
/// <summary>email id or unique Id of the user</summary>
[Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string UserId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Licensing.v1.Data.LicenseAssignment Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{productId}/sku/{skuId}/user/{userId}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"productId", new Google.Apis.Discovery.Parameter
{
Name = "productId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"skuId", new Google.Apis.Discovery.Parameter
{
Name = "skuId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userId", new Google.Apis.Discovery.Parameter
{
Name = "userId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Assign License.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="productId">Name for product</param>
/// <param name="skuId">Name for sku for which license would be
/// revoked</param>
/// <param name="userId">email id or unique Id of the user</param>
public virtual UpdateRequest Update(Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId)
{
return new UpdateRequest(service, body, productId, skuId, userId);
}
/// <summary>Assign License.</summary>
public class UpdateRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment>
{
/// <summary>Constructs a new Update request.</summary>
public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId)
: base(service)
{
ProductId = productId;
SkuId = skuId;
UserId = userId;
Body = body;
InitParameters();
}
/// <summary>Name for product</summary>
[Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ProductId { get; private set; }
/// <summary>Name for sku for which license would be revoked</summary>
[Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string SkuId { get; private set; }
/// <summary>email id or unique Id of the user</summary>
[Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string UserId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Licensing.v1.Data.LicenseAssignment Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "update"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PUT"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "{productId}/sku/{skuId}/user/{userId}"; }
}
/// <summary>Initializes Update parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"productId", new Google.Apis.Discovery.Parameter
{
Name = "productId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"skuId", new Google.Apis.Discovery.Parameter
{
Name = "skuId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userId", new Google.Apis.Discovery.Parameter
{
Name = "userId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Licensing.v1.Data
{
/// <summary>Template for LiscenseAssignment Resource</summary>
public class LicenseAssignment : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etags")]
public virtual string Etags { get; set; }
/// <summary>Identifies the resource as a LicenseAssignment.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Id of the product.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("productId")]
public virtual string ProductId { get; set; }
/// <summary>Display Name of the product.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("productName")]
public virtual string ProductName { get; set; }
/// <summary>Link to this page.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("selfLink")]
public virtual string SelfLink { get; set; }
/// <summary>Id of the sku of the product.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("skuId")]
public virtual string SkuId { get; set; }
/// <summary>Display Name of the sku of the product.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("skuName")]
public virtual string SkuName { get; set; }
/// <summary>Email id of the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("userId")]
public virtual string UserId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Template for LicenseAssignment Insert request</summary>
public class LicenseAssignmentInsert : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Email id of the user</summary>
[Newtonsoft.Json.JsonPropertyAttribute("userId")]
public virtual string UserId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>LicesnseAssignment List for a given product/sku for a customer.</summary>
public class LicenseAssignmentList : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The LicenseAssignments in this page of results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<LicenseAssignment> Items { get; set; }
/// <summary>Identifies the resource as a collection of LicenseAssignments.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The continuation token, used to page through large result sets. Provide this value in a subsequent
/// request to return the next page of results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Orleans.TestingHost.Utils
{
/// <summary>
/// A wrapper on Azure Storage Emulator.
/// </summary>
/// <remarks>It might be tricky to implement this as a <see cref="IDisposable">IDisposable</see>, isolated, autonomous instance,
/// see at <see href="http://azure.microsoft.com/en-us/documentation/articles/storage-use-emulator/">Use the Azure Storage Emulator for Development and Testing</see>
/// for pointers.</remarks>
public static class StorageEmulator
{
/// <summary>
/// The storage emulator process name. One way to enumerate running process names is
/// Get-Process | Format-Table Id, ProcessName -autosize. If there were multiple storage emulator
/// processes running, they would named WASTOR~1, WASTOR~2, ... WASTOR~n.
/// </summary>
private static readonly string[] storageEmulatorProcessNames = new[]
{
"AzureStorageEmulator", // newest
"Windows Azure Storage Emulator Service", // >= 2.7
"WAStorageEmulator", // < 2.7
};
//The file names aren't the same as process names.
private static readonly string[] storageEmulatorFilenames = new[]
{
"AzureStorageEmulator.exe", // >= 2.7
"WAStorageEmulator.exe", // < 2.7
};
/// <summary>
/// Is the storage emulator already started.
/// </summary>
/// <returns></returns>
public static bool IsStarted()
{
return GetStorageEmulatorProcess() != null;
}
/// <summary>
/// Checks if the storage emulator exists, i.e. is installed.
/// </summary>
public static bool Exists
{
get
{
return GetStorageEmulatorPath() != null;
}
}
/// <summary>
/// Storage Emulator help.
/// </summary>
/// <returns>Storage emulator help.</returns>
public static string Help()
{
if (!IsStarted()) return "Error happened. Has StorageEmulator.Start() been called?";
try
{
//This process handle returns immediately.
using(var process = Process.Start(CreateProcessArguments("help")))
{
process.WaitForExit();
var help = string.Empty;
while(!process.StandardOutput.EndOfStream)
{
help += process.StandardOutput.ReadLine();
}
return help;
}
}
catch (Exception exc)
{
return exc.ToString();
}
}
/// <summary>
/// Tries to start the storage emulator.
/// </summary>
/// <returns><em>TRUE</em> if the process was started successfully. <em>FALSE</em> otherwise.</returns>
public static bool TryStart()
{
if (!StorageEmulator.Exists)
return false;
return Start();
}
/// <summary>
/// Starts the storage emulator if not already started.
/// </summary>
/// <returns><em>TRUE</em> if the process was stopped successfully or was already started. <em>FALSE</em> otherwise.</returns>
public static bool Start()
{
if (IsStarted()) return true;
try
{
//This process handle returns immediately.
using(var process = Process.Start(CreateProcessArguments("start")))
{
if (process == null) return false;
process.WaitForExit();
return process.ExitCode == 0;
}
}
catch
{
return false;
}
}
/// <summary>
/// Stops the storage emulator if started.
/// </summary>
/// <returns><em>TRUE</em> if the process was stopped successfully or was already stopped. <em>FALSE</em> otherwise.</returns>
public static bool Stop()
{
if (!IsStarted()) return false;
try
{
//This process handle returns immediately.
using(var process = Process.Start(CreateProcessArguments("stop")))
{
process.WaitForExit();
return process.ExitCode == 0;
}
}
catch
{
return false;
}
}
/// <summary>
/// Creates a new <see cref="ProcessStartInfo">ProcessStartInfo</see> to be used as an argument
/// to other operations in this class.
/// </summary>
/// <param name="arguments">The arguments.</param>
/// <returns>A new <see cref="ProcessStartInfo">ProcessStartInfo</see> that has the given arguments.</returns>
private static ProcessStartInfo CreateProcessArguments(string arguments)
{
return new ProcessStartInfo(GetStorageEmulatorPath())
{
WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = true,
LoadUserProfile = true,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = arguments
};
}
/// <summary>
/// Queries the storage emulator process from the system.
/// </summary>
/// <returns></returns>
private static Process GetStorageEmulatorProcess()
{
return (storageEmulatorProcessNames
.Select(Process.GetProcessesByName)
.Where(processes => processes.Length > 0)
.Select(processes => processes[0])).FirstOrDefault();
}
/// <summary>
/// Returns a full path to the storage emulator executable, including the executable name and file extension.
/// </summary>
/// <returns>A full path to the storage emulator executable, or null if not found.</returns>
private static string GetStorageEmulatorPath()
{
//Try to take the newest known emulator path. If it does not exist, try an older one.
string exeBasePath = Path.Combine(GetProgramFilesBasePath(), @"Microsoft SDKs\Azure\Storage Emulator\");
return storageEmulatorFilenames
.Select(filename => Path.Combine(exeBasePath, filename))
.Where(File.Exists)
.FirstOrDefault();
}
/// <summary>
/// Determines the Program Files base directory.
/// </summary>
/// <returns>The Program files base directory.</returns>
private static string GetProgramFilesBasePath()
{
return Environment.Is64BitOperatingSystem ? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) : Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using OpenSim.Data;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Console;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using log4net;
namespace OpenSim.Services.UserAccountService
{
public class UserAccountService : UserAccountServiceBase, IUserAccountService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static UserAccountService m_RootInstance;
protected IGridService m_GridService;
protected IAuthenticationService m_AuthenticationService;
protected IGridUserService m_GridUserService;
protected IInventoryService m_InventoryService;
public UserAccountService(IConfigSource config)
: base(config)
{
IConfig userConfig = config.Configs["UserAccountService"];
if (userConfig == null)
throw new Exception("No UserAccountService configuration");
// In case there are several instances of this class in the same process,
// the console commands are only registered for the root instance
if (m_RootInstance == null)
{
m_RootInstance = this;
string gridServiceDll = userConfig.GetString("GridService", string.Empty);
if (gridServiceDll != string.Empty)
m_GridService = LoadPlugin<IGridService>(gridServiceDll, new Object[] { config });
string authServiceDll = userConfig.GetString("AuthenticationService", string.Empty);
if (authServiceDll != string.Empty)
m_AuthenticationService = LoadPlugin<IAuthenticationService>(authServiceDll, new Object[] { config });
string presenceServiceDll = userConfig.GetString("GridUserService", string.Empty);
if (presenceServiceDll != string.Empty)
m_GridUserService = LoadPlugin<IGridUserService>(presenceServiceDll, new Object[] { config });
string invServiceDll = userConfig.GetString("InventoryService", string.Empty);
if (invServiceDll != string.Empty)
m_InventoryService = LoadPlugin<IInventoryService>(invServiceDll, new Object[] { config });
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("UserService", false,
"create user",
"create user [<first> [<last> [<pass> [<email>]]]]",
"Create a new user", HandleCreateUser);
MainConsole.Instance.Commands.AddCommand("UserService", false, "reset user password",
"reset user password [<first> [<last> [<password>]]]",
"Reset a user password", HandleResetUserPassword);
}
}
}
#region IUserAccountService
public UserAccount GetUserAccount(UUID scopeID, string firstName,
string lastName)
{
UserAccountData[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new string[] { "ScopeID", "FirstName", "LastName" },
new string[] { scopeID.ToString(), firstName, lastName });
if (d.Length < 1)
{
d = m_Database.Get(
new string[] { "ScopeID", "FirstName", "LastName" },
new string[] { UUID.Zero.ToString(), firstName, lastName });
}
}
else
{
d = m_Database.Get(
new string[] { "FirstName", "LastName" },
new string[] { firstName, lastName });
}
if (d.Length < 1)
return null;
return MakeUserAccount(d[0]);
}
private UserAccount MakeUserAccount(UserAccountData d)
{
UserAccount u = new UserAccount();
u.FirstName = d.FirstName;
u.LastName = d.LastName;
u.PrincipalID = d.PrincipalID;
u.ScopeID = d.ScopeID;
if (d.Data.ContainsKey("Email") && d.Data["Email"] != null)
u.Email = d.Data["Email"].ToString();
else
u.Email = string.Empty;
u.Created = Convert.ToInt32(d.Data["Created"].ToString());
if (d.Data.ContainsKey("UserTitle") && d.Data["UserTitle"] != null)
u.UserTitle = d.Data["UserTitle"].ToString();
else
u.UserTitle = string.Empty;
if (d.Data.ContainsKey("UserLevel") && d.Data["UserLevel"] != null)
Int32.TryParse(d.Data["UserLevel"], out u.UserLevel);
if (d.Data.ContainsKey("UserFlags") && d.Data["UserFlags"] != null)
Int32.TryParse(d.Data["UserFlags"], out u.UserFlags);
if (d.Data.ContainsKey("ServiceURLs") && d.Data["ServiceURLs"] != null)
{
string[] URLs = d.Data["ServiceURLs"].ToString().Split(new char[] { ' ' });
u.ServiceURLs = new Dictionary<string, object>();
foreach (string url in URLs)
{
string[] parts = url.Split(new char[] { '=' });
if (parts.Length != 2)
continue;
string name = System.Web.HttpUtility.UrlDecode(parts[0]);
string val = System.Web.HttpUtility.UrlDecode(parts[1]);
u.ServiceURLs[name] = val;
}
}
else
u.ServiceURLs = new Dictionary<string, object>();
return u;
}
public UserAccount GetUserAccount(UUID scopeID, string email)
{
UserAccountData[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new string[] { "ScopeID", "Email" },
new string[] { scopeID.ToString(), email });
if (d.Length < 1)
{
d = m_Database.Get(
new string[] { "ScopeID", "Email" },
new string[] { UUID.Zero.ToString(), email });
}
}
else
{
d = m_Database.Get(
new string[] { "Email" },
new string[] { email });
}
if (d.Length < 1)
return null;
return MakeUserAccount(d[0]);
}
public UserAccount GetUserAccount(UUID scopeID, UUID principalID)
{
UserAccountData[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new string[] { "ScopeID", "PrincipalID" },
new string[] { scopeID.ToString(), principalID.ToString() });
if (d.Length < 1)
{
d = m_Database.Get(
new string[] { "ScopeID", "PrincipalID" },
new string[] { UUID.Zero.ToString(), principalID.ToString() });
}
}
else
{
d = m_Database.Get(
new string[] { "PrincipalID" },
new string[] { principalID.ToString() });
}
if (d.Length < 1)
{
return null;
}
return MakeUserAccount(d[0]);
}
public bool StoreUserAccount(UserAccount data)
{
UserAccountData d = new UserAccountData();
d.FirstName = data.FirstName;
d.LastName = data.LastName;
d.PrincipalID = data.PrincipalID;
d.ScopeID = data.ScopeID;
d.Data = new Dictionary<string, string>();
d.Data["Email"] = data.Email;
d.Data["Created"] = data.Created.ToString();
d.Data["UserLevel"] = data.UserLevel.ToString();
d.Data["UserFlags"] = data.UserFlags.ToString();
if (data.UserTitle != null)
d.Data["UserTitle"] = data.UserTitle.ToString();
List<string> parts = new List<string>();
foreach (KeyValuePair<string, object> kvp in data.ServiceURLs)
{
string key = System.Web.HttpUtility.UrlEncode(kvp.Key);
string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
parts.Add(key + "=" + val);
}
d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray());
return m_Database.Store(d);
}
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
UserAccountData[] d = m_Database.GetUsers(scopeID, query);
if (d == null)
return new List<UserAccount>();
List<UserAccount> ret = new List<UserAccount>();
foreach (UserAccountData data in d)
ret.Add(MakeUserAccount(data));
return ret;
}
#endregion
#region Console commands
/// <summary>
/// Handle the create user command from the console.
/// </summary>
/// <param name="cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param>
protected void HandleCreateUser(string module, string[] cmdparams)
{
string firstName;
string lastName;
string password;
string email;
if (cmdparams.Length < 3)
firstName = MainConsole.Instance.CmdPrompt("First name", "Default");
else firstName = cmdparams[2];
if (cmdparams.Length < 4)
lastName = MainConsole.Instance.CmdPrompt("Last name", "User");
else lastName = cmdparams[3];
if (cmdparams.Length < 5)
password = MainConsole.Instance.PasswdPrompt("Password");
else password = cmdparams[4];
if (cmdparams.Length < 6)
email = MainConsole.Instance.CmdPrompt("Email", "");
else email = cmdparams[5];
CreateUser(firstName, lastName, password, email);
}
protected void HandleResetUserPassword(string module, string[] cmdparams)
{
string firstName;
string lastName;
string newPassword;
if (cmdparams.Length < 4)
firstName = MainConsole.Instance.CmdPrompt("First name");
else firstName = cmdparams[3];
if (cmdparams.Length < 5)
lastName = MainConsole.Instance.CmdPrompt("Last name");
else lastName = cmdparams[4];
if (cmdparams.Length < 6)
newPassword = MainConsole.Instance.PasswdPrompt("New password");
else newPassword = cmdparams[5];
UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
if (account == null)
m_log.ErrorFormat("[USER ACCOUNT SERVICE]: No such user");
bool success = false;
if (m_AuthenticationService != null)
success = m_AuthenticationService.SetPassword(account.PrincipalID, newPassword);
if (!success)
m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Unable to reset password for account {0} {1}.",
firstName, lastName);
else
m_log.InfoFormat("[USER ACCOUNT SERVICE]: Password reset for user {0} {1}", firstName, lastName);
}
#endregion
/// <summary>
/// Create a user
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="password"></param>
/// <param name="email"></param>
public void CreateUser(string firstName, string lastName, string password, string email)
{
UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
if (null == account)
{
account = new UserAccount(UUID.Zero, firstName, lastName, email);
if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
{
account.ServiceURLs = new Dictionary<string, object>();
account.ServiceURLs["HomeURI"] = string.Empty;
account.ServiceURLs["GatekeeperURI"] = string.Empty;
account.ServiceURLs["InventoryServerURI"] = string.Empty;
account.ServiceURLs["AssetServerURI"] = string.Empty;
}
if (StoreUserAccount(account))
{
bool success = false;
if (m_AuthenticationService != null)
success = m_AuthenticationService.SetPassword(account.PrincipalID, password);
if (!success)
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.",
firstName, lastName);
GridRegion home = null;
if (m_GridService != null)
{
List<GridRegion> defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero);
if (defaultRegions != null && defaultRegions.Count >= 1)
home = defaultRegions[0];
if (m_GridUserService != null && home != null)
m_GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
else
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.",
firstName, lastName);
}
else
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.",
firstName, lastName);
if (m_InventoryService != null)
success = m_InventoryService.CreateUserInventory(account.PrincipalID);
if (!success)
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.",
firstName, lastName);
m_log.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} {1} created successfully", firstName, lastName);
}
}
else
{
m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName);
}
}
}
}
| |
# CS_ARCH_PPC, CS_MODE_BIG_ENDIAN, CS_OPT_SYNTAX_NOREGNAME
// 0x4d,0x82,0x00,0x20 = beqlr 0
// 0x4d,0x86,0x00,0x20 = beqlr 1
// 0x4d,0x8a,0x00,0x20 = beqlr 2
// 0x4d,0x8e,0x00,0x20 = beqlr 3
// 0x4d,0x92,0x00,0x20 = beqlr 4
// 0x4d,0x96,0x00,0x20 = beqlr 5
// 0x4d,0x9a,0x00,0x20 = beqlr 6
// 0x4d,0x9e,0x00,0x20 = beqlr 7
// 0x4d,0x80,0x00,0x20 = bclr 12, 0, 0
// 0x4d,0x81,0x00,0x20 = bclr 12, 1, 0
// 0x4d,0x82,0x00,0x20 = bclr 12, 2, 0
// 0x4d,0x83,0x00,0x20 = bclr 12, 3, 0
// 0x4d,0x83,0x00,0x20 = bclr 12, 3, 0
// 0x4d,0x84,0x00,0x20 = bclr 12, 4, 0
// 0x4d,0x85,0x00,0x20 = bclr 12, 5, 0
// 0x4d,0x86,0x00,0x20 = bclr 12, 6, 0
// 0x4d,0x87,0x00,0x20 = bclr 12, 7, 0
// 0x4d,0x87,0x00,0x20 = bclr 12, 7, 0
// 0x4d,0x88,0x00,0x20 = bclr 12, 8, 0
// 0x4d,0x89,0x00,0x20 = bclr 12, 9, 0
// 0x4d,0x8a,0x00,0x20 = bclr 12, 10, 0
// 0x4d,0x8b,0x00,0x20 = bclr 12, 11, 0
// 0x4d,0x8b,0x00,0x20 = bclr 12, 11, 0
// 0x4d,0x8c,0x00,0x20 = bclr 12, 12, 0
// 0x4d,0x8d,0x00,0x20 = bclr 12, 13, 0
// 0x4d,0x8e,0x00,0x20 = bclr 12, 14, 0
// 0x4d,0x8f,0x00,0x20 = bclr 12, 15, 0
// 0x4d,0x8f,0x00,0x20 = bclr 12, 15, 0
// 0x4d,0x90,0x00,0x20 = bclr 12, 16, 0
// 0x4d,0x91,0x00,0x20 = bclr 12, 17, 0
// 0x4d,0x92,0x00,0x20 = bclr 12, 18, 0
// 0x4d,0x93,0x00,0x20 = bclr 12, 19, 0
// 0x4d,0x93,0x00,0x20 = bclr 12, 19, 0
// 0x4d,0x94,0x00,0x20 = bclr 12, 20, 0
// 0x4d,0x95,0x00,0x20 = bclr 12, 21, 0
// 0x4d,0x96,0x00,0x20 = bclr 12, 22, 0
// 0x4d,0x97,0x00,0x20 = bclr 12, 23, 0
// 0x4d,0x97,0x00,0x20 = bclr 12, 23, 0
// 0x4d,0x98,0x00,0x20 = bclr 12, 24, 0
// 0x4d,0x99,0x00,0x20 = bclr 12, 25, 0
// 0x4d,0x9a,0x00,0x20 = bclr 12, 26, 0
// 0x4d,0x9b,0x00,0x20 = bclr 12, 27, 0
// 0x4d,0x9b,0x00,0x20 = bclr 12, 27, 0
// 0x4d,0x9c,0x00,0x20 = bclr 12, 28, 0
// 0x4d,0x9d,0x00,0x20 = bclr 12, 29, 0
// 0x4d,0x9e,0x00,0x20 = bclr 12, 30, 0
// 0x4d,0x9f,0x00,0x20 = bclr 12, 31, 0
// 0x4d,0x9f,0x00,0x20 = bclr 12, 31, 0
0x4e,0x80,0x00,0x20 = blr
0x4e,0x80,0x04,0x20 = bctr
0x4e,0x80,0x00,0x21 = blrl
0x4e,0x80,0x04,0x21 = bctrl
// 0x4d,0x82,0x00,0x20 = bclr 12, 2, 0
// 0x4d,0x82,0x04,0x20 = bcctr 12, 2, 0
// 0x4d,0x82,0x00,0x21 = bclrl 12, 2, 0
// 0x4d,0x82,0x04,0x21 = bcctrl 12, 2, 0
// 0x4d,0xe2,0x00,0x20 = bclr 15, 2, 0
// 0x4d,0xe2,0x04,0x20 = bcctr 15, 2, 0
// 0x4d,0xe2,0x00,0x21 = bclrl 15, 2, 0
// 0x4d,0xe2,0x04,0x21 = bcctrl 15, 2, 0
// 0x4d,0xc2,0x00,0x20 = bclr 14, 2, 0
// 0x4d,0xc2,0x04,0x20 = bcctr 14, 2, 0
// 0x4d,0xc2,0x00,0x21 = bclrl 14, 2, 0
// 0x4d,0xc2,0x04,0x21 = bcctrl 14, 2, 0
// 0x4c,0x82,0x00,0x20 = bclr 4, 2, 0
// 0x4c,0x82,0x04,0x20 = bcctr 4, 2, 0
// 0x4c,0x82,0x00,0x21 = bclrl 4, 2, 0
// 0x4c,0x82,0x04,0x21 = bcctrl 4, 2, 0
// 0x4c,0xe2,0x00,0x20 = bclr 7, 2, 0
// 0x4c,0xe2,0x04,0x20 = bcctr 7, 2, 0
// 0x4c,0xe2,0x00,0x21 = bclrl 7, 2, 0
// 0x4c,0xe2,0x04,0x21 = bcctrl 7, 2, 0
// 0x4c,0xc2,0x00,0x20 = bclr 6, 2, 0
// 0x4c,0xc2,0x04,0x20 = bcctr 6, 2, 0
// 0x4c,0xc2,0x00,0x21 = bclrl 6, 2, 0
// 0x4c,0xc2,0x04,0x21 = bcctrl 6, 2, 0
0x4e,0x00,0x00,0x20 = bdnzlr
0x4e,0x00,0x00,0x21 = bdnzlrl
0x4f,0x20,0x00,0x20 = bdnzlr+
0x4f,0x20,0x00,0x21 = bdnzlrl+
0x4f,0x00,0x00,0x20 = bdnzlr-
0x4f,0x00,0x00,0x21 = bdnzlrl-
// 0x4d,0x02,0x00,0x20 = bclr 8, 2, 0
// 0x4d,0x02,0x00,0x21 = bclrl 8, 2, 0
// 0x4c,0x02,0x00,0x20 = bclr 0, 2, 0
// 0x4c,0x02,0x00,0x21 = bclrl 0, 2, 0
0x4e,0x40,0x00,0x20 = bdzlr
0x4e,0x40,0x00,0x21 = bdzlrl
0x4f,0x60,0x00,0x20 = bdzlr+
0x4f,0x60,0x00,0x21 = bdzlrl+
0x4f,0x40,0x00,0x20 = bdzlr-
0x4f,0x40,0x00,0x21 = bdzlrl-
// 0x4d,0x42,0x00,0x20 = bclr 10, 2, 0
// 0x4d,0x42,0x00,0x21 = bclrl 10, 2, 0
// 0x4c,0x42,0x00,0x20 = bclr 2, 2, 0
// 0x4c,0x42,0x00,0x21 = bclrl 2, 2, 0
// 0x4d,0x88,0x00,0x20 = bltlr 2
// 0x4d,0x80,0x00,0x20 = bltlr 0
// 0x4d,0x88,0x04,0x20 = bltctr 2
// 0x4d,0x80,0x04,0x20 = bltctr 0
// 0x4d,0x88,0x00,0x21 = bltlrl 2
// 0x4d,0x80,0x00,0x21 = bltlrl 0
// 0x4d,0x88,0x04,0x21 = bltctrl 2
// 0x4d,0x80,0x04,0x21 = bltctrl 0
// 0x4d,0xe8,0x00,0x20 = bltlr+ 2
// 0x4d,0xe0,0x00,0x20 = bltlr+ 0
// 0x4d,0xe8,0x04,0x20 = bltctr+ 2
// 0x4d,0xe0,0x04,0x20 = bltctr+ 0
// 0x4d,0xe8,0x00,0x21 = bltlrl+ 2
// 0x4d,0xe0,0x00,0x21 = bltlrl+ 0
// 0x4d,0xe8,0x04,0x21 = bltctrl+ 2
// 0x4d,0xe0,0x04,0x21 = bltctrl+ 0
// 0x4d,0xc8,0x00,0x20 = bltlr- 2
// 0x4d,0xc0,0x00,0x20 = bltlr- 0
// 0x4d,0xc8,0x04,0x20 = bltctr- 2
// 0x4d,0xc0,0x04,0x20 = bltctr- 0
// 0x4d,0xc8,0x00,0x21 = bltlrl- 2
// 0x4d,0xc0,0x00,0x21 = bltlrl- 0
// 0x4d,0xc8,0x04,0x21 = bltctrl- 2
// 0x4d,0xc0,0x04,0x21 = bltctrl- 0
// 0x4c,0x89,0x00,0x20 = blelr 2
// 0x4c,0x81,0x00,0x20 = blelr 0
// 0x4c,0x89,0x04,0x20 = blectr 2
// 0x4c,0x81,0x04,0x20 = blectr 0
// 0x4c,0x89,0x00,0x21 = blelrl 2
// 0x4c,0x81,0x00,0x21 = blelrl 0
// 0x4c,0x89,0x04,0x21 = blectrl 2
// 0x4c,0x81,0x04,0x21 = blectrl 0
// 0x4c,0xe9,0x00,0x20 = blelr+ 2
// 0x4c,0xe1,0x00,0x20 = blelr+ 0
// 0x4c,0xe9,0x04,0x20 = blectr+ 2
// 0x4c,0xe1,0x04,0x20 = blectr+ 0
// 0x4c,0xe9,0x00,0x21 = blelrl+ 2
// 0x4c,0xe1,0x00,0x21 = blelrl+ 0
// 0x4c,0xe9,0x04,0x21 = blectrl+ 2
// 0x4c,0xe1,0x04,0x21 = blectrl+ 0
// 0x4c,0xc9,0x00,0x20 = blelr- 2
// 0x4c,0xc1,0x00,0x20 = blelr- 0
// 0x4c,0xc9,0x04,0x20 = blectr- 2
// 0x4c,0xc1,0x04,0x20 = blectr- 0
// 0x4c,0xc9,0x00,0x21 = blelrl- 2
// 0x4c,0xc1,0x00,0x21 = blelrl- 0
// 0x4c,0xc9,0x04,0x21 = blectrl- 2
// 0x4c,0xc1,0x04,0x21 = blectrl- 0
// 0x4d,0x8a,0x00,0x20 = beqlr 2
// 0x4d,0x82,0x00,0x20 = beqlr 0
// 0x4d,0x8a,0x04,0x20 = beqctr 2
// 0x4d,0x82,0x04,0x20 = beqctr 0
// 0x4d,0x8a,0x00,0x21 = beqlrl 2
// 0x4d,0x82,0x00,0x21 = beqlrl 0
// 0x4d,0x8a,0x04,0x21 = beqctrl 2
// 0x4d,0x82,0x04,0x21 = beqctrl 0
// 0x4d,0xea,0x00,0x20 = beqlr+ 2
// 0x4d,0xe2,0x00,0x20 = beqlr+ 0
// 0x4d,0xea,0x04,0x20 = beqctr+ 2
// 0x4d,0xe2,0x04,0x20 = beqctr+ 0
// 0x4d,0xea,0x00,0x21 = beqlrl+ 2
// 0x4d,0xe2,0x00,0x21 = beqlrl+ 0
// 0x4d,0xea,0x04,0x21 = beqctrl+ 2
// 0x4d,0xe2,0x04,0x21 = beqctrl+ 0
// 0x4d,0xca,0x00,0x20 = beqlr- 2
// 0x4d,0xc2,0x00,0x20 = beqlr- 0
// 0x4d,0xca,0x04,0x20 = beqctr- 2
// 0x4d,0xc2,0x04,0x20 = beqctr- 0
// 0x4d,0xca,0x00,0x21 = beqlrl- 2
// 0x4d,0xc2,0x00,0x21 = beqlrl- 0
// 0x4d,0xca,0x04,0x21 = beqctrl- 2
// 0x4d,0xc2,0x04,0x21 = beqctrl- 0
// 0x4c,0x88,0x00,0x20 = bgelr 2
// 0x4c,0x80,0x00,0x20 = bgelr 0
// 0x4c,0x88,0x04,0x20 = bgectr 2
// 0x4c,0x80,0x04,0x20 = bgectr 0
// 0x4c,0x88,0x00,0x21 = bgelrl 2
// 0x4c,0x80,0x00,0x21 = bgelrl 0
// 0x4c,0x88,0x04,0x21 = bgectrl 2
// 0x4c,0x80,0x04,0x21 = bgectrl 0
// 0x4c,0xe8,0x00,0x20 = bgelr+ 2
// 0x4c,0xe0,0x00,0x20 = bgelr+ 0
// 0x4c,0xe8,0x04,0x20 = bgectr+ 2
// 0x4c,0xe0,0x04,0x20 = bgectr+ 0
// 0x4c,0xe8,0x00,0x21 = bgelrl+ 2
// 0x4c,0xe0,0x00,0x21 = bgelrl+ 0
// 0x4c,0xe8,0x04,0x21 = bgectrl+ 2
// 0x4c,0xe0,0x04,0x21 = bgectrl+ 0
// 0x4c,0xc8,0x00,0x20 = bgelr- 2
// 0x4c,0xc0,0x00,0x20 = bgelr- 0
// 0x4c,0xc8,0x04,0x20 = bgectr- 2
// 0x4c,0xc0,0x04,0x20 = bgectr- 0
// 0x4c,0xc8,0x00,0x21 = bgelrl- 2
// 0x4c,0xc0,0x00,0x21 = bgelrl- 0
// 0x4c,0xc8,0x04,0x21 = bgectrl- 2
// 0x4c,0xc0,0x04,0x21 = bgectrl- 0
// 0x4d,0x89,0x00,0x20 = bgtlr 2
// 0x4d,0x81,0x00,0x20 = bgtlr 0
// 0x4d,0x89,0x04,0x20 = bgtctr 2
// 0x4d,0x81,0x04,0x20 = bgtctr 0
// 0x4d,0x89,0x00,0x21 = bgtlrl 2
// 0x4d,0x81,0x00,0x21 = bgtlrl 0
// 0x4d,0x89,0x04,0x21 = bgtctrl 2
// 0x4d,0x81,0x04,0x21 = bgtctrl 0
// 0x4d,0xe9,0x00,0x20 = bgtlr+ 2
// 0x4d,0xe1,0x00,0x20 = bgtlr+ 0
// 0x4d,0xe9,0x04,0x20 = bgtctr+ 2
// 0x4d,0xe1,0x04,0x20 = bgtctr+ 0
// 0x4d,0xe9,0x00,0x21 = bgtlrl+ 2
// 0x4d,0xe1,0x00,0x21 = bgtlrl+ 0
// 0x4d,0xe9,0x04,0x21 = bgtctrl+ 2
// 0x4d,0xe1,0x04,0x21 = bgtctrl+ 0
// 0x4d,0xc9,0x00,0x20 = bgtlr- 2
// 0x4d,0xc1,0x00,0x20 = bgtlr- 0
// 0x4d,0xc9,0x04,0x20 = bgtctr- 2
// 0x4d,0xc1,0x04,0x20 = bgtctr- 0
// 0x4d,0xc9,0x00,0x21 = bgtlrl- 2
// 0x4d,0xc1,0x00,0x21 = bgtlrl- 0
// 0x4d,0xc9,0x04,0x21 = bgtctrl- 2
// 0x4d,0xc1,0x04,0x21 = bgtctrl- 0
// 0x4c,0x88,0x00,0x20 = bgelr 2
// 0x4c,0x80,0x00,0x20 = bgelr 0
// 0x4c,0x88,0x04,0x20 = bgectr 2
// 0x4c,0x80,0x04,0x20 = bgectr 0
// 0x4c,0x88,0x00,0x21 = bgelrl 2
// 0x4c,0x80,0x00,0x21 = bgelrl 0
// 0x4c,0x88,0x04,0x21 = bgectrl 2
// 0x4c,0x80,0x04,0x21 = bgectrl 0
// 0x4c,0xe8,0x00,0x20 = bgelr+ 2
// 0x4c,0xe0,0x00,0x20 = bgelr+ 0
// 0x4c,0xe8,0x04,0x20 = bgectr+ 2
// 0x4c,0xe0,0x04,0x20 = bgectr+ 0
// 0x4c,0xe8,0x00,0x21 = bgelrl+ 2
// 0x4c,0xe0,0x00,0x21 = bgelrl+ 0
// 0x4c,0xe8,0x04,0x21 = bgectrl+ 2
// 0x4c,0xe0,0x04,0x21 = bgectrl+ 0
// 0x4c,0xc8,0x00,0x20 = bgelr- 2
// 0x4c,0xc0,0x00,0x20 = bgelr- 0
// 0x4c,0xc8,0x04,0x20 = bgectr- 2
// 0x4c,0xc0,0x04,0x20 = bgectr- 0
// 0x4c,0xc8,0x00,0x21 = bgelrl- 2
// 0x4c,0xc0,0x00,0x21 = bgelrl- 0
// 0x4c,0xc8,0x04,0x21 = bgectrl- 2
// 0x4c,0xc0,0x04,0x21 = bgectrl- 0
// 0x4c,0x8a,0x00,0x20 = bnelr 2
// 0x4c,0x82,0x00,0x20 = bnelr 0
// 0x4c,0x8a,0x04,0x20 = bnectr 2
// 0x4c,0x82,0x04,0x20 = bnectr 0
// 0x4c,0x8a,0x00,0x21 = bnelrl 2
// 0x4c,0x82,0x00,0x21 = bnelrl 0
// 0x4c,0x8a,0x04,0x21 = bnectrl 2
// 0x4c,0x82,0x04,0x21 = bnectrl 0
// 0x4c,0xea,0x00,0x20 = bnelr+ 2
// 0x4c,0xe2,0x00,0x20 = bnelr+ 0
// 0x4c,0xea,0x04,0x20 = bnectr+ 2
// 0x4c,0xe2,0x04,0x20 = bnectr+ 0
// 0x4c,0xea,0x00,0x21 = bnelrl+ 2
// 0x4c,0xe2,0x00,0x21 = bnelrl+ 0
// 0x4c,0xea,0x04,0x21 = bnectrl+ 2
// 0x4c,0xe2,0x04,0x21 = bnectrl+ 0
// 0x4c,0xca,0x00,0x20 = bnelr- 2
// 0x4c,0xc2,0x00,0x20 = bnelr- 0
// 0x4c,0xca,0x04,0x20 = bnectr- 2
// 0x4c,0xc2,0x04,0x20 = bnectr- 0
// 0x4c,0xca,0x00,0x21 = bnelrl- 2
// 0x4c,0xc2,0x00,0x21 = bnelrl- 0
// 0x4c,0xca,0x04,0x21 = bnectrl- 2
// 0x4c,0xc2,0x04,0x21 = bnectrl- 0
// 0x4c,0x89,0x00,0x20 = blelr 2
// 0x4c,0x81,0x00,0x20 = blelr 0
// 0x4c,0x89,0x04,0x20 = blectr 2
// 0x4c,0x81,0x04,0x20 = blectr 0
// 0x4c,0x89,0x00,0x21 = blelrl 2
// 0x4c,0x81,0x00,0x21 = blelrl 0
// 0x4c,0x89,0x04,0x21 = blectrl 2
// 0x4c,0x81,0x04,0x21 = blectrl 0
// 0x4c,0xe9,0x00,0x20 = blelr+ 2
// 0x4c,0xe1,0x00,0x20 = blelr+ 0
// 0x4c,0xe9,0x04,0x20 = blectr+ 2
// 0x4c,0xe1,0x04,0x20 = blectr+ 0
// 0x4c,0xe9,0x00,0x21 = blelrl+ 2
// 0x4c,0xe1,0x00,0x21 = blelrl+ 0
// 0x4c,0xe9,0x04,0x21 = blectrl+ 2
// 0x4c,0xe1,0x04,0x21 = blectrl+ 0
// 0x4c,0xc9,0x00,0x20 = blelr- 2
// 0x4c,0xc1,0x00,0x20 = blelr- 0
// 0x4c,0xc9,0x04,0x20 = blectr- 2
// 0x4c,0xc1,0x04,0x20 = blectr- 0
// 0x4c,0xc9,0x00,0x21 = blelrl- 2
// 0x4c,0xc1,0x00,0x21 = blelrl- 0
// 0x4c,0xc9,0x04,0x21 = blectrl- 2
// 0x4c,0xc1,0x04,0x21 = blectrl- 0
// 0x4d,0x8b,0x00,0x20 = bunlr 2
// 0x4d,0x83,0x00,0x20 = bunlr 0
// 0x4d,0x8b,0x04,0x20 = bunctr 2
// 0x4d,0x83,0x04,0x20 = bunctr 0
// 0x4d,0x8b,0x00,0x21 = bunlrl 2
// 0x4d,0x83,0x00,0x21 = bunlrl 0
// 0x4d,0x8b,0x04,0x21 = bunctrl 2
// 0x4d,0x83,0x04,0x21 = bunctrl 0
// 0x4d,0xeb,0x00,0x20 = bunlr+ 2
// 0x4d,0xe3,0x00,0x20 = bunlr+ 0
// 0x4d,0xeb,0x04,0x20 = bunctr+ 2
// 0x4d,0xe3,0x04,0x20 = bunctr+ 0
// 0x4d,0xeb,0x00,0x21 = bunlrl+ 2
// 0x4d,0xe3,0x00,0x21 = bunlrl+ 0
// 0x4d,0xeb,0x04,0x21 = bunctrl+ 2
// 0x4d,0xe3,0x04,0x21 = bunctrl+ 0
// 0x4d,0xcb,0x00,0x20 = bunlr- 2
// 0x4d,0xc3,0x00,0x20 = bunlr- 0
// 0x4d,0xcb,0x04,0x20 = bunctr- 2
// 0x4d,0xc3,0x04,0x20 = bunctr- 0
// 0x4d,0xcb,0x00,0x21 = bunlrl- 2
// 0x4d,0xc3,0x00,0x21 = bunlrl- 0
// 0x4d,0xcb,0x04,0x21 = bunctrl- 2
// 0x4d,0xc3,0x04,0x21 = bunctrl- 0
// 0x4c,0x8b,0x00,0x20 = bnulr 2
// 0x4c,0x83,0x00,0x20 = bnulr 0
// 0x4c,0x8b,0x04,0x20 = bnuctr 2
// 0x4c,0x83,0x04,0x20 = bnuctr 0
// 0x4c,0x8b,0x00,0x21 = bnulrl 2
// 0x4c,0x83,0x00,0x21 = bnulrl 0
// 0x4c,0x8b,0x04,0x21 = bnuctrl 2
// 0x4c,0x83,0x04,0x21 = bnuctrl 0
// 0x4c,0xeb,0x00,0x20 = bnulr+ 2
// 0x4c,0xe3,0x00,0x20 = bnulr+ 0
// 0x4c,0xeb,0x04,0x20 = bnuctr+ 2
// 0x4c,0xe3,0x04,0x20 = bnuctr+ 0
// 0x4c,0xeb,0x00,0x21 = bnulrl+ 2
// 0x4c,0xe3,0x00,0x21 = bnulrl+ 0
// 0x4c,0xeb,0x04,0x21 = bnuctrl+ 2
// 0x4c,0xe3,0x04,0x21 = bnuctrl+ 0
// 0x4c,0xcb,0x00,0x20 = bnulr- 2
// 0x4c,0xc3,0x00,0x20 = bnulr- 0
// 0x4c,0xcb,0x04,0x20 = bnuctr- 2
// 0x4c,0xc3,0x04,0x20 = bnuctr- 0
// 0x4c,0xcb,0x00,0x21 = bnulrl- 2
// 0x4c,0xc3,0x00,0x21 = bnulrl- 0
// 0x4c,0xcb,0x04,0x21 = bnuctrl- 2
// 0x4c,0xc3,0x04,0x21 = bnuctrl- 0
// 0x4d,0x8b,0x00,0x20 = bunlr 2
// 0x4d,0x83,0x00,0x20 = bunlr 0
// 0x4d,0x8b,0x04,0x20 = bunctr 2
// 0x4d,0x83,0x04,0x20 = bunctr 0
// 0x4d,0x8b,0x00,0x21 = bunlrl 2
// 0x4d,0x83,0x00,0x21 = bunlrl 0
// 0x4d,0x8b,0x04,0x21 = bunctrl 2
// 0x4d,0x83,0x04,0x21 = bunctrl 0
// 0x4d,0xeb,0x00,0x20 = bunlr+ 2
// 0x4d,0xe3,0x00,0x20 = bunlr+ 0
// 0x4d,0xeb,0x04,0x20 = bunctr+ 2
// 0x4d,0xe3,0x04,0x20 = bunctr+ 0
// 0x4d,0xeb,0x00,0x21 = bunlrl+ 2
// 0x4d,0xe3,0x00,0x21 = bunlrl+ 0
// 0x4d,0xeb,0x04,0x21 = bunctrl+ 2
// 0x4d,0xe3,0x04,0x21 = bunctrl+ 0
// 0x4d,0xcb,0x00,0x20 = bunlr- 2
// 0x4d,0xc3,0x00,0x20 = bunlr- 0
// 0x4d,0xcb,0x04,0x20 = bunctr- 2
// 0x4d,0xc3,0x04,0x20 = bunctr- 0
// 0x4d,0xcb,0x00,0x21 = bunlrl- 2
// 0x4d,0xc3,0x00,0x21 = bunlrl- 0
// 0x4d,0xcb,0x04,0x21 = bunctrl- 2
// 0x4d,0xc3,0x04,0x21 = bunctrl- 0
// 0x4c,0x8b,0x00,0x20 = bnulr 2
// 0x4c,0x83,0x00,0x20 = bnulr 0
// 0x4c,0x8b,0x04,0x20 = bnuctr 2
// 0x4c,0x83,0x04,0x20 = bnuctr 0
// 0x4c,0x8b,0x00,0x21 = bnulrl 2
// 0x4c,0x83,0x00,0x21 = bnulrl 0
// 0x4c,0x8b,0x04,0x21 = bnuctrl 2
// 0x4c,0x83,0x04,0x21 = bnuctrl 0
// 0x4c,0xeb,0x00,0x20 = bnulr+ 2
// 0x4c,0xe3,0x00,0x20 = bnulr+ 0
// 0x4c,0xeb,0x04,0x20 = bnuctr+ 2
// 0x4c,0xe3,0x04,0x20 = bnuctr+ 0
// 0x4c,0xeb,0x00,0x21 = bnulrl+ 2
// 0x4c,0xe3,0x00,0x21 = bnulrl+ 0
// 0x4c,0xeb,0x04,0x21 = bnuctrl+ 2
// 0x4c,0xe3,0x04,0x21 = bnuctrl+ 0
// 0x4c,0xcb,0x00,0x20 = bnulr- 2
// 0x4c,0xc3,0x00,0x20 = bnulr- 0
// 0x4c,0xcb,0x04,0x20 = bnuctr- 2
// 0x4c,0xc3,0x04,0x20 = bnuctr- 0
// 0x4c,0xcb,0x00,0x21 = bnulrl- 2
// 0x4c,0xc3,0x00,0x21 = bnulrl- 0
// 0x4c,0xcb,0x04,0x21 = bnuctrl- 2
// 0x4c,0xc3,0x04,0x21 = bnuctrl- 0
// 0x4c,0x42,0x12,0x42 = creqv 2, 2, 2
// 0x4c,0x42,0x11,0x82 = crxor 2, 2, 2
// 0x4c,0x43,0x1b,0x82 = cror 2, 3, 3
// 0x4c,0x43,0x18,0x42 = crnor 2, 3, 3
// 0x38,0x43,0xff,0x80 = addi 2, 3, -128
// 0x3c,0x43,0xff,0x80 = addis 2, 3, -128
// 0x30,0x43,0xff,0x80 = addic 2, 3, -128
// 0x34,0x43,0xff,0x80 = addic. 2, 3, -128
0x7c,0x44,0x18,0x50 = subf 2, 4, 3
0x7c,0x44,0x18,0x51 = subf. 2, 4, 3
0x7c,0x44,0x18,0x10 = subfc 2, 4, 3
0x7c,0x44,0x18,0x11 = subfc. 2, 4, 3
0x2d,0x23,0x00,0x80 = cmpdi 2, 3, 128
// 0x2c,0x23,0x00,0x80 = cmpdi 0, 3, 128
0x7d,0x23,0x20,0x00 = cmpd 2, 3, 4
// 0x7c,0x23,0x20,0x00 = cmpd 0, 3, 4
0x29,0x23,0x00,0x80 = cmpldi 2, 3, 128
// 0x28,0x23,0x00,0x80 = cmpldi 0, 3, 128
0x7d,0x23,0x20,0x40 = cmpld 2, 3, 4
// 0x7c,0x23,0x20,0x40 = cmpld 0, 3, 4
0x2d,0x03,0x00,0x80 = cmpwi 2, 3, 128
// 0x2c,0x03,0x00,0x80 = cmpwi 0, 3, 128
0x7d,0x03,0x20,0x00 = cmpw 2, 3, 4
// 0x7c,0x03,0x20,0x00 = cmpw 0, 3, 4
0x29,0x03,0x00,0x80 = cmplwi 2, 3, 128
// 0x28,0x03,0x00,0x80 = cmplwi 0, 3, 128
0x7d,0x03,0x20,0x40 = cmplw 2, 3, 4
// 0x7c,0x03,0x20,0x40 = cmplw 0, 3, 4
// 0x0e,0x03,0x00,0x04 = twi 16, 3, 4
// 0x7e,0x03,0x20,0x08 = tw 16, 3, 4
// 0x0a,0x03,0x00,0x04 = tdi 16, 3, 4
// 0x7e,0x03,0x20,0x88 = td 16, 3, 4
0x0e,0x83,0x00,0x04 = twi 20, 3, 4
0x7e,0x83,0x20,0x08 = tw 20, 3, 4
0x0a,0x83,0x00,0x04 = tdi 20, 3, 4
0x7e,0x83,0x20,0x88 = td 20, 3, 4
// 0x0c,0x83,0x00,0x04 = twi 4, 3, 4
// 0x7c,0x83,0x20,0x08 = tw 4, 3, 4
// 0x08,0x83,0x00,0x04 = tdi 4, 3, 4
// 0x7c,0x83,0x20,0x88 = td 4, 3, 4
0x0d,0x83,0x00,0x04 = twi 12, 3, 4
0x7d,0x83,0x20,0x08 = tw 12, 3, 4
0x09,0x83,0x00,0x04 = tdi 12, 3, 4
0x7d,0x83,0x20,0x88 = td 12, 3, 4
// 0x0d,0x03,0x00,0x04 = twi 8, 3, 4
// 0x7d,0x03,0x20,0x08 = tw 8, 3, 4
// 0x09,0x03,0x00,0x04 = tdi 8, 3, 4
// 0x7d,0x03,0x20,0x88 = td 8, 3, 4
0x0d,0x83,0x00,0x04 = twi 12, 3, 4
0x7d,0x83,0x20,0x08 = tw 12, 3, 4
0x09,0x83,0x00,0x04 = tdi 12, 3, 4
0x7d,0x83,0x20,0x88 = td 12, 3, 4
// 0x0f,0x03,0x00,0x04 = twi 24, 3, 4
// 0x7f,0x03,0x20,0x08 = tw 24, 3, 4
// 0x0b,0x03,0x00,0x04 = tdi 24, 3, 4
// 0x7f,0x03,0x20,0x88 = td 24, 3, 4
0x0e,0x83,0x00,0x04 = twi 20, 3, 4
0x7e,0x83,0x20,0x08 = tw 20, 3, 4
0x0a,0x83,0x00,0x04 = tdi 20, 3, 4
0x7e,0x83,0x20,0x88 = td 20, 3, 4
// 0x0c,0x43,0x00,0x04 = twi 2, 3, 4
// 0x7c,0x43,0x20,0x08 = tw 2, 3, 4
// 0x08,0x43,0x00,0x04 = tdi 2, 3, 4
// 0x7c,0x43,0x20,0x88 = td 2, 3, 4
0x0c,0xc3,0x00,0x04 = twi 6, 3, 4
0x7c,0xc3,0x20,0x08 = tw 6, 3, 4
0x08,0xc3,0x00,0x04 = tdi 6, 3, 4
0x7c,0xc3,0x20,0x88 = td 6, 3, 4
0x0c,0xa3,0x00,0x04 = twi 5, 3, 4
0x7c,0xa3,0x20,0x08 = tw 5, 3, 4
0x08,0xa3,0x00,0x04 = tdi 5, 3, 4
0x7c,0xa3,0x20,0x88 = td 5, 3, 4
// 0x0c,0x23,0x00,0x04 = twi 1, 3, 4
// 0x7c,0x23,0x20,0x08 = tw 1, 3, 4
// 0x08,0x23,0x00,0x04 = tdi 1, 3, 4
// 0x7c,0x23,0x20,0x88 = td 1, 3, 4
0x0c,0xa3,0x00,0x04 = twi 5, 3, 4
0x7c,0xa3,0x20,0x08 = tw 5, 3, 4
0x08,0xa3,0x00,0x04 = tdi 5, 3, 4
0x7c,0xa3,0x20,0x88 = td 5, 3, 4
0x0c,0xc3,0x00,0x04 = twi 6, 3, 4
0x7c,0xc3,0x20,0x08 = tw 6, 3, 4
0x08,0xc3,0x00,0x04 = tdi 6, 3, 4
0x7c,0xc3,0x20,0x88 = td 6, 3, 4
// 0x0f,0xe3,0x00,0x04 = twi 31, 3, 4
// 0x7f,0xe3,0x20,0x08 = tw 31, 3, 4
// 0x0b,0xe3,0x00,0x04 = tdi 31, 3, 4
// 0x7f,0xe3,0x20,0x88 = td 31, 3, 4
0x7f,0xe0,0x00,0x08 = trap
0x78,0x62,0x28,0xc4 = rldicr 2, 3, 5, 3
0x78,0x62,0x28,0xc5 = rldicr. 2, 3, 5, 3
0x78,0x62,0x4f,0x20 = rldicl 2, 3, 9, 60
0x78,0x62,0x4f,0x21 = rldicl. 2, 3, 9, 60
0x78,0x62,0xb9,0x4e = rldimi 2, 3, 55, 5
0x78,0x62,0xb9,0x4f = rldimi. 2, 3, 55, 5
// 0x78,0x62,0x20,0x00 = rldicl 2, 3, 4, 0
// 0x78,0x62,0x20,0x01 = rldicl. 2, 3, 4, 0
// 0x78,0x62,0xe0,0x02 = rldicl 2, 3, 60, 0
// 0x78,0x62,0xe0,0x03 = rldicl. 2, 3, 60, 0
// 0x78,0x62,0x20,0x10 = rldcl 2, 3, 4, 0
// 0x78,0x62,0x20,0x11 = rldcl. 2, 3, 4, 0
0x78,0x62,0x26,0xe4 = sldi 2, 3, 4
0x78,0x62,0x26,0xe5 = rldicr. 2, 3, 4, 59
0x78,0x62,0xe1,0x02 = rldicl 2, 3, 60, 4
0x78,0x62,0xe1,0x03 = rldicl. 2, 3, 60, 4
// 0x78,0x62,0x01,0x00 = rldicl 2, 3, 0, 4
// 0x78,0x62,0x01,0x01 = rldicl. 2, 3, 0, 4
0x78,0x62,0x06,0xe4 = rldicr 2, 3, 0, 59
0x78,0x62,0x06,0xe5 = rldicr. 2, 3, 0, 59
0x78,0x62,0x20,0x48 = rldic 2, 3, 4, 1
0x78,0x62,0x20,0x49 = rldic. 2, 3, 4, 1
0x54,0x62,0x28,0x06 = rlwinm 2, 3, 5, 0, 3
0x54,0x62,0x28,0x07 = rlwinm. 2, 3, 5, 0, 3
0x54,0x62,0x4f,0x3e = rlwinm 2, 3, 9, 28, 31
0x54,0x62,0x4f,0x3f = rlwinm. 2, 3, 9, 28, 31
0x50,0x62,0xd9,0x50 = rlwimi 2, 3, 27, 5, 8
0x50,0x62,0xd9,0x51 = rlwimi. 2, 3, 27, 5, 8
0x50,0x62,0xb9,0x50 = rlwimi 2, 3, 23, 5, 8
0x50,0x62,0xb9,0x51 = rlwimi. 2, 3, 23, 5, 8
// 0x54,0x62,0x20,0x3e = rlwinm 2, 3, 4, 0, 31
// 0x54,0x62,0x20,0x3f = rlwinm. 2, 3, 4, 0, 31
// 0x54,0x62,0xe0,0x3e = rlwinm 2, 3, 28, 0, 31
// 0x54,0x62,0xe0,0x3f = rlwinm. 2, 3, 28, 0, 31
// 0x5c,0x62,0x20,0x3e = rlwnm 2, 3, 4, 0, 31
// 0x5c,0x62,0x20,0x3f = rlwnm. 2, 3, 4, 0, 31
0x54,0x62,0x20,0x36 = slwi 2, 3, 4
0x54,0x62,0x20,0x37 = rlwinm. 2, 3, 4, 0, 27
0x54,0x62,0xe1,0x3e = srwi 2, 3, 4
0x54,0x62,0xe1,0x3f = rlwinm. 2, 3, 28, 4, 31
// 0x54,0x62,0x01,0x3e = rlwinm 2, 3, 0, 4, 31
// 0x54,0x62,0x01,0x3f = rlwinm. 2, 3, 0, 4, 31
0x54,0x62,0x00,0x36 = rlwinm 2, 3, 0, 0, 27
0x54,0x62,0x00,0x37 = rlwinm. 2, 3, 0, 0, 27
0x54,0x62,0x20,0x76 = rlwinm 2, 3, 4, 1, 27
0x54,0x62,0x20,0x77 = rlwinm. 2, 3, 4, 1, 27
// 0x7c,0x41,0x03,0xa6 = mtspr 1, 2
// 0x7c,0x41,0x02,0xa6 = mfspr 2, 1
0x7c,0x48,0x03,0xa6 = mtlr 2
0x7c,0x48,0x02,0xa6 = mflr 2
0x7c,0x49,0x03,0xa6 = mtctr 2
0x7c,0x49,0x02,0xa6 = mfctr 2
0x60,0x00,0x00,0x00 = nop
// 0x68,0x00,0x00,0x00 = xori 0, 0, 0
0x38,0x40,0x00,0x80 = li 2, 128
0x3c,0x40,0x00,0x80 = lis 2, 128
0x7c,0x62,0x1b,0x78 = mr 2, 3
0x7c,0x62,0x1b,0x79 = or. 2, 3, 3
0x7c,0x62,0x18,0xf8 = nor 2, 3, 3
0x7c,0x62,0x18,0xf9 = nor. 2, 3, 3
0x7c,0x4f,0xf1,0x20 = mtcrf 255, 2
| |
// Copyright 2013-2015 Serilog Contributors
//
// 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Serilog.Context;
using Serilog.Core;
using Serilog.Core.Enrichers;
using Serilog.Debugging;
using Serilog.Events;
namespace Serilog.Configuration
{
/// <summary>
/// Controls enrichment configuration.
/// </summary>
public class LoggerEnrichmentConfiguration
{
readonly LoggerConfiguration _loggerConfiguration;
readonly Action<ILogEventEnricher> _addEnricher;
internal LoggerEnrichmentConfiguration(
LoggerConfiguration loggerConfiguration,
Action<ILogEventEnricher> addEnricher)
{
_loggerConfiguration = loggerConfiguration ?? throw new ArgumentNullException(nameof(loggerConfiguration));
_addEnricher = addEnricher ?? throw new ArgumentNullException(nameof(addEnricher));
}
/// <summary>
/// Specifies one or more enrichers that may add properties dynamically to
/// log events.
/// </summary>
/// <param name="enrichers">Enrichers to apply to all events passing through
/// the logger.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="enrichers"/> is <code>null</code></exception>
/// <exception cref="ArgumentException">When any element of <paramref name="enrichers"/> is <code>null</code></exception>
public LoggerConfiguration With(params ILogEventEnricher[] enrichers)
{
if (enrichers == null) throw new ArgumentNullException(nameof(enrichers));
foreach (var logEventEnricher in enrichers)
{
if (logEventEnricher == null) throw new ArgumentException("Null enricher is not allowed.");
_addEnricher(logEventEnricher);
}
return _loggerConfiguration;
}
/// <summary>
/// Specifies an enricher that may add properties dynamically to
/// log events.
/// </summary>
/// <typeparam name="TEnricher">Enricher type to apply to all events passing through
/// the logger.</typeparam>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration With<TEnricher>()
where TEnricher : ILogEventEnricher, new()
{
return With(new TEnricher());
}
/// <summary>
/// Include the specified property value in all events logged to the logger.
/// </summary>
/// <param name="name">The name of the property to add.</param>
/// <param name="value">The property value to add.</param>
/// <param name="destructureObjects">If true, objects of unknown type will be logged as structures; otherwise they will be converted using <see cref="object.ToString"/>.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration WithProperty(string name, object value, bool destructureObjects = false)
{
return With(new PropertyEnricher(name, value, destructureObjects));
}
/// <summary>
/// Enrich log events with properties from <see cref="Context.LogContext"/>.
/// </summary>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>Configuration object allowing method chaining.</returns>
public LoggerConfiguration FromLogContext() => With<LogContextEnricher>();
/// <summary>
/// Apply an enricher only when <paramref name="condition"/> evaluates to <c>true</c>.
/// </summary>
/// <param name="condition">A predicate that evaluates to <c>true</c> when the supplied <see cref="LogEvent"/>
/// should be enriched.</param>
/// <param name="configureEnricher">An action that configures the wrapped enricher.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="condition"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="configureEnricher"/> is <code>null</code></exception>
public LoggerConfiguration When(Func<LogEvent, bool> condition, Action<LoggerEnrichmentConfiguration> configureEnricher)
{
if (condition == null) throw new ArgumentNullException(nameof(condition));
if (configureEnricher == null) throw new ArgumentNullException(nameof(configureEnricher));
return Wrap(this, e => new ConditionalEnricher(e, condition), configureEnricher);
}
/// <summary>
/// Apply an enricher only to events with a <see cref="LogEventLevel"/> greater than or equal to <paramref name="enrichFromLevel"/>.
/// </summary>
/// <param name="enrichFromLevel">The level from which the enricher will be applied.</param>
/// <param name="configureEnricher">An action that configures the wrapped enricher.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <remarks>This method permits additional information to be attached to e.g. warnings and errors, that might be too expensive
/// to collect or store at lower levels.</remarks>
/// <exception cref="ArgumentNullException">When <paramref name="configureEnricher"/> is <code>null</code></exception>
public LoggerConfiguration AtLevel(LogEventLevel enrichFromLevel, Action<LoggerEnrichmentConfiguration> configureEnricher)
{
if (configureEnricher == null) throw new ArgumentNullException(nameof(configureEnricher));
return Wrap(this, e => new ConditionalEnricher(e, le => le.Level >= enrichFromLevel), configureEnricher);
}
/// <summary>
/// Apply an enricher only to events with a <see cref="LogEventLevel"/> greater than or equal to the level specified by <paramref name="levelSwitch"/>.
/// </summary>
/// <param name="levelSwitch">A <see cref="LoggingLevelSwitch"/> that specifies the level from which the enricher will be applied.</param>
/// <param name="configureEnricher">An action that configures the wrapped enricher.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <remarks>This method permits additional information to be attached to e.g. warnings and errors, that might be too expensive
/// to collect or store at lower levels.</remarks>
/// <exception cref="ArgumentNullException">When <paramref name="configureEnricher"/> is <code>null</code></exception>
public LoggerConfiguration AtLevel(LoggingLevelSwitch levelSwitch, Action<LoggerEnrichmentConfiguration> configureEnricher)
{
if (configureEnricher == null) throw new ArgumentNullException(nameof(configureEnricher));
return Wrap(this, e => new ConditionalEnricher(e, le => le.Level >= levelSwitch.MinimumLevel), configureEnricher);
}
/// <summary>
/// Helper method for wrapping sinks.
/// </summary>
/// <param name="loggerEnrichmentConfiguration">The parent enrichment configuration.</param>
/// <param name="wrapEnricher">A function that allows for wrapping <see cref="ILogEventEnricher"/>s
/// added in <paramref name="configureWrappedEnricher"/>.</param>
/// <param name="configureWrappedEnricher">An action that configures enrichers to be wrapped in <paramref name="wrapEnricher"/>.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="loggerEnrichmentConfiguration"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="wrapEnricher"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="configureWrappedEnricher"/> is <code>null</code></exception>
public static LoggerConfiguration Wrap(
LoggerEnrichmentConfiguration loggerEnrichmentConfiguration,
Func<ILogEventEnricher, ILogEventEnricher> wrapEnricher,
Action<LoggerEnrichmentConfiguration> configureWrappedEnricher)
{
if (loggerEnrichmentConfiguration == null) throw new ArgumentNullException(nameof(loggerEnrichmentConfiguration));
if (wrapEnricher == null) throw new ArgumentNullException(nameof(wrapEnricher));
if (configureWrappedEnricher == null) throw new ArgumentNullException(nameof(configureWrappedEnricher));
var enrichersToWrap = new List<ILogEventEnricher>();
var capturingConfiguration = new LoggerConfiguration();
var capturingLoggerEnrichmentConfiguration = new LoggerEnrichmentConfiguration(
capturingConfiguration,
enrichersToWrap.Add);
// `Enrich.With()` will return the capturing configuration; this ensures chained `Enrich` gets back
// to the capturing enrichment configuration, enabling `Enrich.WithX().Enrich.WithY()`.
capturingConfiguration.Enrich = capturingLoggerEnrichmentConfiguration;
configureWrappedEnricher(capturingLoggerEnrichmentConfiguration);
if (enrichersToWrap.Count == 0)
return loggerEnrichmentConfiguration._loggerConfiguration;
var enclosed = enrichersToWrap.Count == 1 ?
enrichersToWrap.Single() :
// Enrichment failures are not considered blocking for auditing purposes.
new SafeAggregateEnricher(enrichersToWrap);
var wrappedEnricher = wrapEnricher(enclosed);
// ReSharper disable once SuspiciousTypeConversion.Global
if (!(wrappedEnricher is IDisposable))
{
SelfLog.WriteLine("Wrapping enricher {0} does not implement IDisposable; to ensure " +
"wrapped enrichers are properly disposed, wrappers should dispose " +
"their wrapped contents", wrappedEnricher);
}
return loggerEnrichmentConfiguration.With(wrappedEnricher);
}
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Environment.ObjectState
{
/// <summary>
/// Enumeration values for MinefieldLaneMarker (env.obj.appear.linear.marker, Minefield Lane Marker,
/// section 12.1.2.3.3)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public struct MinefieldLaneMarker
{
/// <summary>
/// Describes the side of the lane marker which is visible.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Describes the side of the lane marker which is visible.")]
public enum VisibleSideValue : uint
{
/// <summary>
/// Left side is visible
/// </summary>
LeftSideIsVisible = 0,
/// <summary>
/// Right side is visible
/// </summary>
RightSideIsVisible = 1,
/// <summary>
/// Both sides are visible
/// </summary>
BothSidesAreVisible = 2,
/// <summary>
/// null
/// </summary>
Unknown = 3
}
private MinefieldLaneMarker.VisibleSideValue visibleSide;
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(MinefieldLaneMarker left, MinefieldLaneMarker right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(MinefieldLaneMarker left, MinefieldLaneMarker right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
// If parameters are null return false (cast to object to prevent recursive loop!)
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
/// <summary>
/// Performs an explicit conversion from <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> to <see cref="System.UInt32"/>.
/// </summary>
/// <param name="obj">The <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> scheme instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator uint(MinefieldLaneMarker obj)
{
return obj.ToUInt32();
}
/// <summary>
/// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/>.
/// </summary>
/// <param name="value">The uint value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator MinefieldLaneMarker(uint value)
{
return MinefieldLaneMarker.FromUInt32(value);
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance from the byte array.
/// </summary>
/// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/>.</param>
/// <param name="index">The starting position within value.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance, represented by a byte array.</returns>
/// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception>
/// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception>
public static MinefieldLaneMarker FromByteArray(byte[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (index < 0 ||
index > array.Length - 1 ||
index + 4 > array.Length - 1)
{
throw new IndexOutOfRangeException();
}
return FromUInt32(BitConverter.ToUInt32(array, index));
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance from the uint value.
/// </summary>
/// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance, represented by the uint value.</returns>
public static MinefieldLaneMarker FromUInt32(uint value)
{
MinefieldLaneMarker ps = new MinefieldLaneMarker();
uint mask0 = 0x30000;
byte shift0 = 16;
uint newValue0 = value & mask0 >> shift0;
ps.VisibleSide = (MinefieldLaneMarker.VisibleSideValue)newValue0;
return ps;
}
/// <summary>
/// Gets or sets the visibleside.
/// </summary>
/// <value>The visibleside.</value>
public MinefieldLaneMarker.VisibleSideValue VisibleSide
{
get { return this.visibleSide; }
set { this.visibleSide = value; }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!(obj is MinefieldLaneMarker))
{
return false;
}
return this.Equals((MinefieldLaneMarker)obj);
}
/// <summary>
/// Determines whether the specified <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(MinefieldLaneMarker other)
{
// If parameter is null return false (cast to object to prevent recursive loop!)
if ((object)other == null)
{
return false;
}
return
this.VisibleSide == other.VisibleSide;
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> to the byte array.
/// </summary>
/// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance.</returns>
public byte[] ToByteArray()
{
return BitConverter.GetBytes(this.ToUInt32());
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> to the uint value.
/// </summary>
/// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.Environment.ObjectState.MinefieldLaneMarker"/> instance.</returns>
public uint ToUInt32()
{
uint val = 0;
val |= (uint)((uint)this.VisibleSide << 16);
return val;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
int hash = 17;
// Overflow is fine, just wrap
unchecked
{
hash = (hash * 29) + this.VisibleSide.GetHashCode();
}
return hash;
}
}
}
| |
// 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.Globalization;
using System.Runtime.Tests.Common;
using Xunit;
public static class UInt32Tests
{
[Fact]
public static void TestCtorEmpty()
{
uint i = new uint();
Assert.Equal((uint)0, i);
}
[Fact]
public static void TestCtorValue()
{
uint i = 41;
Assert.Equal((uint)41, i);
}
[Fact]
public static void TestMaxValue()
{
Assert.Equal(0xFFFFFFFF, uint.MaxValue);
}
[Fact]
public static void TestMinValue()
{
Assert.Equal((uint)0, uint.MinValue);
}
[Theory]
[InlineData((uint)234, 0)]
[InlineData(uint.MinValue, 1)]
[InlineData((uint)0, 1)]
[InlineData((uint)45, 1)]
[InlineData((uint)123, 1)]
[InlineData((uint)456, -1)]
[InlineData(uint.MaxValue, -1)]
public static void TestCompareTo(uint value, int expected)
{
uint i = 234;
int result = CompareHelper.NormalizeCompare(i.CompareTo(value));
Assert.Equal(expected, result);
}
[Theory]
[InlineData(null, 1)]
[InlineData((uint)234, 0)]
[InlineData(uint.MinValue, 1)]
[InlineData((uint)0, 1)]
[InlineData((uint)45, 1)]
[InlineData((uint)123, 1)]
[InlineData((uint)456, -1)]
[InlineData(uint.MaxValue, -1)]
public static void TestCompareToObject(object obj, int expected)
{
IComparable comparable = (uint)234;
int i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj));
Assert.Equal(expected, i);
}
[Fact]
public static void TestCompareToObjectInvalid()
{
IComparable comparable = (uint)234;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a byte
}
[Theory]
[InlineData((uint)789, true)]
[InlineData((uint)0, false)]
public static void TestEqualsObject(object obj, bool expected)
{
uint i = 789;
Assert.Equal(expected, i.Equals(obj));
}
[Theory]
[InlineData((uint)789, true)]
[InlineData((uint)0, false)]
public static void TestEquals(uint i2, bool expected)
{
uint i = 789;
Assert.Equal(expected, i.Equals(i2));
}
[Fact]
public static void TestGetHashCode()
{
uint i1 = 123;
uint i2 = 654;
Assert.NotEqual(0, i1.GetHashCode());
Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
}
[Fact]
public static void TestToString()
{
uint i1 = 6310;
Assert.Equal("6310", i1.ToString());
}
[Fact]
public static void TestToStringFormatProvider()
{
var numberFormat = new NumberFormatInfo();
uint i1 = 6310;
Assert.Equal("6310", i1.ToString(numberFormat));
}
[Fact]
public static void TestToStringFormat()
{
uint i1 = 6310;
Assert.Equal("6310", i1.ToString("G"));
uint i2 = 8249;
Assert.Equal("8249", i2.ToString("g"));
uint i3 = 2468;
Assert.Equal(string.Format("{0:N}", 2468.00), i3.ToString("N"));
uint i4 = 0x248;
Assert.Equal("248", i4.ToString("x"));
}
[Fact]
public static void TestToStringFormatFormatProvider()
{
var numberFormat = new NumberFormatInfo();
uint i1 = 6310;
Assert.Equal("6310", i1.ToString("G", numberFormat));
uint i2 = 8249;
Assert.Equal("8249", i2.ToString("g", numberFormat));
numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
numberFormat.NumberGroupSeparator = "*";
numberFormat.NumberNegativePattern = 0;
uint i3 = 2468;
Assert.Equal("2*468.00", i3.ToString("N", numberFormat));
}
public static IEnumerable<object[]> ParseValidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
yield return new object[] { "0", defaultStyle, defaultFormat, (uint)0 };
yield return new object[] { "123", defaultStyle, defaultFormat, (uint)123 };
yield return new object[] { " 123 ", defaultStyle, defaultFormat, (uint)123 };
yield return new object[] { "4294967295", defaultStyle, defaultFormat, (uint)4294967295 };
yield return new object[] { "12", NumberStyles.HexNumber, defaultFormat, (uint)0x12 };
yield return new object[] { "1000", NumberStyles.AllowThousands, defaultFormat, (uint)1000 };
yield return new object[] { "123", defaultStyle, emptyNfi, (uint)123 };
yield return new object[] { "123", NumberStyles.Any, emptyNfi, (uint)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyNfi, (uint)0x12 };
yield return new object[] { "abc", NumberStyles.HexNumber, emptyNfi, (uint)0xabc };
yield return new object[] { "$1,000", NumberStyles.Currency, testNfi, (uint)1000 };
}
public static IEnumerable<object[]> ParseInvalidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
testNfi.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, defaultFormat, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { " ", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, defaultFormat, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, defaultFormat, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, defaultFormat, typeof(FormatException) }; // Parentheses
yield return new object[] { 100.ToString("C0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, defaultFormat, typeof(FormatException) }; //Decimal
yield return new object[] { "abc", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Negative hex value
yield return new object[] { " 123 ", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "678.90", defaultStyle, testNfi, typeof(FormatException) }; // Decimal
yield return new object[] { "-1", defaultStyle, defaultFormat, typeof(OverflowException) }; // < min value
yield return new object[] { "4294967296", defaultStyle, defaultFormat, typeof(OverflowException) }; // > max value
yield return new object[] { "(123)", NumberStyles.AllowParentheses, defaultFormat, typeof(OverflowException) }; // Parentheses = negative
}
[Theory, MemberData(nameof(ParseValidData))]
public static void TestParse(string value, NumberStyles style, NumberFormatInfo nfi, uint expected)
{
uint i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(true, uint.TryParse(value, out i));
Assert.Equal(expected, i);
Assert.Equal(expected, uint.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Equal(expected, uint.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(true, uint.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(expected, i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Equal(expected, uint.Parse(value, style));
}
Assert.Equal(expected, uint.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
[Theory, MemberData(nameof(ParseInvalidData))]
public static void TestParseInvalid(string value, NumberStyles style, NumberFormatInfo nfi, Type exceptionType)
{
uint i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(false, uint.TryParse(value, out i));
Assert.Equal(default(uint), i);
Assert.Throws(exceptionType, () => uint.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Throws(exceptionType, () => uint.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(false, uint.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(default(uint), i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Throws(exceptionType, () => uint.Parse(value, style));
}
Assert.Throws(exceptionType, () => uint.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForPropertiesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new UseExpressionBodyForPropertiesDiagnosticAnalyzer(), new UseExpressionBodyForPropertiesCodeFixProvider());
private static readonly Dictionary<OptionKey, object> UseExpressionBody =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CodeStyleOptions.TrueWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement },
};
private static readonly Dictionary<OptionKey, object> UseBlockBody =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CodeStyleOptions.FalseWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement }
};
private static readonly Dictionary<OptionKey, object> UseBlockBodyExceptAccessor =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CodeStyleOptions.FalseWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.TrueWithNoneEnforcement }
};
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get
{
[|return|] Bar();
}
}
}",
@"class C
{
int Foo => Bar();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingWithSetter()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int Foo
{
get
{
[|return|] Bar();
}
set
{
}
}
}", new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingWithAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int Foo
{
[A]
get
{
[|return|] Bar();
}
}
}", new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingOnSetter1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int Foo
{
set
{
[|Bar|]();
}
}
}", new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get
{
[|throw|] new NotImplementedException();
}
}
}",
@"class C
{
int Foo => throw new NotImplementedException();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo
{
get
{
[|throw|] new NotImplementedException(); // comment
}
}
}",
@"class C
{
int Foo => throw new NotImplementedException(); // comment
}", ignoreTrivia: false, options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo [|=>|] Bar();
}",
@"class C
{
int Foo
{
get
{
return Bar();
}
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBodyIfAccessorWantExpression1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo [|=>|] Bar();
}",
@"class C
{
int Foo
{
get => Bar();
}
}", options: UseBlockBodyExceptAccessor);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo [|=>|] throw new NotImplementedException();
}",
@"class C
{
int Foo
{
get
{
throw new NotImplementedException();
}
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int Foo [|=>|] throw new NotImplementedException(); // comment
}",
@"class C
{
int Foo
{
get
{
throw new NotImplementedException(); // comment
}
}
}", ignoreTrivia: false, options: UseBlockBody);
}
[WorkItem(16386, "https://github.com/dotnet/roslyn/issues/16386")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBodyKeepTrailingTrivia()
{
await TestInRegularAndScriptAsync(
@"class C
{
private string _prop = ""HELLO THERE!"";
public string Prop { get { [|return|] _prop; } }
public string OtherThing => ""Pickles"";
}",
@"class C
{
private string _prop = ""HELLO THERE!"";
public string Prop => _prop;
public string OtherThing => ""Pickles"";
}", ignoreTrivia: false, options: UseExpressionBody);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// BuildResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Serverless.V1.Service
{
public class BuildResource : Resource
{
public sealed class StatusEnum : StringEnum
{
private StatusEnum(string value) : base(value) {}
public StatusEnum() {}
public static implicit operator StatusEnum(string value)
{
return new StatusEnum(value);
}
public static readonly StatusEnum Building = new StatusEnum("building");
public static readonly StatusEnum Completed = new StatusEnum("completed");
public static readonly StatusEnum Failed = new StatusEnum("failed");
}
public sealed class RuntimeEnum : StringEnum
{
private RuntimeEnum(string value) : base(value) {}
public RuntimeEnum() {}
public static implicit operator RuntimeEnum(string value)
{
return new RuntimeEnum(value);
}
public static readonly RuntimeEnum Node8 = new RuntimeEnum("node8");
public static readonly RuntimeEnum Node10 = new RuntimeEnum("node10");
public static readonly RuntimeEnum Node12 = new RuntimeEnum("node12");
public static readonly RuntimeEnum Node14 = new RuntimeEnum("node14");
}
private static Request BuildReadRequest(ReadBuildOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Serverless,
"/v1/Services/" + options.PathServiceSid + "/Builds",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Builds.
/// </summary>
/// <param name="options"> Read Build parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Build </returns>
public static ResourceSet<BuildResource> Read(ReadBuildOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<BuildResource>.FromJson("builds", response.Content);
return new ResourceSet<BuildResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Builds.
/// </summary>
/// <param name="options"> Read Build parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Build </returns>
public static async System.Threading.Tasks.Task<ResourceSet<BuildResource>> ReadAsync(ReadBuildOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<BuildResource>.FromJson("builds", response.Content);
return new ResourceSet<BuildResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Builds.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the Build resources from </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Build </returns>
public static ResourceSet<BuildResource> Read(string pathServiceSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadBuildOptions(pathServiceSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Builds.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the Build resources from </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Build </returns>
public static async System.Threading.Tasks.Task<ResourceSet<BuildResource>> ReadAsync(string pathServiceSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadBuildOptions(pathServiceSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<BuildResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<BuildResource>.FromJson("builds", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<BuildResource> NextPage(Page<BuildResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Serverless)
);
var response = client.Request(request);
return Page<BuildResource>.FromJson("builds", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<BuildResource> PreviousPage(Page<BuildResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Serverless)
);
var response = client.Request(request);
return Page<BuildResource>.FromJson("builds", response.Content);
}
private static Request BuildFetchRequest(FetchBuildOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Serverless,
"/v1/Services/" + options.PathServiceSid + "/Builds/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a specific Build resource.
/// </summary>
/// <param name="options"> Fetch Build parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Build </returns>
public static BuildResource Fetch(FetchBuildOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Retrieve a specific Build resource.
/// </summary>
/// <param name="options"> Fetch Build parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Build </returns>
public static async System.Threading.Tasks.Task<BuildResource> FetchAsync(FetchBuildOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Retrieve a specific Build resource.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the Build resource from </param>
/// <param name="pathSid"> The SID of the Build resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Build </returns>
public static BuildResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchBuildOptions(pathServiceSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a specific Build resource.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the Build resource from </param>
/// <param name="pathSid"> The SID of the Build resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Build </returns>
public static async System.Threading.Tasks.Task<BuildResource> FetchAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchBuildOptions(pathServiceSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteBuildOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Serverless,
"/v1/Services/" + options.PathServiceSid + "/Builds/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Delete a Build resource.
/// </summary>
/// <param name="options"> Delete Build parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Build </returns>
public static bool Delete(DeleteBuildOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// Delete a Build resource.
/// </summary>
/// <param name="options"> Delete Build parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Build </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteBuildOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// Delete a Build resource.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the Build resource from </param>
/// <param name="pathSid"> The SID of the Build resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Build </returns>
public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteBuildOptions(pathServiceSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Delete a Build resource.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the Build resource from </param>
/// <param name="pathSid"> The SID of the Build resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Build </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteBuildOptions(pathServiceSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateBuildOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Serverless,
"/v1/Services/" + options.PathServiceSid + "/Builds",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a new Build resource. At least one function version or asset version is required.
/// </summary>
/// <param name="options"> Create Build parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Build </returns>
public static BuildResource Create(CreateBuildOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a new Build resource. At least one function version or asset version is required.
/// </summary>
/// <param name="options"> Create Build parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Build </returns>
public static async System.Threading.Tasks.Task<BuildResource> CreateAsync(CreateBuildOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a new Build resource. At least one function version or asset version is required.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the Build resource under </param>
/// <param name="assetVersions"> The list of Asset Version resource SIDs to include in the Build </param>
/// <param name="functionVersions"> The list of the Function Version resource SIDs to include in the Build </param>
/// <param name="dependencies"> A list of objects that describe the Dependencies included in the Build </param>
/// <param name="runtime"> The Runtime version that will be used to run the Build. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Build </returns>
public static BuildResource Create(string pathServiceSid,
List<string> assetVersions = null,
List<string> functionVersions = null,
string dependencies = null,
string runtime = null,
ITwilioRestClient client = null)
{
var options = new CreateBuildOptions(pathServiceSid){AssetVersions = assetVersions, FunctionVersions = functionVersions, Dependencies = dependencies, Runtime = runtime};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a new Build resource. At least one function version or asset version is required.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the Build resource under </param>
/// <param name="assetVersions"> The list of Asset Version resource SIDs to include in the Build </param>
/// <param name="functionVersions"> The list of the Function Version resource SIDs to include in the Build </param>
/// <param name="dependencies"> A list of objects that describe the Dependencies included in the Build </param>
/// <param name="runtime"> The Runtime version that will be used to run the Build. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Build </returns>
public static async System.Threading.Tasks.Task<BuildResource> CreateAsync(string pathServiceSid,
List<string> assetVersions = null,
List<string> functionVersions = null,
string dependencies = null,
string runtime = null,
ITwilioRestClient client = null)
{
var options = new CreateBuildOptions(pathServiceSid){AssetVersions = assetVersions, FunctionVersions = functionVersions, Dependencies = dependencies, Runtime = runtime};
return await CreateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a BuildResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> BuildResource object represented by the provided JSON </returns>
public static BuildResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<BuildResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the Build resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the Build resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Service that the Build resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The status of the Build
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public BuildResource.StatusEnum Status { get; private set; }
/// <summary>
/// The list of Asset Version resource SIDs that are included in the Build
/// </summary>
[JsonProperty("asset_versions")]
public List<object> AssetVersions { get; private set; }
/// <summary>
/// The list of Function Version resource SIDs that are included in the Build
/// </summary>
[JsonProperty("function_versions")]
public List<object> FunctionVersions { get; private set; }
/// <summary>
/// A list of objects that describe the Dependencies included in the Build
/// </summary>
[JsonProperty("dependencies")]
public List<object> Dependencies { get; private set; }
/// <summary>
/// The Runtime version that will be used to run the Build.
/// </summary>
[JsonProperty("runtime")]
[JsonConverter(typeof(StringEnumConverter))]
public BuildResource.RuntimeEnum Runtime { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the Build resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the Build resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The absolute URL of the Build resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The links
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private BuildResource()
{
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
/// <summary>
/// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it
/// easier to split the class into abstract and implementation classes if desired.)
/// </summary>
internal sealed partial class X509Pal : IX509Pal
{
public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages)
{
unsafe
{
ushort keyUsagesAsShort = (ushort)keyUsages;
CRYPT_BIT_BLOB blob = new CRYPT_BIT_BLOB()
{
cbData = 2,
pbData = (byte*)&keyUsagesAsShort,
cUnusedBits = 0,
};
return Interop.crypt32.EncodeObject(CryptDecodeObjectStructType.X509_KEY_USAGE, &blob);
}
}
public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages)
{
unsafe
{
uint keyUsagesAsUint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_KEY_USAGE,
delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CRYPT_BIT_BLOB));
CRYPT_BIT_BLOB* pBlob = (CRYPT_BIT_BLOB*)pvDecoded;
keyUsagesAsUint = 0;
byte* pbData = pBlob->pbData;
if (pbData != null)
{
Debug.Assert((uint)pBlob->cbData < 3, "Unexpected length for X509_KEY_USAGE data");
switch (pBlob->cbData)
{
case 1:
keyUsagesAsUint = *pbData;
break;
case 2:
keyUsagesAsUint = *(ushort*)(pbData);
break;
}
}
}
);
keyUsages = (X509KeyUsageFlags)keyUsagesAsUint;
}
}
public bool SupportsLegacyBasicConstraintsExtension
{
get { return true; }
}
public byte[] EncodeX509BasicConstraints2Extension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint)
{
unsafe
{
CERT_BASIC_CONSTRAINTS2_INFO constraintsInfo = new CERT_BASIC_CONSTRAINTS2_INFO()
{
fCA = certificateAuthority ? 1 : 0,
fPathLenConstraint = hasPathLengthConstraint ? 1 : 0,
dwPathLenConstraint = pathLengthConstraint,
};
return Interop.crypt32.EncodeObject(Oids.BasicConstraints2, &constraintsInfo);
}
}
public void DecodeX509BasicConstraintsExtension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint)
{
unsafe
{
bool localCertificateAuthority = false;
bool localHasPathLengthConstraint = false;
int localPathLengthConstraint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS,
delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_BASIC_CONSTRAINTS_INFO));
CERT_BASIC_CONSTRAINTS_INFO* pBasicConstraints = (CERT_BASIC_CONSTRAINTS_INFO*)pvDecoded;
localCertificateAuthority = (pBasicConstraints->SubjectType.pbData[0] & CERT_BASIC_CONSTRAINTS_INFO.CERT_CA_SUBJECT_FLAG) != 0;
localHasPathLengthConstraint = pBasicConstraints->fPathLenConstraint != 0;
localPathLengthConstraint = pBasicConstraints->dwPathLenConstraint;
}
);
certificateAuthority = localCertificateAuthority;
hasPathLengthConstraint = localHasPathLengthConstraint;
pathLengthConstraint = localPathLengthConstraint;
}
}
public void DecodeX509BasicConstraints2Extension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint)
{
unsafe
{
bool localCertificateAuthority = false;
bool localHasPathLengthConstraint = false;
int localPathLengthConstraint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS2,
delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_BASIC_CONSTRAINTS2_INFO));
CERT_BASIC_CONSTRAINTS2_INFO* pBasicConstraints2 = (CERT_BASIC_CONSTRAINTS2_INFO*)pvDecoded;
localCertificateAuthority = pBasicConstraints2->fCA != 0;
localHasPathLengthConstraint = pBasicConstraints2->fPathLenConstraint != 0;
localPathLengthConstraint = pBasicConstraints2->dwPathLenConstraint;
}
);
certificateAuthority = localCertificateAuthority;
hasPathLengthConstraint = localHasPathLengthConstraint;
pathLengthConstraint = localPathLengthConstraint;
}
}
public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
{
int numUsages;
using (SafeHandle usagesSafeHandle = usages.ToLpstrArray(out numUsages))
{
unsafe
{
CERT_ENHKEY_USAGE enhKeyUsage = new CERT_ENHKEY_USAGE()
{
cUsageIdentifier = numUsages,
rgpszUsageIdentifier = (IntPtr*)(usagesSafeHandle.DangerousGetHandle()),
};
return Interop.crypt32.EncodeObject(Oids.EnhancedKeyUsage, &enhKeyUsage);
}
}
}
public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages)
{
OidCollection localUsages = new OidCollection();
unsafe
{
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE,
delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_ENHKEY_USAGE));
CERT_ENHKEY_USAGE* pEnhKeyUsage = (CERT_ENHKEY_USAGE*)pvDecoded;
int count = pEnhKeyUsage->cUsageIdentifier;
for (int i = 0; i < count; i++)
{
IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i];
string oidValue = Marshal.PtrToStringAnsi(oidValuePointer);
Oid oid = new Oid(oidValue);
localUsages.Add(oid);
}
}
);
}
usages = localUsages;
}
public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier)
{
unsafe
{
fixed (byte* pSubkectKeyIdentifier = subjectKeyIdentifier)
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(subjectKeyIdentifier.Length, pSubkectKeyIdentifier);
return Interop.crypt32.EncodeObject(Oids.SubjectKeyIdentifier, &blob);
}
}
}
public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier)
{
unsafe
{
byte[] localSubjectKeyIdentifier = null;
encoded.DecodeObject(
Oids.SubjectKeyIdentifier,
delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CRYPTOAPI_BLOB));
CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded;
localSubjectKeyIdentifier = pBlob->ToByteArray();
}
);
subjectKeyIdentifier = localSubjectKeyIdentifier;
}
}
public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
{
unsafe
{
fixed (byte* pszOidValue = key.Oid.ValueAsAscii())
{
byte[] encodedParameters = key.EncodedParameters.RawData;
fixed (byte* pEncodedParameters = encodedParameters)
{
byte[] encodedKeyValue = key.EncodedKeyValue.RawData;
fixed (byte* pEncodedKeyValue = encodedKeyValue)
{
CERT_PUBLIC_KEY_INFO publicKeyInfo = new CERT_PUBLIC_KEY_INFO()
{
Algorithm = new CRYPT_ALGORITHM_IDENTIFIER()
{
pszObjId = new IntPtr(pszOidValue),
Parameters = new CRYPTOAPI_BLOB(encodedParameters.Length, pEncodedParameters),
},
PublicKey = new CRYPT_BIT_BLOB()
{
cbData = encodedKeyValue.Length,
pbData = pEncodedKeyValue,
cUnusedBits = 0,
},
};
int cb = 20;
byte[] buffer = new byte[cb];
if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
if (cb < buffer.Length)
{
byte[] newBuffer = new byte[cb];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, cb);
buffer = newBuffer;
}
return buffer;
}
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using NDesk.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Runs a command and can capture or modify its console output.
/// </summary>
class CommandRunner
{
static int Main(string[] args)
{
List<string> ruleFiles = new List<string>();
List<string> commands = new List<string>();
List<string> commandFiles = new List<string>();
List<string> searchReplaceFiles = new List<string>();
var outputHandler = new OutputHandler ();
bool timeRun = false;
bool statistics = false;
bool report = false;
bool rulesOnly = false;
bool searchReplaceOnly = false;
bool showHelp = false;
bool showExampleRule = false;
bool showExampleSearchReplace = false;
bool stopOnFirstError = false;
bool sumReturnValues = false;
bool forceReturn = false;
int forceReturnValue = 0;
bool passedRuleExists = false;
OutputRule passedRule = new OutputRule();
var options = new OptionSet () {
{ "c=|command=", "Command to run", arg => commands.Add(arg)},
{ "cf=|commandfile=", "Path to text file of commands to run", arg => commandFiles.Add(arg)},
{ "fr=|forcereturn=", "Sets the return value explicitly, ignoring any command returns", arg => {
forceReturn = arg != null;
if(!int.TryParse(arg, out forceReturnValue))
{
Console.WriteLine ("ERROR - Error in options - cannot convert passed return value to integer: " + arg);
Environment.Exit(1);
}
}
},
{ "h|?|help", "Shows help and quits", arg => showHelp = arg != null },
{ "mp|matchpass", "Allows or disallows a matched rule from passing the original output line", arg => outputHandler.outputMatchPass = arg != null},
{ "mse|matchstderr", "Allows or disallows a matched rule from printing its stderr output", arg => outputHandler.outputMatchStderr = arg != null},
{ "mso|matchstdout", "Allows or disallows a matched rule from printing its stdout output", arg => outputHandler.outputMatchStdout = arg != null},
{ "p|pass", "Allows or disallows passing the original output line if it did not match any rules", arg => outputHandler.outputMissPass = arg != null},
{ "printrules", "Reads all rules, prints them in input file format, and quits", arg => rulesOnly = arg != null},
{ "printexamplerule", "Prints an example rule in input file format and quits", arg => showExampleRule = arg != null},
{ "printexamplesearchreplace", "Reads all search/replace pairs, prints them in an input file format, and quits", arg => showExampleSearchReplace = arg != null},
{ "q|quiet", "Turns off most stadard output, including: unmatched pass, match pass, match stdout, match stderr", arg => {
outputHandler.outputMissPass = arg == null;
outputHandler.outputMatchPass = arg == null;
outputHandler.outputMatchStdout = arg == null;
outputHandler.outputMatchStderr = arg == null;
}
},
{ "r|report", "Prints report output of any matched rules at the end of the command run", arg => report = arg != null},
{ "rf=|rulefile=", "Path to file of rules to match", arg => ruleFiles.Add(arg)},
{ "rme|rulematcherror", "Passed rule - allows or disallows forcing a non-zero return for the command on match", arg => {
passedRuleExists = true;
passedRule.setError = arg != null;
}
},
{ "rmp|rulematchpass", "Passed rule - allows or disallows passing original output line on match", arg => {
passedRuleExists = true;
passedRule.passOutput = arg != null;
}
},
{ "rms|rulematchstop", "Passed rule - allows or disallows stopping further rule processing on match", arg => {
passedRuleExists = true;
passedRule.stopProcessing = arg != null;
}
},
{ "rp=|rulepattern=", "Passed rule - regex pattern to match against", arg => {
passedRuleExists = true;
passedRule.pattern = arg;
}
},
{ "rpse|ruleprocessstderr", "Passed rule - allows or disallows processing stderr output lines", arg => {
passedRuleExists = true;
passedRule.processStdErr = arg != null;
}
},
{ "rpso|ruleprocessstdout", "Passed rule - allows or disallows processing stdout output lines", arg => {
passedRuleExists = true;
passedRule.processStdOut = arg != null;
}
},
{ "rr=|rulereport=", "Passed rule - report output format on match", arg => {
passedRuleExists = true;
passedRule.reportFormat = arg;
}
},
{ "rse=|rulestderr=", "Passed rule - stderr output format on match", arg => {
passedRuleExists = true;
passedRule.stderrFormat = arg;
}
},
{ "rso=|rulestdout=", "Passed rule - stdout output format on match", arg => {
passedRuleExists = true;
passedRule.stdoutFormat = arg;
}
},
{ "rsp=|ruleshortpattern=", "Passed rule - short regex pattern to match against first for expensive rule patterns", arg => {
passedRuleExists = true;
passedRule.shortPattern = arg;
}
},
{ "s|stats", "Shows statistics for rules", arg => statistics = arg != null},
{ "srf=|searchreplacefile=", "Path to file of search/replace pairs", arg => searchReplaceFiles.Add(arg)},
{ "stoponerror", "When running multiple commands, stop execution after first error", arg => stopOnFirstError = arg != null},
{ "sumreturns", "When running multiple commands, set final return value to sum of all subcommand return values", arg => sumReturnValues = arg != null},
{ "t|time", "Shows processing time", arg => timeRun = arg != null},
};
string[] otherArgs = null;
try
{
otherArgs = options.Parse(args).ToArray();
}
catch (NDesk.Options.OptionException e)
{
Console.WriteLine ("ERROR - Error in options - " + e.Message);
Environment.Exit(1);
}
catch (System.ArgumentNullException e)
{
Console.WriteLine ("ERROR - Error in options - " + e.Message);
Environment.Exit(1);
}
if (showHelp)
{
ShowHelp (options);
Environment.Exit(0);
}
if (showExampleRule)
{
OutputRule exampleRule = new OutputRule();
exampleRule.title = "Example Report Rule";
exampleRule.description = "A rule that matches an input string from dir, shows a shortPattern to reduce misses on expensive patterns, shows parsing, and creates a report entry.";
exampleRule.example = @" Directory of D:\projects\CommandRunner";
exampleRule.pattern = "^ Directory of ([a-zA-Z]):(.+)$";
exampleRule.shortPattern = "Directory";
exampleRule.reportFormat = "Drive: {1}\nFolder: {2}";
exampleRule.stopProcessing = false;
OutputRule exampleRule2 = new OutputRule();
exampleRule2.title = "Example Error Rule";
exampleRule2.description = "A rule that matches an input string from dir and marks the command as an error (making sure the command returns a non-zero value) if run on drive D.";
exampleRule2.example = @" Directory of D:\projects\CommandRunner";
exampleRule2.pattern = "^ Directory of D:.+$";
exampleRule2.stderrFormat = "\n**********\nERROR - This was run on drive D.\n**********\n";
exampleRule2.stopProcessing = true;
exampleRule2.setError = true;
List<OutputRule> exampleRuleList = new List<OutputRule>(){exampleRule, exampleRule2};
Console.Write (JsonConvert.SerializeObject(exampleRuleList, Formatting.Indented));
Environment.Exit(0);
}
if (showExampleSearchReplace)
{
Dictionary<string, OrderedDictionary> exampleReplacements = new Dictionary<string, OrderedDictionary>();
exampleReplacements["html_reserved"] = new OrderedDictionary {
{"$", "%24"},
{"&", "%26"},
{"+", "%2B"},
{",", "%2C"},
{"/", "%2F"},
{":", "%3A"},
{";", "%3B"},
{"=", "%3D"},
{"?", "%3F"},
{"@", "%40"},
};
exampleReplacements["html_unsafe"] = new OrderedDictionary {
{"%", "%25"},
{"<", "%3C"},
{">", "%3E"},
{" ", "%20"},
{"#", "%23"},
{"{", "%7B"},
{"}", "%7D"},
{"|", "%7C"},
{"\\", "%5C"},
{"^", "%5E"},
{"~", "%7E"},
{"[", "%5B"},
{"]", "%5D"},
{"`", "%60"},
};
Console.Write (JsonConvert.SerializeObject(exampleReplacements, Formatting.Indented));
Environment.Exit(0);
}
if (passedRuleExists)
{
if (!passedRule.IsValid())
{
Console.WriteLine ("ERROR - Passed rule is invalid:");
Console.Write (JsonConvert.SerializeObject(passedRule, Formatting.Indented));
Environment.Exit(1);
}
outputHandler.rules.Add(passedRule);
}
if (commandFiles.Count != 0)
{
foreach (var commandFile in commandFiles)
{
if (!System.IO.File.Exists(commandFile))
{
Console.WriteLine ("ERROR - Cannot find command file: " + commandFile);
Environment.Exit(1);
}
using (StreamReader sr = new StreamReader(commandFile))
{
while (sr.Peek() >= 0)
{
commands.Add(sr.ReadLine());
}
}
}
}
if (otherArgs.Length > 0)
{
commands.Add(String.Join(" ", otherArgs));
}
foreach (var ruleFile in ruleFiles)
{
if (!System.IO.File.Exists(ruleFile))
{
Console.WriteLine ("ERROR - Cannot find rule file: " + ruleFile);
Environment.Exit(1);
}
using (StreamReader sr = new StreamReader(ruleFile))
{
try {
OutputRule[] rules = JsonConvert.DeserializeObject<OutputRule[]>(sr.ReadToEnd());
foreach (var rule in rules)
{
if (!rule.IsValid())
{
Console.WriteLine ("ERROR - Rule is invalid in rule file: " + ruleFile);
Console.Write (JsonConvert.SerializeObject(rule, Formatting.Indented));
Environment.Exit(1);
}
outputHandler.rules.Add(rule);
}
}
catch (Newtonsoft.Json.JsonSerializationException e)
{
Console.WriteLine ("ERROR - Cannot parse rule file: " + ruleFile + " - " + e.Message);
Environment.Exit(1);
}
catch (Newtonsoft.Json.JsonReaderException e)
{
Console.WriteLine ("ERROR - Cannot parse rule file: " + ruleFile + " - " + e.Message);
Environment.Exit(1);
}
}
}
foreach (string searchReplaceFile in searchReplaceFiles)
{
if (!System.IO.File.Exists(searchReplaceFile))
{
Console.WriteLine ("ERROR - Cannot find search/replace file: " + searchReplaceFile);
Environment.Exit(1);
}
using (StreamReader sr = new StreamReader(searchReplaceFile))
{
try {
Dictionary<string, OrderedDictionary> replacements = JsonConvert.DeserializeObject<Dictionary<string, OrderedDictionary>>(sr.ReadToEnd());
foreach (var replacementKey in replacements.Keys)
{
// if (outputHandler.stringFunctionFormatter.replacements.ContainsKey(replacementKey))
// {
// Replacing search/replace dictionary.
// This is not currently an error, nor can it be easily logged without affecting output.
// }
outputHandler.stringFunctionFormatter.replacements[replacementKey] = replacements[replacementKey];
}
}
catch (Newtonsoft.Json.JsonSerializationException e)
{
Console.WriteLine ("ERROR - Cannot parse search/replace file: " + searchReplaceFile + " - " + e.Message);
Environment.Exit(1);
}
catch (Newtonsoft.Json.JsonReaderException e)
{
Console.WriteLine ("ERROR - Cannot parse search/replace file: " + searchReplaceFile + " - " + e.Message);
Environment.Exit(1);
}
}
}
if (rulesOnly)
{
Console.WriteLine (JsonConvert.SerializeObject(outputHandler.rules, Formatting.Indented));
Environment.Exit(0);
}
if (searchReplaceOnly)
{
Console.WriteLine (JsonConvert.SerializeObject(outputHandler.stringFunctionFormatter.replacements, Formatting.Indented));
Environment.Exit(0);
}
int returnInt = 0;
DateTime start = DateTime.Now;
foreach (var commandLine in commands)
{
int commandReturnInt = RunCommandWithOutputHandler (commandLine, ".", outputHandler);
if (sumReturnValues)
{
returnInt += commandReturnInt;
}
else
{
returnInt = commandReturnInt;
}
if (stopOnFirstError && (returnInt > 0 || outputHandler.error))
{
break;
}
}
TimeSpan timeSpan = DateTime.Now - start;
if (report)
{
outputHandler.Report();
}
if (statistics)
{
Console.Write(outputHandler.Statistics());
}
if (timeRun)
{
Console.WriteLine("Time elapsed: " + timeSpan);
}
if (returnInt == 0 && outputHandler.error)
{
returnInt = 1;
}
if (forceReturn)
{
returnInt = forceReturnValue;
}
return returnInt;
}
static List<OutputRule> ParseRuleFile (string ruleFilePath)
{
var rules = new List<OutputRule> ();
return rules;
}
static void ShowHelp (OptionSet p)
{
Console.WriteLine ("Usage: cr [OPTIONS]+ [command]");
Console.WriteLine ("Run commands and inspect/replace their standard and error output.");
Console.WriteLine ();
Console.WriteLine ("Options:");
p.WriteOptionDescriptions (Console.Out);
Environment.Exit(0);
}
public static int RunCommandWithOutputHandler (string commandLine, string startingDirectory, OutputHandler outputHandler)
{
var subProcess = new Process();
// Windows
// This will need additional setups for other platforms.
subProcess.StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
// mode is used to redefine the command window width, so there will be no arbitrary linewrap.
Arguments = "/c mode 1000,50&&" + commandLine,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
WorkingDirectory = startingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true
};
subProcess.OutputDataReceived += outputHandler.HandleOutput;
subProcess.ErrorDataReceived += outputHandler.HandleErrorOutput;
bool error = false;
try
{
subProcess.Start ();
subProcess.BeginOutputReadLine ();
subProcess.BeginErrorReadLine ();
}
catch (Exception e)
{
Console.WriteLine (string.Format ("Could not complete subprocess: {0} with exception:{1}", commandLine, e));
error = true;
}
finally
{
subProcess.WaitForExit();
}
if (error)
{
return 1;
}
// If we have flagged an error via a rule, pass through any non-zero return value
// or return 1 if the process returned 0.
if (outputHandler.error && subProcess.ExitCode == 0)
{
return 1;
}
return subProcess.ExitCode;
}
public class OutputHandler
{
public StringFunctionFormatter stringFunctionFormatter = new StringFunctionFormatter();
public List<OutputRule> rules = new List<OutputRule>();
public bool outputMissPass = true;
public bool outputMatchPass = true;
public bool outputMatchStdout = true;
public bool outputMatchStderr = true;
public List<string> report = new List<string>();
public bool error = false;
public enum InputStream
{
STDOUT,
STDERR,
}
public void HandleOutput (object sendingProcessObject, DataReceivedEventArgs eventArgs)
{
ProcessRules(eventArgs.Data, InputStream.STDOUT);
}
public void HandleErrorOutput (object sendingProcess, DataReceivedEventArgs eventArgs)
{
ProcessRules(eventArgs.Data, InputStream.STDERR);
}
public void ProcessRules (string line, InputStream inputStream)
{
if (string.IsNullOrEmpty(line)) return;
// If any rule matches, matched will be set to true.
bool matched = false;
// If any rule matches and passes the output, passed will be set to true.
// This prevents multiple rules passing the same string and duplicating output.
bool passed = false;
foreach (OutputRule rule in rules)
{
if ((inputStream == InputStream.STDOUT && rule.processStdOut) ||
(inputStream == InputStream.STDERR && rule.processStdErr))
{
Match match = rule.RegexMatch(line);
if (match == null)
{
continue;
}
if (!match.Success)
{
continue;
}
// GroupCollection doesn't support linq.
// var groups = from x in match.Groups select x.ToString();
List<string> groupList = new List<string>();
foreach (Group g in match.Groups)
{
groupList.Add(g.ToString());
}
var groups = groupList.ToArray();
matched = true;
if (!passed && rule.passOutput && outputMatchPass)
{
passed = true;
PassOutput (line, inputStream);
}
if (!string.IsNullOrEmpty(rule.stdoutFormat) && outputMatchStdout)
{
try
{
Console.WriteLine(string.Format(stringFunctionFormatter, rule.stdoutFormat, groups));
}
catch (System.FormatException)
{
Console.WriteLine("Error - stdout format is incorrect");
Console.WriteLine (JsonConvert.SerializeObject(rule, Formatting.Indented));
Environment.Exit(1);
}
}
if (!string.IsNullOrEmpty(rule.stderrFormat) && outputMatchStderr)
{
try
{
Console.Error.WriteLine(string.Format(rule.stderrFormat, groups));
}
catch (System.FormatException)
{
Console.WriteLine(string.Format("Error - stderr format is incorrect\n pattern: {0}\n stderr: {1}", rule.pattern, rule.stderrFormat));
Environment.Exit(1);
}
}
if (!string.IsNullOrEmpty(rule.reportFormat))
{
lock (report)
{
try
{
report.Add(string.Format(rule.reportFormat, groups));
}
catch (System.FormatException)
{
Console.WriteLine(string.Format("Error - Report format is incorrect\n pattern: {0}\n report: {1}", rule.pattern, rule.reportFormat));
Environment.Exit(1);
}
}
}
if (rule.setError)
{
error = true;
}
if (rule.stopProcessing)
{
break;
}
}
}
if (!matched && outputMissPass)
{
PassOutput (line, inputStream);
}
}
private void PassOutput (string line, InputStream inputStream)
{
if (inputStream == InputStream.STDOUT)
{
Console.WriteLine(line);
}
else
{
Console.Error.WriteLine(line);
}
}
public void Report ()
{
foreach (string line in report)
{
Console.WriteLine(line);
}
}
public string Statistics ()
{
StringWriter sr = new StringWriter();
sr.WriteLine(string.Format("Number of Rules: {0}", rules.Count));
long regexMatchCount = 0;
long regexMissCount = 0;
long shortRegexMatchCount = 0;
long shortRegexMissCount = 0;
TimeSpan shortRegexMatchCumulativeDuration = new TimeSpan();
TimeSpan shortRegexMissCumulativeDuration = new TimeSpan();
TimeSpan regexMatchCumulativeDuration = new TimeSpan();
TimeSpan regexMissCumulativeDuration = new TimeSpan();
foreach (OutputRule rule in rules)
{
sr.Write(rule.Statistics());
regexMatchCount += rule.regexMatchCount;
regexMissCount += rule.regexMissCount;
shortRegexMatchCount += rule.shortRegexMatchCount;
shortRegexMissCount += rule.shortRegexMissCount;
shortRegexMatchCumulativeDuration += rule.shortRegexMatchCumulativeDuration;
shortRegexMissCumulativeDuration += rule.shortRegexMissCumulativeDuration;
regexMatchCumulativeDuration += rule.regexMatchCumulativeDuration;
regexMissCumulativeDuration += rule.regexMissCumulativeDuration;
}
int maxWidth = (regexMatchCount + regexMissCount + shortRegexMatchCount + shortRegexMissCount).ToString().Length;
string statsOutputPattern = "{0,-21} {1," + maxWidth + "} Duration {2} (Avg: {3})";
if (rules.Count > 0)
{
sr.WriteLine(string.Format(statsOutputPattern, "Pattern Hits:", regexMatchCount, regexMatchCumulativeDuration, regexMatchCount == 0?new TimeSpan(0):TimeSpan.FromTicks(regexMatchCumulativeDuration.Ticks/regexMatchCount)));
sr.WriteLine(string.Format(statsOutputPattern, "Pattern Misses:", regexMissCount, regexMissCumulativeDuration, regexMissCount == 0?new TimeSpan(0):TimeSpan.FromTicks(regexMissCumulativeDuration.Ticks/regexMissCount)));
sr.WriteLine(string.Format(statsOutputPattern, "Pattern Total:", regexMatchCount + regexMissCount, regexMatchCumulativeDuration + regexMissCumulativeDuration, regexMatchCount + regexMissCount == 0?new TimeSpan(0):TimeSpan.FromTicks((regexMatchCumulativeDuration + regexMissCumulativeDuration).Ticks/(regexMatchCount + regexMissCount))));
sr.WriteLine(string.Format(statsOutputPattern, "Short Pattern Hits:", shortRegexMatchCount, shortRegexMatchCumulativeDuration, shortRegexMatchCount == 0?new TimeSpan(0):TimeSpan.FromTicks(shortRegexMatchCumulativeDuration.Ticks/shortRegexMatchCount)));
sr.WriteLine(string.Format(statsOutputPattern, "Short Pattern Misses:", shortRegexMissCount, shortRegexMissCumulativeDuration, shortRegexMissCount == 0?new TimeSpan(0):TimeSpan.FromTicks(shortRegexMissCumulativeDuration.Ticks/shortRegexMissCount)));
sr.WriteLine(string.Format(statsOutputPattern, "Short Pattern Total:", shortRegexMatchCount + shortRegexMissCount, shortRegexMatchCumulativeDuration + shortRegexMissCumulativeDuration, shortRegexMatchCount + shortRegexMissCount == 0?new TimeSpan(0):TimeSpan.FromTicks((shortRegexMatchCumulativeDuration + shortRegexMissCumulativeDuration).Ticks/(shortRegexMatchCount + shortRegexMissCount))));
}
return sr.ToString();
}
}
// ToDo: Case Insensitive
[JsonObject(MemberSerialization.OptIn)]
public class OutputRule
{
// A short description of the rule.
[JsonProperty]
public string title;
// A longer description of the rule.
[JsonProperty]
public string description;
// An example string that the parser would match against.
[JsonProperty]
public string example;
// If true, a copy of output will be sent to the same stream it was received on.
[JsonProperty]
public bool passOutput=true;
// If true and this rule is matched, no further rules will be attempted.
[JsonProperty]
public bool stopProcessing=true;
// If true, if matched will prevent process from returning 0;
[JsonProperty]
public bool setError=false;
// If true, this rule will be used to evaluate output from the stream.
[JsonProperty]
public bool processStdErr=true;
[JsonProperty]
public bool processStdOut=true;
// The short regex pattern to match against. When set, it will create the regex.
// This pattern should be simple and faster to match than the full regex, with no groups.
// Needs error handling for pattern mistakes.
private string _shortPattern;
[JsonProperty]
public string shortPattern
{
get
{
return _shortPattern;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_shortPattern = value;
_shortRegex = new Regex(_shortPattern);
// Compiling doesn't seem to help speed here.
// _shortRegex = new Regex(_shortPattern, RegexOptions.Compiled);
}
}
}
private Regex _shortRegex = null;
public Regex shortRegex
{
get
{
return _shortRegex;
}
}
// The regex pattern to match against. When set, it will create the regex.
// Needs error handling for pattern mistakes.
private string _pattern;
[JsonProperty]
public string pattern
{
get
{
return _pattern;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_pattern = value;
_regex = new Regex(_pattern);
// Compiling doesn't seem to help speed here.
// _regex = new Regex(_pattern, RegexOptions.Compiled);
}
}
}
private Regex _regex;
public Regex regex
{
get
{
return _regex;
}
}
public int shortRegexMatchCount = 0;
public int shortRegexMissCount = 0;
public TimeSpan shortRegexMatchCumulativeDuration = new TimeSpan();
public TimeSpan shortRegexMissCumulativeDuration = new TimeSpan();
public int regexMatchCount = 0;
public int regexMissCount = 0;
public TimeSpan regexMatchCumulativeDuration = new TimeSpan();
public TimeSpan regexMissCumulativeDuration = new TimeSpan();
public Match RegexMatch (string testString)
{
if (string.IsNullOrEmpty(testString)) return null;
if (shortRegex != null)
{
DateTime shortRegexMatchStart = DateTime.Now;
Match shortRegexMatch = shortRegex.Match(testString);
TimeSpan shortRegexMatchDuration = DateTime.Now - shortRegexMatchStart;
if (!shortRegexMatch.Success)
{
// Short regex failed so processing can stop early.
shortRegexMissCount++;
shortRegexMissCumulativeDuration += shortRegexMatchDuration;
return shortRegexMatch;
}
else
{
shortRegexMatchCount++;
shortRegexMatchCumulativeDuration += shortRegexMatchDuration;
}
}
if (regex != null)
{
DateTime regexMatchStart = DateTime.Now;
Match regexMatch = regex.Match(testString);
TimeSpan regexMatchDuration = DateTime.Now - regexMatchStart;
if (!regexMatch.Success)
{
regexMissCount++;
regexMissCumulativeDuration += regexMatchDuration;
}
else
{
regexMatchCount++;
regexMatchCumulativeDuration += regexMatchDuration;
}
return regexMatch;
}
return null;
}
public string Statistics ()
{
StringWriter sr = new StringWriter();
int maxWidth = (regexMatchCount + regexMissCount).ToString().Length;
string statsOutputPattern = " {0,-7} {1," + maxWidth + "} Duration {2} (Avg: {3})";
if (!string.IsNullOrEmpty(title)) sr.WriteLine("Title: " + title);
if (!string.IsNullOrEmpty(description)) sr.WriteLine("Description: " + description);
if (!string.IsNullOrEmpty(example)) sr.WriteLine("Example: " + example);
sr.WriteLine("Pattern: " + pattern);
sr.WriteLine(string.Format(statsOutputPattern, "Hits:", regexMatchCount, regexMatchCumulativeDuration, regexMatchCount == 0?new TimeSpan(0):TimeSpan.FromTicks(regexMatchCumulativeDuration.Ticks/regexMatchCount)));
sr.WriteLine(string.Format(statsOutputPattern, "Misses:", regexMissCount, regexMissCumulativeDuration, regexMissCount == 0?new TimeSpan(0):TimeSpan.FromTicks(regexMissCumulativeDuration.Ticks/regexMissCount)));
sr.WriteLine(string.Format(statsOutputPattern, "Total:", regexMatchCount + regexMissCount, regexMatchCumulativeDuration + regexMissCumulativeDuration, regexMatchCount + regexMissCount == 0?new TimeSpan(0):TimeSpan.FromTicks((regexMatchCumulativeDuration + regexMissCumulativeDuration).Ticks/(regexMatchCount + regexMissCount))));
if (shortRegex != null)
{
int shortMaxWidth = (shortRegexMatchCount + shortRegexMissCount).ToString().Length;
string shortStatsOutputPattern = " {0,-7} {1," + shortMaxWidth + "} Duration {2} (Avg: {3})";
sr.WriteLine(" Short Pattern: " + shortPattern);
sr.WriteLine(string.Format(shortStatsOutputPattern, "Hits:", shortRegexMatchCount, shortRegexMatchCumulativeDuration, shortRegexMatchCount == 0?new TimeSpan(0):TimeSpan.FromTicks(shortRegexMatchCumulativeDuration.Ticks/shortRegexMatchCount)));
sr.WriteLine(string.Format(shortStatsOutputPattern, "Misses:", shortRegexMissCount, shortRegexMissCumulativeDuration, shortRegexMissCount == 0?new TimeSpan(0):TimeSpan.FromTicks(shortRegexMissCumulativeDuration.Ticks/shortRegexMissCount)));
sr.WriteLine(string.Format(shortStatsOutputPattern, "Total:", shortRegexMatchCount + shortRegexMissCount, shortRegexMatchCumulativeDuration + shortRegexMissCumulativeDuration, shortRegexMatchCount + shortRegexMissCount == 0?new TimeSpan(0):TimeSpan.FromTicks((shortRegexMatchCumulativeDuration + shortRegexMissCumulativeDuration).Ticks/(shortRegexMatchCount + shortRegexMissCount))));
}
return sr.ToString();
}
// If present, these format strings will be used with the groups result from the regex match
// to generate custom output.
// stdout and stderr will output immediately.
// report will be output in order at the end of processing.
// Groups are 1 based. Should investigate defining 0 as full original line.
// May need to provide option of order of output. (pass, stdout, stderr is the current default)
[JsonProperty]
public string stdoutFormat;
[JsonProperty]
public string stderrFormat;
[JsonProperty]
public string reportFormat;
public bool IsValid ()
{
// Could test pattern groups against format specifiers here.
return (pattern != null);
}
}
public class StringFunctionFormatter : IFormatProvider, ICustomFormatter
{
public Dictionary<string, OrderedDictionary> replacements = new Dictionary<string, OrderedDictionary>();
// Matchs function_name(parameters)
public Regex findFunctionsRegex = new Regex(@"([^\s]+)[ ]*\(([^\s]+)\)");
public delegate string FormatFunction (string inputString, string[] functionAndArgs);
private Dictionary<string, FormatFunction> formatFunctions = new Dictionary<string, FormatFunction>();
public StringFunctionFormatter ()
{
formatFunctions.Add("replace", FormatReplace);
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (! formatProvider.Equals(this)) return null;
var workString = arg.ToString();
var functionsToCall = ParseFormatFunctions(format);
foreach (string[] functionAndArgs in functionsToCall)
{
if (formatFunctions.ContainsKey(functionAndArgs[0]))
{
workString = formatFunctions[functionAndArgs[0]](workString, functionAndArgs);
}
else
{
Console.WriteLine("ERROR - specified format function does not exist: " + functionAndArgs[0]);
Environment.Exit(1);
}
}
return workString;
}
public List<string[]> ParseFormatFunctions (string functionString)
{
List<string[]> returnList = new List<string[]>();
if (string.IsNullOrEmpty(functionString)) return returnList;
Match match = findFunctionsRegex.Match (functionString);
while (match.Success)
{
List<string> tempFunctionAndArgs = new List<string>();
// First group is the full matched string.
// Second group is the function name.
tempFunctionAndArgs.Add(match.Groups[1].ToString());
// For more than one arg, they will be separated by commas.
tempFunctionAndArgs.AddRange(match.Groups[2].ToString().Split(','));
returnList.Add(tempFunctionAndArgs.ToArray());
match = match.NextMatch();
}
return returnList;
}
public string FormatReplace(string inputString, string[] functionAndArgs)
{
string workString = inputString;
for (int i = 1; i < functionAndArgs.Length; i++)
{
if (replacements.ContainsKey(functionAndArgs[i]))
{
foreach (DictionaryEntry de in replacements[functionAndArgs[i]])
{
workString = workString.Replace((string)de.Key, (string)de.Value);
}
}
else
{
Console.WriteLine("ERROR - specified format replace group does not exist: " + functionAndArgs[i]);
Environment.Exit(1);
}
}
return workString;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Npgsql;
using OpenMetaverse;
using OpenSim.Framework;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for the Asset server
/// </summary>
public class PGSQLAssetData : AssetDataBase
{
private const string _migrationStore = "AssetStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private long m_ticksToEpoch;
/// <summary>
/// Database manager
/// </summary>
private PGSQLManager m_database;
private string m_connectionString;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
#region IPlugin Members
override public void Dispose()
{
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
// [Obsolete("Cannot be default-initialized!")]
override public void Initialise()
{
m_log.Info("[PGSQLAssetData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// Initialises asset interface
/// </summary>
/// <para>
/// a string instead of file, if someone writes the support
/// </para>
/// <param name="connectionString">connect string</param>
override public void Initialise(string connectionString)
{
m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;
m_database = new PGSQLManager(connectionString);
m_connectionString = connectionString;
//New migration to check for DB changes
m_database.CheckMigration(_migrationStore);
}
/// <summary>
/// Database provider version.
/// </summary>
override public string Version
{
get { return m_database.getVersion(); }
}
/// <summary>
/// The name of this DB provider.
/// </summary>
override public string Name
{
get { return "PGSQL Asset storage engine"; }
}
#endregion IPlugin Members
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset from m_database
/// </summary>
/// <param name="assetID">the asset UUID</param>
/// <returns></returns>
override public AssetBase GetAsset(UUID assetID)
{
string sql = "SELECT * FROM assets WHERE id = :id";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("id", assetID));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = new AssetBase(
DBGuid.FromDB(reader["id"]),
(string)reader["name"],
Convert.ToSByte(reader["assetType"]),
reader["creatorid"].ToString()
);
// Region Main
asset.Description = (string)reader["description"];
asset.Local = Convert.ToBoolean(reader["local"]);
asset.Temporary = Convert.ToBoolean(reader["temporary"]);
asset.Flags = (AssetFlags)(Convert.ToInt32(reader["asset_flags"]));
asset.Data = (byte[])reader["data"];
return asset;
}
return null; // throw new Exception("No rows to return");
}
}
}
/// <summary>
/// Create asset in m_database
/// </summary>
/// <param name="asset">the asset</param>
override public void StoreAsset(AssetBase asset)
{
string sql =
@"UPDATE assets set name = :name, description = :description, " + "\"assetType\" " + @" = :assetType,
local = :local, temporary = :temporary, creatorid = :creatorid, data = :data
WHERE id=:id;
INSERT INTO assets
(id, name, description, " + "\"assetType\" " + @", local,
temporary, create_time, access_time, creatorid, asset_flags, data)
Select :id, :name, :description, :assetType, :local,
:temporary, :create_time, :access_time, :creatorid, :asset_flags, :data
Where not EXISTS(SELECT * FROM assets WHERE id=:id)
";
string assetName = asset.Name;
if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
{
assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
m_log.WarnFormat(
"[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
{
assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
m_log.WarnFormat(
"[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
{
int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
command.Parameters.Add(m_database.CreateParameter("name", assetName));
command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
command.Parameters.Add(m_database.CreateParameter("access_time", now));
command.Parameters.Add(m_database.CreateParameter("create_time", now));
command.Parameters.Add(m_database.CreateParameter("asset_flags", (int)asset.Flags));
command.Parameters.Add(m_database.CreateParameter("creatorid", asset.Metadata.CreatorID));
command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch (Exception e)
{
m_log.Error("[ASSET DB]: Error storing item :" + e.Message + " sql " + sql);
}
}
}
// Commented out since currently unused - this probably should be called in GetAsset()
// private void UpdateAccessTime(AssetBase asset)
// {
// using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = :access_time WHERE id=:id"))
// {
// int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
// cmd.Parameters.AddWithValue(":id", asset.FullID.ToString());
// cmd.Parameters.AddWithValue(":access_time", now);
// try
// {
// cmd.ExecuteNonQuery();
// }
// catch (Exception e)
// {
// m_log.Error(e.ToString());
// }
// }
// }
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuids">The assets' IDs</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public override bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exist = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format("SELECT id FROM assets WHERE id IN ({0})", ids);
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UUID id = DBGuid.FromDB(reader["id"]);
exist.Add(id);
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exist.Contains(uuids[i]);
return results;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
string sql = @" SELECT id, name, description, " + "\"assetType\"" + @", temporary, creatorid
FROM assets
order by id
limit :stop
offset :start;";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("start", start));
cmd.Parameters.Add(m_database.CreateParameter("stop", start + count - 1));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.FullID = DBGuid.FromDB(reader["id"]);
metadata.Name = (string)reader["name"];
metadata.Description = (string)reader["description"];
metadata.Type = Convert.ToSByte(reader["assetType"]);
metadata.Temporary = Convert.ToBoolean(reader["temporary"]);
metadata.CreatorID = (string)reader["creatorid"];
retList.Add(metadata);
}
}
}
return retList;
}
public override bool Delete(string id)
{
return false;
}
#endregion IAssetDataPlugin Members
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Imaging.BitmapImage.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Imaging
{
sealed public partial class BitmapImage : BitmapSource, System.ComponentModel.ISupportInitialize, System.Windows.Markup.IUriContext
{
#region Methods and constructors
public void BeginInit()
{
}
public BitmapImage()
{
}
public BitmapImage(Uri uriSource)
{
}
public BitmapImage(Uri uriSource, System.Net.Cache.RequestCachePolicy uriCachePolicy)
{
}
public System.Windows.Media.Imaging.BitmapImage Clone()
{
return default(System.Windows.Media.Imaging.BitmapImage);
}
protected override void CloneCore(System.Windows.Freezable source)
{
}
public System.Windows.Media.Imaging.BitmapImage CloneCurrentValue()
{
return default(System.Windows.Media.Imaging.BitmapImage);
}
protected override void CloneCurrentValueCore(System.Windows.Freezable source)
{
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
public void EndInit()
{
}
protected override void GetAsFrozenCore(System.Windows.Freezable source)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable source)
{
}
#endregion
#region Properties and indexers
public Uri BaseUri
{
get
{
return default(Uri);
}
set
{
}
}
public BitmapCacheOption CacheOption
{
get
{
return default(BitmapCacheOption);
}
set
{
}
}
public BitmapCreateOptions CreateOptions
{
get
{
return default(BitmapCreateOptions);
}
set
{
}
}
public int DecodePixelHeight
{
get
{
return default(int);
}
set
{
}
}
public int DecodePixelWidth
{
get
{
return default(int);
}
set
{
}
}
public override bool IsDownloading
{
get
{
return default(bool);
}
}
public override System.Windows.Media.ImageMetadata Metadata
{
get
{
return default(System.Windows.Media.ImageMetadata);
}
}
public Rotation Rotation
{
get
{
return default(Rotation);
}
set
{
}
}
public System.Windows.Int32Rect SourceRect
{
get
{
return default(System.Windows.Int32Rect);
}
set
{
}
}
public Stream StreamSource
{
get
{
return default(Stream);
}
set
{
}
}
public System.Net.Cache.RequestCachePolicy UriCachePolicy
{
get
{
return default(System.Net.Cache.RequestCachePolicy);
}
set
{
}
}
public Uri UriSource
{
get
{
return default(Uri);
}
set
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty CacheOptionProperty;
public readonly static System.Windows.DependencyProperty CreateOptionsProperty;
public readonly static System.Windows.DependencyProperty DecodePixelHeightProperty;
public readonly static System.Windows.DependencyProperty DecodePixelWidthProperty;
public readonly static System.Windows.DependencyProperty RotationProperty;
public readonly static System.Windows.DependencyProperty SourceRectProperty;
public readonly static System.Windows.DependencyProperty StreamSourceProperty;
public readonly static System.Windows.DependencyProperty UriCachePolicyProperty;
public readonly static System.Windows.DependencyProperty UriSourceProperty;
#endregion
}
}
| |
// 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.IO;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbNegotiate Response.
/// Do not support LM Negotiate response.
/// </summary>
public class SmbNegotiateResponsePacket : SmbSingleResponsePacket
{
#region Fields
private SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Parameters smbParameters;
private SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Data smbData;
// If the server has selected the Core Protocol dialect, or if none of the offered protocols is supported
// by the server, then WordCount MUST be 0x01 and the dialect index (the selected dialect) MUST be returned
// as the only parameter.
private const byte WordCountOfCoreProtocol = 0x01;
// If the server has selected any dialect from LAN Manager 1.0 through LAN Manager 2.1, then WordCount MUST
// be 0x0D.
private const byte WordCountOfLanManager = 0x0D;
// If the server has selected the NT LAN Manager dialect, then WordCount MUST be 0x11.
private const byte WordCountOfNtLanManager = 0x11;
#endregion
#region Properties
/// <summary>
/// get or set the Smb_Parameters:SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Parameters
/// Core Protocol response share the DialectIndex member, others members will be ignore.
/// </summary>
public SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Parameters SmbParameters
{
get
{
return this.smbParameters;
}
set
{
this.smbParameters = value;
}
}
/// <summary>
/// get or set the Smb_Data:SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Data
/// Core Protocol response share the same SmbData structure with NTLM.
/// </summary>
public SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Data SmbData
{
get
{
return this.smbData;
}
set
{
this.smbData = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbNegotiateResponsePacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbNegotiateResponsePacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbNegotiateResponsePacket(SmbNegotiateResponsePacket packet)
: base(packet)
{
this.InitDefaultValue();
this.smbParameters.WordCount = packet.SmbParameters.WordCount;
this.smbParameters.DialectIndex = packet.SmbParameters.DialectIndex;
this.smbParameters.SecurityMode = packet.SmbParameters.SecurityMode;
this.smbParameters.MaxMpxCount = packet.SmbParameters.MaxMpxCount;
this.smbParameters.MaxNumberVcs = packet.SmbParameters.MaxNumberVcs;
this.smbParameters.MaxBufferSize = packet.SmbParameters.MaxBufferSize;
this.smbParameters.MaxRawSize = packet.SmbParameters.MaxRawSize;
this.smbParameters.SessionKey = packet.SmbParameters.SessionKey;
this.smbParameters.Capabilities = packet.SmbParameters.Capabilities;
this.smbParameters.SystemTime = new FileTime();
this.smbParameters.SystemTime.Time = packet.SmbParameters.SystemTime.Time;
this.smbParameters.ServerTimeZone = packet.SmbParameters.ServerTimeZone;
this.smbParameters.ChallengeLength = packet.SmbParameters.ChallengeLength;
this.smbData.ByteCount = packet.SmbData.ByteCount;
if (packet.smbData.Challenge != null)
{
this.smbData.Challenge = new byte[packet.smbData.Challenge.Length];
Array.Copy(packet.smbData.Challenge, this.smbData.Challenge, packet.smbData.Challenge.Length);
}
else
{
this.smbData.Challenge = new byte[0];
}
if (packet.smbData.DomainName != null)
{
this.smbData.DomainName = new byte[packet.smbData.DomainName.Length];
Array.Copy(packet.smbData.DomainName, this.smbData.DomainName, packet.smbData.DomainName.Length);
}
else
{
this.smbData.DomainName = new byte[0];
}
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override StackPacket Clone()
{
return new SmbNegotiateResponsePacket(this);
}
/// <summary>
/// Encode the struct of SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Parameters
/// into the struct of SmbParameters
/// </summary>
protected override void EncodeParameters()
{
if (this.smbParameters.WordCount == WordCountOfCoreProtocol)
{
this.smbParametersBlock.WordCount = WordCountOfCoreProtocol;
this.smbParametersBlock.Words = new ushort[WordCountOfCoreProtocol] { this.smbParameters.DialectIndex };
}
else
{
this.smbParametersBlock = TypeMarshal.ToStruct<SmbParameters>(
CifsMessageUtils.ToBytes<SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Parameters>(this.smbParameters));
}
}
/// <summary>
/// Encode the struct of SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Data into the struct of SmbData
/// </summary>
protected override void EncodeData()
{
this.smbDataBlock.ByteCount = this.SmbData.ByteCount;
this.smbDataBlock.Bytes = new byte[this.smbDataBlock.ByteCount];
using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
if (this.smbData.Challenge != null)
{
channel.WriteBytes(this.smbData.Challenge);
}
if (this.smbData.DomainName != null)
{
channel.WriteBytes(this.smbData.DomainName);
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters.
/// </summary>
protected override void DecodeParameters()
{
if (this.smbParametersBlock.WordCount == WordCountOfCoreProtocol)
{
this.smbParameters.WordCount = this.smbParametersBlock.WordCount;
using (MemoryStream memoryStream = new MemoryStream(CifsMessageUtils.ToBytesArray(this.SmbParametersBlock.Words)))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.smbParameters.DialectIndex = channel.Read<ushort>();
}
}
}
else if (this.smbParametersBlock.WordCount == WordCountOfNtLanManager)
{
this.smbParameters = TypeMarshal.ToStruct<SMB_COM_NEGOTIATE_NtLanManagerResponse_SMB_Parameters>(
CifsMessageUtils.ToBytes<SmbParameters>(this.smbParametersBlock));
}
else if (this.smbParametersBlock.WordCount == WordCountOfLanManager)
{
throw new NotImplementedException("TD did not define the SmbParameters for Lan Manager Dialect.");
}
else
{
throw new NotSupportedException("Unknow SmbParameters structure.");
}
}
/// <summary>
/// to decode the smb data: from the general SmbDada to the concrete Smb Data.
/// </summary>
protected override void DecodeData()
{
this.smbData.ByteCount = this.smbDataBlock.ByteCount;
if (this.smbParametersBlock.WordCount == WordCountOfNtLanManager
|| this.smbParametersBlock.WordCount == WordCountOfCoreProtocol)
{
using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.smbData.Challenge = channel.ReadBytes(this.SmbParameters.ChallengeLength);
this.smbData.DomainName = channel.ReadBytes(this.smbData.ByteCount
- this.SmbParameters.ChallengeLength);
}
}
}
else if (this.smbParametersBlock.WordCount == WordCountOfLanManager)
{
throw new NotImplementedException("TD did not define the SmbParameters for Lan Manager Dialect.");
}
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
this.smbData.Challenge = new byte[0];
this.smbData.DomainName = new byte[0];
}
#endregion
}
}
| |
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static class OpenSsl
{
#region structures
[StructLayout(LayoutKind.Sequential)]
private struct SslContext
{
internal IntPtr sslPtr;
internal IntPtr readBioPtr;
internal IntPtr writeBioPtr;
internal bool isServer;
}
#endregion
#region internal methods
//TODO Set remote certificate options
internal static IntPtr AllocateSslContext(long options, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, bool isServer, bool remoteCertRequired)
{
IntPtr sslContextPtr = Marshal.AllocHGlobal(Marshal.SizeOf<SslContext>());
SslContext sslContext = new SslContext
{
sslPtr = IntPtr.Zero,
readBioPtr = IntPtr.Zero,
writeBioPtr = IntPtr.Zero,
isServer = isServer,
};
sslContext.isServer = isServer;
try
{
IntPtr method = GetSslMethod(isServer, options);
var contextPtr = libssl.SSL_CTX_new(method);
if (IntPtr.Zero == contextPtr)
{
throw CreateSslException("Failed to allocate SSL/TLS context");
}
libssl.SSL_CTX_ctrl(contextPtr, libssl.SSL_CTRL_OPTIONS, options, IntPtr.Zero);
libssl.SSL_CTX_set_quiet_shutdown(contextPtr, 1);
if (certHandle != null && certKeyHandle != null)
{
SetSslCertificate(contextPtr, certHandle, certKeyHandle);
}
sslContext.sslPtr = libssl.SSL_new(contextPtr);
libssl.SSL_CTX_free(contextPtr);
if (IntPtr.Zero == sslContext.sslPtr)
{
throw CreateSslException("Failed to create SSSL object from SSL context");
}
IntPtr memMethodRead = libcrypto.BIO_s_mem();
IntPtr memMethodWrite = libcrypto.BIO_s_mem();
if ((IntPtr.Zero == memMethodWrite) || (IntPtr.Zero == memMethodRead))
{
throw CreateSslException("Failed to return memory BIO method function");
}
sslContext.readBioPtr = libssl.BIO_new(memMethodRead);
sslContext.writeBioPtr = libssl.BIO_new(memMethodWrite);
if ((IntPtr.Zero == sslContext.readBioPtr) || (IntPtr.Zero == sslContext.writeBioPtr))
{
throw CreateSslException("Failed to retun new BIO for a given method type");
}
if (isServer)
{
libssl.SSL_set_accept_state(sslContext.sslPtr);
}
else
{
libssl.SSL_set_connect_state(sslContext.sslPtr);
}
libssl.SSL_set_bio(sslContext.sslPtr, sslContext.readBioPtr, sslContext.writeBioPtr);
}
catch
{
Marshal.StructureToPtr(sslContext, sslContextPtr, false);
FreeSslContext(sslContextPtr);
return IntPtr.Zero;
}
Marshal.StructureToPtr(sslContext, sslContextPtr, false);
return sslContextPtr;
}
internal static bool DoSslHandshake(IntPtr sslContextPtr, IntPtr recvPtr, int recvCount, out IntPtr sendPtr, out int sendCount)
{
sendPtr = IntPtr.Zero;
sendCount = 0;
SslContext context = Marshal.PtrToStructure<SslContext>(sslContextPtr);
bool isServer = context.isServer;
if ((IntPtr.Zero != recvPtr) && (recvCount > 0))
{
BioWrite(context.readBioPtr, recvPtr, recvCount);
}
int retVal = libssl.SSL_do_handshake(context.sslPtr);
if ((retVal == 1) && !isServer)
{
return true;
}
int error;
if (retVal != 1)
{
error = GetSslError(context.sslPtr, retVal, "SSL Handshake failed: ");
if ((retVal != -1) || (error != libssl.SslErrorCode.SSL_ERROR_WANT_READ))
{
throw CreateSslException(context.sslPtr, "SSL Handshake failed: ", error);
}
}
sendCount = libssl.BIO_ctrl_pending(context.writeBioPtr);
if (sendCount > 0)
{
sendPtr = Marshal.AllocHGlobal(sendCount);
sendCount = BioRead(context.writeBioPtr, sendPtr, sendCount);
if (sendCount <= 0)
{
error = sendCount;
Marshal.FreeHGlobal(sendPtr);
sendPtr = IntPtr.Zero;
sendCount = 0;
error = GetSslError(context.sslPtr, error, "Read Bio failed: ");
throw CreateSslException("SSL Handshake failed", error);
}
}
return ((libssl.SSL_state(context.sslPtr) == libssl.SslState.SSL_ST_OK)) ? true : false;
}
internal static int Encrypt(IntPtr handlePtr, IntPtr buffer, int offset, int count, int bufferCapacity)
{
SslContext context = Marshal.PtrToStructure<SslContext>(handlePtr);
var retVal = libssl.SSL_write(context.sslPtr, new IntPtr(buffer.ToInt64() + offset), count);
if (retVal != count)
{
int error = GetSslError(context.sslPtr, retVal, "");
if (libssl.SslErrorCode.SSL_ERROR_ZERO_RETURN == error)
{
return 0; // indicate end-of-file
}
throw CreateSslException("OpenSsl::Encrypt failed");
}
int capacityNeeded = libssl.BIO_ctrl_pending(context.writeBioPtr);
if (retVal == count)
{
if (capacityNeeded > bufferCapacity)
{
throw CreateSslException("OpenSsl::Encrypt outBufferPtr should be null");
}
IntPtr outBufferPtr = buffer;
retVal = BioRead(context.writeBioPtr, outBufferPtr, capacityNeeded);
if (retVal < 0)
{
throw CreateSslException("OpenSsl::Encrypt failed");
}
}
return retVal;
}
internal static int Decrypt(IntPtr sslContextPtr, IntPtr outBufferPtr, int count)
{
SslContext context = Marshal.PtrToStructure<SslContext>(sslContextPtr);
var retVal = BioWrite(context.readBioPtr, outBufferPtr, count);
if (retVal == count)
{
retVal = libssl.SSL_read(context.sslPtr, outBufferPtr, retVal);
if (retVal > 0) count = retVal;
}
if (retVal != count)
{
int error = GetSslError(context.sslPtr, retVal, "");
if (libssl.SslErrorCode.SSL_ERROR_ZERO_RETURN == error)
{
return 0; // indicate end-of-file
}
throw CreateSslException("OpenSsl::Decrypt failed");
}
return retVal;
}
internal static IntPtr GetPeerCertificate(IntPtr sslContextPtr)
{
SslContext context = Marshal.PtrToStructure<SslContext>(sslContextPtr);
IntPtr sslPtr = context.sslPtr;
IntPtr certPtr = libssl.SSL_get_peer_certificate(sslPtr);
return certPtr;
}
internal static libssl.SSL_CIPHER GetConnectionInfo(IntPtr sslContextPtr)
{
SslContext context = Marshal.PtrToStructure<SslContext>(sslContextPtr);
IntPtr sslPtr = context.sslPtr;
IntPtr cipherPtr = libssl.SSL_get_current_cipher(sslPtr);
var cipher = new libssl.SSL_CIPHER();
if (IntPtr.Zero != cipherPtr)
{
cipher = Marshal.PtrToStructure<libssl.SSL_CIPHER>(cipherPtr);
}
return cipher;
}
internal static void FreeSslContext(IntPtr sslContextPtr)
{
if (IntPtr.Zero == sslContextPtr)
{
return;
}
SslContext context = Marshal.PtrToStructure<SslContext>(sslContextPtr);
Disconnect(context.sslPtr);
Marshal.FreeHGlobal(sslContextPtr);
sslContextPtr = IntPtr.Zero;
}
#endregion
#region private methods
private static IntPtr GetSslMethod(bool isServer, long options)
{
long protocolMask = libssl.Options.SSL_OP_NO_SSLv2 | libssl.Options.SSL_OP_NO_SSLv3 |
libssl.Options.SSL_OP_NO_TLSv1 | libssl.Options.SSL_OP_NO_TLSv1_1 |
libssl.Options.SSL_OP_NO_TLSv1_2;
options &= protocolMask;
Debug.Assert(options != protocolMask, "All protocols are disabled");
var noSsl2 = (options & libssl.Options.SSL_OP_NO_SSLv2) != 0;
var noSsl3 = (options & libssl.Options.SSL_OP_NO_SSLv3) != 0;
var noTls10 = (options & libssl.Options.SSL_OP_NO_TLSv1) != 0;
var noTls11 = (options & libssl.Options.SSL_OP_NO_TLSv1_1) != 0;
var noTls12 = (options & libssl.Options.SSL_OP_NO_TLSv1_2) != 0;
var method = IntPtr.Zero;
if (noSsl2 && noSsl3 && noTls11 && noTls12)
{
method = isServer ? libssl.TLSv1_server_method() : libssl.TLSv1_client_method();
}
else if (noSsl2 && noSsl3 && noTls10 && noTls12)
{
method = isServer ? libssl.TLSv1_1_server_method() : libssl.TLSv1_1_client_method();
}
else if (noSsl2 && noSsl3 && noTls10 && noTls11)
{
method = isServer ? libssl.TLSv1_2_server_method() : libssl.TLSv1_2_client_method();
}
else if (noSsl2 && noTls10 && noTls11 && noTls12)
{
method = isServer ? libssl.SSLv3_server_method() : libssl.SSLv3_client_method();
}
else
{
method = isServer ? libssl.SSLv23_server_method() : libssl.SSLv23_client_method();
}
if (IntPtr.Zero == method)
{
throw CreateSslException("Failed to get SSL method");
}
return method;
}
private static void Disconnect(IntPtr sslPtr)
{
if (IntPtr.Zero != sslPtr)
{
int retVal = libssl.SSL_shutdown(sslPtr);
if (retVal < 0)
{
libssl.SSL_get_error(sslPtr, retVal);
}
libssl.SSL_free(sslPtr);
}
}
//TODO should we check Bio should retry?
private static int BioRead(IntPtr BioPtr, IntPtr buffer, int count)
{
int bytes = libssl.BIO_read(BioPtr, buffer, count);
if (bytes != count)
{
throw CreateSslException("Failed in Read BIO");
}
return bytes;
}
//TODO should we check Bio should retry?
private static int BioWrite(IntPtr BioPtr, IntPtr buffer, int count)
{
int bytes = libssl.BIO_write(BioPtr, buffer, count);
if (bytes != count)
{
throw CreateSslException("Failed in Write BIO");
}
return bytes;
}
private static int GetSslError(IntPtr sslPtr, int result, string message)
{
int retVal = libssl.SSL_get_error(sslPtr, result);
if (retVal == libssl.SslErrorCode.SSL_ERROR_SYSCALL)
{
retVal = (int)libssl.ERR_get_error();
}
return retVal;
}
private static void SetSslCertificate(IntPtr contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr)
{
Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid");
Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid");
int retVal = libssl.SSL_CTX_use_certificate(contextPtr, certPtr);
if (1 != retVal)
{
throw CreateSslException("Failed to use SSL certificate");
}
retVal = libssl.SSL_CTX_use_PrivateKey(contextPtr, keyPtr);
if (1 != retVal)
{
throw CreateSslException("Failed to use SSL certificate private key");
}
//check private key
retVal = libssl.SSL_CTX_check_private_key(contextPtr);
if (1 != retVal)
{
throw CreateSslException("Certificate pivate key check failed");
}
}
private static SslException CreateSslException(string message)
{
return new SslException(message);
}
private static SslException CreateSslException(string message, int error)
{
if (error == libssl.SslErrorCode.SSL_ERROR_SYSCALL)
{
return new SslException(message);
}
else
{
return new SslException(message, error);
}
}
private static SslException CreateSslException(IntPtr sslPtr, string message, int error)
{
return CreateSslException(message, libssl.SSL_get_error(sslPtr, error));
}
private sealed class SslException : Exception
{
public SslException(string message)
: base(message + ": " + Marshal.PtrToStringAnsi(libssl.ERR_reason_error_string(libssl.ERR_get_error())))
{
HResult = (int)libssl.ERR_get_error();
}
public SslException(string message, int error)
: base(message + ": " + error)
{
HResult = error;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Moq;
using NuGet.Test.Mocks;
using Xunit;
using Xunit.Extensions;
namespace NuGet.Test
{
public class PackageSourceProviderTest
{
[Fact]
public void LoadPackageSourcesPerformMigrationIfSpecified()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true)).Returns(
new[] {
new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false),
}
);
// disable package "three"
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("three", "true" ) });
IList<KeyValuePair<string, string>> savedSettingValues = null;
settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback<string, IList<KeyValuePair<string, string>>>((_, savedVals) => { savedSettingValues = savedVals; })
.Verifiable();
var provider = CreatePackageSourceProvider(settings.Object,
null,
new Dictionary<PackageSource, PackageSource> {
{ new PackageSource("onesource", "one"), new PackageSource("goodsource", "good") },
{ new PackageSource("foo", "bar"), new PackageSource("foo", "bar") },
{ new PackageSource("threesource", "three"), new PackageSource("awesomesource", "awesome") }
}
);
// Act
var values = provider.LoadPackageSources().ToList();
savedSettingValues = savedSettingValues.ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[0], "good", "goodsource", true);
AssertPackageSource(values[1], "two", "twosource", true);
AssertPackageSource(values[2], "awesome", "awesomesource", false);
Assert.Equal(3, savedSettingValues.Count);
Assert.Equal("good", savedSettingValues[0].Key);
Assert.Equal("goodsource", savedSettingValues[0].Value);
Assert.Equal("two", savedSettingValues[1].Key);
Assert.Equal("twosource", savedSettingValues[1].Value);
Assert.Equal("awesome", savedSettingValues[2].Key);
Assert.Equal("awesomesource", savedSettingValues[2].Value);
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("two", "true") });
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
var provider = CreatePackageSourceProvider(settings.Object);
}
[Fact]
public void TestNoPackageSourcesAreReturnedIfUserSettingsIsEmpty()
{
// Arrange
var provider = CreatePackageSourceProvider();
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(0, values.Count);
}
[Fact]
public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsNull()
{
// Arrange
var settings = new Mock<ISettings>();
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null);
// Act
var values = provider.LoadPackageSources();
// Assert
Assert.False(values.Any());
}
[Fact]
public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsEmpty()
{
// Arrange
var settings = new Mock<ISettings>();
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: new PackageSource[] { });
// Act
var values = provider.LoadPackageSources();
// Assert
Assert.False(values.Any());
}
[Fact]
public void LoadPackageSourcesReturnsDefaultSourcesIfSpecified()
{
// Arrange
var settings = new Mock<ISettings>().Object;
var provider = CreatePackageSourceProvider(settings, providerDefaultSources: new[] { new PackageSource("A"), new PackageSource("B") });
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(2, values.Count);
Assert.Equal("A", values.First().Source);
Assert.Equal("B", values.Last().Source);
}
[Fact]
public void LoadPackageSourcesWhereAMigratedSourceIsAlsoADefaultSource()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("AOld", "urlA", false), new SettingValue("userDefinedSource", "userDefinedSourceUrl", false) });
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
var defaultPackageSourceA = new PackageSource("urlA", "ANew");
var defaultPackageSourceB = new PackageSource("urlB", "B");
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: new[] { defaultPackageSourceA, defaultPackageSourceB },
migratePackageSources: new Dictionary<PackageSource, PackageSource>
{
{ new PackageSource("urlA", "AOld"), defaultPackageSourceA },
});
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
// Package Source AOld will be migrated to ANew. B will simply get added
// Since default source B got added when there are other package sources it will be disabled
// However, package source ANew must stay enabled
// PackageSource userDefinedSource is a user package source and is untouched
Assert.Equal(3, values.Count);
Assert.Equal("urlA", values[0].Source);
Assert.Equal("ANew", values[0].Name);
Assert.True(values[0].IsEnabled);
Assert.Equal("userDefinedSourceUrl", values[1].Source);
Assert.Equal("userDefinedSource", values[1].Name);
Assert.True(values[1].IsEnabled);
Assert.Equal("urlB", values[2].Source);
Assert.Equal("B", values[2].Name);
Assert.False(values[2].IsEnabled);
}
[Fact]
public void CallSaveMethodAndLoadMethodShouldReturnTheSamePackageSet()
{
// Arrange
var expectedSources = new[] { new PackageSource("one", "one"), new PackageSource("two", "two"), new PackageSource("three", "three") };
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "one", false),
new SettingValue("two", "two", false),
new SettingValue("three", "three", false)
})
.Verifiable();
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable();
settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable();
settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable();
settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, IList<KeyValuePair<string, string>> values) =>
{
Assert.Equal(3, values.Count);
Assert.Equal("one", values[0].Key);
Assert.Equal("one", values[0].Value);
Assert.Equal("two", values[1].Key);
Assert.Equal("two", values[1].Value);
Assert.Equal("three", values[2].Key);
Assert.Equal("three", values[2].Value);
})
.Verifiable();
settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, IList<KeyValuePair<string, string>> values) =>
{
Assert.Empty(values);
})
.Verifiable();
var provider = CreatePackageSourceProvider(settings.Object);
// Act
var sources = provider.LoadPackageSources().ToList();
provider.SavePackageSources(sources);
// Assert
settings.Verify();
Assert.Equal(3, sources.Count);
for (int i = 0; i < sources.Count; i++)
{
AssertPackageSource(expectedSources[i], sources[i].Name, sources[i].Source, true);
}
}
[Fact]
public void WithMachineWideSources()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "one", true),
new SettingValue("two", "two", false),
new SettingValue("three", "three", false)
});
settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, IList<KeyValuePair<string, string>> values) =>
{
// verifies that only sources "two" and "three" are passed.
// the machine wide source "one" is not.
Assert.Equal(2, values.Count);
Assert.Equal("two", values[0].Key);
Assert.Equal("two", values[0].Value);
Assert.Equal("three", values[1].Key);
Assert.Equal("three", values[1].Value);
})
.Verifiable();
settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, IList<KeyValuePair<string, string>> values) =>
{
// verifies that the machine wide source "one" is passed here
// since it is disabled.
Assert.Equal(1, values.Count);
Assert.Equal("one", values[0].Key);
Assert.Equal("true", values[0].Value);
})
.Verifiable();
var provider = CreatePackageSourceProvider(settings.Object);
// Act
var sources = provider.LoadPackageSources().ToList();
// disable the machine wide source "one", and save the result in provider.
Assert.Equal("one", sources[2].Name);
sources[2].IsEnabled = false;
provider.SavePackageSources(sources);
// Assert
// all assertions are done inside Callback()'s
}
[Fact]
public void LoadPackageSourcesReturnCorrectDataFromSettings()
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", true),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
})
.Verifiable();
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
var provider = CreatePackageSourceProvider(settings.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[0], "two", "twosource", true);
AssertPackageSource(values[1], "three", "threesource", true);
AssertPackageSource(values[2], "one", "onesource", true, true);
}
[Fact]
public void LoadPackageSourcesReturnCorrectDataFromSettingsWhenSomePackageSourceIsDisabled()
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("two", "true") });
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
var provider = CreatePackageSourceProvider(settings.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[0], "one", "onesource", true);
AssertPackageSource(values[1], "two", "twosource", false);
AssertPackageSource(values[2], "three", "threesource", true);
}
/// <summary>
/// The following test tests case 1 listed in PackageSourceProvider.SetDefaultPackageSources(...)
/// Case 1. Default Package Source is already present matching both feed source and the feed name
/// </summary>
[Fact]
public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInNameAndSource()
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false)});
// Disable package source one
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("one", "true") });
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
string configurationDefaultsFileContent = @"
<configuration>
<packageSources>
<add key='one' value='onesource' />
</packageSources>
</configuration>";
var mockFileSystem = new MockFileSystem();
var configurationDefaultsPath = "NuGetDefaults.config";
mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent);
ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath);
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources);
// Act
var values = provider.LoadPackageSources();
// Assert
Assert.Equal(1, values.Count());
// Package source 'one' represents case 1. No real change takes place. IsOfficial will become true though. IsEnabled remains false as it is ISettings
AssertPackageSource(values.First(), "one", "onesource", false, false, true);
}
/// <summary>
/// The following test tests case 2 listed in PackageSourceProvider.SetDefaultPackageSources(...)
/// Case 2. Default Package Source is already present matching feed source but with a different feed name. DO NOTHING
/// </summary>
[Fact]
public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInSourceButNotInName()
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("two", "twosource", false) });
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
string configurationDefaultsFileContent = @"
<configuration>
<packageSources>
<add key='twodefault' value='twosource' />
</packageSources>
<disabledPackageSources>
<add key='twodefault' value='true' />
</disabledPackageSources>
</configuration>";
var mockFileSystem = new MockFileSystem();
var configurationDefaultsPath = "NuGetDefaults.config";
mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent);
ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath);
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources);
// Act
var values = provider.LoadPackageSources();
// Assert
Assert.Equal(1, values.Count());
// Package source 'two' represents case 2. No Change effected. The existing feed will not be official
AssertPackageSource(values.First(), "two", "twosource", true, false, false);
}
/// <summary>
/// The following test tests case 3 listed in PackageSourceProvider.SetDefaultPackageSources(...)
/// Case 3. Default Package Source is not present, but there is another feed source with the same feed name. Override that feed entirely
/// </summary>
[Fact]
public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInNameButNotInSource()
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("three", "threesource", false) });
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
string configurationDefaultsFileContent = @"
<configuration>
<packageSources>
<add key='three' value='threedefaultsource' />
</packageSources>
</configuration>";
var mockFileSystem = new MockFileSystem();
var configurationDefaultsPath = "NuGetDefaults.config";
mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent);
ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath);
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources);
// Act
var values = provider.LoadPackageSources();
// Assert
Assert.Equal(1, values.Count());
// Package source 'three' represents case 3. Completely overwritten. Noticeably, Feed Source will match Configuration Default settings
AssertPackageSource(values.First(), "three", "threedefaultsource", true, false, true);
}
/// <summary>
/// The following test tests case 3 listed in PackageSourceProvider.SetDefaultPackageSources(...)
/// Case 4. Default Package Source is not present, simply, add it
/// </summary>
[Fact]
public void LoadPackageSourcesWhereNoLoadedSourceMatchesADefaultSource()
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new List<SettingValue>());
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
string configurationDefaultsFileContent = @"
<configuration>
<packageSources>
<add key='four' value='foursource' />
</packageSources>
</configuration>";
var mockFileSystem = new MockFileSystem();
var configurationDefaultsPath = "NuGetDefaults.config";
mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent);
ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath);
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources);
// Act
var values = provider.LoadPackageSources();
// Assert
Assert.Equal(1, values.Count());
// Package source 'four' represents case 4. Simply Added to the list increasing the count by 1. ISettings only has 3 package sources. But, LoadPackageSources returns 4
AssertPackageSource(values.First(), "four", "foursource", true, false, true);
}
[Fact]
public void LoadPackageSourcesDoesNotReturnProviderDefaultsWhenConfigurationDefaultPackageSourcesIsNotEmpty()
{
// Arrange
var settings = new Mock<ISettings>().Object;
string configurationDefaultsFileContent = @"
<configuration>
<packageSources>
<add key='configurationDefaultOne' value='configurationDefaultOneSource' />
<add key='configurationDefaultTwo' value='configurationDefaultTwoSource' />
</packageSources>
</configuration>";
var mockFileSystem = new MockFileSystem();
var configurationDefaultsPath = "NuGetDefaults.config";
mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent);
ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath);
var provider = CreatePackageSourceProvider(settings,
providerDefaultSources: new[] { new PackageSource("providerDefaultA"), new PackageSource("providerDefaultB") },
migratePackageSources: null,
configurationDefaultSources: configurationDefaults.DefaultPackageSources);
// Act
var values = provider.LoadPackageSources();
// Assert
Assert.Equal(2, values.Count());
Assert.Equal("configurationDefaultOneSource", values.First().Source);
Assert.Equal("configurationDefaultTwoSource", values.Last().Source);
}
[Fact]
public void LoadPackageSourcesAddsAConfigurationDefaultBackEvenAfterMigration()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false) });
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
string configurationDefaultsFileContent = @"
<configuration>
<packageSources>
<add key='NuGet official package source' value='https://nuget.org/api/v2' />
</packageSources>
</configuration>";
var mockFileSystem = new MockFileSystem();
var configurationDefaultsPath = "NuGetDefaults.config";
mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent);
ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath);
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null,
migratePackageSources: new Dictionary<PackageSource, PackageSource>
{
{ new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") }
},
configurationDefaultSources: configurationDefaults.DefaultPackageSources);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(2, values.Count);
Assert.Equal("nuget.org", values[0].Name);
Assert.Equal("https://www.nuget.org/api/v2", values[0].Source);
Assert.Equal("NuGet official package source", values[1].Name);
Assert.Equal("https://nuget.org/api/v2", values[1].Source);
}
[Fact]
public void LoadPackageSourcesDoesNotDuplicateFeedsOnMigration()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false),
new SettingValue("nuget.org", "https://www.nuget.org/api/v2", false) });
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null,
migratePackageSources: new Dictionary<PackageSource, PackageSource>
{
{ new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") }
});
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(1, values.Count);
Assert.Equal("nuget.org", values[0].Name);
Assert.Equal("https://www.nuget.org/api/v2", values[0].Source);
}
[Fact]
public void LoadPackageSourcesDoesNotDuplicateFeedsOnMigrationAndSavesIt()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false),
new SettingValue("nuget.org", "https://www.nuget.org/api/v2", false) });
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]);
settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable();
settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable();
settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable();
settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, IList<KeyValuePair<string, string>> valuePairs) =>
{
Assert.Equal(1, valuePairs.Count);
Assert.Equal("nuget.org", valuePairs[0].Key);
Assert.Equal("https://www.nuget.org/api/v2", valuePairs[0].Value);
})
.Verifiable();
var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null,
migratePackageSources: new Dictionary<PackageSource, PackageSource>
{
{ new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") }
});
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(1, values.Count);
Assert.Equal("nuget.org", values[0].Name);
Assert.Equal("https://www.nuget.org/api/v2", values[0].Source);
settings.Verify();
}
[Fact]
public void DisablePackageSourceAddEntryToSettings()
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.SetValue("disabledPackageSources", "A", "true")).Verifiable();
var provider = CreatePackageSourceProvider(settings.Object);
// Act
provider.DisablePackageSource(new PackageSource("source", "A"));
// Assert
settings.Verify();
}
[Fact]
public void IsPackageSourceEnabledReturnsFalseIfTheSourceIsDisabled()
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetValue("disabledPackageSources", "A")).Returns("sdfds");
var provider = CreatePackageSourceProvider(settings.Object);
// Act
bool isEnabled = provider.IsPackageSourceEnabled(new PackageSource("source", "A"));
// Assert
Assert.False(isEnabled);
}
[Theory]
[InlineData((string)null)]
[InlineData("")]
public void IsPackageSourceEnabledReturnsTrueIfTheSourceIsNotDisabled(string returnValue)
{
// Arrange
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.GetValue("disabledPackageSources", "A")).Returns(returnValue);
var provider = CreatePackageSourceProvider(settings.Object);
// Act
bool isEnabled = provider.IsPackageSourceEnabled(new PackageSource("source", "A"));
// Assert
Assert.True(isEnabled);
}
[Theory]
[InlineData(new object[] { null, "abcd" })]
[InlineData(new object[] { "", "abcd" })]
[InlineData(new object[] { "abcd", null })]
[InlineData(new object[] { "abcd", "" })]
public void LoadPackageSourcesIgnoresInvalidCredentialPairsFromSettings(string userName, string password)
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two"))
.Returns(new [] { new KeyValuePair<string, string>("Username", userName), new KeyValuePair<string, string>("Password", password) });
var provider = CreatePackageSourceProvider(settings.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[1], "two", "twosource", true);
Assert.Null(values[1].UserName);
Assert.Null(values[1].Password);
}
[Fact]
public void LoadPackageSourcesReadsCredentialPairsFromSettings()
{
// Arrange
string encryptedPassword = EncryptionUtility.EncryptString("topsecret");
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two"))
.Returns(new[] { new KeyValuePair<string, string>("Username", "user1"), new KeyValuePair<string, string>("Password", encryptedPassword) });
var provider = CreatePackageSourceProvider(settings.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[1], "two", "twosource", true);
Assert.Equal("user1", values[1].UserName);
Assert.Equal("topsecret", values[1].Password);
Assert.False(values[1].IsPasswordClearText);
}
[Fact]
public void LoadPackageSourcesReadsClearTextCredentialPairsFromSettings()
{
// Arrange
const string clearTextPassword = "topsecret";
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two"))
.Returns(new[] { new KeyValuePair<string, string>("Username", "user1"), new KeyValuePair<string, string>("ClearTextPassword", clearTextPassword) });
var provider = CreatePackageSourceProvider(settings.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[1], "two", "twosource", true);
Assert.Equal("user1", values[1].UserName);
Assert.True(values[1].IsPasswordClearText);
Assert.Equal("topsecret", values[1].Password);
}
[Theory]
[InlineData("Username=john;Password=johnspassword")]
[InlineData("uSerName=john;PASSWOrD=johnspassword")]
[InlineData(" Username=john; Password=johnspassword ")]
public void LoadPackageSourcesLoadsCredentialPairsFromEnvironmentVariables(string rawCredentials)
{
// Arrange
const string userName = "john";
const string password = "johnspassword";
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
var environment = new Mock<IEnvironmentVariableReader>();
environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two"))
.Returns(rawCredentials);
var provider = CreatePackageSourceProvider(settings.Object, environment:environment.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[1], "two", "twosource", true);
Assert.Equal(userName, values[1].UserName);
Assert.Equal(password, values[1].Password);
}
[Theory]
[InlineData("uername=john;Password=johnspassword")]
[InlineData(".Username=john;Password=johnspasswordf")]
[InlineData("What is this I don't even")]
public void LoadPackageSourcesIgnoresMalformedCredentialPairsFromEnvironmentVariables(string rawCredentials)
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
var environment = new Mock<IEnvironmentVariableReader>();
environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two"))
.Returns(rawCredentials);
var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[1], "two", "twosource", true);
Assert.Null(values[1].UserName);
Assert.Null(values[1].Password);
}
[Fact]
public void LoadPackageSourcesEnvironmentCredentialsTakePrecedenceOverSettingsCredentials()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two"))
.Returns(new[] { new KeyValuePair<string, string>("Username", "settinguser"), new KeyValuePair<string, string>("ClearTextPassword", "settingpassword") });
var environment = new Mock<IEnvironmentVariableReader>();
environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two"))
.Returns("Username=envirouser;Password=enviropassword");
var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[1], "two", "twosource", true);
Assert.Equal("envirouser", values[1].UserName);
Assert.Equal("enviropassword", values[1].Password);
}
[Fact]
public void LoadPackageSourcesWhenEnvironmentCredentialsAreMalformedFallsbackToSettingsCredentials()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("three", "threesource", false)
});
settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two"))
.Returns(new[] { new KeyValuePair<string, string>("Username", "settinguser"), new KeyValuePair<string, string>("ClearTextPassword", "settingpassword") });
var environment = new Mock<IEnvironmentVariableReader>();
environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two"))
.Returns("I for one don't understand environment variables");
var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(3, values.Count);
AssertPackageSource(values[1], "two", "twosource", true);
Assert.Equal("settinguser", values[1].UserName);
Assert.Equal("settingpassword", values[1].Password);
}
// Test that when there are duplicate sources, i.e. sources with the same name,
// then the source specified in one Settings with the highest priority is used.
[Fact]
public void DuplicatePackageSources()
{
// Arrange
var settings = new Mock<ISettings>();
settings.Setup(s => s.GetSettingValues("packageSources", true))
.Returns(new[] { new SettingValue("one", "onesource", false),
new SettingValue("two", "twosource", false),
new SettingValue("one", "threesource", false)
});
var provider = CreatePackageSourceProvider(settings.Object);
// Act
var values = provider.LoadPackageSources().ToList();
// Assert
Assert.Equal(2, values.Count);
AssertPackageSource(values[0], "two", "twosource", true);
AssertPackageSource(values[1], "one", "threesource", true);
}
[Fact]
public void SavePackageSourcesSaveCorrectDataToSettings()
{
// Arrange
var sources = new[] { new PackageSource("one"), new PackageSource("two"), new PackageSource("three") };
var settings = new Mock<ISettings>(MockBehavior.Strict);
settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable();
settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable();
settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable();
settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, IList<KeyValuePair<string, string>> values) =>
{
Assert.Equal(3, values.Count);
Assert.Equal("one", values[0].Key);
Assert.Equal("one", values[0].Value);
Assert.Equal("two", values[1].Key);
Assert.Equal("two", values[1].Value);
Assert.Equal("three", values[2].Key);
Assert.Equal("three", values[2].Value);
})
.Verifiable();
settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, IList<KeyValuePair<string, string>> values) =>
{
Assert.Empty(values);
})
.Verifiable();
var provider = CreatePackageSourceProvider(settings.Object);
// Act
provider.SavePackageSources(sources);
// Assert
settings.Verify();
}
[Fact]
public void SavePackageSourcesSaveCorrectDataToSettingsWhenSomePackageSourceIsDisabled()
{
// Arrange
var sources = new[] { new PackageSource("one"), new PackageSource("two", "two", isEnabled: false), new PackageSource("three") };
var settings = new Mock<ISettings>();
settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable();
settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, IList<KeyValuePair<string, string>> values) =>
{
Assert.Equal(1, values.Count);
Assert.Equal("two", values[0].Key);
Assert.Equal("true", values[0].Value, StringComparer.OrdinalIgnoreCase);
})
.Verifiable();
var provider = CreatePackageSourceProvider(settings.Object);
// Act
provider.SavePackageSources(sources);
// Assert
settings.Verify();
}
[Fact]
public void SavePackageSourcesSavesCredentials()
{
// Arrange
var entropyBytes = Encoding.UTF8.GetBytes("NuGet");
var sources = new[] { new PackageSource("one"),
new PackageSource("twosource", "twoname") { UserName = "User", Password = "password" },
new PackageSource("three")
};
var settings = new Mock<ISettings>();
settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable();
settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable();
settings.Setup(s => s.SetNestedValues("packageSourceCredentials", It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, string key, IList<KeyValuePair<string, string>> values) =>
{
Assert.Equal("twoname", key);
Assert.Equal(2, values.Count);
AssertKVP(new KeyValuePair<string, string>("Username", "User"), values[0]);
Assert.Equal("Password", values[1].Key);
string decryptedPassword = Encoding.UTF8.GetString(
ProtectedData.Unprotect(Convert.FromBase64String(values[1].Value), entropyBytes, DataProtectionScope.CurrentUser));
Assert.Equal("Password", values[1].Key);
Assert.Equal("password", decryptedPassword);
})
.Verifiable();
var provider = CreatePackageSourceProvider(settings.Object);
// Act
provider.SavePackageSources(sources);
// Assert
settings.Verify();
}
[Fact]
public void SavePackageSourcesSavesClearTextCredentials()
{
// Arrange
var sources = new[] { new PackageSource("one"),
new PackageSource("twosource", "twoname") { UserName = "User", Password = "password", IsPasswordClearText = true},
new PackageSource("three")
};
var settings = new Mock<ISettings>();
settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable();
settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable();
settings.Setup(s => s.SetNestedValues("packageSourceCredentials", It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>()))
.Callback((string section, string key, IList<KeyValuePair<string, string>> values) =>
{
Assert.Equal("twoname", key);
Assert.Equal(2, values.Count);
AssertKVP(new KeyValuePair<string, string>("Username", "User"), values[0]);
AssertKVP(new KeyValuePair<string, string>("ClearTextPassword", "password"), values[1]);
})
.Verifiable();
var provider = CreatePackageSourceProvider(settings.Object);
// Act
provider.SavePackageSources(sources);
// Assert
settings.Verify();
}
[Fact]
public void GetAggregateReturnsAggregateRepositoryForAllSources()
{
// Arrange
var repositoryA = new Mock<IPackageRepository>();
var repositoryB = new Mock<IPackageRepository>();
var factory = new Mock<IPackageRepositoryFactory>();
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object);
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Returns(repositoryB.Object);
var sources = new Mock<IPackageSourceProvider>();
sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B") });
// Act
var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false);
// Assert
Assert.Equal(2, repo.Repositories.Count());
Assert.Equal(repositoryA.Object, repo.Repositories.First());
Assert.Equal(repositoryB.Object, repo.Repositories.Last());
}
[Fact]
public void GetAggregateSkipsInvalidSources()
{
// Arrange
var repositoryA = new Mock<IPackageRepository>();
var repositoryC = new Mock<IPackageRepository>();
var factory = new Mock<IPackageRepositoryFactory>();
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object);
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Throws(new InvalidOperationException());
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Returns(repositoryC.Object);
var sources = new Mock<IPackageSourceProvider>();
sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B"), new PackageSource("C") });
// Act
var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: true);
// Assert
Assert.Equal(2, repo.Repositories.Count());
Assert.Equal(repositoryA.Object, repo.Repositories.First());
Assert.Equal(repositoryC.Object, repo.Repositories.Last());
}
[Fact]
public void GetAggregateSkipsDisabledSources()
{
// Arrange
var repositoryA = new Mock<IPackageRepository>();
var repositoryB = new Mock<IPackageRepository>();
var factory = new Mock<IPackageRepositoryFactory>();
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object);
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Returns(repositoryB.Object);
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Throws(new Exception());
var sources = new Mock<IPackageSourceProvider>();
sources.Setup(c => c.LoadPackageSources()).Returns(new[] {
new PackageSource("A"), new PackageSource("B", "B", isEnabled: false), new PackageSource("C", "C", isEnabled: false) });
// Act
var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false);
// Assert
Assert.Equal(1, repo.Repositories.Count());
Assert.Equal(repositoryA.Object, repo.Repositories.First());
}
[Fact]
public void GetAggregateHandlesInvalidUriSources()
{
// Arrange
var factory = PackageRepositoryFactory.Default;
var sources = new Mock<IPackageSourceProvider>();
sources.Setup(c => c.LoadPackageSources()).Returns(new[] {
new PackageSource("Bad 1"),
new PackageSource(@"x:sjdkfjhsdjhfgjdsgjglhjk"),
new PackageSource(@"http:\\//")
});
// Act
var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory, ignoreFailingRepositories: true);
// Assert
Assert.False(repo.Repositories.Any());
}
[Fact]
public void GetAggregateSetsIgnoreInvalidRepositoryProperty()
{
// Arrange
var factory = new Mock<IPackageRepositoryFactory>();
bool ignoreRepository = true;
var sources = new Mock<IPackageSourceProvider>();
sources.Setup(c => c.LoadPackageSources()).Returns(Enumerable.Empty<PackageSource>());
// Act
var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: ignoreRepository);
// Assert
Assert.True(repo.IgnoreFailingRepositories);
}
[Fact]
public void GetAggregateWithInvalidSourcesThrows()
{
// Arrange
var repositoryA = new Mock<IPackageRepository>();
var repositoryC = new Mock<IPackageRepository>();
var factory = new Mock<IPackageRepositoryFactory>();
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object);
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Throws(new InvalidOperationException());
factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Returns(repositoryC.Object);
var sources = new Mock<IPackageSourceProvider>();
sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B"), new PackageSource("C") });
// Act and Assert
ExceptionAssert.Throws<InvalidOperationException>(() => sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false));
}
[Fact]
public void ResolveSourceLooksUpNameAndSource()
{
// Arrange
var sources = new Mock<IPackageSourceProvider>();
PackageSource source1 = new PackageSource("Source", "SourceName"), source2 = new PackageSource("http://www.test.com", "Baz");
sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2 });
// Act
var result1 = sources.Object.ResolveSource("http://www.test.com");
var result2 = sources.Object.ResolveSource("Baz");
var result3 = sources.Object.ResolveSource("SourceName");
// Assert
Assert.Equal(source2.Source, result1);
Assert.Equal(source2.Source, result2);
Assert.Equal(source1.Source, result3);
}
[Fact]
public void ResolveSourceIgnoreDisabledSources()
{
// Arrange
var sources = new Mock<IPackageSourceProvider>();
PackageSource source1 = new PackageSource("Source", "SourceName");
PackageSource source2 = new PackageSource("http://www.test.com", "Baz", isEnabled: false);
PackageSource source3 = new PackageSource("http://www.bing.com", "Foo", isEnabled: false);
sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2, source3 });
// Act
var result1 = sources.Object.ResolveSource("http://www.test.com");
var result2 = sources.Object.ResolveSource("Baz");
var result3 = sources.Object.ResolveSource("Foo");
var result4 = sources.Object.ResolveSource("SourceName");
// Assert
Assert.Equal("http://www.test.com", result1);
Assert.Equal("Baz", result2);
Assert.Equal("Foo", result3);
Assert.Equal("Source", result4);
}
[Fact]
public void ResolveSourceReturnsOriginalValueIfNotFoundInSources()
{
// Arrange
var sources = new Mock<IPackageSourceProvider>();
PackageSource source1 = new PackageSource("Source", "SourceName"), source2 = new PackageSource("http://www.test.com", "Baz");
sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2 });
var source = "http://www.does-not-exist.com";
// Act
var result = sources.Object.ResolveSource(source);
// Assert
Assert.Equal(source, result);
}
private void AssertPackageSource(PackageSource ps, string name, string source, bool isEnabled, bool isMachineWide = false, bool isOfficial = false)
{
Assert.Equal(name, ps.Name);
Assert.Equal(source, ps.Source);
Assert.True(ps.IsEnabled == isEnabled);
Assert.True(ps.IsMachineWide == isMachineWide);
Assert.True(ps.IsOfficial == isOfficial);
}
private IPackageSourceProvider CreatePackageSourceProvider(
ISettings settings = null,
IEnumerable<PackageSource> providerDefaultSources = null,
IDictionary<PackageSource, PackageSource> migratePackageSources = null,
IEnumerable<PackageSource> configurationDefaultSources = null,
IEnvironmentVariableReader environment = null)
{
settings = settings ?? new Mock<ISettings>().Object;
environment = environment ?? new Mock<IEnvironmentVariableReader>().Object;
return new PackageSourceProvider(settings, providerDefaultSources, migratePackageSources, configurationDefaultSources, environment);
}
private static void AssertKVP(KeyValuePair<string, string> expected, KeyValuePair<string, string> actual)
{
Assert.Equal(expected.Key, actual.Key);
Assert.Equal(expected.Value, actual.Value);
}
}
}
| |
#if DEBUG
using System;
using System.Data.OracleClient;
using ALinq.SqlClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test
{
[TestClass]
public class NorOracleDataTypeProviderTest : OracleDataTypeProviderTest
{
#region MyRegion
//[TestMethod]
//public void ParseSqlDataType()
//{
// var typeProvider = new OracleDataTypeProvider();
// var dbType = "CHAR(1)";
// var sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(char), sqlType.GetClosestRuntimeType());
// Assert.AreEqual(1, sqlType.Size);
// dbType = "NCHAR ( 20 )";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(string), sqlType.GetClosestRuntimeType());
// Assert.IsTrue(sqlType.IsUnicodeType);
// Assert.AreEqual(sqlType.Size, 20);
// dbType = "NVARCHAR2(20)";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(string), sqlType.GetClosestRuntimeType());
// Assert.IsTrue(sqlType.IsUnicodeType);
// Assert.AreEqual(sqlType.Size, 20);
// dbType = "NUMBER(10)";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(decimal), sqlType.GetClosestRuntimeType());
// Assert.AreEqual(sqlType.Precision, 10);
// dbType = "NUMBER(10,2)";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(decimal), sqlType.GetClosestRuntimeType());
// Assert.AreEqual(sqlType.Precision, 10);
// Assert.AreEqual(sqlType.Scale, 2);
// //Assert.AreEqual(sqlType.Size, 10);
// dbType = "NUMBER(10,0)";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(decimal), sqlType.GetClosestRuntimeType());
// Assert.AreEqual(sqlType.Precision, 10);
// Assert.AreEqual(sqlType.Scale, 0);
// dbType = "NUMBER";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(decimal), sqlType.GetClosestRuntimeType());
// Assert.IsTrue(sqlType.Precision > 0);
// Assert.IsTrue(sqlType.Scale > 0);
// dbType = "FLOAT";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(float), sqlType.GetClosestRuntimeType());
// dbType = "FLOAT(10)";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(float), sqlType.GetClosestRuntimeType());
// Assert.AreEqual(sqlType.Size, 10);
// dbType = "RAW";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(byte[]), sqlType.GetClosestRuntimeType());
// dbType = "BLOB";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(byte[]), sqlType.GetClosestRuntimeType());
// Assert.IsTrue(sqlType.IsLargeType);
// dbType = "CLOB";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(string), sqlType.GetClosestRuntimeType());
// Assert.IsTrue(sqlType.IsLargeType);
// dbType = "NCLOB";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(string), sqlType.GetClosestRuntimeType());
// Assert.IsTrue(sqlType.IsLargeType);
// Assert.IsTrue(sqlType.IsUnicodeType);
// dbType = "CURSOR";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(object), sqlType.GetClosestRuntimeType());
// dbType = "DATE";
// sqlType = typeProvider.Parse(dbType);
// Assert.AreEqual(typeof(DateTime), sqlType.GetClosestRuntimeType());
//}
#endregion
internal override ITypeSystemProvider CreateDataProvider()
{
return new ALinq.Oracle.OracleDataTypeProvider();
}
internal override Type GetProviderType()
{
return typeof(ALinq.Oracle.OracleProvider);
}
[TestMethod]
public override void ParseSqlDataType()
{
base.ParseSqlDataType();
var typeProvider = CreateDataProvider();
var dbType = "DATETIME";
var sqlType = typeProvider.Parse(dbType);
Assert.AreEqual(typeof(DateTime), sqlType.GetClosestRuntimeType());
Assert.IsTrue(sqlType.IsSameTypeFamily(typeProvider.From(typeof(DateTime))));
dbType = "BFILE";
sqlType = typeProvider.Parse(dbType);
Assert.AreEqual(typeof(Byte[]), sqlType.GetClosestRuntimeType());
//Assert.IsTrue(sqlType.IsSameTypeFamily(typeProvider.From(typeof(Binary))));
}
[TestMethod]
public void FromTypeTest()
{
var typeProvider = CreateDataProvider();
var dbType = typeProvider.From(typeof(int));
Assert.AreEqual(OracleType.Int32, dbType.SqlDbType);
dbType = typeProvider.From(typeof(string));
Assert.AreEqual(OracleType.VarChar, dbType.SqlDbType);
Assert.AreEqual(4000, dbType.Size);
dbType = typeProvider.From(typeof(DateTime));
Assert.AreEqual(OracleType.DateTime, dbType.SqlDbType);
dbType = typeProvider.From(typeof (byte[]));
Console.WriteLine(dbType.ToQueryString());
}
}
[TestClass]
public class Sql2000DataTypeProvider
{
[TestMethod]
public void ParseSqlDataType()
{
var typeProvider = CreateDataProvider();
var dbType = "CHAR(1)";
var sqlType = typeProvider.Parse(dbType);
//Assert.AreEqual(typeof (char), sqlType.GetClosestRuntimeType());
//Assert.AreEqual(1, sqlType.Size);
dbType = "CHAR";
sqlType = typeProvider.Parse(dbType);
//Assert.AreEqual(typeof(char), sqlType.GetClosestRuntimeType());
dbType = "BigInt";
sqlType = typeProvider.Parse(dbType);
dbType = "Binary";
sqlType = typeProvider.Parse(dbType);
dbType = "Bit";
sqlType = typeProvider.Parse(dbType);
dbType = "DateTime";
sqlType = typeProvider.Parse(dbType);
dbType = "Decimal";
sqlType = typeProvider.Parse(dbType);
dbType = "Float";
sqlType = typeProvider.Parse(dbType);
dbType = "Image";
sqlType = typeProvider.Parse(dbType);
dbType = "Int";
sqlType = typeProvider.Parse(dbType);
dbType = "Money";
sqlType = typeProvider.Parse(dbType);
dbType = "NChar";
sqlType = typeProvider.Parse(dbType);
dbType = "NText";
sqlType = typeProvider.Parse(dbType);
dbType = "NVarChar";
sqlType = typeProvider.Parse(dbType);
dbType = "Real";
sqlType = typeProvider.Parse(dbType);
dbType = "UniqueIdentifier";
sqlType = typeProvider.Parse(dbType);
dbType = "SmallDateTime";
sqlType = typeProvider.Parse(dbType);
dbType = "SmallInt";
sqlType = typeProvider.Parse(dbType);
dbType = "SmallMoney";
sqlType = typeProvider.Parse(dbType);
dbType = "Text";
sqlType = typeProvider.Parse(dbType);
dbType = "Timestamp";
sqlType = typeProvider.Parse(dbType);
dbType = "TinyInt";
sqlType = typeProvider.Parse(dbType);
dbType = "VarBinary";
sqlType = typeProvider.Parse(dbType);
dbType = "VarChar";
sqlType = typeProvider.Parse(dbType);
dbType = "Variant";
sqlType = typeProvider.Parse(dbType);
dbType = "Xml";
sqlType = typeProvider.Parse(dbType);
dbType = "Udt";
sqlType = typeProvider.Parse(dbType);
dbType = "Structured";
sqlType = typeProvider.Parse(dbType);
dbType = "Date";
sqlType = typeProvider.Parse(dbType);
dbType = "Time";
sqlType = typeProvider.Parse(dbType);
dbType = "DateTime2";
sqlType = typeProvider.Parse(dbType);
dbType = "DateTimeOffset";
sqlType = typeProvider.Parse(dbType);
}
internal ITypeSystemProvider CreateDataProvider()
{
return new ALinq.SqlClient.SqlTypeSystem.Sql2000Provider();
}
}
[TestClass]
public class Sql2005DataTypeProvider
{
[TestMethod]
public void ParseSqlDataType()
{
var typeProvider = CreateDataProvider();
var dbType = "CHAR(1)";
var sqlType = typeProvider.Parse(dbType);
Assert.AreEqual(typeof(char), sqlType.GetClosestRuntimeType());
Assert.AreEqual(1, sqlType.Size);
}
internal ITypeSystemProvider CreateDataProvider()
{
return new ALinq.SqlClient.SqlTypeSystem.Sql2000Provider();
}
}
}
#endif
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// RecipientIdentityPhoneNumber
/// </summary>
[DataContract]
public partial class RecipientIdentityPhoneNumber : IEquatable<RecipientIdentityPhoneNumber>, IValidatableObject
{
public RecipientIdentityPhoneNumber()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="RecipientIdentityPhoneNumber" /> class.
/// </summary>
/// <param name="CountryCode">CountryCode.</param>
/// <param name="CountryCodeLock">CountryCodeLock.</param>
/// <param name="CountryCodeMetadata">CountryCodeMetadata.</param>
/// <param name="Extension">Extension.</param>
/// <param name="ExtensionMetadata">ExtensionMetadata.</param>
/// <param name="Number">Number.</param>
/// <param name="NumberMetadata">NumberMetadata.</param>
public RecipientIdentityPhoneNumber(string CountryCode = default(string), string CountryCodeLock = default(string), PropertyMetadata CountryCodeMetadata = default(PropertyMetadata), string Extension = default(string), PropertyMetadata ExtensionMetadata = default(PropertyMetadata), string Number = default(string), PropertyMetadata NumberMetadata = default(PropertyMetadata))
{
this.CountryCode = CountryCode;
this.CountryCodeLock = CountryCodeLock;
this.CountryCodeMetadata = CountryCodeMetadata;
this.Extension = Extension;
this.ExtensionMetadata = ExtensionMetadata;
this.Number = Number;
this.NumberMetadata = NumberMetadata;
}
/// <summary>
/// Gets or Sets CountryCode
/// </summary>
[DataMember(Name="countryCode", EmitDefaultValue=false)]
public string CountryCode { get; set; }
/// <summary>
/// Gets or Sets CountryCodeLock
/// </summary>
[DataMember(Name="countryCodeLock", EmitDefaultValue=false)]
public string CountryCodeLock { get; set; }
/// <summary>
/// Gets or Sets CountryCodeMetadata
/// </summary>
[DataMember(Name="countryCodeMetadata", EmitDefaultValue=false)]
public PropertyMetadata CountryCodeMetadata { get; set; }
/// <summary>
/// Gets or Sets Extension
/// </summary>
[DataMember(Name="extension", EmitDefaultValue=false)]
public string Extension { get; set; }
/// <summary>
/// Gets or Sets ExtensionMetadata
/// </summary>
[DataMember(Name="extensionMetadata", EmitDefaultValue=false)]
public PropertyMetadata ExtensionMetadata { get; set; }
/// <summary>
/// Gets or Sets Number
/// </summary>
[DataMember(Name="number", EmitDefaultValue=false)]
public string Number { get; set; }
/// <summary>
/// Gets or Sets NumberMetadata
/// </summary>
[DataMember(Name="numberMetadata", EmitDefaultValue=false)]
public PropertyMetadata NumberMetadata { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RecipientIdentityPhoneNumber {\n");
sb.Append(" CountryCode: ").Append(CountryCode).Append("\n");
sb.Append(" CountryCodeLock: ").Append(CountryCodeLock).Append("\n");
sb.Append(" CountryCodeMetadata: ").Append(CountryCodeMetadata).Append("\n");
sb.Append(" Extension: ").Append(Extension).Append("\n");
sb.Append(" ExtensionMetadata: ").Append(ExtensionMetadata).Append("\n");
sb.Append(" Number: ").Append(Number).Append("\n");
sb.Append(" NumberMetadata: ").Append(NumberMetadata).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as RecipientIdentityPhoneNumber);
}
/// <summary>
/// Returns true if RecipientIdentityPhoneNumber instances are equal
/// </summary>
/// <param name="other">Instance of RecipientIdentityPhoneNumber to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RecipientIdentityPhoneNumber other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CountryCode == other.CountryCode ||
this.CountryCode != null &&
this.CountryCode.Equals(other.CountryCode)
) &&
(
this.CountryCodeLock == other.CountryCodeLock ||
this.CountryCodeLock != null &&
this.CountryCodeLock.Equals(other.CountryCodeLock)
) &&
(
this.CountryCodeMetadata == other.CountryCodeMetadata ||
this.CountryCodeMetadata != null &&
this.CountryCodeMetadata.Equals(other.CountryCodeMetadata)
) &&
(
this.Extension == other.Extension ||
this.Extension != null &&
this.Extension.Equals(other.Extension)
) &&
(
this.ExtensionMetadata == other.ExtensionMetadata ||
this.ExtensionMetadata != null &&
this.ExtensionMetadata.Equals(other.ExtensionMetadata)
) &&
(
this.Number == other.Number ||
this.Number != null &&
this.Number.Equals(other.Number)
) &&
(
this.NumberMetadata == other.NumberMetadata ||
this.NumberMetadata != null &&
this.NumberMetadata.Equals(other.NumberMetadata)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CountryCode != null)
hash = hash * 59 + this.CountryCode.GetHashCode();
if (this.CountryCodeLock != null)
hash = hash * 59 + this.CountryCodeLock.GetHashCode();
if (this.CountryCodeMetadata != null)
hash = hash * 59 + this.CountryCodeMetadata.GetHashCode();
if (this.Extension != null)
hash = hash * 59 + this.Extension.GetHashCode();
if (this.ExtensionMetadata != null)
hash = hash * 59 + this.ExtensionMetadata.GetHashCode();
if (this.Number != null)
hash = hash * 59 + this.Number.GetHashCode();
if (this.NumberMetadata != null)
hash = hash * 59 + this.NumberMetadata.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Statistics;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse;
using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// A shim around LLUDPServer that implements the IClientNetworkServer interface
/// </summary>
public sealed class LLUDPServerShim : IClientNetworkServer
{
LLUDPServer m_udpServer;
public LLUDPServerShim()
{
}
public void Initialise(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
{
m_udpServer = new LLUDPServer(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource, circuitManager);
}
public void NetworkStop()
{
m_udpServer.Stop();
}
public void AddScene(IScene scene)
{
m_udpServer.AddScene(scene);
}
public bool HandlesRegion(Location x)
{
return m_udpServer.HandlesRegion(x);
}
public void Start()
{
m_udpServer.Start();
}
public void Stop()
{
m_udpServer.Stop();
}
}
/// <summary>
/// The LLUDP server for a region. This handles incoming and outgoing
/// packets for all UDP connections to the region
/// </summary>
public class LLUDPServer : OpenSimUDPBase
{
/// <summary>Maximum transmission unit, or UDP packet size, for the LLUDP protocol</summary>
public const int MTU = 1400;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>The measured resolution of Environment.TickCount</summary>
public readonly float TickCountResolution;
/// <summary>Number of terse prim updates to put on the queue each time the
/// OnQueueEmpty event is triggered for updates</summary>
public readonly int PrimTerseUpdatesPerPacket;
/// <summary>Number of terse avatar updates to put on the queue each time the
/// OnQueueEmpty event is triggered for updates</summary>
public readonly int AvatarTerseUpdatesPerPacket;
/// <summary>Number of full prim updates to put on the queue each time the
/// OnQueueEmpty event is triggered for updates</summary>
public readonly int PrimFullUpdatesPerPacket;
/// <summary>Number of texture packets to put on the queue each time the
/// OnQueueEmpty event is triggered for textures</summary>
public readonly int TextureSendLimit;
/// <summary>Handlers for incoming packets</summary>
//PacketEventDictionary packetEvents = new PacketEventDictionary();
/// <summary>Incoming packets that are awaiting handling</summary>
private OpenMetaverse.BlockingQueue<IncomingPacket> packetInbox = new OpenMetaverse.BlockingQueue<IncomingPacket>();
/// <summary></summary>
//private UDPClientCollection m_clients = new UDPClientCollection();
/// <summary>Bandwidth throttle for this UDP server</summary>
protected TokenBucket m_throttle;
/// <summary>Bandwidth throttle rates for this UDP server</summary>
protected ThrottleRates m_throttleRates;
/// <summary>Manages authentication for agent circuits</summary>
private AgentCircuitManager m_circuitManager;
/// <summary>Reference to the scene this UDP server is attached to</summary>
protected Scene m_scene;
/// <summary>The X/Y coordinates of the scene this UDP server is attached to</summary>
private Location m_location;
/// <summary>The size of the receive buffer for the UDP socket. This value
/// is passed up to the operating system and used in the system networking
/// stack. Use zero to leave this value as the default</summary>
private int m_recvBufferSize;
/// <summary>Flag to process packets asynchronously or synchronously</summary>
private bool m_asyncPacketHandling;
/// <summary>Tracks whether or not a packet was sent each round so we know
/// whether or not to sleep</summary>
private bool m_packetSent;
/// <summary>Environment.TickCount of the last time that packet stats were reported to the scene</summary>
private int m_elapsedMSSinceLastStatReport = 0;
/// <summary>Environment.TickCount of the last time the outgoing packet handler executed</summary>
private int m_tickLastOutgoingPacketHandler;
/// <summary>Keeps track of the number of elapsed milliseconds since the last time the outgoing packet handler looped</summary>
private int m_elapsedMSOutgoingPacketHandler;
/// <summary>Keeps track of the number of 100 millisecond periods elapsed in the outgoing packet handler executed</summary>
private int m_elapsed100MSOutgoingPacketHandler;
/// <summary>Keeps track of the number of 500 millisecond periods elapsed in the outgoing packet handler executed</summary>
private int m_elapsed500MSOutgoingPacketHandler;
/// <summary>Flag to signal when clients should check for resends</summary>
private bool m_resendUnacked;
/// <summary>Flag to signal when clients should send ACKs</summary>
private bool m_sendAcks;
/// <summary>Flag to signal when clients should send pings</summary>
private bool m_sendPing;
private int m_defaultRTO = 0;
private int m_maxRTO = 0;
public Socket Server { get { return null; } }
public LLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
: base(listenIP, (int)port)
{
#region Environment.TickCount Measurement
// Measure the resolution of Environment.TickCount
TickCountResolution = 0f;
for (int i = 0; i < 5; i++)
{
int start = Environment.TickCount;
int now = start;
while (now == start)
now = Environment.TickCount;
TickCountResolution += (float)(now - start) * 0.2f;
}
m_log.Info("[LLUDPSERVER]: Average Environment.TickCount resolution: " + TickCountResolution + "ms");
TickCountResolution = (float)Math.Ceiling(TickCountResolution);
#endregion Environment.TickCount Measurement
m_circuitManager = circuitManager;
int sceneThrottleBps = 0;
IConfig config = configSource.Configs["ClientStack.LindenUDP"];
if (config != null)
{
m_asyncPacketHandling = config.GetBoolean("async_packet_handling", false);
m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);
PrimTerseUpdatesPerPacket = config.GetInt("PrimTerseUpdatesPerPacket", 25);
AvatarTerseUpdatesPerPacket = config.GetInt("AvatarTerseUpdatesPerPacket", 10);
PrimFullUpdatesPerPacket = config.GetInt("PrimFullUpdatesPerPacket", 100);
TextureSendLimit = config.GetInt("TextureSendLimit", 20);
m_defaultRTO = config.GetInt("DefaultRTO", 0);
m_maxRTO = config.GetInt("MaxRTO", 0);
}
else
{
PrimTerseUpdatesPerPacket = 25;
AvatarTerseUpdatesPerPacket = 10;
PrimFullUpdatesPerPacket = 100;
TextureSendLimit = 20;
}
#region BinaryStats
config = configSource.Configs["Statistics.Binary"];
m_shouldCollectStats = false;
if (config != null)
{
if (config.Contains("enabled") && config.GetBoolean("enabled"))
{
if (config.Contains("collect_packet_headers"))
m_shouldCollectStats = config.GetBoolean("collect_packet_headers");
if (config.Contains("packet_headers_period_seconds"))
{
binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("region_stats_period_seconds"));
}
if (config.Contains("stats_dir"))
{
binStatsDir = config.GetString("stats_dir");
}
}
else
{
m_shouldCollectStats = false;
}
}
#endregion BinaryStats
m_throttle = new TokenBucket(null, sceneThrottleBps, sceneThrottleBps);
m_throttleRates = new ThrottleRates(configSource);
}
public void Start()
{
if (m_scene == null)
throw new InvalidOperationException("[LLUDPSERVER]: Cannot LLUDPServer.Start() without an IScene reference");
m_log.Info("[LLUDPSERVER]: Starting the LLUDP server in " + (m_asyncPacketHandling ? "asynchronous" : "synchronous") + " mode");
base.Start(m_recvBufferSize, m_asyncPacketHandling);
// Start the packet processing threads
Watchdog.StartThread(IncomingPacketHandler, "Incoming Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
Watchdog.StartThread(OutgoingPacketHandler, "Outgoing Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
m_elapsedMSSinceLastStatReport = Environment.TickCount;
}
public new void Stop()
{
m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + m_scene.RegionInfo.RegionName);
base.Stop();
}
public void AddScene(IScene scene)
{
if (m_scene != null)
{
m_log.Error("[LLUDPSERVER]: AddScene() called on an LLUDPServer that already has a scene");
return;
}
if (!(scene is Scene))
{
m_log.Error("[LLUDPSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType());
return;
}
m_scene = (Scene)scene;
m_location = new Location(m_scene.RegionInfo.RegionHandle);
}
public bool HandlesRegion(Location x)
{
return x == m_location;
}
public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
{
// CoarseLocationUpdate and AvatarGroupsReply packets cannot be split in an automated way
if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
allowSplitting = false;
if (allowSplitting && packet.HasVariableBlocks)
{
byte[][] datas = packet.ToBytesMultiple();
int packetCount = datas.Length;
if (packetCount < 1)
m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
for (int i = 0; i < packetCount; i++)
{
byte[] data = datas[i];
m_scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is LLClientView)
SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
}
);
}
}
else
{
byte[] data = packet.ToBytes();
m_scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is LLClientView)
SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
}
);
}
}
public void SendPacket(LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting)
{
// CoarseLocationUpdate packets cannot be split in an automated way
if (packet.Type == PacketType.CoarseLocationUpdate && allowSplitting)
allowSplitting = false;
if (allowSplitting && packet.HasVariableBlocks)
{
byte[][] datas = packet.ToBytesMultiple();
int packetCount = datas.Length;
if (packetCount < 1)
m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
for (int i = 0; i < packetCount; i++)
{
byte[] data = datas[i];
SendPacketData(udpClient, data, packet.Type, category);
}
}
else
{
byte[] data = packet.ToBytes();
SendPacketData(udpClient, data, packet.Type, category);
}
}
public void SendPacketData(LLUDPClient udpClient, byte[] data, PacketType type, ThrottleOutPacketType category)
{
int dataLength = data.Length;
bool doZerocode = (data[0] & Helpers.MSG_ZEROCODED) != 0;
bool doCopy = true;
// Frequency analysis of outgoing packet sizes shows a large clump of packets at each end of the spectrum.
// The vast majority of packets are less than 200 bytes, although due to asset transfers and packet splitting
// there are a decent number of packets in the 1000-1140 byte range. We allocate one of two sizes of data here
// to accomodate for both common scenarios and provide ample room for ACK appending in both
int bufferSize = (dataLength > 180) ? LLUDPServer.MTU : 200;
UDPPacketBuffer buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
// Zerocode if needed
if (doZerocode)
{
try
{
dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data);
doCopy = false;
}
catch (IndexOutOfRangeException)
{
// The packet grew larger than the bufferSize while zerocoding.
// Remove the MSG_ZEROCODED flag and send the unencoded data
// instead
m_log.Debug("[LLUDPSERVER]: Packet exceeded buffer size during zerocoding for " + type + ". DataLength=" + dataLength +
" and BufferLength=" + buffer.Data.Length + ". Removing MSG_ZEROCODED flag");
data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
}
}
// If the packet data wasn't already copied during zerocoding, copy it now
if (doCopy)
{
if (dataLength <= buffer.Data.Length)
{
Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
}
else
{
bufferSize = dataLength;
buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
// m_log.Error("[LLUDPSERVER]: Packet exceeded buffer size! This could be an indication of packet assembly not obeying the MTU. Type=" +
// type + ", DataLength=" + dataLength + ", BufferLength=" + buffer.Data.Length + ". Dropping packet");
Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
}
}
buffer.DataLength = dataLength;
#region Queue or Send
OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category);
if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket))
SendPacketFinal(outgoingPacket);
#endregion Queue or Send
}
public void SendAcks(LLUDPClient udpClient)
{
uint ack;
if (udpClient.PendingAcks.Dequeue(out ack))
{
List<PacketAckPacket.PacketsBlock> blocks = new List<PacketAckPacket.PacketsBlock>();
PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock();
block.ID = ack;
blocks.Add(block);
while (udpClient.PendingAcks.Dequeue(out ack))
{
block = new PacketAckPacket.PacketsBlock();
block.ID = ack;
blocks.Add(block);
}
PacketAckPacket packet = new PacketAckPacket();
packet.Header.Reliable = false;
packet.Packets = blocks.ToArray();
SendPacket(udpClient, packet, ThrottleOutPacketType.Unknown, true);
}
}
public void SendPing(LLUDPClient udpClient)
{
StartPingCheckPacket pc = (StartPingCheckPacket)PacketPool.Instance.GetPacket(PacketType.StartPingCheck);
pc.Header.Reliable = false;
pc.PingID.PingID = (byte)udpClient.CurrentPingSequence++;
// We *could* get OldestUnacked, but it would hurt performance and not provide any benefit
pc.PingID.OldestUnacked = 0;
SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false);
}
public void CompletePing(LLUDPClient udpClient, byte pingID)
{
CompletePingCheckPacket completePing = new CompletePingCheckPacket();
completePing.PingID.PingID = pingID;
SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false);
}
public void ResendUnacked(LLUDPClient udpClient)
{
if (!udpClient.IsConnected)
return;
// Disconnect an agent if no packets are received for some time
//FIXME: Make 60 an .ini setting
if ((Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > 1000 * 60)
{
m_log.Warn("[LLUDPSERVER]: Ack timeout, disconnecting " + udpClient.AgentID);
RemoveClient(udpClient);
return;
}
// Get a list of all of the packets that have been sitting unacked longer than udpClient.RTO
List<OutgoingPacket> expiredPackets = udpClient.NeedAcks.GetExpiredPackets(udpClient.RTO);
if (expiredPackets != null)
{
//m_log.Debug("[LLUDPSERVER]: Resending " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
// Exponential backoff of the retransmission timeout
udpClient.BackoffRTO();
// Resend packets
for (int i = 0; i < expiredPackets.Count; i++)
{
OutgoingPacket outgoingPacket = expiredPackets[i];
//m_log.DebugFormat("[LLUDPSERVER]: Resending packet #{0} (attempt {1}), {2}ms have passed",
// outgoingPacket.SequenceNumber, outgoingPacket.ResendCount, Environment.TickCount - outgoingPacket.TickCount);
// Set the resent flag
outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
outgoingPacket.Category = ThrottleOutPacketType.Resend;
// Bump up the resend count on this packet
Interlocked.Increment(ref outgoingPacket.ResendCount);
//Interlocked.Increment(ref Stats.ResentPackets);
// Requeue or resend the packet
if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket))
SendPacketFinal(outgoingPacket);
}
}
}
public void Flush(LLUDPClient udpClient)
{
// FIXME: Implement?
}
internal void SendPacketFinal(OutgoingPacket outgoingPacket)
{
UDPPacketBuffer buffer = outgoingPacket.Buffer;
byte flags = buffer.Data[0];
bool isResend = (flags & Helpers.MSG_RESENT) != 0;
bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
LLUDPClient udpClient = outgoingPacket.Client;
if (!udpClient.IsConnected)
return;
#region ACK Appending
int dataLength = buffer.DataLength;
// NOTE: I'm seeing problems with some viewers when ACKs are appended to zerocoded packets so I've disabled that here
if (!isZerocoded)
{
// Keep appending ACKs until there is no room left in the buffer or there are
// no more ACKs to append
uint ackCount = 0;
uint ack;
while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
{
Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
dataLength += 4;
++ackCount;
}
if (ackCount > 0)
{
// Set the last byte of the packet equal to the number of appended ACKs
buffer.Data[dataLength++] = (byte)ackCount;
// Set the appended ACKs flag on this packet
buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
}
}
buffer.DataLength = dataLength;
#endregion ACK Appending
#region Sequence Number Assignment
if (!isResend)
{
// Not a resend, assign a new sequence number
uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
outgoingPacket.SequenceNumber = sequenceNumber;
if (isReliable)
{
// Add this packet to the list of ACK responses we are waiting on from the server
udpClient.NeedAcks.Add(outgoingPacket);
}
}
#endregion Sequence Number Assignment
// Stats tracking
Interlocked.Increment(ref udpClient.PacketsSent);
if (isReliable)
Interlocked.Add(ref udpClient.UnackedBytes, outgoingPacket.Buffer.DataLength);
// Put the UDP payload on the wire
AsyncBeginSend(buffer);
// Keep track of when this packet was sent out (right now)
outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
}
protected override void PacketReceived(UDPPacketBuffer buffer)
{
// Debugging/Profiling
//try { Thread.CurrentThread.Name = "PacketReceived (" + m_scene.RegionInfo.RegionName + ")"; }
//catch (Exception) { }
LLUDPClient udpClient = null;
Packet packet = null;
int packetEnd = buffer.DataLength - 1;
IPEndPoint address = (IPEndPoint)buffer.RemoteEndPoint;
#region Decoding
try
{
packet = Packet.BuildPacket(buffer.Data, ref packetEnd,
// Only allocate a buffer for zerodecoding if the packet is zerocoded
((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
}
catch (MalformedDataException)
{
m_log.ErrorFormat("[LLUDPSERVER]: Malformed data, cannot parse packet from {0}:\n{1}",
buffer.RemoteEndPoint, Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
}
// Fail-safe check
if (packet == null)
{
m_log.Warn("[LLUDPSERVER]: Couldn't build a message from incoming data " + buffer.DataLength +
" bytes long from " + buffer.RemoteEndPoint);
return;
}
#endregion Decoding
#region Packet to Client Mapping
// UseCircuitCode handling
if (packet.Type == PacketType.UseCircuitCode)
{
m_log.Debug("[LLUDPSERVER]: Handling UseCircuitCode packet from " + buffer.RemoteEndPoint);
object[] array = new object[] { buffer, packet };
if (m_asyncPacketHandling)
Util.FireAndForget(HandleUseCircuitCode, array);
else
HandleUseCircuitCode(array);
return;
}
// Determine which agent this packet came from
IClientAPI client;
if (!m_scene.TryGetClient(address, out client) || !(client is LLClientView))
{
//m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
return;
}
udpClient = ((LLClientView)client).UDPClient;
if (!udpClient.IsConnected)
return;
#endregion Packet to Client Mapping
// Stats tracking
Interlocked.Increment(ref udpClient.PacketsReceived);
int now = Environment.TickCount & Int32.MaxValue;
udpClient.TickLastPacketReceived = now;
#region ACK Receiving
// Handle appended ACKs
if (packet.Header.AppendedAcks && packet.Header.AckList != null)
{
for (int i = 0; i < packet.Header.AckList.Length; i++)
udpClient.NeedAcks.Remove(packet.Header.AckList[i], now, packet.Header.Resent);
}
// Handle PacketAck packets
if (packet.Type == PacketType.PacketAck)
{
PacketAckPacket ackPacket = (PacketAckPacket)packet;
for (int i = 0; i < ackPacket.Packets.Length; i++)
udpClient.NeedAcks.Remove(ackPacket.Packets[i].ID, now, packet.Header.Resent);
// We don't need to do anything else with PacketAck packets
return;
}
#endregion ACK Receiving
#region ACK Sending
if (packet.Header.Reliable)
{
udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
// This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
// add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
// 2*MTU bytes from the value and send ACKs, and finally add the local value back to
// client.BytesSinceLastACK. Lockless thread safety
int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
bytesSinceLastACK += buffer.DataLength;
if (bytesSinceLastACK > LLUDPServer.MTU * 2)
{
bytesSinceLastACK -= LLUDPServer.MTU * 2;
SendAcks(udpClient);
}
Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
}
#endregion ACK Sending
#region Incoming Packet Accounting
// Check the archive of received reliable packet IDs to see whether we already received this packet
if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
{
if (packet.Header.Resent)
m_log.Debug("[LLUDPSERVER]: Received a resend of already processed packet #" + packet.Header.Sequence + ", type: " + packet.Type);
else
m_log.Warn("[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #" + packet.Header.Sequence + ", type: " + packet.Type);
// Avoid firing a callback twice for the same packet
return;
}
#endregion Incoming Packet Accounting
#region BinaryStats
LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
#endregion BinaryStats
#region Ping Check Handling
if (packet.Type == PacketType.StartPingCheck)
{
// We don't need to do anything else with ping checks
StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
CompletePing(udpClient, startPing.PingID.PingID);
if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
{
udpClient.SendPacketStats();
m_elapsedMSSinceLastStatReport = Environment.TickCount;
}
return;
}
else if (packet.Type == PacketType.CompletePingCheck)
{
// We don't currently track client ping times
return;
}
#endregion Ping Check Handling
// Inbox insertion
packetInbox.Enqueue(new IncomingPacket(udpClient, packet));
}
#region BinaryStats
public class PacketLogger
{
public DateTime StartTime;
public string Path = null;
public System.IO.BinaryWriter Log = null;
}
public static PacketLogger PacketLog;
protected static bool m_shouldCollectStats = false;
// Number of seconds to log for
static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
static object binStatsLogLock = new object();
static string binStatsDir = "";
public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
{
if (!m_shouldCollectStats) return;
// Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
// Put the incoming bit into the least significant bit of the flags byte
if (incoming)
flags |= 0x01;
else
flags &= 0xFE;
// Put the flags byte into the most significant bits of the type integer
uint type = (uint)packetType;
type |= (uint)flags << 24;
// m_log.Debug("1 LogPacketHeader(): Outside lock");
lock (binStatsLogLock)
{
DateTime now = DateTime.Now;
// m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
try
{
if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
{
if (PacketLog != null && PacketLog.Log != null)
{
PacketLog.Log.Close();
}
// First log file or time has expired, start writing to a new log file
PacketLog = new PacketLogger();
PacketLog.StartTime = now;
PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
+ String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
}
// Serialize the data
byte[] output = new byte[18];
Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
// Write the serialized data to disk
if (PacketLog != null && PacketLog.Log != null)
PacketLog.Log.Write(output);
}
catch (Exception ex)
{
m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
if (PacketLog.Log != null)
{
PacketLog.Log.Close();
}
PacketLog = null;
}
}
}
#endregion BinaryStats
private void HandleUseCircuitCode(object o)
{
object[] array = (object[])o;
UDPPacketBuffer buffer = (UDPPacketBuffer)array[0];
UseCircuitCodePacket packet = (UseCircuitCodePacket)array[1];
IPEndPoint remoteEndPoint = (IPEndPoint)buffer.RemoteEndPoint;
// Begin the process of adding the client to the simulator
AddNewClient((UseCircuitCodePacket)packet, remoteEndPoint);
// Acknowledge the UseCircuitCode packet
SendAckImmediate(remoteEndPoint, packet.Header.Sequence);
}
private void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
{
PacketAckPacket ack = new PacketAckPacket();
ack.Header.Reliable = false;
ack.Packets = new PacketAckPacket.PacketsBlock[1];
ack.Packets[0] = new PacketAckPacket.PacketsBlock();
ack.Packets[0].ID = sequenceNumber;
byte[] packetData = ack.ToBytes();
int length = packetData.Length;
UDPPacketBuffer buffer = new UDPPacketBuffer(remoteEndpoint, length);
buffer.DataLength = length;
Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
AsyncBeginSend(buffer);
}
private bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
{
UUID agentID = useCircuitCode.CircuitCode.ID;
UUID sessionID = useCircuitCode.CircuitCode.SessionID;
uint circuitCode = useCircuitCode.CircuitCode.Code;
sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
return sessionInfo.Authorised;
}
private void AddNewClient(UseCircuitCodePacket useCircuitCode, IPEndPoint remoteEndPoint)
{
UUID agentID = useCircuitCode.CircuitCode.ID;
UUID sessionID = useCircuitCode.CircuitCode.SessionID;
uint circuitCode = useCircuitCode.CircuitCode.Code;
if (m_scene.RegionStatus != RegionStatus.SlaveScene)
{
AuthenticateResponse sessionInfo;
if (IsClientAuthorized(useCircuitCode, out sessionInfo))
{
AddClient(circuitCode, agentID, sessionID, remoteEndPoint, sessionInfo);
}
else
{
// Don't create circuits for unauthorized clients
m_log.WarnFormat(
"[LLUDPSERVER]: Connection request for client {0} connecting with unnotified circuit code {1} from {2}",
useCircuitCode.CircuitCode.ID, useCircuitCode.CircuitCode.Code, remoteEndPoint);
}
}
else
{
// Slave regions don't accept new clients
m_log.Debug("[LLUDPSERVER]: Slave region " + m_scene.RegionInfo.RegionName + " ignoring UseCircuitCode packet");
}
}
protected virtual void AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
{
// Create the LLUDPClient
LLUDPClient udpClient = new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
IClientAPI existingClient;
if (!m_scene.TryGetClient(agentID, out existingClient))
{
// Create the LLClientView
LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
client.OnLogout += LogoutHandler;
// Start the IClientAPI
client.Start();
}
else
{
m_log.WarnFormat("[LLUDPSERVER]: Ignoring a repeated UseCircuitCode from {0} at {1} for circuit {2}",
udpClient.AgentID, remoteEndPoint, circuitCode);
}
}
private void RemoveClient(LLUDPClient udpClient)
{
// Remove this client from the scene
IClientAPI client;
if (m_scene.TryGetClient(udpClient.AgentID, out client))
client.Close();
}
private void IncomingPacketHandler()
{
// Set this culture for the thread that incoming packets are received
// on to en-US to avoid number parsing issues
Culture.SetCurrentCulture();
while (base.IsRunning)
{
try
{
IncomingPacket incomingPacket = null;
// HACK: This is a test to try and rate limit packet handling on Mono.
// If it works, a more elegant solution can be devised
if (Util.FireAndForgetCount() < 2)
{
//m_log.Debug("[LLUDPSERVER]: Incoming packet handler is sleeping");
Thread.Sleep(30);
}
if (packetInbox.Dequeue(100, ref incomingPacket))
ProcessInPacket(incomingPacket);//, incomingPacket); Util.FireAndForget(ProcessInPacket, incomingPacket);
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
}
Watchdog.UpdateThread();
}
if (packetInbox.Count > 0)
m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
packetInbox.Clear();
Watchdog.RemoveThread();
}
private void OutgoingPacketHandler()
{
// Set this culture for the thread that outgoing packets are sent
// on to en-US to avoid number parsing issues
Culture.SetCurrentCulture();
// Typecast the function to an Action<IClientAPI> once here to avoid allocating a new
// Action generic every round
Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;
while (base.IsRunning)
{
try
{
m_packetSent = false;
#region Update Timers
m_resendUnacked = false;
m_sendAcks = false;
m_sendPing = false;
// Update elapsed time
int thisTick = Environment.TickCount & Int32.MaxValue;
if (m_tickLastOutgoingPacketHandler > thisTick)
m_elapsedMSOutgoingPacketHandler += ((Int32.MaxValue - m_tickLastOutgoingPacketHandler) + thisTick);
else
m_elapsedMSOutgoingPacketHandler += (thisTick - m_tickLastOutgoingPacketHandler);
m_tickLastOutgoingPacketHandler = thisTick;
// Check for pending outgoing resends every 100ms
if (m_elapsedMSOutgoingPacketHandler >= 100)
{
m_resendUnacked = true;
m_elapsedMSOutgoingPacketHandler = 0;
m_elapsed100MSOutgoingPacketHandler += 1;
}
// Check for pending outgoing ACKs every 500ms
if (m_elapsed100MSOutgoingPacketHandler >= 5)
{
m_sendAcks = true;
m_elapsed100MSOutgoingPacketHandler = 0;
m_elapsed500MSOutgoingPacketHandler += 1;
}
// Send pings to clients every 5000ms
if (m_elapsed500MSOutgoingPacketHandler >= 10)
{
m_sendPing = true;
m_elapsed500MSOutgoingPacketHandler = 0;
}
#endregion Update Timers
// Handle outgoing packets, resends, acknowledgements, and pings for each
// client. m_packetSent will be set to true if a packet is sent
m_scene.ForEachClient(clientPacketHandler, false);
// If nothing was sent, sleep for the minimum amount of time before a
// token bucket could get more tokens
if (!m_packetSent)
Thread.Sleep((int)TickCountResolution);
Watchdog.UpdateThread();
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
}
}
Watchdog.RemoveThread();
}
private void ClientOutgoingPacketHandler(IClientAPI client)
{
try
{
if (client is LLClientView)
{
LLUDPClient udpClient = ((LLClientView)client).UDPClient;
if (udpClient.IsConnected)
{
if (m_resendUnacked)
ResendUnacked(udpClient);
if (m_sendAcks)
SendAcks(udpClient);
if (m_sendPing)
SendPing(udpClient);
// Dequeue any outgoing packets that are within the throttle limits
if (udpClient.DequeueOutgoing())
m_packetSent = true;
}
}
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name +
" threw an exception: " + ex.Message, ex);
}
}
private void ProcessInPacket(object state)
{
IncomingPacket incomingPacket = (IncomingPacket)state;
Packet packet = incomingPacket.Packet;
LLUDPClient udpClient = incomingPacket.Client;
IClientAPI client;
// Sanity check
if (packet == null || udpClient == null)
{
m_log.WarnFormat("[LLUDPSERVER]: Processing a packet with incomplete state. Packet=\"{0}\", UDPClient=\"{1}\"",
packet, udpClient);
}
// Make sure this client is still alive
if (m_scene.TryGetClient(udpClient.AgentID, out client))
{
try
{
// Process this packet
client.ProcessInPacket(packet);
}
catch (ThreadAbortException)
{
// If something is trying to abort the packet processing thread, take that as a hint that it's time to shut down
m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
Stop();
}
catch (Exception e)
{
// Don't let a failure in an individual client thread crash the whole sim.
m_log.ErrorFormat("[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw an exception", udpClient.AgentID, packet.Type);
m_log.Error(e.Message, e);
}
}
else
{
m_log.DebugFormat("[LLUDPSERVER]: Dropping incoming {0} packet for dead client {1}", packet.Type, udpClient.AgentID);
}
}
protected void LogoutHandler(IClientAPI client)
{
client.SendLogoutPacket();
if (client.IsActive)
RemoveClient(((LLClientView)client).UDPClient);
}
}
}
| |
#region Copyright
//
// Nini Configuration Project.
//
// Copyright (C) 2014 Nicholas Omann. All rights reserved.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.IO;
using System.Xml;
using Nini.Config;
using Microsoft.Win32;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Nini.Test.Config
{
[TestClass]
public class RegistryConfigSourceTests
{
#region Tests
[TestMethod]
public void GetSingleLevel ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
IConfig config = source.Configs["Pets"];
Assert.AreEqual ("Pets", config.Name);
Assert.AreEqual (3, config.GetKeys ().Length);
Assert.AreEqual (source, config.ConfigSource);
Assert.AreEqual ("Chi-chi", config.Get ("cat"));
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual (5, config.GetInt ("count"));
}
[TestMethod]
[ExpectedException (typeof (ArgumentException))]
public void NonExistantKey ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\Does\\NotExist");
}
[TestMethod]
public void SetAndSaveNormal ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
IConfig config = source.Configs["Pets"];
Assert.AreEqual ("Chi-chi", config.Get ("cat"));
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual (5, config.GetInt ("count"));
config.Set ("cat", "Muffy");
config.Set ("dog", "Spots");
config.Set ("DoesNotExist", "SomeValue");
config.Set ("count", 4);
source.Save ();
source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
config = source.Configs["Pets"];
Assert.AreEqual ("Muffy", config.Get ("cat"));
Assert.AreEqual ("Spots", config.Get ("dog"));
Assert.AreEqual ("SomeValue", config.Get ("DoesNotExist"));
Assert.AreEqual (4, config.GetInt ("count"));
}
[TestMethod]
public void Flattened ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine,
"Software\\NiniTestApp",
RegistryRecurse.Flattened);
IConfig config = source.Configs["NiniTestApp"];
Assert.AreEqual ("Configuration Library", config.Get ("Description"));
config = source.Configs["Pets"];
Assert.AreEqual ("Pets", config.Name);
Assert.AreEqual (3, config.GetKeys ().Length);
Assert.AreEqual (source, config.ConfigSource);
Assert.AreEqual ("Chi-chi", config.Get ("cat"));
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual (5, config.GetInt ("count"));
config.Set ("cat", "Muffy");
config.Set ("dog", "Spots");
config.Set ("count", 4);
source.Save ();
source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
config = source.Configs["Pets"];
Assert.AreEqual ("Muffy", config.Get ("cat"));
Assert.AreEqual ("Spots", config.Get ("dog"));
Assert.AreEqual (4, config.GetInt ("count"));
}
[TestMethod]
public void Namespacing ()
{
RegistryConfigSource source = new RegistryConfigSource ();
RegistryKey key = Registry.LocalMachine.OpenSubKey ("Software");
source.AddMapping (key, "NiniTestApp",
RegistryRecurse.Namespacing);
IConfig config = source.Configs["NiniTestApp"];
Assert.AreEqual ("Configuration Library", config.Get ("Description"));
config = source.Configs["NiniTestApp\\Pets"];
Assert.AreEqual ("NiniTestApp\\Pets", config.Name);
Assert.AreEqual (3, config.GetKeys ().Length);
Assert.AreEqual (source, config.ConfigSource);
Assert.AreEqual ("Chi-chi", config.Get ("cat"));
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual (5, config.GetInt ("count"));
config.Set ("cat", "Muffy");
config.Set ("dog", "Spots");
config.Set ("count", 4);
source.Save ();
source = new RegistryConfigSource ();
key = Registry.LocalMachine.OpenSubKey ("Software");
source.AddMapping (key, "NiniTestApp",
RegistryRecurse.Namespacing);
config = source.Configs["NiniTestApp\\Pets"];
Assert.AreEqual ("Muffy", config.Get ("cat"));
Assert.AreEqual ("Spots", config.Get ("dog"));
Assert.AreEqual (4, config.GetInt ("count"));
}
[TestMethod]
public void MergeAndSave ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
IConfig config = source.Configs["Pets"];
Assert.AreEqual ("Chi-chi", config.Get ("cat"));
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual (5, config.GetInt ("count"));
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Pets]");
writer.WriteLine ("cat = Becky"); // overwrite
writer.WriteLine ("lizard = Saurus"); // new
writer.WriteLine ("[People]");
writer.WriteLine (" woman = Jane");
writer.WriteLine (" man = John");
IniConfigSource iniSource = new IniConfigSource
(new StringReader (writer.ToString ()));
source.Merge (iniSource);
config = source.Configs["Pets"];
Assert.AreEqual (4, config.GetKeys ().Length);
Assert.AreEqual ("Becky", config.Get ("cat"));
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual ("Saurus", config.Get ("lizard"));
config = source.Configs["People"];
Assert.AreEqual (2, config.GetKeys ().Length);
Assert.AreEqual ("Jane", config.Get ("woman"));
Assert.AreEqual ("John", config.Get ("man"));
config.Set ("woman", "Tara");
config.Set ("man", "Quentin");
source.Save ();
source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
config = source.Configs["Pets"];
Assert.AreEqual (4, config.GetKeys ().Length);
Assert.AreEqual ("Becky", config.Get ("cat"));
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual ("Saurus", config.Get ("lizard"));
config = source.Configs["People"];
Assert.IsNull (config); // you cannot merge new sections
/*
Assert.AreEqual (2, config.GetKeys ().Length);
Assert.AreEqual ("Tara", config.Get ("woman"));
Assert.AreEqual ("Quentin", config.Get ("man"));
*/
}
[TestMethod]
public void Reload ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
source.Configs["Pets"].Set ("cat", "Muffy");
source.Save ();
Assert.AreEqual (3, source.Configs["Pets"].GetKeys ().Length);
Assert.AreEqual ("Muffy", source.Configs["Pets"].Get ("cat"));
RegistryConfigSource newSource = new RegistryConfigSource ();
newSource.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
Assert.AreEqual (3, newSource.Configs["Pets"].GetKeys ().Length);
Assert.AreEqual ("Muffy", newSource.Configs["Pets"].Get ("cat"));
source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
source.Configs["Pets"].Set ("cat", "Misha");
source.Save (); // saves new value
newSource.Reload ();
Assert.AreEqual (3, newSource.Configs["Pets"].GetKeys ().Length);
Assert.AreEqual ("Misha", newSource.Configs["Pets"].Get ("cat"));
}
[TestMethod]
public void AddConfig ()
{
RegistryConfigSource source = new RegistryConfigSource ();
RegistryKey key =
Registry.LocalMachine.OpenSubKey("Software\\NiniTestApp", true);
IConfig config = source.AddConfig ("People", key);
config.Set ("woman", "Tara");
config.Set ("man", "Quentin");
source.Save ();
source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\People");
Assert.AreEqual (1, source.Configs.Count);
config = source.Configs["People"];
Assert.AreEqual (2, config.GetKeys ().Length);
Assert.AreEqual ("Tara", config.Get ("woman"));
Assert.AreEqual ("Quentin", config.Get ("man"));
}
[TestMethod]
public void AddConfigDefaultKey ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.DefaultKey =
Registry.LocalMachine.OpenSubKey("Software\\NiniTestApp", true);
IConfig config = source.AddConfig ("People");
config.Set ("woman", "Tara");
config.Set ("man", "Quentin");
source.Save ();
source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\People");
Assert.AreEqual (1, source.Configs.Count);
config = source.Configs["People"];
Assert.AreEqual (2, config.GetKeys ().Length);
Assert.AreEqual ("Tara", config.Get ("woman"));
Assert.AreEqual ("Quentin", config.Get ("man"));
}
[TestMethod]
[ExpectedException (typeof (ApplicationException))]
public void AddConfigNoDefaultKey ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
IConfig config = source.AddConfig ("People");
}
[TestMethod]
public void RemoveKey ()
{
RegistryConfigSource source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
IConfig config = source.Configs["Pets"];
Assert.AreEqual ("Pets", config.Name);
Assert.AreEqual (3, config.GetKeys ().Length);
Assert.AreEqual (source, config.ConfigSource);
Assert.AreEqual ("Chi-chi", config.Get ("cat"));
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual (5, config.GetInt ("count"));
config.Remove ("dog");
source.Save ();
source = new RegistryConfigSource ();
source.AddMapping (Registry.LocalMachine, "Software\\NiniTestApp\\Pets");
config = source.Configs["Pets"];
Assert.AreEqual ("Pets", config.Name);
Assert.AreEqual (2, config.GetKeys ().Length);
Assert.AreEqual (source, config.ConfigSource);
Assert.AreEqual ("Chi-chi", config.Get ("cat"));
Assert.IsNull (config.Get ("dog"));
Assert.AreEqual (5, config.GetInt ("count"));
}
#endregion
#region Setup/tearDown
[TestInitialize]
public void Setup ()
{
RegistryKey software = Registry.LocalMachine.OpenSubKey ("Software", true);
RegistryKey nini = software.CreateSubKey ("NiniTestApp");
nini.SetValue ("Description", "Configuration Library");
nini.Flush ();
RegistryKey pets = nini.CreateSubKey ("Pets");
pets.SetValue ("dog", "Rover");
pets.SetValue ("cat", "Chi-chi");
pets.SetValue ("count", 5); // set DWORD
pets.Flush ();
}
[TestCleanup]
public void TearDown ()
{
RegistryKey software = Registry.LocalMachine.OpenSubKey ("Software", true);
software.DeleteSubKeyTree ("NiniTestApp");
}
#endregion
#region Private methods
#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 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
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>
/// </summary>
public partial class ManagementLockClient : ServiceClient<ManagementLockClient>, IManagementLockClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public 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>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { 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; }
public virtual IManagementLocksOperations ManagementLocks { get; private set; }
/// <summary>
/// Initializes a new instance of the ManagementLockClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ManagementLockClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the ManagementLockClient 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 ManagementLockClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the ManagementLockClient 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>
protected ManagementLockClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ManagementLockClient 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>
protected ManagementLockClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ManagementLockClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public ManagementLockClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ManagementLockClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </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>
public ManagementLockClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ManagementLockClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public ManagementLockClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ManagementLockClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </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>
public ManagementLockClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.ManagementLocks = new ManagementLocksOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2015-01-01";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// 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 MaxSingle()
{
var test = new SimpleBinaryOpTest__MaxSingle();
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__MaxSingle
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single> _dataTable;
static SimpleBinaryOpTest__MaxSingle()
{
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<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__MaxSingle()
{
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<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<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 => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Max(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Max(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Max(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Max), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Max(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = Avx.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__MaxSingle();
var result = Avx.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Max(_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(Vector256<Single> left, Vector256<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(MathF.Max(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.SingleToInt32Bits(MathF.Max(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Max)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.Azure.Gallery;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
namespace Microsoft.Azure.Gallery
{
public partial class GalleryClient : ServiceClient<GalleryClient>, IGalleryClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IItemOperations _items;
/// <summary>
/// Operations for working with gallery items.
/// </summary>
public virtual IItemOperations Items
{
get { return this._items; }
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
private GalleryClient()
: base()
{
this._items = new ItemOperations(this);
this._apiVersion = "2013-03-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public GalleryClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public GalleryClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://gallery.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private GalleryClient(HttpClient httpClient)
: base(httpClient)
{
this._items = new ItemOperations(this);
this._apiVersion = "2013-03-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public GalleryClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the GalleryClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public GalleryClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://gallery.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another GalleryClient
/// instance
/// </summary>
/// <param name='client'>
/// Instance of GalleryClient to clone to
/// </param>
protected override void Clone(ServiceClient<GalleryClient> client)
{
base.Clone(client);
if (client is GalleryClient)
{
GalleryClient clonedClient = ((GalleryClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
// The MIT License
//
// Copyright (c) 2012-2015 Jordan E. Terrell
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Transactions;
using NUnit.Framework;
using iSynaptic.Commons.Transactions;
using Rhino.Mocks;
namespace iSynaptic.Commons.Transactions
{
[TestFixture]
public class TransactionalTests
{
[Test]
public void NullOnCreation()
{
Transactional<SimpleObject> tso = new Transactional<SimpleObject>();
Assert.IsNull(tso.Value);
}
[Test]
public void InitialValue()
{
SimpleObject so = new SimpleObject();
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(so);
Assert.IsNotNull(tso.Value);
Assert.AreEqual(so, tso.Value);
}
[Test]
public void CopiesNullOnNewTransaction()
{
Transactional<SimpleObject> tso = new Transactional<SimpleObject>();
using (TransactionScope scope = new TransactionScope())
{
Assert.IsNull(tso.Value);
scope.Complete();
}
}
[Test]
public void CopiesInitalValueOnNewTransaction()
{
SimpleObject so = new SimpleObject();
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(so);
using (TransactionScope scope = new TransactionScope())
{
Assert.IsFalse(object.ReferenceEquals(so, tso.Value));
Assert.AreEqual(so.TestInt, tso.Value.TestInt);
Assert.AreEqual(so.TestGuid, tso.Value.TestGuid);
Assert.AreEqual(so.TestString, tso.Value.TestString);
scope.Complete();
}
}
[Test]
public void ChangesNotVisibleOutsideOfTransaction()
{
SimpleObject so = new SimpleObject();
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(so);
Guid testGuid = Guid.NewGuid();
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = testGuid;
tso.Value.TestString = "Testing";
using (TransactionScope suppressScope = new TransactionScope(TransactionScopeOption.Suppress))
{
Assert.AreNotEqual(7, tso.Value.TestInt);
Assert.AreNotEqual(testGuid, tso.Value.TestGuid);
Assert.AreNotEqual("Testing", tso.Value.TestString);
suppressScope.Complete();
}
scope.Complete();
}
}
[Test]
public void ChangesVisibleWithinTransaction()
{
SimpleObject so = new SimpleObject();
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(so);
Guid testGuid = Guid.NewGuid();
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = testGuid;
tso.Value.TestString = "Testing";
Assert.AreEqual(7, tso.Value.TestInt);
Assert.AreEqual(testGuid, tso.Value.TestGuid);
Assert.AreEqual("Testing", tso.Value.TestString);
scope.Complete();
}
}
[Test]
public void ChangesRolledBack()
{
SimpleObject so = new SimpleObject();
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(so);
Guid testGuid = Guid.NewGuid();
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = testGuid;
tso.Value.TestString = "Testing";
}
Assert.AreNotEqual(7, tso.Value.TestInt);
Assert.AreNotEqual(testGuid, tso.Value.TestGuid);
Assert.AreNotEqual("Testing", tso.Value.TestString);
}
[Test]
public void ChangesCommited()
{
SimpleObject so = new SimpleObject();
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(so);
Guid testGuid = Guid.NewGuid();
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = testGuid;
tso.Value.TestString = "Testing";
scope.Complete();
}
Assert.AreEqual(7, tso.Value.TestInt);
Assert.AreEqual(testGuid, tso.Value.TestGuid);
Assert.AreEqual("Testing", tso.Value.TestString);
}
[Test]
public void ConcurrencyCollision()
{
SimpleObject so = new SimpleObject();
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(so);
Assert.Throws<TransactionAbortedException>(() =>
{
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = Guid.NewGuid();
tso.Value.TestString = "Testing";
using (TransactionScope scopeTwo = new TransactionScope(TransactionScopeOption.RequiresNew))
{
tso.Value.TestInt = 9;
tso.Value.TestGuid = Guid.NewGuid();
tso.Value.TestString = "Testing Two";
scopeTwo.Complete();
}
scope.Complete();
}
});
}
[Test]
public void DependentTransactions()
{
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(new SimpleObject());
Guid id = Guid.NewGuid();
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = id;
tso.Value.TestString = "Testing";
DependentTransaction dt = Transaction.Current.DependentClone(DependentCloneOption.RollbackIfNotComplete);
Action assertAction = delegate()
{
using (dt)
using (TransactionScope scopeTwo = new TransactionScope(dt))
{
Assert.AreEqual(7, tso.Value.TestInt);
Assert.AreEqual(id, tso.Value.TestGuid);
Assert.AreEqual("Testing", tso.Value.TestString);
scopeTwo.Complete();
dt.Complete();
}
};
IAsyncResult ar = assertAction.BeginInvoke(null, null);
ar.AsyncWaitHandle.WaitOne();
assertAction.EndInvoke(ar);
scope.Complete();
}
}
[Test]
public void NotVisibleOnOtherThread()
{
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(new SimpleObject());
Guid id = Guid.NewGuid();
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = id;
tso.Value.TestString = "Testing";
Action assertAction = delegate()
{
Assert.AreNotEqual(7, tso.Value.TestInt);
Assert.AreNotEqual(id, tso.Value.TestGuid);
Assert.AreNotEqual("Testing", tso.Value.TestString);
};
IAsyncResult ar = assertAction.BeginInvoke(null, null);
ar.AsyncWaitHandle.WaitOne();
assertAction.EndInvoke(ar);
scope.Complete();
}
}
[Test]
public void ConcurrencyCollisionAcrossThreads()
{
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(new SimpleObject());
Guid id = Guid.NewGuid();
Assert.Throws<TransactionAbortedException>(() =>
{
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = id;
tso.Value.TestString = "Testing";
Action assertAction = delegate()
{
using (TransactionScope scopeTwo = new TransactionScope())
{
tso.Value.TestInt = 9;
tso.Value.TestGuid = Guid.NewGuid();
tso.Value.TestString = "Testing Two";
scopeTwo.Complete();
}
};
IAsyncResult ar = assertAction.BeginInvoke(null, null);
ar.AsyncWaitHandle.WaitOne();
assertAction.EndInvoke(ar);
scope.Complete();
}
});
}
[Test]
public void MultipleSerializedTransactions()
{
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(new SimpleObject());
Guid id = Guid.NewGuid();
Guid idTwo = Guid.NewGuid();
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = id;
tso.Value.TestString = "Testing";
scope.Complete();
}
Assert.AreEqual(7, tso.Value.TestInt);
Assert.AreEqual(id, tso.Value.TestGuid);
Assert.AreEqual("Testing", tso.Value.TestString);
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 9;
tso.Value.TestGuid = idTwo;
tso.Value.TestString = "Testing Two";
scope.Complete();
}
Assert.AreEqual(9, tso.Value.TestInt);
Assert.AreEqual(idTwo, tso.Value.TestGuid);
Assert.AreEqual("Testing Two", tso.Value.TestString);
}
[Test]
public void MultipleSerializedTransactionsAcrossThreads()
{
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(new SimpleObject());
Guid id = Guid.NewGuid();
Guid idTwo = Guid.NewGuid();
Action firstChange = delegate()
{
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = id;
tso.Value.TestString = "Testing";
scope.Complete();
}
};
IAsyncResult ar = firstChange.BeginInvoke(null, null);
ar.AsyncWaitHandle.WaitOne();
firstChange.EndInvoke(ar);
Assert.AreEqual(7, tso.Value.TestInt);
Assert.AreEqual(id, tso.Value.TestGuid);
Assert.AreEqual("Testing", tso.Value.TestString);
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 9;
tso.Value.TestGuid = idTwo;
tso.Value.TestString = "Testing Two";
scope.Complete();
}
Assert.AreEqual(9, tso.Value.TestInt);
Assert.AreEqual(idTwo, tso.Value.TestGuid);
Assert.AreEqual("Testing Two", tso.Value.TestString);
}
public class ExposedValuesTransactional<T> : Transactional<T>
{
public ExposedValuesTransactional(T value) : base(value)
{
}
public Dictionary<string, KeyValuePair<Guid, T>> GetValues()
{
return Values;
}
}
[Test]
public void NoMemoryLeakOnCommit()
{
ExposedValuesTransactional<SimpleObject> tso = new ExposedValuesTransactional<SimpleObject>(new SimpleObject());
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = Guid.NewGuid();
tso.Value.TestString = "Testing";
Assert.AreEqual(1, tso.GetValues().Count);
scope.Complete();
}
Assert.AreEqual(0, tso.GetValues().Count);
}
[Test]
public void NoMemoryLeakOnRollback()
{
ExposedValuesTransactional<SimpleObject> tso = new ExposedValuesTransactional<SimpleObject>(new SimpleObject());
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = Guid.NewGuid();
tso.Value.TestString = "Testing";
Assert.AreEqual(1, tso.GetValues().Count);
}
Assert.AreEqual(0, tso.GetValues().Count);
}
[Test]
public void ExceptionUponCompletionRollback()
{
MockRepository mocks = new MockRepository();
IEnlistmentNotification concurrencyConflictResource = mocks.StrictMock<IEnlistmentNotification>();
concurrencyConflictResource.Prepare(null);
LastCall.IgnoreArguments().Throw(new TransactionalConcurrencyException());
mocks.ReplayAll();
Transactional<SimpleObject> tso = new Transactional<SimpleObject>(new SimpleObject());
tso.Value.TestInt = 0;
tso.Value.TestGuid = Guid.Empty;
tso.Value.TestString = null;
Assert.Throws<TransactionalConcurrencyException>(() =>
{
using (TransactionScope scope = new TransactionScope())
{
tso.Value.TestInt = 7;
tso.Value.TestGuid = Guid.NewGuid();
tso.Value.TestString = "Testing";
Transaction.Current.EnlistVolatile(concurrencyConflictResource, EnlistmentOptions.None);
scope.Complete();
}
});
Assert.AreEqual(0, tso.Value.TestInt);
Assert.AreEqual(Guid.Empty, tso.Value.TestGuid);
Assert.AreEqual(null, tso.Value.TestString);
}
[Test]
public void SetValueWithoutTransaction()
{
var tso = new Transactional<SimpleObject>();
SimpleObject state = new SimpleObject();
state.TestInt = 7;
state.TestGuid = Guid.NewGuid();
state.TestString = "Testing";
Assert.IsNull(tso.Value);
tso.Value = state;
Assert.IsNotNull(state);
Assert.IsTrue(object.ReferenceEquals(state, tso.Value));
}
[Test]
public void SetValue()
{
var tso = new Transactional<SimpleObject>();
SimpleObject state = new SimpleObject();
state.TestInt = 7;
state.TestGuid = Guid.NewGuid();
state.TestString = "Testing";
Assert.IsNull(tso.Value);
using (TransactionScope scope = new TransactionScope())
{
tso.Value = state;
using (TransactionScope scopeTwo = new TransactionScope(TransactionScopeOption.Suppress))
{
Assert.IsNull(tso.Value);
}
scope.Complete();
}
Assert.IsNotNull(tso.Value);
Assert.IsTrue(object.ReferenceEquals(state, tso.Value));
}
[Test]
public void SetValueTwice()
{
var tso = new Transactional<SimpleObject>();
SimpleObject state = new SimpleObject();
state.TestInt = 7;
state.TestGuid = Guid.NewGuid();
state.TestString = "Testing";
SimpleObject state2 = new SimpleObject();
state2.TestInt = 9;
state2.TestGuid = Guid.NewGuid();
state2.TestString = "Testing2";
Assert.IsNull(tso.Value);
using (TransactionScope scope = new TransactionScope())
{
tso.Value = state;
tso.Value = state2;
using (TransactionScope scopeTwo = new TransactionScope(TransactionScopeOption.Suppress))
{
Assert.IsNull(tso.Value);
}
scope.Complete();
}
Assert.IsNotNull(tso.Value);
Assert.IsTrue(object.ReferenceEquals(state2, tso.Value));
}
[Test]
public void NonCloneableType()
{
Assert.Throws<InvalidOperationException>(() => new Transactional<Func<int>>());
}
[Test]
public void InDoubt()
{
var tso = new Transactional<SimpleObject>();
SimpleObject obj = new SimpleObject
{
TestInt = 7,
TestGuid = Guid.NewGuid(),
TestString = "Testing"
};
MockRepository mocks = new MockRepository();
ISinglePhaseNotification badResource = mocks.StrictMock<ISinglePhaseNotification>();
badResource.SinglePhaseCommit(null);
Action<SinglePhaseEnlistment> onCommit = (SinglePhaseEnlistment spe) => spe.InDoubt();
LastCall.IgnoreArguments().Do(onCommit);
mocks.ReplayAll();
Assert.Throws<TransactionInDoubtException>(() =>
{
using (TransactionScope scope = new TransactionScope())
{
tso.Value = obj;
Transaction.Current.EnlistDurable(Guid.NewGuid(), badResource, EnlistmentOptions.None);
scope.Complete();
}
});
Assert.IsNull(tso.Value);
}
//[Test]
//public void CommitingOverlappingTransactionsWithNoValueChange()
//{
// var tso = new Transactional<SimpleObject>();
// using (TransactionScope scope = new TransactionScope())
// {
// var x = tso.Value;
// using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew))
// {
// var y = tso.Value;
// scope2.Complete();
// }
// scope.Complete();
// }
//}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Linq;
using System.Abstract;
using System.Collections.Generic;
using Spring.Objects.Factory;
using Spring.Context.Support;
using Spring.Context;
namespace Contoso.Abstract
{
/// <summary>
/// ISpringServiceLocator
/// </summary>
public interface ISpringServiceLocator : IServiceLocator
{
/// <summary>
/// Gets the container.
/// </summary>
GenericApplicationContext Container { get; }
}
/// <summary>
/// SpringServiceLocator
/// </summary>
[Serializable]
public class SpringServiceLocator : ISpringServiceLocator, IDisposable, ServiceLocatorManager.ISetupRegistration
{
private GenericApplicationContext _container;
private SpringServiceRegistrar _registrar;
static SpringServiceLocator() { ServiceLocatorManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="SpringServiceLocator"/> class.
/// </summary>
public SpringServiceLocator()
: this(new GenericApplicationContext()) { }
/// <summary>
/// Initializes a new instance of the <see cref="SpringServiceLocator"/> class.
/// </summary>
/// <param name="container">The container.</param>
public SpringServiceLocator(GenericApplicationContext container)
{
if (container == null)
throw new ArgumentNullException("container");
Container = container;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (_container != null)
{
var container = _container;
_container = null;
_registrar = null;
// prevent cyclical dispose
if (container != null)
container.Dispose();
}
}
Action<IServiceLocator, string> ServiceLocatorManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceLocatorManager.RegisterInstance<ISpringServiceLocator>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.
/// -or-
/// null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { return Resolve(serviceType); }
/// <summary>
/// Creates the child.
/// </summary>
/// <returns></returns>
public IServiceLocator CreateChild(object tag) { throw new NotSupportedException(); }
/// <summary>
/// Gets the underlying container.
/// </summary>
/// <typeparam name="TContainer">The type of the container.</typeparam>
/// <returns></returns>
public TContainer GetUnderlyingContainer<TContainer>()
where TContainer : class { return (_container as TContainer); }
// registrar
/// <summary>
/// Gets the registrar.
/// </summary>
public IServiceRegistrar Registrar
{
get { return _registrar; }
}
// resolve
/// <summary>
/// Resolves this instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public TService Resolve<TService>()
where TService : class
{
var serviceType = typeof(TService);
try { return (TService)_container.GetObject(GetName(serviceType), serviceType); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
internal static string GetName(Type serviceType) { return serviceType.FullName; }
/// <summary>
/// Resolves the specified name.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="name">The name.</param>
/// <returns></returns>
public TService Resolve<TService>(string name)
where TService : class
{
var serviceType = typeof(TService);
try { return (TService)_container.GetObject(name, serviceType); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public object Resolve(Type serviceType)
{
try { return _container.GetObject(GetName(serviceType), serviceType); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public object Resolve(Type serviceType, string name)
{
try { return _container.GetObject(name, serviceType); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
//
/// <summary>
/// Resolves all.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public IEnumerable<TService> ResolveAll<TService>()
where TService : class { throw new NotSupportedException(); }
/// <summary>
/// Resolves all.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public IEnumerable<object> ResolveAll(Type serviceType) { throw new NotSupportedException(); }
// inject
/// <summary>
/// Injects the specified instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
/// <returns></returns>
public TService Inject<TService>(TService instance)
where TService : class
{
try { return (TService)_container.ConfigureObject(instance, GetName(typeof(TService))); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
// release and teardown
/// <summary>
/// Releases the specified instance.
/// </summary>
/// <param name="instance">The instance.</param>
public void Release(object instance) { throw new NotSupportedException(); }
/// <summary>
/// Tears down.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
public void TearDown<TService>(TService instance)
where TService : class { throw new NotSupportedException(); }
#region Domain specific
/// <summary>
/// Gets the container.
/// </summary>
public GenericApplicationContext Container
{
get { return _container; }
private set
{
_container = value;
_registrar = new SpringServiceRegistrar(this, value);
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using NDesk.Options;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
/// <summary>
/// This module loads and saves OpenSimulator inventory archives
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryArchiverModule")]
public class InventoryArchiverModule : ISharedRegionModule, IInventoryArchiverModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// Enable or disable checking whether the iar user is actually logged in
/// </value>
// public bool DisablePresenceChecks { get; set; }
public event InventoryArchiveSaved OnInventoryArchiveSaved;
public event InventoryArchiveLoaded OnInventoryArchiveLoaded;
/// <summary>
/// The file to load and save inventory if no filename has been specified
/// </summary>
protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar";
/// <value>
/// Pending save and load completions initiated from the console
/// </value>
protected List<UUID> m_pendingConsoleTasks = new List<UUID>();
/// <value>
/// All scenes that this module knows about
/// </value>
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
private Scene m_aScene;
private IUserAccountService m_UserAccountService;
protected IUserAccountService UserAccountService
{
get
{
if (m_UserAccountService == null)
// What a strange thing to do...
foreach (Scene s in m_scenes.Values)
{
m_UserAccountService = s.RequestModuleInterface<IUserAccountService>();
break;
}
return m_UserAccountService;
}
}
public InventoryArchiverModule() {}
// public InventoryArchiverModule(bool disablePresenceChecks)
// {
// DisablePresenceChecks = disablePresenceChecks;
// }
#region ISharedRegionModule
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
if (m_scenes.Count == 0)
{
scene.RegisterModuleInterface<IInventoryArchiverModule>(this);
OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted;
OnInventoryArchiveLoaded += LoadInvConsoleCommandCompleted;
scene.AddCommand(
"Archiving", this, "load iar",
"load iar [-m|--merge] <first> <last> <inventory path> <password> [<IAR path>]",
"Load user inventory archive (IAR).",
"-m|--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones"
+ "<first> is user's first name." + Environment.NewLine
+ "<last> is user's last name." + Environment.NewLine
+ "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine
+ "<password> is the user's password." + Environment.NewLine
+ "<IAR path> is the filesystem path or URI from which to load the IAR."
+ string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME),
HandleLoadInvConsoleCommand);
scene.AddCommand(
"Archiving", this, "save iar",
"save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]",
"Save user inventory archive (IAR).",
"<first> is the user's first name.\n"
+ "<last> is the user's last name.\n"
+ "<inventory path> is the path inside the user's inventory for the folder/item to be saved.\n"
+ "<IAR path> is the filesystem path at which to save the IAR."
+ string.Format(" If this is not given then the filename {0} in the current directory is used.\n", DEFAULT_INV_BACKUP_FILENAME)
+ "-h|--home=<url> adds the url of the profile service to the saved user information.\n"
+ "-c|--creators preserves information about foreign creators.\n"
+ "-e|--exclude=<name/uuid> don't save the inventory item in archive" + Environment.NewLine
+ "-f|--excludefolder=<folder/uuid> don't save contents of the folder in archive" + Environment.NewLine
+ "-v|--verbose extra debug messages.\n"
+ "--noassets stops assets being saved to the IAR."
+ "--perm=<permissions> stops items with insufficient permissions from being saved to the IAR.\n"
+ " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer, \"M\" = Modify.\n",
HandleSaveInvConsoleCommand);
m_aScene = scene;
}
m_scenes[scene.RegionInfo.RegionID] = scene;
}
public void RemoveRegion(Scene scene)
{
}
public void Close() {}
public void RegionLoaded(Scene scene)
{
}
public void PostInitialise()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name { get { return "Inventory Archiver Module"; } }
#endregion
/// <summary>
/// Trigger the inventory archive saved event.
/// </summary>
protected internal void TriggerInventoryArchiveSaved(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException, int SaveCount, int FilterCount)
{
InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved;
if (handlerInventoryArchiveSaved != null)
handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException, SaveCount , FilterCount);
}
/// <summary>
/// Trigger the inventory archive loaded event.
/// </summary>
protected internal void TriggerInventoryArchiveLoaded(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream loadStream,
Exception reportedException, int LoadCount)
{
InventoryArchiveLoaded handlerInventoryArchiveLoaded = OnInventoryArchiveLoaded;
if (handlerInventoryArchiveLoaded != null)
handlerInventoryArchiveLoaded(id, succeeded, userInfo, invPath, loadStream, reportedException, LoadCount);
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream saveStream)
{
return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>());
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream saveStream,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
try
{
new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, string savePath,
Dictionary<string, object> options)
{
// if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, savePath))
// return false;
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
try
{
new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
public bool DearchiveInventory(UUID id, string firstName, string lastName, string invPath, string pass, Stream loadStream)
{
return DearchiveInventory(id, firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>());
}
public bool DearchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream loadStream,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
InventoryArchiveReadRequest request;
bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false);
try
{
request = new InventoryArchiveReadRequest(id, this, m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadStream, merge);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
else
m_log.ErrorFormat("[INVENTORY ARCHIVER]: User {0} {1} not found",
firstName, lastName);
}
return false;
}
public bool DearchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, string loadPath,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
InventoryArchiveReadRequest request;
bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false);
try
{
request = new InventoryArchiveReadRequest(id, this, m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadPath, merge);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
/// <summary>
/// Load inventory from an inventory file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams)
{
try
{
UUID id = UUID.Random();
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet optionSet = new OptionSet().Add("m|merge", delegate (string v) { options["merge"] = v != null; });
List<string> mainParams = optionSet.Parse(cmdparams);
if (mainParams.Count < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: usage is load iar [-m|--merge] <first name> <last name> <inventory path> <user password> [<load file path>]");
return;
}
string firstName = mainParams[2];
string lastName = mainParams[3];
string invPath = mainParams[4];
string pass = mainParams[5];
string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}",
loadPath, invPath, firstName, lastName);
lock (m_pendingConsoleTasks)
m_pendingConsoleTasks.Add(id);
DearchiveInventory(id, firstName, lastName, invPath, pass, loadPath, options);
}
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
/// <summary>
/// Save inventory to a file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
{
UUID id = UUID.Random();
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet ops = new OptionSet();
//ops.Add("v|version=", delegate(string v) { options["version"] = v; });
ops.Add("h|home=", delegate(string v) { options["home"] = v; });
ops.Add("v|verbose", delegate(string v) { options["verbose"] = v; });
ops.Add("c|creators", delegate(string v) { options["creators"] = v; });
ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; });
ops.Add("e|exclude=", delegate(string v)
{
if (!options.ContainsKey("exclude"))
options["exclude"] = new List<String>();
((List<String>)options["exclude"]).Add(v);
});
ops.Add("f|excludefolder=", delegate(string v)
{
if (!options.ContainsKey("excludefolders"))
options["excludefolders"] = new List<String>();
((List<String>)options["excludefolders"]).Add(v);
});
ops.Add("perm=", delegate(string v) { options["checkPermissions"] = v; });
List<string> mainParams = ops.Parse(cmdparams);
try
{
if (mainParams.Count < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]");
return;
}
if (options.ContainsKey("home"))
m_log.WarnFormat("[INVENTORY ARCHIVER]: Please be aware that inventory archives with creator information are not compatible with OpenSim 0.7.0.2 and earlier. Do not use the -home option if you want to produce a compatible IAR");
string firstName = mainParams[2];
string lastName = mainParams[3];
string invPath = mainParams[4];
string pass = mainParams[5];
string savePath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}",
savePath, invPath, firstName, lastName);
lock (m_pendingConsoleTasks)
m_pendingConsoleTasks.Add(id);
ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options);
}
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
private void SaveInvConsoleCommandCompleted(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException, int SaveCount, int FilterCount)
{
lock (m_pendingConsoleTasks)
{
if (m_pendingConsoleTasks.Contains(id))
m_pendingConsoleTasks.Remove(id);
else
return;
}
if (succeeded)
{
// Report success and include item count and filter count (Skipped items due to --perm or --exclude switches)
if(FilterCount == 0)
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive with {0} items for {1} {2}", SaveCount, userInfo.FirstName, userInfo.LastName);
else
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive with {0} items for {1} {2}. Skipped {3} items due to exclude and/or perm switches", SaveCount, userInfo.FirstName, userInfo.LastName, FilterCount);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}",
userInfo.FirstName, userInfo.LastName, reportedException.Message);
}
}
private void LoadInvConsoleCommandCompleted(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream loadStream,
Exception reportedException, int LoadCount)
{
lock (m_pendingConsoleTasks)
{
if (m_pendingConsoleTasks.Contains(id))
m_pendingConsoleTasks.Remove(id);
else
return;
}
if (succeeded)
{
m_log.InfoFormat("[INVENTORY ARCHIVER]: Loaded {0} items from archive {1} for {2} {3}", LoadCount, invPath, userInfo.FirstName, userInfo.LastName);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Archive load for {0} {1} failed - {2}",
userInfo.FirstName, userInfo.LastName, reportedException.Message);
}
}
/// <summary>
/// Get user information for the given name.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="pass">User password</param>
/// <returns></returns>
protected UserAccount GetUserInfo(string firstName, string lastName, string pass)
{
UserAccount account
= m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName);
if (null == account)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}",
firstName, lastName);
return null;
}
try
{
string encpass = Util.Md5Hash(pass);
if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty)
{
return account;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.",
firstName, lastName);
return null;
}
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e);
return null;
}
}
/// <summary>
/// Notify the client of loaded nodes if they are logged in
/// </summary>
/// <param name="loadedNodes">Can be empty. In which case, nothing happens</param>
private void UpdateClientWithLoadedNodes(UserAccount userInfo, HashSet<InventoryNodeBase> loadedNodes)
{
if (loadedNodes.Count == 0)
return;
foreach (Scene scene in m_scenes.Values)
{
ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID);
if (user != null && !user.IsChildAgent)
{
foreach (InventoryNodeBase node in loadedNodes)
{
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}",
// user.Name, node.Name);
user.ControllingClient.SendBulkUpdateInventory(node);
}
break;
}
}
}
// /// <summary>
// /// Check if the given user is present in any of the scenes.
// /// </summary>
// /// <param name="userId">The user to check</param>
// /// <returns>true if the user is in any of the scenes, false otherwise</returns>
// protected bool CheckPresence(UUID userId)
// {
// if (DisablePresenceChecks)
// return true;
//
// foreach (Scene scene in m_scenes.Values)
// {
// ScenePresence p;
// if ((p = scene.GetScenePresence(userId)) != null)
// {
// p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false);
// return true;
// }
// }
//
// return false;
// }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Binding.Expressions;
using DotVVM.Framework.Compilation.Javascript;
using DotVVM.Framework.Compilation.Javascript.Ast;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Utils;
using Newtonsoft.Json;
namespace DotVVM.Framework.Controls
{
public static class KnockoutHelper
{
/// <summary>
/// Adds the data-bind attribute to the next HTML element that is being rendered. The binding expression is taken from the specified property. If in server rendering mode, the binding is also not rendered.
/// </summary>
/// <param name="nullBindingAction">Action that is executed when there is not a value binding in the specified property, or in server rendering</param>
/// <param name="renderEvenInServerRenderingMode">When set to true, the binding is rendered even in server rendering mode. By default, the data-bind attribute is only added in client-rendering mode.</param>
public static void AddKnockoutDataBind(this IHtmlWriter writer, string name, DotvvmBindableObject control, DotvvmProperty property, Action? nullBindingAction = null,
string? valueUpdate = null, bool renderEvenInServerRenderingMode = false, bool setValueBack = false)
{
var expression = control.GetValueBinding(property);
if (expression != null && (!control.RenderOnServer || renderEvenInServerRenderingMode))
{
writer.AddKnockoutDataBind(name, expression.GetKnockoutBindingExpression(control));
if (valueUpdate != null)
{
writer.AddKnockoutDataBind("valueUpdate", $"'{valueUpdate}'");
}
}
else
{
nullBindingAction?.Invoke();
if (setValueBack && expression != null) control.SetValue(property, expression.Evaluate(control));
}
}
[Obsolete("Use the AddKnockoutDataBind(this IHtmlWriter writer, string name, IValueBinding valueBinding, DotvvmControl control) or AddKnockoutDataBind(this IHtmlWriter writer, string name, string expression) overload")]
public static void AddKnockoutDataBind(this IHtmlWriter writer, string name, IValueBinding valueBinding)
{
writer.AddKnockoutDataBind(name, valueBinding.GetKnockoutBindingExpression());
}
/// <summary>
/// Adds the data-bind attribute to the next HTML element that is being rendered. The binding expression is taken from the specified value binding.
/// </summary>
public static void AddKnockoutDataBind(this IHtmlWriter writer, string name, IValueBinding valueBinding, DotvvmBindableObject control)
{
writer.AddKnockoutDataBind(name, valueBinding.GetKnockoutBindingExpression(control));
}
/// <summary>
/// Adds the data-bind attribute to the next HTML element that is being rendered. The binding will be of form { Key: Value }, for each entry of the <paramref name="expressions" /> collection.
/// </summary>
/// <param name="property">This parameter is here for historical reasons, it's not useful for anything</param>
public static void AddKnockoutDataBind(this IHtmlWriter writer, string name, IEnumerable<KeyValuePair<string, IValueBinding>> expressions, DotvvmBindableObject control, DotvvmProperty? property = null)
{
writer.AddKnockoutDataBind(name, $"{{{String.Join(",", expressions.Select(e => "'" + e.Key + "': " + e.Value.GetKnockoutBindingExpression(control)))}}}");
}
public static void WriteKnockoutForeachComment(this IHtmlWriter writer, string binding)
{
writer.WriteKnockoutDataBindComment("foreach", binding);
}
public static void WriteKnockoutWithComment(this IHtmlWriter writer, string binding)
{
writer.WriteKnockoutDataBindComment("with", binding);
}
/// <summary> Writes knockout virtual element (the >!-- ko name: --> comment). It must be ended using <see cref="IHtmlWriter.WriteKnockoutDataBindEndComment" /> method. The binding expression is taken from a binding in the specified <paramref name="property" />. </summary>
/// <param name="name">The name of the binding handler.</param>
public static void WriteKnockoutDataBindComment(this IHtmlWriter writer, string name, DotvvmBindableObject control, DotvvmProperty property)
{
var binding = control.GetValueBinding(property);
if (binding is null) throw new DotvvmControlException(control, $"A value binding expression was expected in property {property}.");
writer.WriteKnockoutDataBindComment(name, binding.GetKnockoutBindingExpression(control));
}
public static void AddKnockoutForeachDataBind(this IHtmlWriter writer, string expression)
{
writer.AddKnockoutDataBind("foreach", expression);
}
/// <summary> Generates a function expression that invokes the command with specified commandArguments. Creates code like `(...commandArguments) => dotvvm.postBack(...)` </summary>
public static string GenerateClientPostbackLambda(string propertyName, ICommandBinding command, DotvvmBindableObject control, PostbackScriptOptions? options = null)
{
options ??= new PostbackScriptOptions(
elementAccessor: "$element",
koContext: CodeParameterAssignment.FromIdentifier("$context", true)
);
var hasArguments = command is IStaticCommandBinding || command.CommandJavascript.EnumerateAllParameters().Any(p => p == CommandBindingExpression.CommandArgumentsParameter);
options.CommandArgs = hasArguments ? new CodeParameterAssignment(new ParametrizedCode("args", OperatorPrecedence.Max)) : default;
// just few commands have arguments so it's worth checking if we need to clutter the output with argument propagation
var call = KnockoutHelper.GenerateClientPostBackExpression(
propertyName,
command,
control,
options);
return hasArguments ? $"(...args)=>({call})" : $"()=>({call})";
}
/// <summary> Generates Javascript code which executes the specified command binding <paramref name="expression" />. </summary>
/// <remarks> If you want a Javascript expression which returns a promise, use the <see cref="GenerateClientPostBackExpression(string, ICommandBinding, DotvvmBindableObject, PostbackScriptOptions)" /> method. </remarks>
/// <param name="propertyName">Name of the property which contains this command binding. It is used for looking up postback handlers.</param>
/// <param name="useWindowSetTimeout">If true, the command invocation will be wrapped in window.setTimeout with timeout 0. This is necessary for some event handlers, when the handler is invoked before the change is actually applied.</param>
/// <param name="returnValue">Return value of the event handler. If set to false, the script will also include event.stopPropagation()</param>
/// <param name="isOnChange">If set to true, the command will be suppressed during updating of view model. This is necessary for certain onChange events, if we don't want to trigger the command when the view model changes.</param>
/// <param name="elementAccessor">Javascript variable where the sender element can be found. Set to $element when in knockout binding.</param>
public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmBindableObject control, bool useWindowSetTimeout = false,
bool? returnValue = false, bool isOnChange = false, string elementAccessor = "this")
{
return GenerateClientPostBackScript(propertyName, expression, control, new PostbackScriptOptions(useWindowSetTimeout, returnValue, isOnChange, elementAccessor));
}
/// <summary> Generates Javascript code which executes the specified command binding <paramref name="expression" />. </summary>
/// <remarks> If you want a Javascript expression which returns a promise, use the <see cref="GenerateClientPostBackExpression(string, ICommandBinding, DotvvmBindableObject, PostbackScriptOptions)" /> method. </remarks>
/// <param name="propertyName">Name of the property which contains this command binding. It is used for looking up postback handlers.</param>
public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmBindableObject control, PostbackScriptOptions options)
{
var expr = GenerateClientPostBackExpression(propertyName, expression, control, options);
expr += ".catch(dotvvm.log.logPostBackScriptError)";
if (options.ReturnValue == false)
return expr + ";event.stopPropagation();return false;";
else
return expr;
}
/// <summary> Generates Javascript expression which executes the specified command binding <paramref name="expression" /> and returns Promise<DotvvmAfterPostBackEventArgs>. </summary>
/// <remarks> If you want a JS statement that you can place into an event handler, use the <see cref="GenerateClientPostBackScript(string, ICommandBinding, DotvvmBindableObject, PostbackScriptOptions)" /> method. </remarks>
/// <param name="propertyName">Name of the property which contains this command binding. It is used for looking up postback handlers.</param>
public static string GenerateClientPostBackExpression(string propertyName, ICommandBinding expression, DotvvmBindableObject control, PostbackScriptOptions options)
{
var target = (DotvvmControl?)control.GetClosestControlBindingTarget();
var uniqueControlId = target?.GetDotvvmUniqueId();
string getContextPath(DotvvmBindableObject? current)
{
var result = new List<string>();
while (current != null)
{
var pathFragment = current.GetDataContextPathFragment();
if (pathFragment != null)
{
result.Add(JsonConvert.ToString(pathFragment));
}
current = current.Parent;
}
result.Reverse();
return "[" + string.Join(",", result) + "]";
}
string getHandlerScript()
{
if (!options.AllowPostbackHandlers) return "[]";
// turn validation off for static commands
var validationPath = expression is IStaticCommandBinding ? null : GetValidationTargetExpression(control);
return GetPostBackHandlersScript(control, propertyName,
// validation handler
validationPath == null ? null :
validationPath == RootValidationTargetExpression ? "\"validate-root\"" :
validationPath == "$data" ? "\"validate-this\"" :
$"[\"validate\", {{path:{JsonConvert.ToString(validationPath)}}}]",
// use window.setTimeout
options.UseWindowSetTimeout ? "\"timeout\"" : null,
options.IsOnChange ? "\"suppressOnUpdating\"" : null,
GenerateConcurrencyModeHandler(propertyName, control)
);
}
var (isStaticCommand, jsExpression) =
expression switch {
IStaticCommandBinding { OptionsLambdaJavascript: var optionsLambdaExpression } => (true, optionsLambdaExpression),
_ => (false, expression.CommandJavascript)
};
var adjustedExpression =
JavascriptTranslator.AdjustKnockoutScriptContext(jsExpression,
dataContextLevel: expression.FindDataContextTarget(control).stepsUp);
// when the expression changes the dataContext, we need to override the default knockout context fo the command binding.
CodeParameterAssignment knockoutContext;
CodeParameterAssignment viewModel = default;
if (!isStaticCommand)
{
knockoutContext = options.KoContext ?? (
// adjustedExpression != expression.CommandJavascript ?
new CodeParameterAssignment(new ParametrizedCode.Builder { "ko.contextFor(", options.ElementAccessor.Code!, ")" }.Build(OperatorPrecedence.Max))
);
viewModel = JavascriptTranslator.KnockoutViewModelParameter.DefaultAssignment.Code;
}
else
{
knockoutContext = options.KoContext ?? CodeParameterAssignment.FromIdentifier("options.knockoutContext");
viewModel = CodeParameterAssignment.FromIdentifier("options.viewModel");
}
var abortSignal = options.AbortSignal ?? CodeParameterAssignment.FromIdentifier("undefined");
var optionalKnockoutContext =
options.KoContext is object ?
knockoutContext :
default;
var call = SubstituteArguments(adjustedExpression);
if (isStaticCommand)
{
var commandArgsString = (options.CommandArgs?.Code != null) ? SubstituteArguments(options.CommandArgs!.Value.Code!) : "[]";
var args = new List<string> {
SubstituteArguments(options.ElementAccessor.Code!),
getHandlerScript(),
commandArgsString,
optionalKnockoutContext.Code?.Apply(SubstituteArguments) ?? "undefined",
SubstituteArguments(abortSignal.Code!)
};
// remove default values to reduce mess in generated HTML :)
if (args.Last() == "undefined")
{
args.RemoveAt(4);
if (args.Last() == "undefined")
{
args.RemoveAt(3);
if (args.Last() == "[]")
{
args.RemoveAt(2);
if (args.Last() == "[]")
args.RemoveAt(1);
}
}
}
return $"dotvvm.applyPostbackHandlers({call},{string.Join(",", args)})";
}
else return call;
string SubstituteArguments(ParametrizedCode parametrizedCode)
{
return parametrizedCode.ToString(p =>
p == CommandBindingExpression.SenderElementParameter ? options.ElementAccessor :
p == CommandBindingExpression.CurrentPathParameter ? CodeParameterAssignment.FromIdentifier(getContextPath(control)) :
p == CommandBindingExpression.ControlUniqueIdParameter ? (
uniqueControlId is IValueBinding ?
((IValueBinding)uniqueControlId).GetParametrizedKnockoutExpression(control) :
CodeParameterAssignment.FromIdentifier(MakeStringLiteral((string)uniqueControlId!))
) :
p == JavascriptTranslator.KnockoutContextParameter ? knockoutContext :
p == JavascriptTranslator.KnockoutViewModelParameter ? viewModel :
p == CommandBindingExpression.OptionalKnockoutContextParameter ? optionalKnockoutContext :
p == CommandBindingExpression.CommandArgumentsParameter ? options.CommandArgs ?? default :
p == CommandBindingExpression.PostbackHandlersParameter ? CodeParameterAssignment.FromIdentifier(getHandlerScript()) :
p == CommandBindingExpression.AbortSignalParameter ? abortSignal :
default
);
}
}
/// <summary>
/// Generates a list of postback update handlers.
/// </summary>
private static string GetPostBackHandlersScript(DotvvmBindableObject control, string eventName, params string?[] moreHandlers)
{
var handlers = (List<PostBackHandler>?)control.GetValue(PostBack.HandlersProperty);
if ((handlers == null || handlers.Count == 0) && moreHandlers.Length == 0) return "[]";
var sb = new StringBuilder();
sb.Append('[');
if (handlers != null) foreach (var handler in handlers)
{
if (!string.IsNullOrEmpty(handler.EventName) && handler.EventName != eventName) continue;
var options = handler.GetHandlerOptions();
var name = handler.ClientHandlerName;
if (handler.GetValueBinding(PostBackHandler.EnabledProperty) is IValueBinding binding) options.Add("enabled", binding);
else if (!handler.Enabled) continue;
if (sb.Length > 1)
sb.Append(',');
if (options.Count == 0)
{
sb.Append(JsonConvert.ToString(name));
}
else
{
string script = GenerateHandlerOptions(handler, options);
sb.Append("[");
sb.Append(JsonConvert.ToString(name));
sb.Append(",");
sb.Append(script);
sb.Append("]");
}
}
if (moreHandlers != null) foreach (var h in moreHandlers) if (h != null)
{
if (sb.Length > 1)
sb.Append(',');
sb.Append(h);
}
sb.Append(']');
return sb.ToString();
}
private static string GenerateHandlerOptions(DotvvmBindableObject handler, Dictionary<string, object?> options)
{
JsExpression optionsExpr = new JsObjectExpression(
options.Where(o => o.Value != null).Select(o => new JsObjectProperty(o.Key, TransformOptionValueToExpression(handler, o.Value)))
);
if (options.Any(o => o.Value is IValueBinding))
{
optionsExpr = new JsArrowFunctionExpression(
new[] { new JsIdentifier("c"), new JsIdentifier("d") },
optionsExpr
);
}
optionsExpr.FixParenthesis();
var script = new JsFormattingVisitor().ApplyAction(optionsExpr.AcceptVisitor).GetParameterlessResult();
return script;
}
private static JsExpression TransformOptionValueToExpression(DotvvmBindableObject handler, object? optionValue)
{
switch (optionValue)
{
case IValueBinding binding: {
var adjustedCode = binding.GetParametrizedKnockoutExpression(handler, unwrapped: true).AssignParameters(o =>
o == JavascriptTranslator.KnockoutContextParameter ? new ParametrizedCode("c") :
o == JavascriptTranslator.KnockoutViewModelParameter ? new ParametrizedCode("d") :
default(CodeParameterAssignment)
);
return new JsSymbolicParameter(new CodeSymbolicParameter("tmp symbol", defaultAssignment: adjustedCode));
}
case IStaticValueBinding staticValueBinding:
return new JsLiteral(staticValueBinding.Evaluate(handler));
case JsExpression expression:
return expression.Clone();
case IBinding _:
throw new ArgumentException("Option value can contains only IValueBinding or IStaticValueBinding. Other bindings are not supported.");
default:
return new JsLiteral(optionValue);
}
}
static string? GenerateConcurrencyModeHandler(string propertyName, DotvvmBindableObject obj)
{
var mode = (obj.GetValue(PostBack.ConcurrencyProperty) as PostbackConcurrencyMode?) ?? PostbackConcurrencyMode.Default;
// determine concurrency queue
string? queueName = null;
var queueSettings = obj.GetValueRaw(PostBack.ConcurrencyQueueSettingsProperty) as ConcurrencyQueueSettingsCollection;
if (queueSettings != null)
{
queueName = queueSettings.FirstOrDefault(q => string.Equals(q.EventName, propertyName, StringComparison.OrdinalIgnoreCase))?.ConcurrencyQueue;
}
if (queueName == null)
{
queueName = obj.GetValue(PostBack.ConcurrencyQueueProperty) as string ?? "default";
}
// return the handler script
if (mode == PostbackConcurrencyMode.Default && "default".Equals(queueName))
{
return null;
}
var handlerName = $"concurrency-{mode.ToString().ToLowerInvariant()}";
if ("default".Equals(queueName))
{
return JsonConvert.ToString(handlerName);
}
else
{
return $"[{JsonConvert.ToString(handlerName)},{GenerateHandlerOptions(obj, new Dictionary<string, object?> { ["q"] = queueName })}]";
}
}
public const string RootValidationTargetExpression = "dotvvm.viewModelObservables['root']";
/// <summary>
/// Gets the validation target expression.
/// </summary>
public static string? GetValidationTargetExpression(DotvvmBindableObject control)
{
if (!(bool)control.GetValue(Validation.EnabledProperty)!)
{
return null;
}
return control.GetValueBinding(Validation.TargetProperty)?.GetKnockoutBindingExpression(control) ??
RootValidationTargetExpression;
}
/// <summary>
/// Writes text iff the property contains hard-coded value OR
/// writes knockout text binding iff the property contains binding
/// </summary>
/// <param name="writer">HTML output writer</param>
/// <param name="obj">Dotvvm control which contains the <see cref="DotvvmProperty"/> with value to be written</param>
/// <param name="property">Value of this property will be written</param>
/// <param name="wrapperTag">Name of wrapper tag, null => knockout binding comment</param>
public static void WriteTextOrBinding(this IHtmlWriter writer, DotvvmBindableObject obj, DotvvmProperty property, string? wrapperTag = null)
{
var valueBinding = obj.GetValueBinding(property);
if (valueBinding != null)
{
if (wrapperTag == null)
{
writer.WriteKnockoutDataBindComment("text", valueBinding.GetKnockoutBindingExpression(obj));
writer.WriteKnockoutDataBindEndComment();
}
else
{
writer.AddKnockoutDataBind("text", valueBinding.GetKnockoutBindingExpression(obj));
writer.RenderBeginTag(wrapperTag);
writer.RenderEndTag();
}
}
else
{
if (wrapperTag != null) writer.RenderBeginTag(wrapperTag);
writer.WriteText(obj.GetValue(property) + "");
if (wrapperTag != null) writer.RenderEndTag();
}
}
/// <summary>
/// Returns Javascript expression that represents the property value (even if the property contains hard-coded value)
/// </summary>
public static string GetKnockoutBindingExpression(this DotvvmBindableObject obj, DotvvmProperty property)
{
var binding = obj.GetValueBinding(property);
if (binding != null) return binding.GetKnockoutBindingExpression(obj);
return JsonConvert.SerializeObject(obj.GetValue(property), DefaultSerializerSettingsProvider.Instance.Settings);
}
/// <summary>
/// Encodes the string so it can be used in Javascript code.
/// </summary>
public static string MakeStringLiteral(string value, bool useApos = false)
{
return JsonConvert.ToString(value, useApos ? '\'' : '"', StringEscapeHandling.Default);
}
public static string ConvertToCamelCase(string name)
{
return name.Substring(0, 1).ToLowerInvariant() + name.Substring(1);
}
}
}
| |
namespace java.lang
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class StrictMath : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal StrictMath(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static long abs(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m0.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m0 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "abs", "(J)J");
return @__env.CallStaticLongMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public static double abs(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m1.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m1 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "abs", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
public static float abs(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m2.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m2 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "abs", "(F)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public static int abs(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m3.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m3 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "abs", "(I)I");
return @__env.CallStaticIntMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public static double sin(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m4.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m4 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "sin", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public static double cos(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m5.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m5 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "cos", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public static double tan(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m6.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m6 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "tan", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public static double atan2(double arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m7.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m7 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "atan2", "(DD)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m8;
public static double sqrt(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m8.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m8 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "sqrt", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
public static double log(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m9.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m9 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "log", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public static double log10(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m10.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m10 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "log10", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public static double pow(double arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m11.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m11 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "pow", "(DD)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m12;
public static double exp(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m12.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m12 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "exp", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public static double min(double arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m13.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m13 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "min", "(DD)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m14;
public static float min(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m14.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m14 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "min", "(FF)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m15;
public static long min(long arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m15.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m15 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "min", "(JJ)J");
return @__env.CallStaticLongMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m16;
public static int min(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m16.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m16 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "min", "(II)I");
return @__env.CallStaticIntMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m17;
public static float max(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m17.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m17 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "max", "(FF)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m18;
public static long max(long arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m18.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m18 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "max", "(JJ)J");
return @__env.CallStaticLongMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m19;
public static int max(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m19.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m19 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "max", "(II)I");
return @__env.CallStaticIntMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m20;
public static double max(double arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m20.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m20 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "max", "(DD)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m21;
public static float scalb(float arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m21.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m21 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "scalb", "(FI)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m22;
public static double scalb(double arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m22.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m22 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "scalb", "(DI)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m23;
public static int getExponent(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m23.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m23 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "getExponent", "(D)I");
return @__env.CallStaticIntMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m24;
public static int getExponent(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m24.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m24 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "getExponent", "(F)I");
return @__env.CallStaticIntMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
public static float signum(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m25.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m25 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "signum", "(F)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public static double signum(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m26.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m26 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "signum", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m27;
public static double asin(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m27.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m27 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "asin", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m28;
public static double acos(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m28.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m28 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "acos", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
public static double atan(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m29.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m29 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "atan", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m30;
public static double toRadians(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m30.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m30 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "toRadians", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m31;
public static double toDegrees(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m31.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m31 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "toDegrees", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m32;
public static double cbrt(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m32.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m32 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "cbrt", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m33;
public static double IEEEremainder(double arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m33.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m33 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "IEEEremainder", "(DD)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m34;
public static double ceil(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m34.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m34 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "ceil", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
public static double floor(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m35.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m35 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "floor", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m36;
public static double rint(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m36.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m36 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "rint", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m37;
public static int round(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m37.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m37 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "round", "(F)I");
return @__env.CallStaticIntMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m38;
public static long round(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m38.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m38 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "round", "(D)J");
return @__env.CallStaticLongMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m39;
public static double random()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m39.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m39 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "random", "()D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m39);
}
private static global::MonoJavaBridge.MethodId _m40;
public static double ulp(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m40.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m40 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "ulp", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m41;
public static float ulp(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m41.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m41 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "ulp", "(F)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m42;
public static double sinh(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m42.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m42 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "sinh", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m43;
public static double cosh(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m43.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m43 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "cosh", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m44;
public static double tanh(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m44.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m44 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "tanh", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m45;
public static double hypot(double arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m45.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m45 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "hypot", "(DD)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m46;
public static double expm1(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m46.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m46 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "expm1", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m47;
public static double log1p(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m47.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m47 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "log1p", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m48;
public static float copySign(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m48.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m48 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "copySign", "(FF)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m49;
public static double copySign(double arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m49.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m49 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "copySign", "(DD)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m50;
public static double nextAfter(double arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m50.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m50 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "nextAfter", "(DD)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m51;
public static float nextAfter(float arg0, double arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m51.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m51 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "nextAfter", "(FD)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m52;
public static float nextUp(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m52.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m52 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "nextUp", "(F)F");
return @__env.CallStaticFloatMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m53;
public static double nextUp(double arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.StrictMath._m53.native == global::System.IntPtr.Zero)
global::java.lang.StrictMath._m53 = @__env.GetStaticMethodIDNoThrow(global::java.lang.StrictMath.staticClass, "nextUp", "(D)D");
return @__env.CallStaticDoubleMethod(java.lang.StrictMath.staticClass, global::java.lang.StrictMath._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public static double E
{
get
{
return 2.718281828459045;
}
}
public static double PI
{
get
{
return 3.141592653589793;
}
}
static StrictMath()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.StrictMath.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/StrictMath"));
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data.SqlTypes;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Xml;
using System.Xml.Serialization;
using BLToolkit.Common;
using BLToolkit.ComponentModel;
using BLToolkit.Mapping;
using BLToolkit.Reflection;
using BLToolkit.TypeBuilder;
using BLToolkit.Validation;
namespace BLToolkit.EditableObjects
{
#region Instance Types
[GlobalInstanceType(typeof(byte), typeof(EditableValue<byte>))]
[GlobalInstanceType(typeof(char), typeof(EditableValue<char>))]
[GlobalInstanceType(typeof(ushort), typeof(EditableValue<ushort>))]
[GlobalInstanceType(typeof(uint), typeof(EditableValue<uint>))]
[GlobalInstanceType(typeof(ulong), typeof(EditableValue<ulong>))]
[GlobalInstanceType(typeof(bool), typeof(EditableValue<bool>))]
[GlobalInstanceType(typeof(sbyte), typeof(EditableValue<sbyte>))]
[GlobalInstanceType(typeof(short), typeof(EditableValue<short>))]
[GlobalInstanceType(typeof(int), typeof(EditableValue<int>))]
[GlobalInstanceType(typeof(long), typeof(EditableValue<long>))]
[GlobalInstanceType(typeof(float), typeof(EditableValue<float>))]
[GlobalInstanceType(typeof(double), typeof(EditableValue<double>))]
[GlobalInstanceType(typeof(string), typeof(EditableValue<string>), "")]
[GlobalInstanceType(typeof(DateTime), typeof(EditableValue<DateTime>))]
[GlobalInstanceType(typeof(decimal), typeof(EditableValue<decimal>))]
[GlobalInstanceType(typeof(Guid), typeof(EditableValue<Guid>))]
[GlobalInstanceType(typeof(byte?), typeof(EditableValue<byte?>))]
[GlobalInstanceType(typeof(char?), typeof(EditableValue<char?>))]
[GlobalInstanceType(typeof(ushort?), typeof(EditableValue<ushort?>))]
[GlobalInstanceType(typeof(uint?), typeof(EditableValue<uint?>))]
[GlobalInstanceType(typeof(ulong?), typeof(EditableValue<ulong?>))]
[GlobalInstanceType(typeof(bool?), typeof(EditableValue<bool?>))]
[GlobalInstanceType(typeof(sbyte?), typeof(EditableValue<sbyte?>))]
[GlobalInstanceType(typeof(short?), typeof(EditableValue<short?>))]
[GlobalInstanceType(typeof(int?), typeof(EditableValue<int?>))]
[GlobalInstanceType(typeof(long?), typeof(EditableValue<long?>))]
[GlobalInstanceType(typeof(float?), typeof(EditableValue<float?>))]
[GlobalInstanceType(typeof(double?), typeof(EditableValue<double?>))]
[GlobalInstanceType(typeof(DateTime?), typeof(EditableValue<DateTime?>))]
[GlobalInstanceType(typeof(decimal?), typeof(EditableValue<decimal?>))]
[GlobalInstanceType(typeof(Guid?), typeof(EditableValue<Guid?>))]
[GlobalInstanceType(typeof(SqlBoolean), typeof(EditableValue<SqlBoolean>))]
[GlobalInstanceType(typeof(SqlByte), typeof(EditableValue<SqlByte>))]
[GlobalInstanceType(typeof(SqlDateTime), typeof(EditableValue<SqlDateTime>))]
[GlobalInstanceType(typeof(SqlDecimal), typeof(EditableValue<SqlDecimal>))]
[GlobalInstanceType(typeof(SqlDouble), typeof(EditableValue<SqlDouble>))]
[GlobalInstanceType(typeof(SqlGuid), typeof(EditableValue<SqlGuid>))]
[GlobalInstanceType(typeof(SqlInt16), typeof(EditableValue<SqlInt16>))]
[GlobalInstanceType(typeof(SqlInt32), typeof(EditableValue<SqlInt32>))]
[GlobalInstanceType(typeof(SqlInt64), typeof(EditableValue<SqlInt64>))]
[GlobalInstanceType(typeof(SqlMoney), typeof(EditableValue<SqlMoney>))]
[GlobalInstanceType(typeof(SqlSingle), typeof(EditableValue<SqlSingle>))]
[GlobalInstanceType(typeof(SqlString), typeof(EditableValue<SqlString>), "")]
[GlobalInstanceType(typeof(XmlDocument), typeof(EditableXmlDocument))]
[GlobalInstanceType(typeof(EditableObject), typeof(EditableObjectHolder), IsObjectHolder=true)]
#endregion
[ImplementInterface(typeof(IEditable))]
[ImplementInterface(typeof(IMemberwiseEditable))]
[ImplementInterface(typeof(IPrintDebugState))]
[ImplementInterface(typeof(ISetParent))]
[ComVisible(true)]
[Serializable]
public abstract class EditableObject : EntityBase,
ICloneable, IEditableObject, INotifyPropertyChanged,
ISupportMapping, IValidatable, IPropertyChanged, INotifyObjectEdit
{
#region Constructor
protected EditableObject()
{
ISetParent setParent = this as ISetParent;
if (setParent != null)
setParent.SetParent(this, null);
}
#endregion
#region IEditable
public virtual void AcceptChanges()
{
if (this is IEditable)
((IEditable)this).AcceptChanges();
}
public virtual void RejectChanges()
{
PropertyInfo[] dirtyMembers = GetDirtyMembers();
if (this is IEditable)
((IEditable)this).RejectChanges();
foreach (PropertyInfo dirtyMember in dirtyMembers)
OnPropertyChanged(dirtyMember.Name);
}
public virtual void CancelLastChanges()
{
PropertyInfo[] dirtyMembers = GetDirtyMembers();
if (this is IEditable)
((IEditable)this).CancelLastChanges();
foreach (PropertyInfo dirtyMember in dirtyMembers)
OnPropertyChanged(dirtyMember.Name);
}
[MapIgnore, Bindable(false)]
public virtual bool IsDirty
{
get { return this is IEditable? ((IEditable)this).IsDirty: false; }
}
public virtual void AcceptMemberChanges(string memberName)
{
if (this is IMemberwiseEditable)
((IMemberwiseEditable)this).AcceptMemberChanges(null, memberName);
}
public virtual void RejectMemberChanges(string memberName)
{
bool notifyChange = IsDirtyMember(memberName);
if (this is IMemberwiseEditable)
((IMemberwiseEditable)this).RejectMemberChanges(null, memberName);
if (notifyChange)
OnPropertyChanged(memberName);
}
public virtual void CancelMemberLastChanges(string memberName)
{
bool notifyChange = IsDirtyMember(memberName);
if (this is IMemberwiseEditable)
((IMemberwiseEditable)this).CancelMemberLastChanges(null, memberName);
if (notifyChange)
OnPropertyChanged(memberName);
}
public virtual bool IsDirtyMember(string memberName)
{
bool isDirty = false;
if (this is IMemberwiseEditable)
((IMemberwiseEditable)this).IsDirtyMember(null, memberName, ref isDirty);
return isDirty;
}
public virtual PropertyInfo[] GetDirtyMembers()
{
ArrayList list = new ArrayList();
if (this is IMemberwiseEditable)
((IMemberwiseEditable)this).GetDirtyMembers(null, list);
return (PropertyInfo[])list.ToArray(typeof(PropertyInfo));
}
[MapIgnore, Bindable(false)]
public virtual string PrintDebugState
{
get
{
#if DEBUG
if (this is IPrintDebugState)
{
string s = string.Format(
"====== {0} ======\r\nIsDirty: {1}\r\n" +
"Property IsDirty Original Current\r\n" +
"==================== = ======================================== ========================================\r\n",
GetType().Name, IsDirty);
((IPrintDebugState)this).PrintDebugState(null, ref s);
return s + "\r\n";
}
#endif
return "";
}
}
#endregion
#region ISupportMapping Members
private bool _isInMapping;
[MapIgnore, Bindable(false)]
public bool IsInMapping
{
get { return _isInMapping; }
}
protected void SetIsInMapping(bool isInMapping)
{
_isInMapping = isInMapping;
}
public virtual void BeginMapping(InitContext initContext)
{
_isInMapping = true;
}
public virtual void EndMapping(InitContext initContext)
{
if (initContext.IsDestination)
AcceptChanges();
_isInMapping = false;
if (initContext.IsDestination)
OnPropertyChanged("");
}
#endregion
#region Notify Changes
protected internal virtual void OnPropertyChanged(string propertyName)
{
if (NotifyChanges && PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private int _notNotifyChangesCount = 0;
[MapIgnore, Bindable(false), XmlIgnore]
public bool NotifyChanges
{
get { return _notNotifyChangesCount == 0; }
set { _notNotifyChangesCount = value? 0: 1; }
}
public void LockNotifyChanges()
{
_notNotifyChangesCount++;
}
public void UnlockNotifyChanges()
{
_notNotifyChangesCount--;
if (_notNotifyChangesCount < 0)
throw new InvalidOperationException();
}
#endregion
#region IPropertyChanged Members
void IPropertyChanged.OnPropertyChanged(PropertyInfo propertyInfo)
{
if (_isInMapping == false)
OnPropertyChanged(propertyInfo.Name);
}
#endregion
#region INotifyPropertyChanged Members
[field : NonSerialized]
public virtual event PropertyChangedEventHandler PropertyChanged;
#endregion
#region IEditableObject Members
public virtual void BeginEdit()
{
if (ObjectEdit != null)
ObjectEdit(this, new ObjectEditEventArgs(ObjectEditType.Begin));
}
public virtual void CancelEdit()
{
if (ObjectEdit != null)
ObjectEdit(this, new ObjectEditEventArgs(ObjectEditType.Cancel));
}
public virtual void EndEdit()
{
if (ObjectEdit != null)
ObjectEdit(this, new ObjectEditEventArgs(ObjectEditType.End));
}
#endregion
#region INotifyObjectEdit Members
public event ObjectEditEventHandler ObjectEdit;
#endregion
#region ICloneable Members
///<summary>
///Creates a new object that is a copy of the current instance.
///</summary>
///<returns>
///A new object that is a copy of this instance.
///</returns>
public virtual object Clone() // BVChanges: public virtual
{
return TypeAccessor.Copy(this);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Concurrency;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime;
namespace Orleans.Streams
{
internal class PersistentStreamPullingAgent : SystemTarget, IPersistentStreamPullingAgent
{
private static readonly IBackoffProvider DeliveryBackoffProvider = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1));
private static readonly IBackoffProvider ReadLoopBackoff = new ExponentialBackoff(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1));
private const int ReadLoopRetryMax = 6;
private static readonly IStreamFilterPredicateWrapper DefaultStreamFilter = new DefaultStreamFilterPredicateWrapper();
private const int StreamInactivityCheckFrequency = 10;
private readonly string streamProviderName;
private readonly IStreamPubSub pubSub;
private readonly Dictionary<StreamId, StreamConsumerCollection> pubSubCache;
private readonly SafeRandom safeRandom;
private readonly StreamPullingAgentOptions options;
private readonly ILogger logger;
private readonly CounterStatistic numReadMessagesCounter;
private readonly CounterStatistic numSentMessagesCounter;
private int numMessages;
private IQueueAdapter queueAdapter;
private IQueueCache queueCache;
private IQueueAdapterReceiver receiver;
private IStreamFailureHandler streamFailureHandler;
private DateTime lastTimeCleanedPubSubCache;
private IDisposable timer;
internal readonly QueueId QueueId;
private Task receiverInitTask;
private bool IsShutdown => timer == null;
private string StatisticUniquePostfix => streamProviderName + "." + QueueId;
internal PersistentStreamPullingAgent(
GrainId id,
string strProviderName,
IStreamProviderRuntime runtime,
ILoggerFactory loggerFactory,
IStreamPubSub streamPubSub,
QueueId queueId,
StreamPullingAgentOptions options)
: base(id, runtime.ExecutingSiloAddress, true, loggerFactory)
{
if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null");
if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null");
QueueId = queueId;
streamProviderName = strProviderName;
pubSub = streamPubSub;
pubSubCache = new Dictionary<StreamId, StreamConsumerCollection>();
safeRandom = new SafeRandom();
this.options = options;
numMessages = 0;
logger = runtime.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger($"{this.GetType().Namespace}.{((ISystemTargetBase)this).GrainId}.{streamProviderName}");
logger.Info(ErrorCode.PersistentStreamPullingAgent_01,
"Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.",
GetType().Name, ((ISystemTargetBase)this).GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode());
numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, StatisticUniquePostfix));
numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, StatisticUniquePostfix));
// TODO: move queue cache size statistics tracking into queue cache implementation once Telemetry APIs and LogStatistics have been reconciled.
//IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, statUniquePostfix), () => queueCache != null ? queueCache.Size : 0);
}
/// <summary>
/// Take responsibility for a new queues that was assigned to me via a new range.
/// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer.
/// ERROR HANDLING:
/// The responsibility to handle initialization and shutdown failures is inside the INewQueueAdapterReceiver code.
/// The agent will call Initialize once and log an error. It will not call initialize again.
/// The receiver itself may attempt later to recover from this error and do initialization again.
/// The agent will assume initialization has succeeded and will subsequently start calling pumping receive.
/// Same applies to shutdown.
/// </summary>
/// <param name="qAdapter"></param>
/// <param name="queueAdapterCache"></param>
/// <param name="failureHandler"></param>
/// <returns></returns>
public Task Initialize(Immutable<IQueueAdapter> qAdapter, Immutable<IQueueAdapterCache> queueAdapterCache, Immutable<IStreamFailureHandler> failureHandler)
{
if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null");
if (failureHandler.Value == null) throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null");
return OrleansTaskExtentions.WrapInTask(() => InitializeInternal(qAdapter.Value, queueAdapterCache.Value, failureHandler.Value));
}
private void InitializeInternal(IQueueAdapter qAdapter, IQueueAdapterCache queueAdapterCache, IStreamFailureHandler failureHandler)
{
logger.Info(ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.",
GetType().Name, ((ISystemTargetBase)this).GrainId.ToDetailedString(), Silo, QueueId.ToStringWithHashCode());
// Remove cast once we cleanup
queueAdapter = qAdapter;
streamFailureHandler = failureHandler;
lastTimeCleanedPubSubCache = DateTime.UtcNow;
try
{
receiver = queueAdapter.CreateReceiver(QueueId);
}
catch (Exception exc)
{
logger.Error(ErrorCode.PersistentStreamPullingAgent_02, "Exception while calling IQueueAdapter.CreateNewReceiver.", exc);
throw;
}
try
{
if (queueAdapterCache != null)
{
queueCache = queueAdapterCache.CreateQueueCache(QueueId);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.PersistentStreamPullingAgent_23, "Exception while calling IQueueAdapterCache.CreateQueueCache.", exc);
throw;
}
try
{
receiverInitTask = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(this.options.InitQueueTimeout))
.LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, $"QueueAdapterReceiver {QueueId.ToStringWithHashCode()} failed to Initialize.");
receiverInitTask.Ignore();
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Initialize. No need to log again.
}
// Setup a reader for a new receiver.
// Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization.
var randomTimerOffset = safeRandom.NextTimeSpan(this.options.GetQueueMsgsTimerPeriod);
timer = RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, this.options.GetQueueMsgsTimerPeriod);
IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix), () => pubSubCache.Count);
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode());
}
public async Task Shutdown()
{
// Stop pulling from queues that are not in my range anymore.
logger.Info(ErrorCode.PersistentStreamPullingAgent_05, "Shutdown of {0} responsible for queue: {1}", GetType().Name, QueueId.ToStringWithHashCode());
if (timer != null)
{
IDisposable tmp = timer;
timer = null;
Utils.SafeExecute(tmp.Dispose, this.logger);
}
this.queueCache = null;
Task localReceiverInitTask = receiverInitTask;
if (localReceiverInitTask != null)
{
try
{
await localReceiverInitTask;
receiverInitTask = null;
}
catch (Exception)
{
receiverInitTask = null;
// squelch
}
}
try
{
IQueueAdapterReceiver localReceiver = this.receiver;
this.receiver = null;
if (localReceiver != null)
{
var task = OrleansTaskExtentions.SafeExecute(() => localReceiver.Shutdown(this.options.InitQueueTimeout));
task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_07,
$"QueueAdapterReceiver {QueueId} failed to Shutdown.");
await task;
}
}
catch
{
// Just ignore this exception and proceed as if Shutdown has succeeded.
// We already logged individual exceptions for individual calls to Shutdown. No need to log again.
}
var unregisterTasks = new List<Task>();
var meAsStreamProducer = this.AsReference<IStreamProducerExtension>();
foreach (var tuple in pubSubCache)
{
tuple.Value.DisposeAll(logger);
var streamId = tuple.Key;
logger.Info(ErrorCode.PersistentStreamPullingAgent_06, "Unregister PersistentStreamPullingAgent Producer for stream {0}.", streamId);
unregisterTasks.Add(pubSub.UnregisterProducer(streamId, streamProviderName, meAsStreamProducer));
}
try
{
await Task.WhenAll(unregisterTasks);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.PersistentStreamPullingAgent_08,
"Failed to unregister myself as stream producer to some streams that used to be in my responsibility.", exc);
}
pubSubCache.Clear();
IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix));
//IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, StatisticUniquePostfix));
}
public Task AddSubscriber(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
IStreamFilterPredicateWrapper filter)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_09, "AddSubscriber: Stream={0} Subscriber={1}.", streamId, streamConsumer);
// cannot await here because explicit consumers trigger this call, so it could cause a deadlock.
AddSubscriber_Impl(subscriptionId, streamId, streamConsumer, null, filter)
.LogException(logger, ErrorCode.PersistentStreamPullingAgent_26,
$"Failed to add subscription for stream {streamId}.")
.Ignore();
return Task.CompletedTask;
}
// Called by rendezvous when new remote subscriber subscribes to this stream.
private async Task AddSubscriber_Impl(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
StreamSequenceToken cacheToken,
IStreamFilterPredicateWrapper filter)
{
if (IsShutdown) return;
StreamConsumerCollection streamDataCollection;
if (!pubSubCache.TryGetValue(streamId, out streamDataCollection))
{
// If stream is not in pubsub cache, then we've received no events on this stream, and will aquire the subscriptions from pubsub when we do.
return;
}
StreamConsumerData data;
if (!streamDataCollection.TryGetConsumer(subscriptionId, out data))
data = streamDataCollection.AddConsumer(subscriptionId, streamId, streamConsumer, filter ?? DefaultStreamFilter);
if (await DoHandshakeWithConsumer(data, cacheToken))
{
if (data.State == StreamConsumerDataState.Inactive)
RunConsumerCursor(data, data.Filter).Ignore(); // Start delivering events if not actively doing so
}
}
private async Task<bool> DoHandshakeWithConsumer(
StreamConsumerData consumerData,
StreamSequenceToken cacheToken)
{
StreamHandshakeToken requestedHandshakeToken = null;
// if not cache, then we can't get cursor and there is no reason to ask consumer for token.
if (queueCache != null)
{
Exception exceptionOccured = null;
try
{
requestedHandshakeToken = await AsyncExecutorWithRetries.ExecuteWithRetries(
i => consumerData.StreamConsumer.GetSequenceToken(consumerData.SubscriptionId),
AsyncExecutorWithRetries.INFINITE_RETRIES,
(exception, i) => !(exception is ClientNotAvailableException),
this.options.MaxEventDeliveryTime,
DeliveryBackoffProvider);
if (requestedHandshakeToken != null)
{
consumerData.SafeDisposeCursor(logger);
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, requestedHandshakeToken.Token);
}
else
{
if (consumerData.Cursor == null) // if the consumer did not ask for a specific token and we already have a cursor, jsut keep using it.
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken);
}
}
catch (Exception exception)
{
exceptionOccured = exception;
}
if (exceptionOccured != null)
{
bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, false, null, requestedHandshakeToken?.Token);
if (faultedSubscription) return false;
}
}
consumerData.LastToken = requestedHandshakeToken; // use what ever the consumer asked for as LastToken for next handshake (even if he asked for null).
// if we don't yet have a cursor (had errors in the handshake or data not available exc), get a cursor at the event that triggered that consumer subscription.
if (consumerData.Cursor == null && queueCache != null)
{
try
{
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken);
}
catch (Exception)
{
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null); // just in case last GetCacheCursor failed.
}
}
return true;
}
public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId)
{
RemoveSubscriber_Impl(subscriptionId, streamId);
return Task.CompletedTask;
}
public void RemoveSubscriber_Impl(GuidId subscriptionId, StreamId streamId)
{
if (IsShutdown) return;
StreamConsumerCollection streamData;
if (!pubSubCache.TryGetValue(streamId, out streamData)) return;
// remove consumer
bool removed = streamData.RemoveConsumer(subscriptionId, logger);
if (removed && logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_10, "Removed Consumer: subscription={0}, for stream {1}.", subscriptionId, streamId);
if (streamData.Count == 0)
pubSubCache.Remove(streamId);
}
private async Task AsyncTimerCallback(object state)
{
var queueId = (QueueId)state;
try
{
Task localReceiverInitTask = receiverInitTask;
if (localReceiverInitTask != null)
{
await localReceiverInitTask;
receiverInitTask = null;
}
if (IsShutdown) return; // timer was already removed, last tick
// loop through the queue until it is empty.
while (!IsShutdown) // timer will be set to null when we are asked to shudown.
{
int maxCacheAddCount = queueCache?.GetMaxAddCount() ?? QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG;
if (maxCacheAddCount != QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG && maxCacheAddCount <= 0)
return;
// If read succeeds and there is more data, we continue reading.
// If read succeeds and there is no more data, we break out of loop
// If read fails, we retry 6 more times, with backoff policy.
// we log each failure as warnings. After 6 times retry if still fail, we break out of loop and log an error
bool moreData = await AsyncExecutorWithRetries.ExecuteWithRetries(
i => ReadFromQueue(queueId, receiver, maxCacheAddCount),
ReadLoopRetryMax,
ReadLoopRetryExceptionFilter,
Constants.INFINITE_TIMESPAN,
ReadLoopBackoff);
if (!moreData)
return;
}
}
catch (Exception exc)
{
receiverInitTask = null;
logger.Error(ErrorCode.PersistentStreamPullingAgent_12, $"Giving up reading from queue {queueId} after retry attempts {ReadLoopRetryMax}", exc);
}
}
private bool ReadLoopRetryExceptionFilter(Exception e, int retryCounter)
{
this.logger.Warn(ErrorCode.PersistentStreamPullingAgent_12, $"Exception while retrying the {retryCounter}th time reading from queue {this.QueueId}", e);
return !IsShutdown;
}
/// <summary>
/// Read from queue.
/// Returns true, if data was read, false if it was not
/// </summary>
/// <param name="myQueueId"></param>
/// <param name="rcvr"></param>
/// <param name="maxCacheAddCount"></param>
/// <returns></returns>
private async Task<bool> ReadFromQueue(QueueId myQueueId, IQueueAdapterReceiver rcvr, int maxCacheAddCount)
{
if (rcvr == null)
{
return false;
}
var now = DateTime.UtcNow;
// Try to cleanup the pubsub cache at the cadence of 10 times in the configurable StreamInactivityPeriod.
if ((now - lastTimeCleanedPubSubCache) >= this.options.StreamInactivityPeriod.Divide(StreamInactivityCheckFrequency))
{
lastTimeCleanedPubSubCache = now;
CleanupPubSubCache(now);
}
if (queueCache != null)
{
IList<IBatchContainer> purgedItems;
if (queueCache.TryPurgeFromCache(out purgedItems))
{
try
{
await rcvr.MessagesDeliveredAsync(purgedItems);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.PersistentStreamPullingAgent_27,
$"Exception calling MessagesDeliveredAsync on queue {myQueueId}. Ignoring.", exc);
}
}
}
if (queueCache != null && queueCache.IsUnderPressure())
{
// Under back pressure. Exit the loop. Will attempt again in the next timer callback.
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_24, "Stream cache is under pressure. Backing off.");
return false;
}
// Retrieve one multiBatch from the queue. Every multiBatch has an IEnumerable of IBatchContainers, each IBatchContainer may have multiple events.
IList<IBatchContainer> multiBatch = await rcvr.GetQueueMessagesAsync(maxCacheAddCount);
if (multiBatch == null || multiBatch.Count == 0) return false; // queue is empty. Exit the loop. Will attempt again in the next timer callback.
queueCache?.AddToCache(multiBatch);
numMessages += multiBatch.Count;
numReadMessagesCounter.IncrementBy(multiBatch.Count);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.PersistentStreamPullingAgent_11, "Got {0} messages from queue {1}. So far {2} msgs from this queue.",
multiBatch.Count, myQueueId.ToStringWithHashCode(), numMessages);
foreach (var group in
multiBatch
.Where(m => m != null)
.GroupBy(container => new Tuple<Guid, string>(container.StreamGuid, container.StreamNamespace)))
{
var streamId = StreamId.GetStreamId(group.Key.Item1, queueAdapter.Name, group.Key.Item2);
StreamSequenceToken startToken = group.First().SequenceToken;
StreamConsumerCollection streamData;
if (pubSubCache.TryGetValue(streamId, out streamData))
{
streamData.RefreshActivity(now);
if (streamData.StreamRegistered)
{
StartInactiveCursors(streamData,
startToken); // if this is an existing stream, start any inactive cursors
}
else
{
if(this.logger.IsEnabled(LogLevel.Debug))
this.logger.LogDebug($"Pulled new messages in stream {streamId} from the queue, but pulling agent haven't succeeded in" +
$"RegisterStream yet, will start deliver on this stream after RegisterStream succeeded");
}
}
else
{
RegisterStream(streamId, startToken, now).Ignore(); // if this is a new stream register as producer of stream in pub sub system
}
}
return true;
}
private void CleanupPubSubCache(DateTime now)
{
if (pubSubCache.Count == 0) return;
var toRemove = pubSubCache.Where(pair => pair.Value.IsInactive(now, this.options.StreamInactivityPeriod))
.ToList();
toRemove.ForEach(tuple =>
{
pubSubCache.Remove(tuple.Key);
tuple.Value.DisposeAll(logger);
});
}
private async Task RegisterStream(StreamId streamId, StreamSequenceToken firstToken, DateTime now)
{
var streamData = new StreamConsumerCollection(now);
pubSubCache.Add(streamId, streamData);
// Create a fake cursor to point into a cache.
// That way we will not purge the event from the cache, until we talk to pub sub.
// This will help ensure the "casual consistency" between pre-existing subscripton (of a potentially new already subscribed consumer)
// and later production.
var pinCursor = queueCache?.GetCacheCursor(streamId, firstToken);
try
{
await RegisterAsStreamProducer(streamId, firstToken);
streamData.StreamRegistered = true;
}
finally
{
// Cleanup the fake pinning cursor.
pinCursor?.Dispose();
}
}
private void StartInactiveCursors(StreamConsumerCollection streamData, StreamSequenceToken startToken)
{
foreach (StreamConsumerData consumerData in streamData.AllConsumers())
{
consumerData.Cursor?.Refresh(startToken);
if (consumerData.State == StreamConsumerDataState.Inactive)
{
// wake up inactive consumers
RunConsumerCursor(consumerData, consumerData.Filter).Ignore();
}
}
}
private async Task RunConsumerCursor(StreamConsumerData consumerData, IStreamFilterPredicateWrapper filterWrapper)
{
try
{
// double check in case of interleaving
if (consumerData.State == StreamConsumerDataState.Active ||
consumerData.Cursor == null) return;
consumerData.State = StreamConsumerDataState.Active;
while (consumerData.Cursor != null)
{
IBatchContainer batch = null;
Exception exceptionOccured = null;
try
{
batch = GetBatchForConsumer(consumerData.Cursor, filterWrapper, consumerData.StreamId);
if (batch == null)
{
break;
}
}
catch (Exception exc)
{
exceptionOccured = exc;
consumerData.SafeDisposeCursor(logger);
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null);
}
// Apply filtering to this batch, if applicable
if (filterWrapper != null && batch != null)
{
try
{
// Apply batch filter to this input batch, to see whether we should deliver it to this consumer.
if (!batch.ShouldDeliver(
consumerData.StreamId,
filterWrapper.FilterData,
filterWrapper.ShouldReceive)) continue; // Skip this batch -- nothing to do
}
catch (Exception exc)
{
var message =
$"Ignoring exception while trying to evaluate subscription filter function {filterWrapper} on stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor";
logger.Warn((int)ErrorCode.PersistentStreamPullingAgent_13, message, exc);
}
}
try
{
numSentMessagesCounter.Increment();
if (batch != null)
{
StreamHandshakeToken newToken = await AsyncExecutorWithRetries.ExecuteWithRetries(
i => DeliverBatchToConsumer(consumerData, batch),
AsyncExecutorWithRetries.INFINITE_RETRIES,
(exception, i) => !(exception is ClientNotAvailableException),
this.options.MaxEventDeliveryTime,
DeliveryBackoffProvider);
if (newToken != null)
{
consumerData.LastToken = newToken;
IQueueCacheCursor newCursor = queueCache.GetCacheCursor(consumerData.StreamId, newToken.Token);
consumerData.SafeDisposeCursor(logger);
consumerData.Cursor = newCursor;
}
}
}
catch (Exception exc)
{
consumerData.Cursor?.RecordDeliveryFailure();
var message =
$"Exception while trying to deliver msgs to stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor";
logger.Error(ErrorCode.PersistentStreamPullingAgent_14, message, exc);
exceptionOccured = exc is ClientNotAvailableException
? exc
: new StreamEventDeliveryFailureException(consumerData.StreamId);
}
// if we failed to deliver a batch
if (exceptionOccured != null)
{
bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, true, batch, batch?.SequenceToken);
if (faultedSubscription) return;
}
}
consumerData.State = StreamConsumerDataState.Inactive;
}
catch (Exception exc)
{
// RunConsumerCursor is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
logger.Error(ErrorCode.PersistentStreamPullingAgent_15, "Ignored RunConsumerCursor Error", exc);
consumerData.State = StreamConsumerDataState.Inactive;
throw;
}
}
private IBatchContainer GetBatchForConsumer(IQueueCacheCursor cursor, IStreamFilterPredicateWrapper filterWrapper, StreamId streamId)
{
if (this.options.BatchContainerBatchSize <= 1)
{
Exception ignore;
if (!cursor.MoveNext())
{
return null;
}
return cursor.GetCurrent(out ignore);
}
else if (this.options.BatchContainerBatchSize > 1)
{
Exception ignore;
int i = 0;
var batchContainers = new List<IBatchContainer>();
while (i < this.options.BatchContainerBatchSize)
{
if (!cursor.MoveNext())
{
break;
}
var batchContainer = cursor.GetCurrent(out ignore);
if (!batchContainer.ShouldDeliver(
streamId,
filterWrapper.FilterData,
filterWrapper.ShouldReceive)) continue;
batchContainers.Add(batchContainer);
i++;
}
if (i == 0)
{
return null;
}
return new BatchContainerBatch(batchContainers);
}
return null;
}
private async Task<StreamHandshakeToken> DeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch)
{
try
{
StreamHandshakeToken newToken = await ContextualizedDeliverBatchToConsumer(consumerData, batch);
consumerData.LastToken = StreamHandshakeToken.CreateDeliveyToken(batch.SequenceToken); // this is the currently delivered token
return newToken;
}
catch (Exception ex)
{
this.logger.LogWarning(ex, "Failed to deliver message to consumer on {SubscriptionId} for stream {StreamId}, may retry.", consumerData.SubscriptionId, consumerData.StreamId);
throw;
}
}
/// <summary>
/// Add call context for batch delivery call, then clear context immediately, without giving up turn.
/// </summary>
private Task<StreamHandshakeToken> ContextualizedDeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch)
{
bool isRequestContextSet = batch.ImportRequestContext();
try
{
return consumerData.StreamConsumer.DeliverBatch(consumerData.SubscriptionId, consumerData.StreamId, batch.AsImmutable(), consumerData.LastToken);
}
finally
{
if (isRequestContextSet)
{
// clear RequestContext before await!
RequestContext.Clear();
}
}
}
private static async Task DeliverErrorToConsumer(StreamConsumerData consumerData, Exception exc, IBatchContainer batch)
{
Task errorDeliveryTask;
bool isRequestContextSet = batch != null && batch.ImportRequestContext();
try
{
errorDeliveryTask = consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, exc);
}
finally
{
if (isRequestContextSet)
{
RequestContext.Clear(); // clear RequestContext before await!
}
}
await errorDeliveryTask;
}
private async Task<bool> ErrorProtocol(StreamConsumerData consumerData, Exception exceptionOccured, bool isDeliveryError, IBatchContainer batch, StreamSequenceToken token)
{
// for loss of client, we just remove the subscription
if (exceptionOccured is ClientNotAvailableException)
{
logger.Warn(ErrorCode.Stream_ConsumerIsDead,
"Consumer {0} on stream {1} is no longer active - permanently removing Consumer.", consumerData.StreamConsumer, consumerData.StreamId);
pubSub.UnregisterConsumer(consumerData.SubscriptionId, consumerData.StreamId, consumerData.StreamId.ProviderName).Ignore();
return true;
}
// notify consumer about the error or that the data is not available.
await OrleansTaskExtentions.ExecuteAndIgnoreException(
() => DeliverErrorToConsumer(
consumerData, exceptionOccured, batch));
// record that there was a delivery failure
if (isDeliveryError)
{
await OrleansTaskExtentions.ExecuteAndIgnoreException(
() => streamFailureHandler.OnDeliveryFailure(
consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token));
}
else
{
await OrleansTaskExtentions.ExecuteAndIgnoreException(
() => streamFailureHandler.OnSubscriptionFailure(
consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token));
}
// if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription
if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid))
{
try
{
// notify consumer of faulted subscription, if we can.
await OrleansTaskExtentions.ExecuteAndIgnoreException(
() => DeliverErrorToConsumer(
consumerData, new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId), batch));
// mark subscription as faulted.
await pubSub.FaultSubscription(consumerData.StreamId, consumerData.SubscriptionId);
}
finally
{
// remove subscription
RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId);
}
return true;
}
return false;
}
private static async Task<ISet<PubSubSubscriptionState>> PubsubRegisterProducer(IStreamPubSub pubSub, StreamId streamId, string streamProviderName,
IStreamProducerExtension meAsStreamProducer, ILogger logger)
{
try
{
var streamData = await pubSub.RegisterProducer(streamId, streamProviderName, meAsStreamProducer);
return streamData;
}
catch (Exception e)
{
logger.Error(ErrorCode.PersistentStreamPullingAgent_17, $"RegisterAsStreamProducer failed due to {e}", e);
throw e;
}
}
private async Task RegisterAsStreamProducer(StreamId streamId, StreamSequenceToken streamStartToken)
{
try
{
if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetreaveNewStream");
IStreamProducerExtension meAsStreamProducer = this.AsReference<IStreamProducerExtension>();
ISet<PubSubSubscriptionState> streamData = null;
await AsyncExecutorWithRetries.ExecuteWithRetries(
async i => { streamData =
await PubsubRegisterProducer(pubSub, streamId, streamProviderName, meAsStreamProducer, logger); },
AsyncExecutorWithRetries.INFINITE_RETRIES,
(exception, i) => !IsShutdown,
Constants.INFINITE_TIMESPAN,
DeliveryBackoffProvider);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_16, "Got back {0} Subscribers for stream {1}.", streamData.Count, streamId);
var addSubscriptionTasks = new List<Task>(streamData.Count);
foreach (PubSubSubscriptionState item in streamData)
{
addSubscriptionTasks.Add(AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, streamStartToken, item.Filter));
}
await Task.WhenAll(addSubscriptionTasks);
}
catch (Exception exc)
{
// RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
logger.Error(ErrorCode.PersistentStreamPullingAgent_17, "Ignored RegisterAsStreamProducer Error", exc);
throw;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Spectator;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Replays;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Screens;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps;
using osu.Game.Tests.Beatmaps.IO;
using osu.Game.Tests.Visual.Multiplayer;
using osu.Game.Tests.Visual.Spectator;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSpectator : ScreenTestScene
{
private readonly APIUser streamingUser = new APIUser { Id = MultiplayerTestScene.PLAYER_1_ID, Username = "Test user" };
[Cached(typeof(UserLookupCache))]
private UserLookupCache lookupCache = new TestUserLookupCache();
// used just to show beatmap card for the time being.
protected override bool UseOnlineAPI => true;
[Resolved]
private OsuGameBase game { get; set; }
private TestSpectatorClient spectatorClient => dependenciesScreen.SpectatorClient;
private DependenciesScreen dependenciesScreen;
private SoloSpectator spectatorScreen;
private BeatmapSetInfo importedBeatmap;
private int importedBeatmapId;
[SetUpSteps]
public void SetupSteps()
{
AddStep("load dependencies", () =>
{
LoadScreen(dependenciesScreen = new DependenciesScreen());
// The dependencies screen gets suspended so it stops receiving updates. So its children are manually added to the test scene instead.
Children = new Drawable[]
{
dependenciesScreen.UserLookupCache,
dependenciesScreen.SpectatorClient,
};
});
AddUntilStep("wait for dependencies to load", () => dependenciesScreen.IsLoaded);
AddStep("import beatmap", () =>
{
importedBeatmap = BeatmapImportHelper.LoadOszIntoOsu(game, virtualTrack: true).GetResultSafely();
importedBeatmapId = importedBeatmap.Beatmaps.First(b => b.Ruleset.OnlineID == 0).OnlineID;
});
}
[Test]
public void TestFrameStarvationAndResume()
{
loadSpectatingScreen();
AddAssert("screen hasn't changed", () => Stack.CurrentScreen is SoloSpectator);
start();
waitForPlayer();
sendFrames();
AddAssert("ensure frames arrived", () => replayHandler.HasFrames);
AddUntilStep("wait for frame starvation", () => replayHandler.WaitingForFrame);
checkPaused(true);
double? pausedTime = null;
AddStep("store time", () => pausedTime = currentFrameStableTime);
sendFrames();
AddUntilStep("wait for frame starvation", () => replayHandler.WaitingForFrame);
checkPaused(true);
AddAssert("time advanced", () => currentFrameStableTime > pausedTime);
}
[Test]
public void TestPlayStartsWithNoFrames()
{
loadSpectatingScreen();
start();
waitForPlayer();
checkPaused(true);
// send enough frames to ensure play won't be paused
sendFrames(100);
checkPaused(false);
}
[Test]
public void TestSpectatingDuringGameplay()
{
start();
sendFrames(300);
loadSpectatingScreen();
waitForPlayer();
sendFrames(300);
AddUntilStep("playing from correct point in time", () => player.ChildrenOfType<DrawableRuleset>().First().FrameStableClock.CurrentTime > 30000);
}
[Test]
public void TestHostRetriesWhileWatching()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
Player lastPlayer = null;
AddStep("store first player", () => lastPlayer = player);
start();
sendFrames();
waitForPlayer();
AddAssert("player is different", () => lastPlayer != player);
}
[Test]
public void TestHostFails()
{
loadSpectatingScreen();
start();
waitForPlayer();
checkPaused(true);
sendFrames();
finish(SpectatedUserState.Failed);
checkPaused(false); // Should continue playing until out of frames
checkPaused(true); // And eventually stop after running out of frames and fail.
// Todo: Should check for + display a failed message.
}
[Test]
public void TestStopWatchingDuringPlay()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddStep("stop spectating", () => (Stack.CurrentScreen as Player)?.Exit());
AddUntilStep("spectating stopped", () => spectatorScreen.GetChildScreen() == null);
}
[Test]
public void TestStopWatchingThenHostRetries()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddStep("stop spectating", () => (Stack.CurrentScreen as Player)?.Exit());
AddUntilStep("spectating stopped", () => spectatorScreen.GetChildScreen() == null);
// host starts playing a new session
start();
waitForPlayer();
}
[Test]
public void TestWatchingBeatmapThatDoesntExistLocally()
{
loadSpectatingScreen();
start(-1234);
sendFrames();
AddAssert("screen didn't change", () => Stack.CurrentScreen is SoloSpectator);
}
[Test]
public void TestFinalFramesPurgedBeforeEndingPlay()
{
AddStep("begin playing", () => spectatorClient.BeginPlaying(new GameplayState(new TestBeatmap(new OsuRuleset().RulesetInfo), new OsuRuleset()), new Score()));
AddStep("send frames and finish play", () =>
{
spectatorClient.HandleFrame(new OsuReplayFrame(1000, Vector2.Zero));
spectatorClient.EndPlaying(new GameplayState(new TestBeatmap(new OsuRuleset().RulesetInfo), new OsuRuleset()) { HasPassed = true });
});
// We can't access API because we're an "online" test.
AddAssert("last received frame has time = 1000", () => spectatorClient.LastReceivedUserFrames.First().Value.Time == 1000);
}
[Test]
public void TestFinalFrameInBundleHasHeader()
{
FrameDataBundle lastBundle = null;
AddStep("bind to client", () => spectatorClient.OnNewFrames += (_, bundle) => lastBundle = bundle);
start(-1234);
sendFrames();
finish();
AddUntilStep("bundle received", () => lastBundle != null);
AddAssert("first frame does not have header", () => lastBundle.Frames[0].Header == null);
AddAssert("last frame has header", () => lastBundle.Frames[^1].Header != null);
}
[Test]
public void TestPlayingState()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
}
[Test]
public void TestPassedState()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddStep("send passed", () => spectatorClient.SendEndPlay(streamingUser.Id, SpectatedUserState.Passed));
AddUntilStep("state is passed", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Passed);
start();
sendFrames();
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
}
[Test]
public void TestQuitState()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddStep("send quit", () => spectatorClient.SendEndPlay(streamingUser.Id));
AddUntilStep("state is quit", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Quit);
start();
sendFrames();
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
}
[Test]
public void TestFailedState()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddStep("send failed", () => spectatorClient.SendEndPlay(streamingUser.Id, SpectatedUserState.Failed));
AddUntilStep("state is failed", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Failed);
start();
sendFrames();
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
}
private OsuFramedReplayInputHandler replayHandler =>
(OsuFramedReplayInputHandler)Stack.ChildrenOfType<OsuInputManager>().First().ReplayInputHandler;
private Player player => Stack.CurrentScreen as Player;
private double currentFrameStableTime
=> player.ChildrenOfType<FrameStabilityContainer>().First().FrameStableClock.CurrentTime;
private void waitForPlayer() => AddUntilStep("wait for player", () => (Stack.CurrentScreen as Player)?.IsLoaded == true);
private void start(int? beatmapId = null) => AddStep("start play", () => spectatorClient.SendStartPlay(streamingUser.Id, beatmapId ?? importedBeatmapId));
private void finish(SpectatedUserState state = SpectatedUserState.Quit) => AddStep("end play", () => spectatorClient.SendEndPlay(streamingUser.Id, state));
private void checkPaused(bool state) =>
AddUntilStep($"game is {(state ? "paused" : "playing")}", () => player.ChildrenOfType<DrawableRuleset>().First().IsPaused.Value == state);
private void sendFrames(int count = 10)
{
AddStep("send frames", () => spectatorClient.SendFramesFromUser(streamingUser.Id, count));
}
private void loadSpectatingScreen()
{
AddStep("load spectator", () => LoadScreen(spectatorScreen = new SoloSpectator(streamingUser)));
AddUntilStep("wait for screen load", () => spectatorScreen.LoadState == LoadState.Loaded);
}
/// <summary>
/// Used for the sole purpose of adding <see cref="TestSpectatorClient"/> as a resolvable dependency.
/// </summary>
private class DependenciesScreen : OsuScreen
{
[Cached(typeof(SpectatorClient))]
public readonly TestSpectatorClient SpectatorClient = new TestSpectatorClient();
[Cached(typeof(UserLookupCache))]
public readonly TestUserLookupCache UserLookupCache = new TestUserLookupCache();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function initServer()
{
echo("\n--------- Initializing " @ $appName @ ": Server Scripts ---------");
//load prefs
//Force-load the defaults just so we don't have any mistakes
exec( "./defaults.cs" );
//Then, if the user has saved preferences, we load those over-top the defaults
%prefPath = getPrefpath();
if ( isFile( %prefPath @ "/serverPrefs.cs" ) )
exec( %prefPath @ "/serverPrefs.cs" );
exec( "./audio.cs" );
exec( "./commands.cs" );
exec( "./kickban.cs" );
exec( "./message.cs" );
exec( "./levelDownload.cs" );
exec( "./levelLoad.cs" );
exec( "./levelInfo.cs" );
exec( "./connectionToClient.cs" );
// Server::Status is returned in the Game Info Query and represents the
// current status of the server. This string sould be very short.
$Server::Status = "Unknown";
// Turn on testing/debug script functions
$Server::TestCheats = false;
// Specify where the mission files are.
$Server::MissionFileSpec = "data/levels/*.mis";
}
//-----------------------------------------------------------------------------
function initDedicated()
{
enableWinConsole(true);
echo("\n--------- Starting Dedicated Server ---------");
// Make sure this variable reflects the correct state.
$Server::Dedicated = true;
// The server isn't started unless a mission has been specified.
if ($missionArg !$= "") {
createServer("MultiPlayer", $missionArg);
}
else
echo("No mission specified (use -mission filename)");
}
/// Attempt to find an open port to initialize the server with
function portInit(%port)
{
%failCount = 0;
while(%failCount < 10 && !setNetPort(%port))
{
echo("Port init failed on port " @ %port @ " trying next port.");
%port++; %failCount++;
}
}
/// Create a server of the given type, load the given level, and then
/// create a local client connection to the server.
//
/// @return true if successful.
function createAndConnectToLocalServer( %serverType, %level )
{
if( !createServer( %serverType, %level ) )
return false;
%conn = new GameConnection( ServerConnection );
RootGroup.add( ServerConnection );
%conn.setConnectArgs( $pref::Player::Name );
%conn.setJoinPassword( $Client::Password );
%result = %conn.connectLocal();
if( %result !$= "" )
{
%conn.delete();
destroyServer();
MessageBoxOK("Error starting local server!", "There was an error when trying to connect to the local server.");
if(isObject(MainMenuGui))
Canvas.setContent(MainMenuGui);
return false;
}
return true;
}
/// Create a server with either a "SinglePlayer" or "MultiPlayer" type
/// Specify the level to load on the server
function createServer(%serverType, %level)
{
// Increase the server session number. This is used to make sure we're
// working with the server session we think we are.
$Server::Session++;
if (%level $= "")
{
error("createServer(): level name unspecified");
return false;
}
// Make sure our level name is relative so that it can send
// across the network correctly
%level = makeRelativePath(%level, getWorkingDirectory());
destroyServer();
$missionSequence = 0;
$Server::PlayerCount = 0;
$Server::ServerType = %serverType;
$Server::LoadFailMsg = "";
$Physics::isSinglePlayer = true;
// Setup for multi-player, the network must have been
// initialized before now.
if (%serverType $= "MultiPlayer")
{
$Physics::isSinglePlayer = false;
echo("Starting multiplayer mode");
// Make sure the network port is set to the correct pref.
portInit($Pref::Server::Port);
allowConnections(true);
if ($pref::Net::DisplayOnMaster !$= "Never" )
schedule(0,0,startHeartbeat);
}
// Let the game initialize some things now that the
// the server has been created
onServerCreated();
loadMission(%level, true);
$Game::running = true;
return true;
}
function onServerCreated()
{
// Server::GameType is sent to the master server.
// This variable should uniquely identify your game and/or mod.
$Server::GameType = $appName;
// Server::MissionType sent to the master server. Clients can
// filter servers based on mission type.
// $Server::MissionType = "Deathmatch";
// GameStartTime is the sim time the game started. Used to calculated
// game elapsed time.
$Game::StartTime = 0;
// Create the server physics world.
physicsInitWorld( "server" );
physicsStartSimulation("server");
%cnt = DatablockFilesList.count();
loadDatablockFiles( DatablockFilesList, true );
%cnt = DatablockFilesList.count();
// Keep track of when the game started
$Game::StartTime = $Sim::Time;
}
/// Shut down the server
function destroyServer()
{
$Server::ServerType = "";
$Server::Running = false;
allowConnections(false);
stopHeartbeat();
$missionRunning = false;
// End any running levels and shut down the physics sim
onServerDestroyed();
//physicsDestroy();
// Delete all the server objects
if (isObject(ServerGroup))
ServerGroup.delete();
// Delete all the connections:
while (ClientGroup.getCount())
{
%client = ClientGroup.getObject(0);
%client.delete();
}
$Server::GuidList = "";
// Delete all the data blocks...
deleteDataBlocks();
// Save any server settings
%prefPath = getPrefpath();
echo( "Exporting server prefs..." );
export( "$Pref::Server::*", %prefPath@"/serverPrefs.cs", false );
BanList::Export(%prefPath@"/banlist.cs");
// Increase the server session number. This is used to make sure we're
// working with the server session we think we are.
$Server::Session++;
}
function onServerDestroyed()
{
physicsStopSimulation("server");
if (!isObject( getScene(0) ))
return;
echo("*** ENDING MISSION");
// Inform the game code we're done.
if(TheLevelInfo.isMethod("onMissionEnded"))
TheLevelInfo.onMissionEnded();
// Inform the clients
for( %clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++ ) {
// clear ghosts and paths from all clients
%cl = ClientGroup.getObject( %clientIndex );
%cl.endMission();
%cl.resetGhosting();
%cl.clearPaths();
}
// Delete everything
getScene(0).delete();
MissionCleanup.delete();
clearServerPaths();
}
/// Guid list maintenance functions
function addToServerGuidList( %guid )
{
%count = getFieldCount( $Server::GuidList );
for ( %i = 0; %i < %count; %i++ )
{
if ( getField( $Server::GuidList, %i ) == %guid )
return;
}
$Server::GuidList = $Server::GuidList $= "" ? %guid : $Server::GuidList TAB %guid;
}
function removeFromServerGuidList( %guid )
{
%count = getFieldCount( $Server::GuidList );
for ( %i = 0; %i < %count; %i++ )
{
if ( getField( $Server::GuidList, %i ) == %guid )
{
$Server::GuidList = removeField( $Server::GuidList, %i );
return;
}
}
}
/// When the server is queried for information, the value of this function is
/// returned as the status field of the query packet. This information is
/// accessible as the ServerInfo::State variable.
function onServerInfoQuery()
{
return "Doing Ok";
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.