context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
* Copyright (c) .NET Foundation and Contributors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Piranha.Models;
namespace Piranha.Services
{
public interface IPageService
{
/// <summary>
/// Creates and initializes a new page of the specified type.
/// </summary>
/// <returns>The created page</returns>
Task<T> CreateAsync<T>(string typeId = null) where T : Models.PageBase;
/// <summary>
/// Creates and initializes a copy of the given page.
/// </summary>
/// <param name="originalPage">The orginal page</param>
/// <returns>The created copy</returns>
Task<T> CopyAsync<T>(T originalPage) where T : Models.PageBase;
/// <summary>
/// Detaches a copy and initializes it as a standalone page
/// </summary>
/// <returns>The standalone page</returns>
Task DetachAsync<T>(T model) where T : Models.PageBase;
/// <summary>
/// Gets all available models.
/// </summary>
/// <returns>The available models</returns>
Task<IEnumerable<DynamicPage>> GetAllAsync(Guid? siteId = null);
/// <summary>
/// Gets all available models.
/// </summary>
/// <returns>The available models</returns>
Task<IEnumerable<T>> GetAllAsync<T>(Guid? siteId = null) where T : PageBase;
/// <summary>
/// Gets the available blog pages for the current site.
/// </summary>
/// <param name="siteId">The optional site id</param>
/// <returns>The pages</returns>
Task<IEnumerable<DynamicPage>> GetAllBlogsAsync(Guid? siteId = null);
/// <summary>
/// Gets the available blog pages for the current site.
/// </summary>
/// <param name="siteId">The optional site id</param>
/// <returns>The pages</returns>
Task<IEnumerable<T>> GetAllBlogsAsync<T>(Guid? siteId = null) where T : Models.PageBase;
/// <summary>
/// Gets the id of all pages that have a draft for
/// the specified site.
/// </summary>
/// <param name="siteId">The unique site id</param>
/// <returns>The pages that have a draft</returns>
Task<IEnumerable<Guid>> GetAllDraftsAsync(Guid? siteId = null);
/// <summary>
/// Gets the comments available for the page with the specified id. If no page id
/// is provided all comments are fetched.
/// </summary>
/// <param name="pageId">The unique page id</param>
/// <param name="onlyApproved">If only approved comments should be fetched</param>
/// <param name="page">The optional page number</param>
/// <param name="pageSize">The optional page size</param>
/// <returns>The available comments</returns>
Task<IEnumerable<Comment>> GetAllCommentsAsync(Guid? pageId = null, bool onlyApproved = true,
int? page = null, int? pageSize = null);
/// <summary>
/// Gets the pending comments available for the page with the specified id. If no page id
/// is provided all comments are fetched.
/// </summary>
/// <param name="pageId">The unique page id</param>
/// <param name="page">The optional page number</param>
/// <param name="pageSize">The optional page size</param>
/// <returns>The available comments</returns>
Task<IEnumerable<Comment>> GetAllPendingCommentsAsync(Guid? pageId = null,
int? page = null, int? pageSize = null);
/// <summary>
/// Gets the site startpage.
/// </summary>
/// <param name="siteId">The optional site id</param>
/// <returns>The page model</returns>
Task<DynamicPage> GetStartpageAsync(Guid? siteId = null);
/// <summary>
/// Gets the site startpage.
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="siteId">The optional site id</param>
/// <returns>The page model</returns>
Task<T> GetStartpageAsync<T>(Guid? siteId = null) where T : Models.PageBase;
/// <summary>
/// Gets the page model with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
/// <returns>The page model</returns>
Task<DynamicPage> GetByIdAsync(Guid id);
/// <summary>
/// Gets the page models with the specified id's.
/// </summary>
/// <param name="ids">The unique id's</param>
/// <returns>The page models</returns>
Task<IEnumerable<T>> GetByIdsAsync<T>(params Guid[] ids) where T : PageBase;
/// <summary>
/// Gets the model with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
/// <returns>The model, or null if it doesn't exist</returns>
Task<T> GetByIdAsync<T>(Guid id) where T : PageBase;
/// <summary>
/// Gets the page model with the specified slug.
/// </summary>
/// <param name="slug">The unique slug</param>
/// <param name="siteId">The optional site id</param>
/// <returns>The page model</returns>
Task<DynamicPage> GetBySlugAsync(string slug, Guid? siteId = null);
/// <summary>
/// Gets the page model with the specified slug.
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="slug">The unique slug</param>
/// <param name="siteId">The optional site id</param>
/// <returns>The page model</returns>
Task<T> GetBySlugAsync<T>(string slug, Guid? siteId = null) where T : Models.PageBase;
/// <summary>
/// Gets the id for the page with the given slug.
/// </summary>
/// <param name="slug">The unique slug</param>
/// <param name="siteId">The optional page id</param>
/// <returns>The id</returns>
Task<Guid?> GetIdBySlugAsync(string slug, Guid? siteId = null);
/// <summary>
/// Gets the draft for the page model with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
/// <returns>The draft, or null if no draft exists</returns>
Task<DynamicPage> GetDraftByIdAsync(Guid id);
/// <summary>
/// Gets the draft for the page model with the specified id.
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="id">The unique id</param>
/// <returns>The draft, or null if no draft exists</returns>
Task<T> GetDraftByIdAsync<T>(Guid id) where T : PageBase;
/// <summary>
/// Moves the current page in the structure.
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The page to move</param>
/// <param name="parentId">The new parent id</param>
/// <param name="sortOrder">The new sort order</param>
Task MoveAsync<T>(T model, Guid? parentId, int sortOrder) where T : Models.PageBase;
/// <summary>
/// Gets the comment with the given id.
/// </summary>
/// <param name="id">The comment id</param>
/// <returns>The model</returns>
Task<Comment> GetCommentByIdAsync(Guid id);
/// <summary>
/// Saves the given page model
/// </summary>
/// <param name="model">The page model</param>
Task SaveAsync<T>(T model) where T : PageBase;
/// <summary>
/// Saves the given page model as a draft
/// </summary>
/// <param name="model">The page model</param>
Task SaveDraftAsync<T>(T model) where T : PageBase;
/// <summary>
/// Saves the comment.
/// </summary>
/// <param name="pageId">The unique page id</param>
/// <param name="model">The comment model</param>
Task SaveCommentAsync(Guid pageId, PageComment model);
/// <summary>
/// Saves the comment and verifies if should be approved or not.
/// </summary>
/// <param name="pageId">The unique page id</param>
/// <param name="model">The comment model</param>
Task SaveCommentAndVerifyAsync(Guid pageId, PageComment model);
/// <summary>
/// Deletes the model with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
Task DeleteAsync(Guid id);
/// <summary>
/// Deletes the given model.
/// </summary>
/// <param name="model">The model</param>
Task DeleteAsync<T>(T model) where T : Models.PageBase;
/// <summary>
/// Deletes the comment with the specified id.
/// </summary>
/// <param name="id">The unique id</param>
Task DeleteCommentAsync(Guid id);
/// <summary>
/// Deletes the given comment.
/// </summary>
/// <param name="model">The comment</param>
Task DeleteCommentAsync(Comment model);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
namespace System.Collections.Immutable
{
/// <summary>
/// An interface that describes the methods that the <see cref="ImmutableList{T}"/> and <see cref="ImmutableList{T}.Builder"/> types have in common.
/// </summary>
/// <typeparam name="T">The type of element in the collection.</typeparam>
internal interface IImmutableListQueries<T> : IReadOnlyList<T>
{
/// <summary>
/// Converts the elements in the current <see cref="ImmutableList{T}"/> to
/// another type, and returns a list containing the converted elements.
/// </summary>
/// <param name="converter">
/// A <see cref="Func{T, TResult}"/> delegate that converts each element from
/// one type to another type.
/// </param>
/// <typeparam name="TOutput">
/// The type of the elements of the target array.
/// </typeparam>
/// <returns>
/// A <see cref="ImmutableList{T}"/> of the target type containing the converted
/// elements from the current <see cref="ImmutableList{T}"/>.
/// </returns>
ImmutableList<TOutput> ConvertAll<TOutput>(Func<T, TOutput> converter);
/// <summary>
/// Performs the specified action on each element of the list.
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> delegate to perform on each element of the list.</param>
void ForEach(Action<T> action);
/// <summary>
/// Creates a shallow copy of a range of elements in the source <see cref="ImmutableList{T}"/>.
/// </summary>
/// <param name="index">
/// The zero-based <see cref="ImmutableList{T}"/> index at which the range
/// starts.
/// </param>
/// <param name="count">
/// The number of elements in the range.
/// </param>
/// <returns>
/// A shallow copy of a range of elements in the source <see cref="ImmutableList{T}"/>.
/// </returns>
ImmutableList<T> GetRange(int index, int count);
/// <summary>
/// Copies the entire <see cref="ImmutableList{T}"/> to a compatible one-dimensional
/// array, starting at the beginning of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements
/// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have
/// zero-based indexing.
/// </param>
void CopyTo(T[] array);
/// <summary>
/// Copies the entire <see cref="ImmutableList{T}"/> to a compatible one-dimensional
/// array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements
/// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have
/// zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array"/> at which copying begins.
/// </param>
void CopyTo(T[] array, int arrayIndex);
/// <summary>
/// Copies a range of elements from the <see cref="ImmutableList{T}"/> to
/// a compatible one-dimensional array, starting at the specified index of the
/// target array.
/// </summary>
/// <param name="index">
/// The zero-based index in the source <see cref="ImmutableList{T}"/> at
/// which copying begins.
/// </param>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements
/// copied from <see cref="ImmutableList{T}"/>. The <see cref="Array"/> must have
/// zero-based indexing.
/// </param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <param name="count">The number of elements to copy.</param>
void CopyTo(int index, T[] array, int arrayIndex, int count);
/// <summary>
/// Determines whether the <see cref="ImmutableList{T}"/> contains elements
/// that match the conditions defined by the specified predicate.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements
/// to search for.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableList{T}"/> contains one or more elements
/// that match the conditions defined by the specified predicate; otherwise,
/// false.
/// </returns>
bool Exists(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the first occurrence within the entire <see cref="ImmutableList{T}"/>.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The first element that matches the conditions defined by the specified predicate,
/// if found; otherwise, the default value for type <typeparamref name="T"/>.
/// </returns>
T Find(Predicate<T> match);
/// <summary>
/// Retrieves all the elements that match the conditions defined by the specified
/// predicate.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements
/// to search for.
/// </param>
/// <returns>
/// A <see cref="ImmutableList{T}"/> containing all the elements that match
/// the conditions defined by the specified predicate, if found; otherwise, an
/// empty <see cref="ImmutableList{T}"/>.
/// </returns>
ImmutableList<T> FindAll(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the first occurrence within
/// the entire <see cref="ImmutableList{T}"/>.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The zero-based index of the first occurrence of an element that matches the
/// conditions defined by <paramref name="match"/>, if found; otherwise, -1.
/// </returns>
int FindIndex(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the first occurrence within
/// the range of elements in the <see cref="ImmutableList{T}"/> that extends
/// from the specified index to the last element.
/// </summary>
/// <param name="startIndex">The zero-based starting index of the search.</param>
/// <param name="match">The <see cref="Predicate{T}"/> delegate that defines the conditions of the element to search for.</param>
/// <returns>
/// The zero-based index of the first occurrence of an element that matches the
/// conditions defined by <paramref name="match"/>, if found; otherwise, -1.
/// </returns>
int FindIndex(int startIndex, Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the first occurrence within
/// the range of elements in the <see cref="ImmutableList{T}"/> that starts
/// at the specified index and contains the specified number of elements.
/// </summary>
/// <param name="startIndex">The zero-based starting index of the search.</param>
/// <param name="count">The number of elements in the section to search.</param>
/// <param name="match">The <see cref="Predicate{T}"/> delegate that defines the conditions of the element to search for.</param>
/// <returns>
/// The zero-based index of the first occurrence of an element that matches the
/// conditions defined by <paramref name="match"/>, if found; otherwise, -1.
/// </returns>
int FindIndex(int startIndex, int count, Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the last occurrence within the entire <see cref="ImmutableList{T}"/>.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The last element that matches the conditions defined by the specified predicate,
/// if found; otherwise, the default value for type <typeparamref name="T"/>.
/// </returns>
T FindLast(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the last occurrence within
/// the entire <see cref="ImmutableList{T}"/>.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The zero-based index of the last occurrence of an element that matches the
/// conditions defined by <paramref name="match"/>, if found; otherwise, -1.
/// </returns>
int FindLastIndex(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the last occurrence within
/// the range of elements in the <see cref="ImmutableList{T}"/> that extends
/// from the first element to the specified index.
/// </summary>
/// <param name="startIndex">The zero-based starting index of the backward search.</param>
/// <param name="match">The <see cref="Predicate{T}"/> delegate that defines the conditions of the element
/// to search for.</param>
/// <returns>
/// The zero-based index of the last occurrence of an element that matches the
/// conditions defined by <paramref name="match"/>, if found; otherwise, -1.
/// </returns>
int FindLastIndex(int startIndex, Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the last occurrence within
/// the range of elements in the <see cref="ImmutableList{T}"/> that contains
/// the specified number of elements and ends at the specified index.
/// </summary>
/// <param name="startIndex">The zero-based starting index of the backward search.</param>
/// <param name="count">The number of elements in the section to search.</param>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The zero-based index of the last occurrence of an element that matches the
/// conditions defined by <paramref name="match"/>, if found; otherwise, -1.
/// </returns>
int FindLastIndex(int startIndex, int count, Predicate<T> match);
/// <summary>
/// Determines whether every element in the <see cref="ImmutableList{T}"/>
/// matches the conditions defined by the specified predicate.
/// </summary>
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions to check against
/// the elements.
/// </param>
/// <returns>
/// true if every element in the <see cref="ImmutableList{T}"/> matches the
/// conditions defined by the specified predicate; otherwise, false. If the list
/// has no elements, the return value is true.
/// </returns>
bool TrueForAll(Predicate<T> match);
/// <summary>
/// Searches the entire sorted <see cref="IReadOnlyList{T}"/> for an element
/// using the default comparer and returns the zero-based index of the element.
/// </summary>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <returns>
/// The zero-based index of <paramref name="item"/> in the sorted <see cref="IReadOnlyList{T}"/>,
/// if <paramref name="item"/> is found; otherwise, a negative number that is the bitwise complement
/// of the index of the next element that is larger than <paramref name="item"/> or, if there is
/// no larger element, the bitwise complement of <see cref="IReadOnlyCollection{T}.Count"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The default comparer <see cref="Comparer{T}.Default"/> cannot
/// find an implementation of the <see cref="IComparable{T}"/> generic interface or
/// the <see cref="IComparable"/> interface for type <typeparamref name="T"/>.
/// </exception>
int BinarySearch(T item);
/// <summary>
/// Searches the entire sorted <see cref="IReadOnlyList{T}"/> for an element
/// using the specified comparer and returns the zero-based index of the element.
/// </summary>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements.-or-null to use the default comparer <see cref="Comparer{T}.Default"/>.
/// </param>
/// <returns>
/// The zero-based index of <paramref name="item"/> in the sorted <see cref="IReadOnlyList{T}"/>,
/// if <paramref name="item"/> is found; otherwise, a negative number that is the bitwise complement
/// of the index of the next element that is larger than <paramref name="item"/> or, if there is
/// no larger element, the bitwise complement of <see cref="IReadOnlyCollection{T}.Count"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <paramref name="comparer"/> is null, and the default comparer <see cref="Comparer{T}.Default"/>
/// cannot find an implementation of the <see cref="IComparable{T}"/> generic interface
/// or the <see cref="IComparable"/> interface for type <typeparamref name="T"/>.
/// </exception>
int BinarySearch(T item, IComparer<T> comparer);
/// <summary>
/// Searches a range of elements in the sorted <see cref="IReadOnlyList{T}"/>
/// for an element using the specified comparer and returns the zero-based index
/// of the element.
/// </summary>
/// <param name="index">The zero-based starting index of the range to search.</param>
/// <param name="count"> The length of the range to search.</param>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements, or null to use the default comparer <see cref="Comparer{T}.Default"/>.
/// </param>
/// <returns>
/// The zero-based index of <paramref name="item"/> in the sorted <see cref="IReadOnlyList{T}"/>,
/// if <paramref name="item"/> is found; otherwise, a negative number that is the bitwise complement
/// of the index of the next element that is larger than <paramref name="item"/> or, if there is
/// no larger element, the bitwise complement of <see cref="IReadOnlyCollection{T}.Count"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than 0.-or-<paramref name="count"/> is less than 0.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="index"/> and <paramref name="count"/> do not denote a valid range in the <see cref="IReadOnlyList{T}"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// <paramref name="comparer"/> is null, and the default comparer <see cref="Comparer{T}.Default"/>
/// cannot find an implementation of the <see cref="IComparable{T}"/> generic interface
/// or the <see cref="IComparable"/> interface for type <typeparamref name="T"/>.
/// </exception>
int BinarySearch(int index, int count, T item, IComparer<T> comparer);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose:
**
**
===========================================================*/
using System.Globalization;
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System
{
// A place holder class for signed bytes.
[Serializable]
[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct SByte : IComparable, IFormattable, IConvertible
, IComparable<SByte>, IEquatable<SByte>
{
private sbyte m_value; // Do not rename (binary serialization)
// The maximum value that a Byte may represent: 127.
public const sbyte MaxValue = (sbyte)0x7F;
// The minimum value that a Byte may represent: -128.
public const sbyte MinValue = unchecked((sbyte)0x80);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type SByte, this method throws an ArgumentException.
//
public int CompareTo(Object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is SByte))
{
throw new ArgumentException(SR.Arg_MustBeSByte);
}
return m_value - ((SByte)obj).m_value;
}
public int CompareTo(SByte value)
{
return m_value - value;
}
// Determines whether two Byte objects are equal.
public override bool Equals(Object obj)
{
if (!(obj is SByte))
{
return false;
}
return m_value == ((SByte)obj).m_value;
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(SByte obj)
{
return m_value == obj;
}
// Gets a hash code for this instance.
public override int GetHashCode()
{
return ((int)m_value ^ (int)m_value << 8);
}
// Provides a string representation of a byte.
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
private String ToString(String format, NumberFormatInfo info)
{
Contract.Ensures(Contract.Result<String>() != null);
if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
{
uint temp = (uint)(m_value & 0x000000FF);
return Number.FormatUInt32(temp, format, info);
}
return Number.FormatInt32(m_value, format, info);
}
[CLSCompliant(false)]
public static sbyte Parse(String s)
{
return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static sbyte Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static sbyte Parse(String s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses a signed byte from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[CLSCompliant(false)]
public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
private static sbyte Parse(String s, NumberStyles style, NumberFormatInfo info)
{
int i = 0;
try
{
i = Number.ParseInt32(s, style, info);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_SByte, e);
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || i > Byte.MaxValue)
{
throw new OverflowException(SR.Overflow_SByte);
}
return (sbyte)i;
}
if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_SByte);
return (sbyte)i;
}
[CLSCompliant(false)]
public static bool TryParse(String s, out SByte result)
{
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out SByte result)
{
result = 0;
int i;
if (!Number.TryParseInt32(s, style, info, out i))
{
return false;
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || i > Byte.MaxValue)
{
return false;
}
result = (sbyte)i;
return true;
}
if (i < MinValue || i > MaxValue)
{
return false;
}
result = (sbyte)i;
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.SByte;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return m_value;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return m_value;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization
{
/// <remarks>
/// Rules for the Hijri calendar:
/// - The Hijri calendar is a strictly Lunar calendar.
/// - Days begin at sunset.
/// - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date
/// 227015 (Friday, July 16, 622 C.E. - Julian).
/// - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th
/// years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11).
/// - There are 12 months which contain alternately 30 and 29 days.
/// - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days
/// in a leap year.
/// - Common years have 354 days. Leap years have 355 days.
/// - There are 10,631 days in a 30-year cycle.
/// - The Islamic months are:
/// 1. Muharram (30 days) 7. Rajab (30 days)
/// 2. Safar (29 days) 8. Sha'ban (29 days)
/// 3. Rabi I (30 days) 9. Ramadan (30 days)
/// 4. Rabi II (29 days) 10. Shawwal (29 days)
/// 5. Jumada I (30 days) 11. Dhu al-Qada (30 days)
/// 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30}
///
/// NOTENOTE
/// The calculation of the HijriCalendar is based on the absolute date. And the
/// absolute date means the number of days from January 1st, 1 A.D.
/// Therefore, we do not support the days before the January 1st, 1 A.D.
///
/// Calendar support range:
/// Calendar Minimum Maximum
/// ========== ========== ==========
/// Gregorian 0622/07/18 9999/12/31
/// Hijri 0001/01/01 9666/04/03
/// </remarks>
public partial class HijriCalendar : Calendar
{
public static readonly int HijriEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
private const int MinAdvancedHijri = -2;
private const int MaxAdvancedHijri = 2;
private static readonly int[] s_hijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 };
private int _hijriAdvance = int.MinValue;
// DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3).
private const int MaxCalendarYear = 9666;
private const int MaxCalendarMonth = 4;
// Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18)
// This is the minimal Gregorian date that we support in the HijriCalendar.
private static readonly DateTime s_calendarMinValue = new DateTime(622, 7, 18);
private static readonly DateTime s_calendarMaxValue = DateTime.MaxValue;
public override DateTime MinSupportedDateTime => s_calendarMinValue;
public override DateTime MaxSupportedDateTime => s_calendarMaxValue;
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunarCalendar;
public HijriCalendar()
{
}
internal override CalendarId ID => CalendarId.HIJRI;
protected override int DaysInYearBeforeMinSupportedYear =>
// the year before the 1st year of the cycle would have been the 30th year
// of the previous cycle which is not a leap year. Common years have 354 days.
354;
private long GetAbsoluteDateHijri(int y, int m, int d)
{
return (long)(DaysUpToHijriYear(y) + s_hijriMonthDays[m - 1] + d - 1 - HijriAdjustment);
}
private long DaysUpToHijriYear(int HijriYear)
{
// Compute the number of years up to the current 30 year cycle.
int numYear30 = ((HijriYear - 1) / 30) * 30;
// Compute the number of years left. This is the number of years
// into the 30 year cycle for the given year.
int numYearsLeft = HijriYear - numYear30 - 1;
// Compute the number of absolute days up to the given year.
long numDays = ((numYear30 * 10631L) / 30L) + 227013L;
while (numYearsLeft > 0)
{
// Common year is 354 days, and leap year is 355 days.
numDays += 354 + (IsLeapYear(numYearsLeft, CurrentEra) ? 1 : 0);
numYearsLeft--;
}
return numDays;
}
public int HijriAdjustment
{
get
{
if (_hijriAdvance == int.MinValue)
{
// Never been set before. Use the system value from registry.
_hijriAdvance = GetHijriDateAdjustment();
}
return _hijriAdvance;
}
set
{
if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, MinAdvancedHijri, MaxAdvancedHijri));
}
VerifyWritable();
_hijriAdvance = value;
}
}
internal static void CheckTicksRange(long ticks)
{
if (ticks < s_calendarMinValue.Ticks || ticks > s_calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
ticks,
SR.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
s_calendarMinValue,
s_calendarMaxValue));
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != HijriEra)
{
throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal static void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear));
}
}
internal static void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
nameof(month),
month,
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), month, SR.ArgumentOutOfRange_Month);
}
}
/// <summary>
/// First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
/// Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year.
/// In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1).
/// From here, we can get the correct Hijri year.
/// </summary>
internal virtual int GetDatePart(long ticks, int part)
{
CheckTicksRange(ticks);
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
long numDays = ticks / GregorianCalendar.TicksPerDay + 1;
// See how much we need to backup or advance
numDays += HijriAdjustment;
// Calculate the appromixate Hijri Year from this magic formula.
int hijriYear = (int)(((numDays - 227013) * 30) / 10631) + 1;
long daysToHijriYear = DaysUpToHijriYear(hijriYear); // The absolute date for HijriYear
long daysOfHijriYear = GetDaysInYear(hijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
if (numDays < daysToHijriYear)
{
daysToHijriYear -= daysOfHijriYear;
hijriYear--;
}
else if (numDays == daysToHijriYear)
{
hijriYear--;
daysToHijriYear -= GetDaysInYear(hijriYear, CurrentEra);
}
else
{
if (numDays > daysToHijriYear + daysOfHijriYear)
{
daysToHijriYear += daysOfHijriYear;
hijriYear++;
}
}
if (part == DatePartYear)
{
return hijriYear;
}
// Calculate the Hijri Month.
int hijriMonth = 1;
numDays -= daysToHijriYear;
if (part == DatePartDayOfYear)
{
return (int)numDays;
}
while ((hijriMonth <= 12) && (numDays > s_hijriMonthDays[hijriMonth - 1]))
{
hijriMonth++;
}
hijriMonth--;
if (part == DatePartMonth)
{
return hijriMonth;
}
// Calculate the Hijri Day.
int hijriDay = (int)(numDays - s_hijriMonthDays[hijriMonth - 1]);
if (part == DatePartDay)
{
return hijriDay;
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
months,
SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000));
}
// Get the date in Hijri calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y += i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y += (i - 11) / 12;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return new DateTime(ticks);
}
public override DateTime AddYears(DateTime time, int years)
{
return AddMonths(time, years * 12);
}
public override int GetDayOfMonth(DateTime time)
{
return GetDatePart(time.Ticks, DatePartDay);
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return (DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7);
}
public override int GetDayOfYear(DateTime time)
{
return GetDatePart(time.Ticks, DatePartDayOfYear);
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if (month == 12)
{
// For the 12th month, leap year has 30 days, and common year has 29 days.
return IsLeapYear(year, CurrentEra) ? 30 : 29;
}
// Other months contain 30 and 29 days alternatively. The 1st month has 30 days.
return ((month % 2) == 1) ? 30 : 29;
}
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
// Common years have 354 days. Leap years have 355 days.
return IsLeapYear(year, CurrentEra) ? 355 : 354;
}
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return HijriEra;
}
public override int[] Eras => new int[] { HijriEra };
public override int GetMonth(DateTime time)
{
return GetDatePart(time.Ticks, DatePartMonth);
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(year, era);
return 12;
}
public override int GetYear(DateTime time)
{
return GetDatePart(time.Ticks, DatePartYear);
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
day,
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
return IsLeapYear(year, era) && month == 12 && day == 30;
}
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return 0;
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return false;
}
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
return (((year * 11) + 14) % 30) < 11;
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
day,
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
long lDate = GetAbsoluteDateHijri(year, month, day);
if (lDate < 0)
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
return new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond));
}
private const int DefaultTwoDigitYearMax = 1451;
public override int TwoDigitYearMax
{
get
{
if (_twoDigitYearMax == -1)
{
_twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax);
}
return _twoDigitYearMax;
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear));
}
_twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year < 100)
{
return base.ToFourDigitYear(year);
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear));
}
return year;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.DirectoryServices;
using System.Net;
using System.Threading;
namespace System.DirectoryServices.AccountManagement
{
/// <summary>
/// This is a class designed to cache DirectoryEntires instead of creating them every time.
/// </summary>
internal class SDSCache
{
public static SDSCache Domain
{
get
{
return SDSCache.s_domainCache;
}
}
public static SDSCache LocalMachine
{
get
{
return SDSCache.s_localMachineCache;
}
}
private static SDSCache s_domainCache = new SDSCache(false);
private static SDSCache s_localMachineCache = new SDSCache(true);
public PrincipalContext GetContext(string name, NetCred credentials, ContextOptions contextOptions)
{
string contextName = name;
string userName = null;
bool explicitCreds = false;
if (credentials != null && credentials.UserName != null)
{
if (credentials.Domain != null)
userName = credentials.Domain + "\\" + credentials.UserName;
else
userName = credentials.UserName;
explicitCreds = true;
}
else
{
userName = Utils.GetNT4UserName();
}
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: looking for context for server {0}, user {1}, explicitCreds={2}, options={3}",
name,
userName,
explicitCreds.ToString(),
contextOptions.ToString());
if (!_isSAM)
{
// Determine the domain DNS name
// DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY
int flags = unchecked((int)(0x40000000 | 0x00000010 | 0x00000100));
UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, contextName, null, flags);
contextName = info.DomainName;
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: final contextName is " + contextName);
ManualResetEvent contextReadyEvent = null;
while (true)
{
Hashtable credTable = null;
PrincipalContext ctx = null;
// Wait for the PrincipalContext to be ready
if (contextReadyEvent != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: waiting");
contextReadyEvent.WaitOne();
}
contextReadyEvent = null;
lock (_tableLock)
{
CredHolder credHolder = (CredHolder)_table[contextName];
if (credHolder != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: found a credHolder for " + contextName);
credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds);
Debug.Assert(credTable != null);
object o = credTable[userName];
if (o is Placeholder)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: credHolder for " + contextName + " has a Placeholder");
// A PrincipalContext is currently being constructed by another thread.
// Wait for it.
contextReadyEvent = ((Placeholder)o).contextReadyEvent;
continue;
}
WeakReference refToContext = o as WeakReference;
if (refToContext != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is non-null");
ctx = (PrincipalContext)refToContext.Target; // null if GC'ed
// If the PrincipalContext hasn't been GCed or disposed, use it.
// Otherwise, we'll need to create a new one
if (ctx != null && ctx.Disposed == false)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: using found refToContext");
return ctx;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is GCed/disposed, removing");
credTable.Remove(userName);
}
}
}
// Either credHolder/credTable are null (no contexts exist for the contextName), or credHolder/credTable
// are non-null (contexts exist, but none for the userName). Either way, we need to create a PrincipalContext.
if (credHolder == null)
{
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: null credHolder for " + contextName + ", explicitCreds=" + explicitCreds.ToString());
// No contexts exist for the contextName. Create a CredHolder for the contextName so we have a place
// to store the PrincipalContext we'll be creating.
credHolder = new CredHolder();
_table[contextName] = credHolder;
credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds);
}
// Put a placeholder on the contextName/userName slot, so that other threads that come along after
// we release the tableLock know we're in the process of creating the needed PrincipalContext and will wait for us
credTable[userName] = new Placeholder();
}
// Now we just need to create a PrincipalContext for the contextName and credentials
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: creating context, contextName=" + contextName + ", options=" + contextOptions.ToString());
ctx = new PrincipalContext(
(_isSAM ? ContextType.Machine : ContextType.Domain),
contextName,
null,
contextOptions,
(credentials != null ? credentials.UserName : null),
(credentials != null ? credentials.Password : null)
);
lock (_tableLock)
{
Placeholder placeHolder = (Placeholder)credTable[userName];
// Replace the placeholder with the newly-created PrincipalContext
credTable[userName] = new WeakReference(ctx);
// Signal waiting threads to continue. We do this after inserting the PrincipalContext
// into the table, so that the PrincipalContext is ready as soon as the other threads wake up.
// (Actually, the order probably doesn't matter, since even if we did it in the
// opposite order and the other thread woke up before we inserted the PrincipalContext, it would
// just block as soon as it tries to acquire the tableLock that we're currently holding.)
bool f = placeHolder.contextReadyEvent.Set();
Debug.Assert(f == true);
}
return ctx;
}
}
//
private SDSCache(bool isSAM)
{
_isSAM = isSAM;
}
private Hashtable _table = new Hashtable();
private object _tableLock = new object();
private bool _isSAM;
private class CredHolder
{
public Hashtable explicitCreds = new Hashtable();
public Hashtable defaultCreds = new Hashtable();
}
private class Placeholder
{
// initially non-signaled
public ManualResetEvent contextReadyEvent = new ManualResetEvent(false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler
{
public partial class CompilerTypeSystemContext : MetadataTypeSystemContext, IMetadataStringDecoderProvider
{
private readonly MetadataRuntimeInterfacesAlgorithm _metadataRuntimeInterfacesAlgorithm = new MetadataRuntimeInterfacesAlgorithm();
private readonly MetadataVirtualMethodAlgorithm _virtualMethodAlgorithm = new MetadataVirtualMethodAlgorithm();
protected SimdHelper _simdHelper;
private MetadataStringDecoder _metadataStringDecoder;
private class ModuleData
{
public string SimpleName;
public string FilePath;
public EcmaModule Module;
public MemoryMappedViewAccessor MappedViewAccessor;
}
private class ModuleHashtable : LockFreeReaderHashtable<EcmaModule, ModuleData>
{
protected override int GetKeyHashCode(EcmaModule key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(ModuleData value)
{
return value.Module.GetHashCode();
}
protected override bool CompareKeyToValue(EcmaModule key, ModuleData value)
{
return Object.ReferenceEquals(key, value.Module);
}
protected override bool CompareValueToValue(ModuleData value1, ModuleData value2)
{
return Object.ReferenceEquals(value1.Module, value2.Module);
}
protected override ModuleData CreateValueFromKey(EcmaModule key)
{
Debug.Fail("CreateValueFromKey not supported");
return null;
}
}
private readonly ModuleHashtable _moduleHashtable = new ModuleHashtable();
private class SimpleNameHashtable : LockFreeReaderHashtable<string, ModuleData>
{
StringComparer _comparer = StringComparer.OrdinalIgnoreCase;
protected override int GetKeyHashCode(string key)
{
return _comparer.GetHashCode(key);
}
protected override int GetValueHashCode(ModuleData value)
{
return _comparer.GetHashCode(value.SimpleName);
}
protected override bool CompareKeyToValue(string key, ModuleData value)
{
return _comparer.Equals(key, value.SimpleName);
}
protected override bool CompareValueToValue(ModuleData value1, ModuleData value2)
{
return _comparer.Equals(value1.SimpleName, value2.SimpleName);
}
protected override ModuleData CreateValueFromKey(string key)
{
Debug.Fail("CreateValueFromKey not supported");
return null;
}
}
private readonly SimpleNameHashtable _simpleNameHashtable = new SimpleNameHashtable();
private readonly SharedGenericsMode _genericsMode;
public IReadOnlyDictionary<string, string> InputFilePaths
{
get;
set;
}
public IReadOnlyDictionary<string, string> ReferenceFilePaths
{
get;
set;
}
public override ModuleDesc ResolveAssembly(System.Reflection.AssemblyName name, bool throwIfNotFound)
{
// TODO: catch typesystem BadImageFormatException and throw a new one that also captures the
// assembly name that caused the failure. (Along with the reason, which makes this rather annoying).
return GetModuleForSimpleName(name.Name, throwIfNotFound);
}
public ModuleDesc GetModuleForSimpleName(string simpleName, bool throwIfNotFound = true)
{
ModuleData existing;
if (_simpleNameHashtable.TryGetValue(simpleName, out existing))
return existing.Module;
string filePath;
if (!InputFilePaths.TryGetValue(simpleName, out filePath))
{
if (!ReferenceFilePaths.TryGetValue(simpleName, out filePath))
{
// We allow the CanonTypesModule to not be an EcmaModule.
if (((IAssemblyDesc)CanonTypesModule).GetName().Name == simpleName)
return CanonTypesModule;
// TODO: the exception is wrong for two reasons: for one, this should be assembly full name, not simple name.
// The other reason is that on CoreCLR, the exception also captures the reason. We should be passing two
// string IDs. This makes this rather annoying.
if (throwIfNotFound)
ThrowHelper.ThrowFileNotFoundException(ExceptionStringID.FileLoadErrorGeneric, simpleName);
return null;
}
}
return AddModule(filePath, simpleName, true);
}
public EcmaModule GetModuleFromPath(string filePath)
{
return GetOrAddModuleFromPath(filePath, true);
}
public EcmaModule GetMetadataOnlyModuleFromPath(string filePath)
{
return GetOrAddModuleFromPath(filePath, false);
}
private EcmaModule GetOrAddModuleFromPath(string filePath, bool useForBinding)
{
// This method is not expected to be called frequently. Linear search is acceptable.
foreach (var entry in ModuleHashtable.Enumerator.Get(_moduleHashtable))
{
if (entry.FilePath == filePath)
return entry.Module;
}
return AddModule(filePath, null, useForBinding);
}
public static unsafe PEReader OpenPEFile(string filePath, out MemoryMappedViewAccessor mappedViewAccessor)
{
// System.Reflection.Metadata has heuristic that tries to save virtual address space. This heuristic does not work
// well for us since it can make IL access very slow (call to OS for each method IL query). We will map the file
// ourselves to get the desired performance characteristics reliably.
FileStream fileStream = null;
MemoryMappedFile mappedFile = null;
MemoryMappedViewAccessor accessor = null;
try
{
// Create stream because CreateFromFile(string, ...) uses FileShare.None which is too strict
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false);
mappedFile = MemoryMappedFile.CreateFromFile(
fileStream, null, fileStream.Length, MemoryMappedFileAccess.Read, HandleInheritability.None, true);
accessor = mappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
var safeBuffer = accessor.SafeMemoryMappedViewHandle;
var peReader = new PEReader((byte*)safeBuffer.DangerousGetHandle(), (int)safeBuffer.ByteLength);
// MemoryMappedFile does not need to be kept around. MemoryMappedViewAccessor is enough.
mappedViewAccessor = accessor;
accessor = null;
return peReader;
}
finally
{
if (accessor != null)
accessor.Dispose();
if (mappedFile != null)
mappedFile.Dispose();
if (fileStream != null)
fileStream.Dispose();
}
}
private EcmaModule AddModule(string filePath, string expectedSimpleName, bool useForBinding)
{
MemoryMappedViewAccessor mappedViewAccessor = null;
PdbSymbolReader pdbReader = null;
try
{
PEReader peReader = OpenPEFile(filePath, out mappedViewAccessor);
pdbReader = OpenAssociatedSymbolFile(filePath, peReader);
EcmaModule module = EcmaModule.Create(this, peReader, containingAssembly: null, pdbReader);
MetadataReader metadataReader = module.MetadataReader;
string simpleName = metadataReader.GetString(metadataReader.GetAssemblyDefinition().Name);
if (expectedSimpleName != null && !simpleName.Equals(expectedSimpleName, StringComparison.OrdinalIgnoreCase))
throw new FileNotFoundException("Assembly name does not match filename " + filePath);
ModuleData moduleData = new ModuleData()
{
SimpleName = simpleName,
FilePath = filePath,
Module = module,
MappedViewAccessor = mappedViewAccessor
};
lock (this)
{
if (useForBinding)
{
ModuleData actualModuleData = _simpleNameHashtable.AddOrGetExisting(moduleData);
if (actualModuleData != moduleData)
{
if (actualModuleData.FilePath != filePath)
throw new FileNotFoundException("Module with same simple name already exists " + filePath);
return actualModuleData.Module;
}
}
mappedViewAccessor = null; // Ownership has been transfered
pdbReader = null; // Ownership has been transferred
_moduleHashtable.AddOrGetExisting(moduleData);
}
return module;
}
finally
{
if (mappedViewAccessor != null)
mappedViewAccessor.Dispose();
if (pdbReader != null)
pdbReader.Dispose();
}
}
protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForDefType(DefType type)
{
return _metadataRuntimeInterfacesAlgorithm;
}
public override VirtualMethodAlgorithm GetVirtualMethodAlgorithmForType(TypeDesc type)
{
Debug.Assert(!type.IsArray, "Wanted to call GetClosestMetadataType?");
return _virtualMethodAlgorithm;
}
protected override Instantiation ConvertInstantiationToCanonForm(Instantiation instantiation, CanonicalFormKind kind, out bool changed)
{
if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes)
return RuntimeDeterminedCanonicalizationAlgorithm.ConvertInstantiationToCanonForm(instantiation, kind, out changed);
Debug.Assert(_genericsMode == SharedGenericsMode.Disabled);
changed = false;
return instantiation;
}
protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, CanonicalFormKind kind)
{
if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes)
return RuntimeDeterminedCanonicalizationAlgorithm.ConvertToCanon(typeToConvert, kind);
Debug.Assert(_genericsMode == SharedGenericsMode.Disabled);
return typeToConvert;
}
protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, ref CanonicalFormKind kind)
{
if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes)
return RuntimeDeterminedCanonicalizationAlgorithm.ConvertToCanon(typeToConvert, ref kind);
Debug.Assert(_genericsMode == SharedGenericsMode.Disabled);
return typeToConvert;
}
public override bool SupportsUniversalCanon => false;
public override bool SupportsCanon => _genericsMode != SharedGenericsMode.Disabled;
public MetadataStringDecoder GetMetadataStringDecoder()
{
if (_metadataStringDecoder == null)
_metadataStringDecoder = new CachingMetadataStringDecoder(0x10000); // TODO: Tune the size
return _metadataStringDecoder;
}
//
// Symbols
//
private PdbSymbolReader OpenAssociatedSymbolFile(string peFilePath, PEReader peReader)
{
// Assume that the .pdb file is next to the binary
var pdbFilename = Path.ChangeExtension(peFilePath, ".pdb");
string searchPath = "";
if (!File.Exists(pdbFilename))
{
pdbFilename = null;
// If the file doesn't exist, try the path specified in the CodeView section of the image
foreach (DebugDirectoryEntry debugEntry in peReader.ReadDebugDirectory())
{
if (debugEntry.Type != DebugDirectoryEntryType.CodeView)
continue;
string candidateFileName = peReader.ReadCodeViewDebugDirectoryData(debugEntry).Path;
if (Path.IsPathRooted(candidateFileName) && File.Exists(candidateFileName))
{
pdbFilename = candidateFileName;
searchPath = Path.GetDirectoryName(pdbFilename);
break;
}
}
if (pdbFilename == null)
return null;
}
// Try to open the symbol file as portable pdb first
PdbSymbolReader reader = PortablePdbSymbolReader.TryOpen(pdbFilename, GetMetadataStringDecoder());
if (reader == null)
{
// Fallback to the diasymreader for non-portable pdbs
reader = UnmanagedPdbSymbolReader.TryOpenSymbolReaderForMetadataFile(peFilePath, searchPath);
}
return reader;
}
}
/// <summary>
/// Specifies the mode in which canonicalization should occur.
/// </summary>
public enum SharedGenericsMode
{
Disabled,
CanonicalReferenceTypes,
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Insights
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// EventsOperations operations.
/// </summary>
internal partial class EventsOperations : Microsoft.Rest.IServiceOperations<InsightsClient>, IEventsOperations
{
/// <summary>
/// Initializes a new instance of the EventsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal EventsOperations(InsightsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the InsightsClient
/// </summary>
public InsightsClient Client { get; private set; }
/// <summary>
/// Provides the list of events. The **$filter** is very restricted and allows
/// only the following patterns. - List events for a resource group:
/// $filter=eventTimestamp ge '<Start Time>' and eventTimestamp le
/// '<End Time>' and eventChannels eq 'Admin, Operation' and
/// resourceGroupName eq '<ResourceGroupName>'. - List events for
/// resource: $filter=eventTimestamp ge '<Start Time>' and eventTimestamp
/// le '<End Time>' and eventChannels eq 'Admin, Operation' and
/// resourceUri eq '<ResourceURI>'. - List events for a subscription:
/// $filter=eventTimestamp ge '<Start Time>' and eventTimestamp le
/// '<End Time>' and eventChannels eq 'Admin, Operation'. -List events
/// for a resource provider: $filter=eventTimestamp ge '<Start Time>' and
/// eventTimestamp le '<End Time>' and eventChannels eq 'Admin,
/// Operation' and resourceProvider eq '<ResourceProviderName>'. - List
/// events for a correlation Id:
/// api-version=2014-04-01&$filter=eventTimestamp ge
/// '2014-07-16T04:36:37.6407898Z' and eventTimestamp le
/// '2014-07-20T04:36:37.6407898Z' and eventChannels eq 'Admin, Operation' and
/// correlationId eq '<CorrelationID>'. No other syntax is allowed.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// Used to fetch events with only the given properties. The filter is a comma
/// separated list of property names to be returned. Possible values are:
/// authorization, channels, claims, correlationId, description, eventDataId,
/// eventName, eventTimestamp, httpRequest, level, operationId, operationName,
/// properties, resourceGroupName, resourceProviderName, resourceId, status,
/// submissionTimestamp, subStatus, subscriptionId
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<EventData>>> ListWithHttpMessagesAsync(Microsoft.Rest.Azure.OData.ODataQuery<EventData> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<EventData>), string select = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-04-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("select", select);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/eventtypes/management/values").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<EventData>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<EventData>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Provides the list of events. The **$filter** is very restricted and allows
/// only the following patterns. - List events for a resource group:
/// $filter=eventTimestamp ge '<Start Time>' and eventTimestamp le
/// '<End Time>' and eventChannels eq 'Admin, Operation' and
/// resourceGroupName eq '<ResourceGroupName>'. - List events for
/// resource: $filter=eventTimestamp ge '<Start Time>' and eventTimestamp
/// le '<End Time>' and eventChannels eq 'Admin, Operation' and
/// resourceUri eq '<ResourceURI>'. - List events for a subscription:
/// $filter=eventTimestamp ge '<Start Time>' and eventTimestamp le
/// '<End Time>' and eventChannels eq 'Admin, Operation'. -List events
/// for a resource provider: $filter=eventTimestamp ge '<Start Time>' and
/// eventTimestamp le '<End Time>' and eventChannels eq 'Admin,
/// Operation' and resourceProvider eq '<ResourceProviderName>'. - List
/// events for a correlation Id:
/// api-version=2014-04-01&$filter=eventTimestamp ge
/// '2014-07-16T04:36:37.6407898Z' and eventTimestamp le
/// '2014-07-20T04:36:37.6407898Z' and eventChannels eq 'Admin, Operation' and
/// correlationId eq '<CorrelationID>'. No other syntax is allowed.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<EventData>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<EventData>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<EventData>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// MultipartSigned.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using Org.BouncyCastle.Bcpg.OpenPgp;
using MimeKit.IO;
using MimeKit.IO.Filters;
namespace MimeKit.Cryptography {
/// <summary>
/// A signed multipart, as used by both S/MIME and PGP/MIME protocols.
/// </summary>
/// <remarks>
/// The first child of a multipart/signed is the content while the second child
/// is the detached signature data. Any other children are not defined and could
/// be anything.
/// </remarks>
public class MultipartSigned : Multipart
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.MultipartSigned"/> class.
/// </summary>
/// <remarks>This constructor is used by <see cref="MimeKit.MimeParser"/>.</remarks>
/// <param name="entity">Information used by the constructor.</param>
public MultipartSigned (MimeEntityConstructorInfo entity) : base (entity)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.MultipartSigned"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="MultipartSigned"/>.
/// </remarks>
public MultipartSigned () : base ("signed")
{
}
static void PrepareEntityForSigning (MimeEntity entity)
{
if (entity is Multipart) {
// Note: we do not want to modify multipart/signed parts
if (entity is MultipartSigned)
return;
var multipart = (Multipart) entity;
foreach (var subpart in multipart)
PrepareEntityForSigning (subpart);
} else if (entity is MessagePart) {
var mpart = (MessagePart) entity;
if (mpart.Message != null && mpart.Message.Body != null)
PrepareEntityForSigning (mpart.Message.Body);
} else {
var part = (MimePart) entity;
switch (part.ContentTransferEncoding) {
case ContentEncoding.SevenBit:
// need to make sure that "From "-lines are properly armored and wrapped at 78 bytes
part.ContentTransferEncoding = part.GetBestEncoding (EncodingConstraint.SevenBit, 78);
break;
case ContentEncoding.EightBit:
part.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
break;
case ContentEncoding.Binary:
part.ContentTransferEncoding = ContentEncoding.Base64;
break;
}
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer and digest algorithm in
/// order to generate a detached signature and then adds the entity along with the
/// detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="ctx">The cryptography context to use for signing.</param>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The <paramref name="digestAlgo"/> is not supported.
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A signing certificate could not be found for <paramref name="signer"/>.
/// </exception>
/// <exception cref="PrivateKeyNotFoundException">
/// The private key could not be found for <paramref name="signer"/>.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static MultipartSigned Create (CryptographyContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
PrepareEntityForSigning (entity);
using (var memory = new MemoryBlockStream ()) {
using (var filtered = new FilteredStream (memory)) {
// Note: see rfc3156, section 3 - second note
filtered.Add (new ArmoredFromFilter ());
// Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156)
filtered.Add (new TrailingWhitespaceFilter ());
// Note: see rfc2015 or rfc3156, section 5.1
filtered.Add (new Unix2DosFilter ());
entity.WriteTo (filtered);
filtered.Flush ();
}
memory.Position = 0;
// Note: we need to parse the modified entity structure to preserve any modifications
var parser = new MimeParser (memory, MimeFormat.Entity);
var parsed = parser.ParseEntity ();
memory.Position = 0;
// sign the cleartext content
var signature = ctx.Sign (signer, digestAlgo, memory);
var micalg = ctx.GetDigestAlgorithmName (digestAlgo);
var signed = new MultipartSigned ();
// set the protocol and micalg Content-Type parameters
signed.ContentType.Parameters["protocol"] = ctx.SignatureProtocol;
signed.ContentType.Parameters["micalg"] = micalg;
// add the modified/parsed entity as our first part
signed.Add (parsed);
// add the detached signature as the second part
signed.Add (signature);
return signed;
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer and digest algorithm in
/// order to generate a detached signature and then adds the entity along with the
/// detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="ctx">The OpenPGP context to use for signing.</param>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="signer"/> cannot be used for signing.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The <paramref name="digestAlgo"/> is not supported.
/// </exception>
/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
/// An error occurred in the OpenPGP subsystem.
/// </exception>
public static MultipartSigned Create (OpenPgpContext ctx, PgpSecretKey signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
PrepareEntityForSigning (entity);
using (var memory = new MemoryBlockStream ()) {
using (var filtered = new FilteredStream (memory)) {
// Note: see rfc3156, section 3 - second note
filtered.Add (new ArmoredFromFilter ());
// Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156)
filtered.Add (new TrailingWhitespaceFilter ());
// Note: see rfc2015 or rfc3156, section 5.1
filtered.Add (new Unix2DosFilter ());
entity.WriteTo (filtered);
filtered.Flush ();
}
memory.Position = 0;
// Note: we need to parse the modified entity structure to preserve any modifications
var parser = new MimeParser (memory, MimeFormat.Entity);
var parsed = parser.ParseEntity ();
memory.Position = 0;
// sign the cleartext content
var micalg = ctx.GetDigestAlgorithmName (digestAlgo);
var signature = ctx.Sign (signer, digestAlgo, memory);
var signed = new MultipartSigned ();
// set the protocol and micalg Content-Type parameters
signed.ContentType.Parameters["protocol"] = ctx.SignatureProtocol;
signed.ContentType.Parameters["micalg"] = micalg;
// add the modified/parsed entity as our first part
signed.Add (parsed);
// add the detached signature as the second part
signed.Add (signature);
return signed;
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer and digest algorithm in
/// order to generate a detached signature and then adds the entity along with the
/// detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="signer"/> cannot be used for signing.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// <para>A cryptography context suitable for signing could not be found.</para>
/// <para>-or-</para>
/// <para>The <paramref name="digestAlgo"/> is not supported.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
/// An error occurred in the OpenPGP subsystem.
/// </exception>
public static MultipartSigned Create (PgpSecretKey signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-signature")) {
return Create (ctx, signer, digestAlgo, entity);
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer in order
/// to generate a detached signature and then adds the entity along with
/// the detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="ctx">The S/MIME context to use for signing.</param>
/// <param name="signer">The signer.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static MultipartSigned Create (SecureMimeContext ctx, CmsSigner signer, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
PrepareEntityForSigning (entity);
using (var memory = new MemoryBlockStream ()) {
using (var filtered = new FilteredStream (memory)) {
// Note: see rfc3156, section 3 - second note
filtered.Add (new ArmoredFromFilter ());
// Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156)
filtered.Add (new TrailingWhitespaceFilter ());
// Note: see rfc2015 or rfc3156, section 5.1
filtered.Add (new Unix2DosFilter ());
entity.WriteTo (filtered);
filtered.Flush ();
}
memory.Position = 0;
// Note: we need to parse the modified entity structure to preserve any modifications
var parser = new MimeParser (memory, MimeFormat.Entity);
var parsed = parser.ParseEntity ();
memory.Position = 0;
// sign the cleartext content
var micalg = ctx.GetDigestAlgorithmName (signer.DigestAlgorithm);
var signature = ctx.Sign (signer, memory);
var signed = new MultipartSigned ();
// set the protocol and micalg Content-Type parameters
signed.ContentType.Parameters["protocol"] = ctx.SignatureProtocol;
signed.ContentType.Parameters["micalg"] = micalg;
// add the modified/parsed entity as our first part
signed.Add (parsed);
// add the detached signature as the second part
signed.Add (signature);
return signed;
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer in order
/// to generate a detached signature and then adds the entity along with
/// the detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="signer">The signer.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.NotSupportedException">
/// A cryptography context suitable for signing could not be found.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static MultipartSigned Create (CmsSigner signer, MimeEntity entity)
{
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-signature")) {
return Create (ctx, signer, entity);
}
}
/// <summary>
/// Verifies the multipart/signed part.
/// </summary>
/// <remarks>
/// Verifies the multipart/signed part using the supplied cryptography context.
/// </remarks>
/// <returns>A signer info collection.</returns>
/// <param name="ctx">The cryptography context to use for verifying the signature.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="ctx"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.FormatException">
/// The multipart is malformed in some way.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// <paramref name="ctx"/> does not support verifying the signature part.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public DigitalSignatureCollection Verify (CryptographyContext ctx)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
var protocol = ContentType.Parameters["protocol"];
if (string.IsNullOrEmpty (protocol))
throw new FormatException ("The multipart/signed part did not specify a protocol.");
if (!ctx.Supports (protocol.Trim ()))
throw new NotSupportedException ("The specified cryptography context does not support the signature protocol.");
if (Count < 2)
throw new FormatException ("The multipart/signed part did not contain the expected children.");
var signature = this[1] as MimePart;
if (signature == null || signature.ContentObject == null)
throw new FormatException ("The signature part could not be found.");
var ctype = signature.ContentType;
var value = string.Format ("{0}/{1}", ctype.MediaType, ctype.MediaSubtype);
if (!ctx.Supports (value))
throw new NotSupportedException (string.Format ("The specified cryptography context does not support '{0}'.", value));
using (var signatureData = new MemoryBlockStream ()) {
signature.ContentObject.DecodeTo (signatureData);
signatureData.Position = 0;
using (var cleartext = new MemoryBlockStream ()) {
// Note: see rfc2015 or rfc3156, section 5.1
var options = FormatOptions.GetDefault ();
options.NewLineFormat = NewLineFormat.Dos;
this[0].WriteTo (options, cleartext);
cleartext.Position = 0;
return ctx.Verify (cleartext, signatureData);
}
}
}
/// <summary>
/// Verifies the multipart/signed part.
/// </summary>
/// <remarks>
/// Verifies the multipart/signed part using the default cryptography context.
/// </remarks>
/// <returns>A signer info collection.</returns>
/// <exception cref="System.FormatException">
/// <para>The <c>protocol</c> parameter was not specified.</para>
/// <para>-or-</para>
/// <para>The multipart is malformed in some way.</para>
/// </exception>
/// <exception cref="System.NotSupportedException">
/// A cryptography context suitable for verifying the signature could not be found.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public DigitalSignatureCollection Verify ()
{
var protocol = ContentType.Parameters["protocol"];
if (string.IsNullOrEmpty (protocol))
throw new FormatException ("The multipart/signed part did not specify a protocol.");
protocol = protocol.Trim ().ToLowerInvariant ();
using (var ctx = CryptographyContext.Create (protocol)) {
return Verify (ctx);
}
}
}
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
namespace ILCompiler.DependencyAnalysisFramework
{
/// <summary>
/// Implement a dependency analysis framework. This works much like a Garbage Collector's mark algorithm
/// in that it finds a set of nodes from an initial root set.
///
/// However, in contrast to a typical GC in addition to simple edges from a node, there may also
/// be conditional edges where a node has a dependency if some other specific node exists in the
/// graph, and dynamic edges in which a node has a dependency if some other node exists in the graph,
/// but what that other node might be is not known until it may exist in the graph.
///
/// This analyzer also attempts to maintain a serialized state of why nodes are in the graph
/// with strings describing the reason a given node was added to the graph. The degree of logging
/// is configurable via the MarkStrategy
///
/// </summary>
public sealed class DependencyAnalyzer<MarkStrategy, DependencyContextType> : DependencyAnalyzerBase<DependencyContextType> where MarkStrategy : struct, IDependencyAnalysisMarkStrategy<DependencyContextType>
{
private MarkStrategy _marker = new MarkStrategy();
private DependencyContextType _dependencyContext;
private IComparer<DependencyNodeCore<DependencyContextType>> _resultSorter = null;
private Stack<DependencyNodeCore<DependencyContextType>> _markStack = new Stack<DependencyNodeCore<DependencyContextType>>();
private List<DependencyNodeCore<DependencyContextType>> _markedNodes = new List<DependencyNodeCore<DependencyContextType>>();
private ImmutableArray<DependencyNodeCore<DependencyContextType>> _markedNodesFinal;
private List<DependencyNodeCore<DependencyContextType>> _rootNodes = new List<DependencyNodeCore<DependencyContextType>>();
private List<DependencyNodeCore<DependencyContextType>> _deferredStaticDependencies = new List<DependencyNodeCore<DependencyContextType>>();
private List<DependencyNodeCore<DependencyContextType>> _dynamicDependencyInterestingList = new List<DependencyNodeCore<DependencyContextType>>();
private List<DynamicDependencyNode> _markedNodesWithDynamicDependencies = new List<DynamicDependencyNode>();
private bool _newDynamicDependenciesMayHaveAppeared = false;
private Dictionary<DependencyNodeCore<DependencyContextType>, HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry>> _conditional_dependency_store = new Dictionary<DependencyNodeCore<DependencyContextType>, HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry>>();
private bool _markingCompleted = false;
private struct DynamicDependencyNode
{
private DependencyNodeCore<DependencyContextType> _node;
private int _next;
public DynamicDependencyNode(DependencyNodeCore<DependencyContextType> node)
{
_node = node;
_next = 0;
}
public void MarkNewDynamicDependencies(DependencyAnalyzer<MarkStrategy, DependencyContextType> analyzer)
{
foreach (DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry dependency in
_node.SearchDynamicDependencies(analyzer._dynamicDependencyInterestingList, _next, analyzer._dependencyContext))
{
analyzer.AddToMarkStack(dependency.Node, dependency.Reason, _node, dependency.OtherReasonNode);
}
_next = analyzer._dynamicDependencyInterestingList.Count;
}
}
// Api surface
public DependencyAnalyzer(DependencyContextType dependencyContext, IComparer<DependencyNodeCore<DependencyContextType>> resultSorter)
{
_dependencyContext = dependencyContext;
_resultSorter = resultSorter;
}
/// <summary>
/// Add a root node
/// </summary>
public override sealed void AddRoot(DependencyNodeCore<DependencyContextType> rootNode, string reason)
{
if (AddToMarkStack(rootNode, reason, null, null))
{
_rootNodes.Add(rootNode);
}
}
public override sealed ImmutableArray<DependencyNodeCore<DependencyContextType>> MarkedNodeList
{
get
{
if (!_markingCompleted)
{
_markingCompleted = true;
ComputeMarkedNodes();
}
return _markedNodesFinal;
}
}
public override sealed event Action<DependencyNodeCore<DependencyContextType>> NewMarkedNode;
public override sealed event Action<List<DependencyNodeCore<DependencyContextType>>> ComputeDependencyRoutine;
private IEnumerable<DependencyNodeCore<DependencyContextType>> MarkedNodesEnumerable()
{
if (_markedNodesFinal != null)
return _markedNodesFinal;
else
return _markedNodes;
}
public override sealed void VisitLogNodes(IDependencyAnalyzerLogNodeVisitor logNodeVisitor)
{
foreach (DependencyNode node in MarkedNodesEnumerable())
{
logNodeVisitor.VisitNode(node);
}
_marker.VisitLogNodes(MarkedNodesEnumerable(), logNodeVisitor);
}
public override sealed void VisitLogEdges(IDependencyAnalyzerLogEdgeVisitor logEdgeVisitor)
{
_marker.VisitLogEdges(MarkedNodesEnumerable(), logEdgeVisitor);
}
/// <summary>
/// Called by the algorithm to ensure that this set of nodes is processed such that static dependencies are computed.
/// </summary>
/// <param name="deferredStaticDependencies">List of nodes which must have static dependencies computed</param>
private void ComputeDependencies(List<DependencyNodeCore<DependencyContextType>> deferredStaticDependencies)
{
if (ComputeDependencyRoutine != null)
ComputeDependencyRoutine(deferredStaticDependencies);
}
// Internal details
private void GetStaticDependenciesImpl(DependencyNodeCore<DependencyContextType> node)
{
IEnumerable<DependencyNodeCore<DependencyContextType>.DependencyListEntry> staticDependencies = node.GetStaticDependencies(_dependencyContext);
if (staticDependencies != null)
{
foreach (DependencyNodeCore<DependencyContextType>.DependencyListEntry dependency in staticDependencies)
{
AddToMarkStack(dependency.Node, dependency.Reason, node, null);
}
}
if (node.HasConditionalStaticDependencies)
{
foreach (DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry dependency in node.GetConditionalStaticDependencies(_dependencyContext))
{
if (dependency.OtherReasonNode.Marked)
{
AddToMarkStack(dependency.Node, dependency.Reason, node, dependency.OtherReasonNode);
}
else
{
HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> storedDependencySet = null;
if (!_conditional_dependency_store.TryGetValue(dependency.OtherReasonNode, out storedDependencySet))
{
storedDependencySet = new HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry>();
_conditional_dependency_store.Add(dependency.OtherReasonNode, storedDependencySet);
}
// Swap out other reason node as we're storing that as the dictionary key
DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry conditionalDependencyStoreEntry = new DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry();
conditionalDependencyStoreEntry.Node = dependency.Node;
conditionalDependencyStoreEntry.Reason = dependency.Reason;
conditionalDependencyStoreEntry.OtherReasonNode = node;
storedDependencySet.Add(conditionalDependencyStoreEntry);
}
}
}
}
private void GetStaticDependencies(DependencyNodeCore<DependencyContextType> node)
{
if (node.StaticDependenciesAreComputed)
{
GetStaticDependenciesImpl(node);
}
else
{
_deferredStaticDependencies.Add(node);
}
}
private void ProcessMarkStack()
{
do
{
while (_markStack.Count > 0)
{
// Pop the top node of the mark stack
DependencyNodeCore<DependencyContextType> currentNode = _markStack.Pop();
Debug.Assert(currentNode.Marked);
// Only some marked objects are interesting for dynamic dependencies
// store those in a seperate list to avoid excess scanning over non-interesting
// nodes during dynamic dependency discovery
if (currentNode.InterestingForDynamicDependencyAnalysis)
{
_dynamicDependencyInterestingList.Add(currentNode);
_newDynamicDependenciesMayHaveAppeared = true;
}
// Add all static dependencies to the mark stack
GetStaticDependencies(currentNode);
// If there are dynamic dependencies, note for later
if (currentNode.HasDynamicDependencies)
{
_newDynamicDependenciesMayHaveAppeared = true;
_markedNodesWithDynamicDependencies.Add(new DynamicDependencyNode(currentNode));
}
// If this new node satisfies any stored conditional dependencies,
// add them to the mark stack
HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> storedDependencySet = null;
if (_conditional_dependency_store.TryGetValue(currentNode, out storedDependencySet))
{
foreach (DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry newlySatisfiedDependency in storedDependencySet)
{
AddToMarkStack(newlySatisfiedDependency.Node, newlySatisfiedDependency.Reason, newlySatisfiedDependency.OtherReasonNode, currentNode);
}
_conditional_dependency_store.Remove(currentNode);
}
}
// Find new dependencies introduced by dynamic depedencies
if (_newDynamicDependenciesMayHaveAppeared)
{
_newDynamicDependenciesMayHaveAppeared = false;
foreach (DynamicDependencyNode dynamicNode in _markedNodesWithDynamicDependencies)
{
dynamicNode.MarkNewDynamicDependencies(this);
}
}
} while (_markStack.Count != 0);
}
private void ComputeMarkedNodes()
{
do
{
// Run mark stack algorithm as much as possible
ProcessMarkStack();
// Compute all dependencies which were not ready during the ProcessMarkStack step
ComputeDependencies(_deferredStaticDependencies);
foreach (DependencyNodeCore<DependencyContextType> node in _deferredStaticDependencies)
{
Debug.Assert(node.StaticDependenciesAreComputed);
GetStaticDependenciesImpl(node);
}
_deferredStaticDependencies.Clear();
} while (_markStack.Count != 0);
if (_resultSorter != null)
_markedNodes.Sort(_resultSorter);
_markedNodesFinal = _markedNodes.ToImmutableArray();
_markedNodes = null;
}
private bool AddToMarkStack(DependencyNodeCore<DependencyContextType> node, string reason, DependencyNodeCore<DependencyContextType> reason1, DependencyNodeCore<DependencyContextType> reason2)
{
if (_marker.MarkNode(node, reason1, reason2, reason))
{
_markStack.Push(node);
_markedNodes.Add(node);
node.CallOnMarked(_dependencyContext);
if (NewMarkedNode != null)
NewMarkedNode(node);
return true;
}
return false;
}
}
}
| |
using System;
using NUnit.Framework;
namespace DotSpatial.Projections.Tests.Projected
{
/// <summary>
/// This class contains all the tests for the NationalGrids category of Projected coordinate systems
/// </summary>
[TestFixture]
public class NationalGrids
{
/// <summary>
/// Creates a new instance of the Africa Class
/// </summary>
[TestFixtureSetUp]
public void Initialize()
{
}
[Test]
public void Abidjan1987TM5NW()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Abidjan1987TM5NW;
Tester.TestProjection(pStart);
}
[Test]
public void AccraGhanaGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.AccraGhanaGrid;
Tester.TestProjection(pStart);
}
[Test]
public void AccraTM1NW()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.AccraTM1NW;
Tester.TestProjection(pStart);
}
[Test]
public void AinelAbdAramcoLambert()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.AinelAbdAramcoLambert;
Tester.TestProjection(pStart);
}
[Test]
public void AmericanSamoa1962SamoaLambert()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.AmericanSamoa1962SamoaLambert;
Tester.TestProjection(pStart);
}
[Test]
public void Anguilla1957BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Anguilla1957BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Antigua1943BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Antigua1943BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void ArgentinaZone1()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ArgentinaZone1;
Tester.TestProjection(pStart);
}
[Test]
public void ArgentinaZone2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ArgentinaZone2;
Tester.TestProjection(pStart);
}
[Test]
public void ArgentinaZone3()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ArgentinaZone3;
Tester.TestProjection(pStart);
}
[Test]
public void ArgentinaZone4()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ArgentinaZone4;
Tester.TestProjection(pStart);
}
[Test]
public void ArgentinaZone5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ArgentinaZone5;
Tester.TestProjection(pStart);
}
[Test]
public void ArgentinaZone6()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ArgentinaZone6;
Tester.TestProjection(pStart);
}
[Test]
public void ArgentinaZone7()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ArgentinaZone7;
Tester.TestProjection(pStart);
}
[Test]
public void AustriaFerroCentralZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.AustriaFerroCentralZone;
Tester.TestProjection(pStart);
}
[Test]
public void AustriaFerroEastZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.AustriaFerroEastZone;
Tester.TestProjection(pStart);
}
[Test]
public void AustriaFerroWestZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.AustriaFerroWestZone;
Tester.TestProjection(pStart);
}
[Test]
public void BahrainStateGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.BahrainStateGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Barbados1938BarbadosGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Barbados1938BarbadosGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Barbados1938BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Barbados1938BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void BataviaNEIEZ()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.BataviaNEIEZ;
Tester.TestProjection(pStart);
}
[Test]
public void BataviaTM109SE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.BataviaTM109SE;
Tester.TestProjection(pStart);
}
[Test]
public void BelgeLambert1950()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.BelgeLambert1950;
Tester.TestProjection(pStart);
}
[Test]
public void BelgeLambert1972()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.BelgeLambert1972;
Tester.TestProjection(pStart);
}
[Test]
public void Bermuda2000NationalGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Bermuda2000NationalGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Bern1898BernLV03C()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Bern1898BernLV03C;
Tester.TestProjection(pStart);
}
[Test]
public void BritishNationalGridOSGB36()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.BritishNationalGridOSGB36;
Tester.TestProjection(pStart);
}
[Test]
public void CamacupaTM1130SE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.CamacupaTM1130SE;
Tester.TestProjection(pStart);
}
[Test]
public void CamacupaTM12SE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.CamacupaTM12SE;
Tester.TestProjection(pStart);
}
[Test]
public void CarthageTM11NE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.CarthageTM11NE;
Tester.TestProjection(pStart);
}
[Test]
public void CentreFrance()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.CentreFrance;
Tester.TestProjection(pStart);
}
[Test]
public void CH1903LV03()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.CH1903LV03;
Tester.TestProjection(pStart);
}
[Test]
public void CH1903LV95()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.CH1903LV95;
Tester.TestProjection(pStart);
}
[Test]
public void ChosMalal1914Argentina2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ChosMalal1914Argentina2;
Tester.TestProjection(pStart);
}
[Test]
public void ColombiaBogotaZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ColombiaBogotaZone;
Tester.TestProjection(pStart);
}
[Test]
public void ColombiaEastZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ColombiaEastZone;
Tester.TestProjection(pStart);
}
[Test]
public void ColombiaECentralZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ColombiaECentralZone;
Tester.TestProjection(pStart);
}
[Test]
public void ColombiaWestZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ColombiaWestZone;
Tester.TestProjection(pStart);
}
[Test]
public void Corse()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Corse;
Tester.TestProjection(pStart);
}
[Test]
public void Datum73HayfordGaussIGeoE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Datum73HayfordGaussIGeoE;
Tester.TestProjection(pStart);
}
[Test]
public void Datum73HayfordGaussIPCC()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Datum73HayfordGaussIPCC;
Tester.TestProjection(pStart);
}
[Test]
public void DeirezZorLevantStereographic()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DeirezZorLevantStereographic;
Tester.TestProjection(pStart);
}
[Test]
public void DeirezZorLevantZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DeirezZorLevantZone;
Tester.TestProjection(pStart);
}
[Test]
public void DeirezZorSyriaLambert()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DeirezZorSyriaLambert;
Tester.TestProjection(pStart);
}
[Test]
public void DHDN3DegreeGaussZone1()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DHDN3DegreeGaussZone1;
Tester.TestProjection(pStart);
}
[Test]
public void DHDN3DegreeGaussZone2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DHDN3DegreeGaussZone2;
Tester.TestProjection(pStart);
}
[Test]
public void DHDN3DegreeGaussZone3()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DHDN3DegreeGaussZone3;
Tester.TestProjection(pStart);
}
[Test]
public void DHDN3DegreeGaussZone4()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DHDN3DegreeGaussZone4;
Tester.TestProjection(pStart);
}
[Test]
public void DHDN3DegreeGaussZone5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DHDN3DegreeGaussZone5;
Tester.TestProjection(pStart);
}
[Test]
public void Dominica1945BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Dominica1945BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Douala1948AOFWest()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Douala1948AOFWest;
Tester.TestProjection(pStart);
}
[Test]
public void DutchRD()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.DutchRD;
Tester.TestProjection(pStart);
// specific coordinates (source: PCTrans; ministerie van defensie)
ProjectionInfo pEnd = KnownCoordinateSystems.Geographic.World.WGS1984;
double[] xy = new double[2];
double[] z = new double[1];
// projection center, amersfoort
xy[0] = 155000;
xy[1] = 463000;
Reproject.ReprojectPoints(xy, z, pStart, pEnd, 0, 1);
Assert.Less(Math.Abs(5.387203658 - xy[0]), 0.000001);
Assert.Less(Math.Abs(52.155172894 - xy[1]), 0.000001);
// 100 km north, 100 east of amersfoort
xy[0] = 255000;
xy[1] = 563000;
Reproject.ReprojectPoints(xy, z, pStart, pEnd, 0, 1);
Assert.Less(Math.Abs(6.878349136 - xy[0]), 0.00001);
Assert.Less(Math.Abs(53.044587289 - xy[1]), 0.00001);
// 100 km south, 100 west of amersfoort
xy[0] = 55000;
xy[1] = 363000;
Reproject.ReprojectPoints(xy, z, pStart, pEnd, 0, 1);
Assert.Less(Math.Abs(3.954917189 - xy[0]), 0.00001);
Assert.Less(Math.Abs(51.247513569 - xy[1]), 0.00001);
}
//private static void PjGeocentricToWgs84(ProjectionInfo source, double[] xy, double[] zArr, int startIndex, int numPoints)
//{
// double[] shift = source.GeographicInfo.Datum.ToWGS84;
// if (source.GeographicInfo.Datum.DatumType == DatumType.Param3)
// {
// for (int i = startIndex; i < numPoints; i++)
// {
// if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
// xy[2 * i] = xy[2 * i] + shift[0]; // dx
// xy[2 * i + 1] = xy[2 * i + 1] + shift[1]; // dy
// zArr[i] = zArr[i] + shift[2];
// }
// }
// else
// {
// for (int i = startIndex; i < numPoints; i++)
// {
// if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
// double x = xy[2 * i];
// double y = xy[2 * i + 1];
// double z = zArr[i];
// xy[2 * i] = shift[6] * (x - shift[5] * y + shift[4] * z) + shift[0];
// xy[2 * i + 1] = shift[6] * (shift[5] * x + y - shift[3] * z) + shift[1];
// zArr[i] = shift[6] * (-shift[4] * x + shift[3] * y + z) + shift[2];
// }
// }
//}
[Test]
public void GeocentricAfterDatumTest()
{
double[] xy = new double[2];
xy[0] = 4257349.7546790326000000;
xy[1] = 401477.6657818287500000;
double[] z = new double[1];
z[0] = 4716473.1891765557000000;
Spheroid s = new Spheroid(Proj4Ellipsoid.WGS_1984);
GeocentricGeodetic gc = new GeocentricGeodetic(s);
gc.GeocentricToGeodetic(xy, z, 0, 1);
}
[Test]
public void ED1950FranceEuroLambert()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950FranceEuroLambert;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM0N()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM0N;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM27()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM27;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM30()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM30;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM33()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM33;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM36()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM36;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM39()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM39;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM42()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM42;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM45()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM45;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950TM5NE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950TM5NE;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950Turkey10()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950Turkey10;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950Turkey11()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950Turkey11;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950Turkey12()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950Turkey12;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950Turkey13()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950Turkey13;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950Turkey14()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950Turkey14;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950Turkey15()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950Turkey15;
Tester.TestProjection(pStart);
}
[Test]
public void ED1950Turkey9()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ED1950Turkey9;
Tester.TestProjection(pStart);
}
[Test]
public void EgyptBlueBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.EgyptBlueBelt;
Tester.TestProjection(pStart);
}
[Test]
public void EgyptExtendedPurpleBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.EgyptExtendedPurpleBelt;
Tester.TestProjection(pStart);
}
[Test]
public void EgyptPurpleBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.EgyptPurpleBelt;
Tester.TestProjection(pStart);
}
[Test]
public void EgyptRedBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.EgyptRedBelt;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya10()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya10;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya11()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya11;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya12()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya12;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya13()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya13;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya5;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya6()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya6;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya7()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya7;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya8()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya8;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979Libya9()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979Libya9;
Tester.TestProjection(pStart);
}
[Test]
public void ELD1979TM12NE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ELD1979TM12NE;
Tester.TestProjection(pStart);
}
[Test]
public void Estonia1997EstoniaNationalGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Estonia1997EstoniaNationalGrid;
Tester.TestProjection(pStart);
}
[Test]
public void EstonianCoordinateSystemof1992()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.EstonianCoordinateSystemof1992;
Tester.TestProjection(pStart);
}
[Test]
public void ETRF1989TMBaltic1993()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRF1989TMBaltic1993;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989Kp2000Bornholm()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989Kp2000Bornholm;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989Kp2000Jutland()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989Kp2000Jutland;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989Kp2000Zealand()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989Kp2000Zealand;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989PolandCS2000Zone5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989PolandCS2000Zone5;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989PolandCS2000Zone6()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989PolandCS2000Zone6;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989PolandCS2000Zone7()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989PolandCS2000Zone7;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989PolandCS2000Zone8()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989PolandCS2000Zone8;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989PolandCS92()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989PolandCS92;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989TM30NE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989TM30NE;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989TMBaltic1993()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989TMBaltic1993;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989UWPP1992()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989UWPP1992;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989UWPP2000PAS5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989UWPP2000PAS5;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989UWPP2000PAS6()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989UWPP2000PAS6;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989UWPP2000PAS7()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989UWPP2000PAS7;
Tester.TestProjection(pStart);
}
[Test]
public void ETRS1989UWPP2000PAS8()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ETRS1989UWPP2000PAS8;
Tester.TestProjection(pStart);
}
[Test]
public void EUREFFINTM35FIN()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.EUREFFINTM35FIN;
Tester.TestProjection(pStart);
}
[Test]
public void EverestModified1969RSOMalayaMeters()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.EverestModified1969RSOMalayaMeters;
Tester.TestProjection(pStart);
}
[Test]
public void FD1958Iraq()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FD1958Iraq;
Tester.TestProjection(pStart);
}
[Test]
public void FinlandZone1()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FinlandZone1;
Tester.TestProjection(pStart);
}
[Test]
public void FinlandZone2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FinlandZone2;
Tester.TestProjection(pStart);
}
[Test]
public void FinlandZone3()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FinlandZone3;
Tester.TestProjection(pStart);
}
[Test]
public void FinlandZone4()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FinlandZone4;
Tester.TestProjection(pStart);
}
[Test]
public void FranceI()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FranceI;
Tester.TestProjection(pStart);
}
[Test]
public void FranceII()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FranceII;
Tester.TestProjection(pStart);
}
[Test]
public void FranceIII()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FranceIII;
Tester.TestProjection(pStart);
}
[Test]
public void FranceIV()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.FranceIV;
Tester.TestProjection(pStart);
}
[Test]
public void GermanyZone1()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GermanyZone1;
Tester.TestProjection(pStart);
}
[Test]
public void GermanyZone2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GermanyZone2;
Tester.TestProjection(pStart);
}
[Test]
public void GermanyZone3()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GermanyZone3;
Tester.TestProjection(pStart);
}
[Test]
public void GermanyZone4()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GermanyZone4;
Tester.TestProjection(pStart);
}
[Test]
public void GermanyZone5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GermanyZone5;
Tester.TestProjection(pStart);
}
[Test]
public void GhanaMetreGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GhanaMetreGrid;
Tester.TestProjection(pStart);
}
[Test]
public void GreekGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GreekGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Grenada1953BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Grenada1953BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void GuernseyGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GuernseyGrid;
Tester.TestProjection(pStart);
}
[Test]
public void GunungSegaraNEIEZ()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.GunungSegaraNEIEZ;
Tester.TestProjection(pStart);
}
[Test]
public void Hanoi1972GK106NE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Hanoi1972GK106NE;
Tester.TestProjection(pStart);
}
[Test]
public void HD1972EgysegesOrszagosVetuleti()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.HD1972EgysegesOrszagosVetuleti;
Tester.TestProjection(pStart);
}
[Test]
public void Helle1954JanMayenGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Helle1954JanMayenGrid;
Tester.TestProjection(pStart);
}
[Test]
public void HitoXVIII1963Argentina2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.HitoXVIII1963Argentina2;
Tester.TestProjection(pStart);
}
[Test]
public void HongKong1980Grid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.HongKong1980Grid;
Tester.TestProjection(pStart);
}
[Test]
public void Indian1960TM106NE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Indian1960TM106NE;
Tester.TestProjection(pStart);
}
[Test]
public void IRENET95IrishTranverseMercator()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.IRENET95IrishTranverseMercator;
Tester.TestProjection(pStart);
}
[Test]
public void IrishNationalGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.IrishNationalGrid;
Tester.TestProjection(pStart);
}
[Test]
public void ISN1993Lambert1993()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ISN1993Lambert1993;
Tester.TestProjection(pStart);
}
[Test]
public void IsraelTMGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.IsraelTMGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Jamaica1875OldGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Jamaica1875OldGrid;
Tester.TestProjection(pStart);
}
[Test]
public void JamaicaGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.JamaicaGrid;
Tester.TestProjection(pStart);
}
[Test]
public void JordanJTM()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.JordanJTM;
Tester.TestProjection(pStart);
}
[Test]
public void KandawalaCeylonBeltIndianYards1937()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KandawalaCeylonBeltIndianYards1937;
Tester.TestProjection(pStart);
}
[Test]
public void KandawalaCeylonBeltMeters()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KandawalaCeylonBeltMeters;
Tester.TestProjection(pStart);
}
[Test]
public void KertauRSOMalayaChains()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KertauRSOMalayaChains;
Tester.TestProjection(pStart);
}
[Test]
public void KertauRSOMalayaMeters()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KertauRSOMalayaMeters;
Tester.TestProjection(pStart);
}
[Test]
public void KertauSingaporeGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KertauSingaporeGrid;
Tester.TestProjection(pStart);
}
[Test]
public void KOCLambert()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KOCLambert;
Tester.TestProjection(pStart);
}
[Test]
public void Korean1985KoreaCentralBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Korean1985KoreaCentralBelt;
Tester.TestProjection(pStart);
}
[Test]
public void Korean1985KoreaEastBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Korean1985KoreaEastBelt;
Tester.TestProjection(pStart);
}
[Test]
public void Korean1985KoreaWestBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Korean1985KoreaWestBelt;
Tester.TestProjection(pStart);
}
[Test]
public void KUDAMSKTM()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KUDAMSKTM;
Tester.TestProjection(pStart);
}
[Test]
public void KuwaitOilCoLambert()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KuwaitOilCoLambert;
Tester.TestProjection(pStart);
}
[Test]
public void KuwaitUtilityKTM()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.KuwaitUtilityKTM;
Tester.TestProjection(pStart);
}
[Test]
public void LakeMaracaiboGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.LakeMaracaiboGrid;
Tester.TestProjection(pStart);
}
[Test]
public void LakeMaracaiboGridM1()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.LakeMaracaiboGridM1;
Tester.TestProjection(pStart);
}
[Test]
public void LakeMaracaiboGridM3()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.LakeMaracaiboGridM3;
Tester.TestProjection(pStart);
}
[Test]
public void LakeMaracaiboLaRosaGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.LakeMaracaiboLaRosaGrid;
Tester.TestProjection(pStart);
}
[Test]
public void LietuvosKoordinaciuSistema()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.LietuvosKoordinaciuSistema;
Tester.TestProjection(pStart);
}
[Test]
public void LisboaBesselBonne()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.LisboaBesselBonne;
Tester.TestProjection(pStart);
}
[Test]
public void LisboaHayfordGaussIGeoE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.LisboaHayfordGaussIGeoE;
Tester.TestProjection(pStart);
}
[Test]
public void LisboaHayfordGaussIPCC()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.LisboaHayfordGaussIPCC;
Tester.TestProjection(pStart);
}
[Test]
public void Locodjo1965TM5NW()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Locodjo1965TM5NW;
Tester.TestProjection(pStart);
}
[Test]
public void Luxembourg1930Gauss()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Luxembourg1930Gauss;
Tester.TestProjection(pStart);
}
[Test]
public void Madrid1870MadridSpain()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Madrid1870MadridSpain;
Tester.TestProjection(pStart);
}
[Test]
public void MakassarNEIEZ()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MakassarNEIEZ;
Tester.TestProjection(pStart);
}
[Test]
public void MGI3DegreeGaussZone5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGI3DegreeGaussZone5;
Tester.TestProjection(pStart);
}
[Test]
public void MGI3DegreeGaussZone6()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGI3DegreeGaussZone6;
Tester.TestProjection(pStart);
}
[Test]
public void MGI3DegreeGaussZone7()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGI3DegreeGaussZone7;
Tester.TestProjection(pStart);
}
[Test]
public void MGI3DegreeGaussZone8()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGI3DegreeGaussZone8;
Tester.TestProjection(pStart);
}
[Test]
public void MGIAustriaLambert()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGIAustriaLambert;
Tester.TestProjection(pStart);
}
[Test]
public void MGIBalkans5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGIBalkans5;
Tester.TestProjection(pStart);
}
[Test]
public void MGIBalkans6()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGIBalkans6;
Tester.TestProjection(pStart);
}
[Test]
public void MGIBalkans7()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGIBalkans7;
Tester.TestProjection(pStart);
}
[Test]
public void MGIBalkans8()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGIBalkans8;
Tester.TestProjection(pStart);
}
[Test]
public void MGIM28()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGIM28;
Tester.TestProjection(pStart);
}
[Test]
public void MGIM31()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGIM31;
Tester.TestProjection(pStart);
}
[Test]
public void MGIM34()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGIM34;
Tester.TestProjection(pStart);
}
[Test]
public void MGISloveniaGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MGISloveniaGrid;
Tester.TestProjection(pStart);
}
[Test]
public void MonteMarioItaly1()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MonteMarioItaly1;
Tester.TestProjection(pStart);
}
[Test]
public void MonteMarioItaly2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MonteMarioItaly2;
Tester.TestProjection(pStart);
}
[Test]
public void MonteMarioRomeItaly1()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MonteMarioRomeItaly1;
Tester.TestProjection(pStart);
}
[Test]
public void MonteMarioRomeItaly2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MonteMarioRomeItaly2;
Tester.TestProjection(pStart);
}
[Test]
public void Montserrat1958BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Montserrat1958BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void MountDillonTobagoGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.MountDillonTobagoGrid;
Tester.TestProjection(pStart);
}
[Test]
public void NAD1927CubaNorte()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1927CubaNorte;
Tester.TestProjection(pStart);
}
[Test]
public void NAD1927CubaSur()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1927CubaSur;
Tester.TestProjection(pStart);
}
[Test]
public void NAD1927GuatemalaNorte()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1927GuatemalaNorte;
Tester.TestProjection(pStart);
}
[Test]
public void NAD1927GuatemalaSur()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1927GuatemalaSur;
Tester.TestProjection(pStart);
}
[Ignore("Doesn't work on x64 TeamCity. x86 is fine.")]
[Test]
public void NAD1927MichiganGeoRefMeters()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1927MichiganGeoRefMeters;
Tester.TestProjection(pStart);
}
[Ignore("Doesn't work on x64 TeamCity. x86 is fine.")]
[Test]
public void NAD1927MichiganGeoRefUSfeet()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1927MichiganGeoRefUSfeet;
Tester.TestProjection(pStart);
}
[Test]
public void NAD1983HARNGuamMapGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1983HARNGuamMapGrid;
Tester.TestProjection(pStart);
}
[Test]
public void NAD1983MichiganGeoReferencedMeters()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1983MichiganGeoReferencedMeters;
Tester.TestProjection(pStart);
}
[Test]
public void NAD1983MichiganGeoRefMeters()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1983MichiganGeoRefMeters;
Tester.TestProjection(pStart);
}
[Test]
public void NAD1983MichiganGeoRefUSfeet()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NAD1983MichiganGeoRefUSfeet;
Tester.TestProjection(pStart);
}
[Test]
public void NewZealandMapGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NewZealandMapGrid;
Tester.TestProjection(pStart);
}
[Test]
public void NewZealandNorthIsland()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NewZealandNorthIsland;
Tester.TestProjection(pStart);
}
[Test]
public void NewZealandSouthIsland()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NewZealandSouthIsland;
Tester.TestProjection(pStart);
}
[Test]
public void NigeriaEastBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NigeriaEastBelt;
Tester.TestProjection(pStart);
}
[Test]
public void NigeriaMidBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NigeriaMidBelt;
Tester.TestProjection(pStart);
}
[Test]
public void NigeriaWestBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NigeriaWestBelt;
Tester.TestProjection(pStart);
}
[Test]
public void NordAlgerie()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NordAlgerie;
Tester.TestProjection(pStart);
}
[Test]
public void NordAlgerieancienne()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NordAlgerieancienne;
Tester.TestProjection(pStart);
}
[Test]
public void NordAlgerieAnciennedegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NordAlgerieAnciennedegrees;
Tester.TestProjection(pStart);
}
[Test]
public void NordAlgeriedegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NordAlgeriedegrees;
Tester.TestProjection(pStart);
}
[Test]
public void NorddeGuerre()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NorddeGuerre;
Tester.TestProjection(pStart);
}
[Test]
public void NordFrance()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NordFrance;
Tester.TestProjection(pStart);
}
[Test]
public void NordMaroc()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NordMaroc;
Tester.TestProjection(pStart);
}
[Test]
public void NordMarocdegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NordMarocdegrees;
Tester.TestProjection(pStart);
}
[Test]
public void NordTunisie()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NordTunisie;
Tester.TestProjection(pStart);
}
[Test]
public void NTFFranceIdegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NTFFranceIdegrees;
Tester.TestProjection(pStart);
}
[Test]
public void NTFFranceIIdegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NTFFranceIIdegrees;
Tester.TestProjection(pStart);
}
[Test]
public void NTFFranceIIIdegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NTFFranceIIIdegrees;
Tester.TestProjection(pStart);
}
[Test]
public void NTFFranceIVdegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.NTFFranceIVdegrees;
Tester.TestProjection(pStart);
}
[Test]
public void ObservatorioMeteorologico1965MacauGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ObservatorioMeteorologico1965MacauGrid;
Tester.TestProjection(pStart);
}
[Test]
public void OSNI1952IrishNationalGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.OSNI1952IrishNationalGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Palestine1923IsraelCSGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Palestine1923IsraelCSGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Palestine1923PalestineBelt()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Palestine1923PalestineBelt;
Tester.TestProjection(pStart);
}
[Test]
public void Palestine1923PalestineGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Palestine1923PalestineGrid;
Tester.TestProjection(pStart);
}
[Test]
public void PampadelCastilloArgentina2()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PampadelCastilloArgentina2;
Tester.TestProjection(pStart);
}
[Test]
public void PeruCentralZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PeruCentralZone;
Tester.TestProjection(pStart);
}
[Test]
public void PeruEastZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PeruEastZone;
Tester.TestProjection(pStart);
}
[Test]
public void PeruWestZone()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PeruWestZone;
Tester.TestProjection(pStart);
}
[Test]
public void PhilippinesZoneI()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PhilippinesZoneI;
Tester.TestProjection(pStart);
}
[Test]
public void PhilippinesZoneII()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PhilippinesZoneII;
Tester.TestProjection(pStart);
}
[Test]
public void PhilippinesZoneIII()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PhilippinesZoneIII;
Tester.TestProjection(pStart);
}
[Test]
public void PhilippinesZoneIV()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PhilippinesZoneIV;
Tester.TestProjection(pStart);
}
[Test]
public void PhilippinesZoneV()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PhilippinesZoneV;
Tester.TestProjection(pStart);
}
[Test]
public void PitondesNeigesTMReunion()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PitondesNeigesTMReunion;
Tester.TestProjection(pStart);
}
[Test]
public void PortugueseNationalGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PortugueseNationalGrid;
Tester.TestProjection(pStart);
}
[Test]
public void PSAD1956ICNRegional()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.PSAD1956ICNRegional;
Tester.TestProjection(pStart);
}
[Test]
public void Qatar1948QatarGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Qatar1948QatarGrid;
Tester.TestProjection(pStart);
}
[Test]
public void QatarNationalGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.QatarNationalGrid;
Tester.TestProjection(pStart);
}
[Test]
public void RassadiranNakhleTaqi()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.RassadiranNakhleTaqi;
Tester.TestProjection(pStart);
}
[Test]
public void RGF1993Lambert93()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.RGF1993Lambert93;
Tester.TestProjection(pStart);
}
[Test]
public void RGNC1991LambertNewCaledonia()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.RGNC1991LambertNewCaledonia;
Tester.TestProjection(pStart);
}
[Test]
public void Rijksdriehoekstelsel()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Rijksdriehoekstelsel;
Tester.TestProjection(pStart);
}
[Test]
public void Roma1940GaussBoagaEst()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Roma1940GaussBoagaEst;
Tester.TestProjection(pStart);
}
[Test]
public void Roma1940GaussBoagaOvest()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Roma1940GaussBoagaOvest;
Tester.TestProjection(pStart);
}
[Test]
public void RT9025gonWest()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.RT9025gonWest;
Tester.TestProjection(pStart);
}
[Test]
public void SAD1969BrazilPolyconic()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SAD1969BrazilPolyconic;
Tester.TestProjection(pStart);
}
[Test]
public void Sahara()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Sahara;
Tester.TestProjection(pStart);
}
[Test]
public void Saharadegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Saharadegrees;
Tester.TestProjection(pStart);
}
[Test]
public void SierraLeone1924NewColonyGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SierraLeone1924NewColonyGrid;
Tester.TestProjection(pStart);
}
[Test]
public void SierraLeone1924NewWarOfficeGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SierraLeone1924NewWarOfficeGrid;
Tester.TestProjection(pStart);
}
[Test]
public void SJTSKFerroKrovak()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SJTSKFerroKrovak;
Tester.TestProjection(pStart);
}
[Test]
public void SJTSKFerroKrovakEastNorth()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SJTSKFerroKrovakEastNorth;
Tester.TestProjection(pStart);
}
[Test]
public void SJTSKKrovak()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SJTSKKrovak;
Tester.TestProjection(pStart);
}
[Test]
public void SJTSKKrovakEastNorth()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SJTSKKrovakEastNorth;
Tester.TestProjection(pStart);
}
[Test]
public void Stereo1933()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Stereo1933;
Tester.TestProjection(pStart);
}
[Test]
public void Stereo1970()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Stereo1970;
Tester.TestProjection(pStart);
}
[Test]
public void StKitts1955BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.StKitts1955BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void StLucia1955BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.StLucia1955BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void StVincent1945BritishWestIndiesGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.StVincent1945BritishWestIndiesGrid;
Tester.TestProjection(pStart);
}
[Test]
public void SudAlgerie()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SudAlgerie;
Tester.TestProjection(pStart);
}
[Test]
public void SudAlgerieAncienneDegree()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SudAlgerieAncienneDegree;
Tester.TestProjection(pStart);
}
[Test]
public void SudAlgeriedegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SudAlgeriedegrees;
Tester.TestProjection(pStart);
}
[Test]
public void SudFrance()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SudFrance;
Tester.TestProjection(pStart);
}
[Test]
public void SudMaroc()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SudMaroc;
Tester.TestProjection(pStart);
}
[Test]
public void SudMarocdegrees()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SudMarocdegrees;
Tester.TestProjection(pStart);
}
[Test]
public void SudTunisie()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SudTunisie;
Tester.TestProjection(pStart);
}
[Test]
public void SwedishNationalGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.SwedishNationalGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Timbalai1948RSOBorneoChains()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Timbalai1948RSOBorneoChains;
Tester.TestProjection(pStart);
}
[Test]
public void Timbalai1948RSOBorneoFeet()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Timbalai1948RSOBorneoFeet;
Tester.TestProjection(pStart);
}
[Test]
public void Timbalai1948RSOBorneoMeters()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Timbalai1948RSOBorneoMeters;
Tester.TestProjection(pStart);
}
[Test]
public void TM75IrishGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.TM75IrishGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Trinidad1903TrinidadGrid()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Trinidad1903TrinidadGrid;
Tester.TestProjection(pStart);
}
[Test]
public void Trinidad1903TrinidadGridFeetClarke()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.Trinidad1903TrinidadGridFeetClarke;
Tester.TestProjection(pStart);
}
[Test]
public void UWPP1992()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.UWPP1992;
Tester.TestProjection(pStart);
}
[Test]
public void UWPP2000pas5()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.UWPP2000pas5;
Tester.TestProjection(pStart);
}
[Test]
public void UWPP2000pas6()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.UWPP2000pas6;
Tester.TestProjection(pStart);
}
[Test]
public void UWPP2000pas7()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.UWPP2000pas7;
Tester.TestProjection(pStart);
}
[Test]
public void UWPP2000pas8()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.UWPP2000pas8;
Tester.TestProjection(pStart);
}
[Test]
public void WGS1972TM106NE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.WGS1972TM106NE;
Tester.TestProjection(pStart);
}
[Test]
public void WGS1984TM116SE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.WGS1984TM116SE;
Tester.TestProjection(pStart);
}
[Test]
public void WGS1984TM132SE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.WGS1984TM132SE;
Tester.TestProjection(pStart);
}
[Test]
public void WGS1984TM36SE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.WGS1984TM36SE;
Tester.TestProjection(pStart);
}
[Test]
public void WGS1984TM6NE()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.WGS1984TM6NE;
Tester.TestProjection(pStart);
}
[Test]
public void ZanderijSurinameOldTM()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ZanderijSurinameOldTM;
Tester.TestProjection(pStart);
}
[Test]
public void ZanderijSurinameTM()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ZanderijSurinameTM;
Tester.TestProjection(pStart);
}
[Test]
public void ZanderijTM54NW()
{
ProjectionInfo pStart = KnownCoordinateSystems.Projected.NationalGrids.ZanderijTM54NW;
Tester.TestProjection(pStart);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace JwtWebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// This file is part of Sdict2db.
//
// Sdict2db 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.
//
// Sdict2db 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 Sdict2db. if not, see <http://www.gnu.org/licenses/>.
//
// Copyright 2008 Alla Morgunova
using System;
using System.Windows.Forms;
using System.ComponentModel;
using Sdict2db.Helpers;
namespace Sdict2db.PagedGridView {
class Scroller: IDisposable {
public delegate bool IsScrollNecessaryChecker(
ScrollEventType scrollEventType);
#region Private members
private VScrollBar _vScrollBar;
private int _currentScrollPosition;
private IsScrollNecessaryChecker _isScrollNecessary;
#endregion
#region Properties
public VScrollBar ScrollBar {
get {
return _vScrollBar;
}
}
public int Position {
get {
return _currentScrollPosition;
}
set {
_currentScrollPosition = RangePosition(value);
ScrollPositionChangedHandler(this, new EventArgs());
if (_vScrollBar.Value != _currentScrollPosition) {
_vScrollBar.Value = _currentScrollPosition;
}
}
}
public int Minimum {
get {
return _vScrollBar.Minimum;
}
set {
_vScrollBar.Minimum =
NumberHelper.GetValueInRange(value, 0, value);
}
}
public int Maximum {
get {
return _vScrollBar.Maximum;
}
set {
_vScrollBar.Maximum =
NumberHelper.GetValueInRange(value, 1, value);
}
}
public int SmallChange {
get {
return _vScrollBar.SmallChange;
}
set {
_vScrollBar.SmallChange = value;
}
}
public int LargeChange {
get {
return _vScrollBar.LargeChange;
}
set {
_vScrollBar.LargeChange = value;
}
}
public bool Visible {
set {
_vScrollBar.Visible = value;
}
}
#endregion
#region Construction
public Scroller(IsScrollNecessaryChecker isScrollNecessaryChecker) {
if (isScrollNecessaryChecker == null) {
throw new ArgumentNullException("isScrollNecessaryChecker");
}
_isScrollNecessary = isScrollNecessaryChecker;
_vScrollBar = new System.Windows.Forms.VScrollBar();
_vScrollBar.Name = "_vScrollBar";
_vScrollBar.Dock = DockStyle.Right;
_vScrollBar.Hide();
_vScrollBar.Scroll += new ScrollEventHandler(
ScrollBarScrollHandler);
_vScrollBar.KeyDown += new KeyEventHandler(
KeyDownScrollHandler);
_vScrollBar.MouseWheel += new MouseEventHandler(
MouseWheelScrollHandler);
}
#endregion
#region Events
public event EventHandler<EventArgs> ScrollPositionChanged;
private void ScrollPositionChangedHandler(object sender, EventArgs e) {
if (ScrollPositionChanged != null) {
ScrollPositionChanged(this, e);
}
}
public event EventHandler<EventArgs> BeginScrolling;
private void BeginScrollingHandler(object sender, EventArgs e) {
if (BeginScrolling != null) {
BeginScrolling(this, e);
}
}
public event EventHandler<EventArgs> EndScrolling;
private void EndScrollingHandler(object sender, EventArgs e) {
if (EndScrolling != null) {
EndScrolling(this, e);
}
}
#endregion
#region Scrolling
private void ScrollBarScrollHandler(object sender, ScrollEventArgs e) {
if (e.ScrollOrientation != ScrollOrientation.VerticalScroll) {
return;
}
BeginScrollingHandler(this, new EventArgs());
if (e.Type == ScrollEventType.Last) {
Position = Maximum;
} else if (e.Type == ScrollEventType.First) {
Position = Minimum;
} else if (e.Type == ScrollEventType.SmallIncrement) {
Position += SmallChange;
} else if (e.Type == ScrollEventType.SmallDecrement) {
Position -= SmallChange;
} else if (e.Type == ScrollEventType.LargeIncrement) {
Position += LargeChange;
} else if (e.Type == ScrollEventType.LargeDecrement) {
Position -= LargeChange;
} else if (e.Type == ScrollEventType.ThumbTrack) {
Position = e.NewValue;
} else if (e.Type == ScrollEventType.ThumbPosition) {
Position = e.NewValue;
}
EndScrollingHandler(this, new EventArgs());
}
public void MouseWheelScrollHandler(object sender,
MouseEventArgs e) {
BeginScrollingHandler(this, new EventArgs());
if (e.Delta < 0) {
if (Position < Maximum) {
Position += SmallChange;
}
} else if (e.Delta > 0) {
if (Position > Minimum) {
Position -= SmallChange;
}
}
EndScrollingHandler(this, new EventArgs());
}
public void KeyDownScrollHandler(object sender, KeyEventArgs e) {
if ((e.KeyCode == Keys.Up) &&
(_isScrollNecessary(ScrollEventType.SmallDecrement))) {
_vScrollBar.Value = RangePosition(_vScrollBar.Value -
_vScrollBar.SmallChange);
InvokeScroll(ScrollEventType.SmallDecrement);
} else if ((e.KeyCode == Keys.Down) &&
(_isScrollNecessary(ScrollEventType.SmallIncrement))) {
_vScrollBar.Value = RangePosition(_vScrollBar.Value +
_vScrollBar.SmallChange);
InvokeScroll(ScrollEventType.SmallIncrement);
} else if ((e.KeyCode == Keys.PageUp) &&
(_isScrollNecessary(ScrollEventType.LargeDecrement))) {
_vScrollBar.Value = RangePosition(_vScrollBar.Value -
_vScrollBar.LargeChange);
InvokeScroll(ScrollEventType.LargeDecrement);
} else if ((e.KeyCode == Keys.PageDown) &&
(_isScrollNecessary(ScrollEventType.LargeIncrement))) {
_vScrollBar.Value = RangePosition(_vScrollBar.Value +
_vScrollBar.LargeChange);
InvokeScroll(ScrollEventType.LargeIncrement);
} else if (e.KeyCode == Keys.Home) {
_isScrollNecessary(ScrollEventType.First);
_vScrollBar.Value = _vScrollBar.Minimum;
InvokeScroll(ScrollEventType.First);
} else if (e.KeyCode == Keys.End) {
_isScrollNecessary(ScrollEventType.Last);
_vScrollBar.Value = _vScrollBar.Maximum;
InvokeScroll(ScrollEventType.Last);
}
e.SuppressKeyPress = true;
}
private void InvokeScroll(ScrollEventType scrollEventType) {
ScrollEventArgs args =
new ScrollEventArgs(scrollEventType, _vScrollBar.Value,
ScrollOrientation.VerticalScroll);
ScrollBarScrollHandler(this, args);
}
public void ResizeScrolling(int minimun, int maximum,
int smallChange, int largeChange) {
Minimum = minimun;
Maximum = maximum - LastPageChunk(largeChange);
SmallChange = smallChange;
LargeChange = largeChange;
_vScrollBar.Visible = (maximum > largeChange) ? true : false;
}
#endregion
#region Wrappers/Helpers
private int RangePosition(int value) {
return NumberHelper.GetValueInRange(value, Minimum, Maximum);
}
private static int LastPageChunk(int pageSize) {
return 4 * pageSize / 5;
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
// dispose managed resources
_vScrollBar.Dispose();
}
// free native resources
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
// Visual Studio Shared Project
// 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 System.Runtime.InteropServices;
using VSLangProj;
using VSLangProj80;
namespace Microsoft.VisualStudioTools.Project.Automation {
/// <summary>
/// Represents the automation equivalent of ReferenceNode
/// </summary>
/// <typeparam name="RefType"></typeparam>
[ComVisible(true)]
public abstract class OAReferenceBase : Reference3 {
#region fields
private ReferenceNode referenceNode;
#endregion
#region ctors
internal OAReferenceBase(ReferenceNode referenceNode) {
this.referenceNode = referenceNode;
}
#endregion
#region properties
internal ReferenceNode BaseReferenceNode {
get { return referenceNode; }
}
#endregion
#region Reference Members
public virtual int BuildNumber {
get { return 0; }
}
public virtual References Collection {
get {
return BaseReferenceNode.Parent.Object as References;
}
}
public virtual EnvDTE.Project ContainingProject {
get {
return BaseReferenceNode.ProjectMgr.GetAutomationObject() as EnvDTE.Project;
}
}
public virtual bool CopyLocal {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public virtual string Culture {
get { throw new NotImplementedException(); }
}
public virtual EnvDTE.DTE DTE {
get {
return BaseReferenceNode.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
}
}
public virtual string Description {
get {
return this.Name;
}
}
public virtual string ExtenderCATID {
get { throw new NotImplementedException(); }
}
public virtual object ExtenderNames {
get { throw new NotImplementedException(); }
}
public virtual string Identity {
get { throw new NotImplementedException(); }
}
public virtual int MajorVersion {
get { return 0; }
}
public virtual int MinorVersion {
get { return 0; }
}
public virtual string Name {
get { throw new NotImplementedException(); }
}
public virtual string Path {
get {
return BaseReferenceNode.Url;
}
}
public virtual string PublicKeyToken {
get { throw new NotImplementedException(); }
}
public virtual void Remove() {
BaseReferenceNode.Remove(false);
}
public virtual int RevisionNumber {
get { return 0; }
}
public virtual EnvDTE.Project SourceProject {
get { return null; }
}
public virtual bool StrongName {
get { return false; }
}
public virtual prjReferenceType Type {
get { throw new NotImplementedException(); }
}
public virtual string Version {
get { return new Version().ToString(); }
}
public virtual object get_Extender(string ExtenderName) {
throw new NotImplementedException();
}
#endregion
public string Aliases {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public bool AutoReferenced {
get { throw new NotImplementedException(); }
}
public virtual bool Isolated {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public virtual uint RefType {
get {
// Default to native reference to help prevent callers from
// making incorrect assumptions
return (uint)__PROJECTREFERENCETYPE.PROJREFTYPE_NATIVE;
}
}
public virtual bool Resolved {
get { return false; }
}
public string RuntimeVersion {
get { throw new NotImplementedException(); }
}
public virtual bool SpecificVersion {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public virtual string SubType {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
}
}
| |
//
// CollectionIndexer.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 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.Collections.Generic;
using DBus;
using Banshee.Library;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection.Database;
namespace Banshee.Collection.Indexer
{
[DBusExportable (ServiceName = "CollectionIndexer")]
public class CollectionIndexerService : ICollectionIndexerService, IDBusExportable, IDisposable
{
private List<LibrarySource> libraries = new List<LibrarySource> ();
private string [] available_export_fields;
private int open_indexers;
public event ActionHandler CollectionChanged;
public event ActionHandler CleanupAndShutdown;
private ActionHandler shutdown_handler;
public ActionHandler ShutdownHandler {
get { return shutdown_handler; }
set { shutdown_handler = value; }
}
public CollectionIndexerService ()
{
DBusConnection.Connect ("CollectionIndexer");
ServiceManager.SourceManager.SourceAdded += OnSourceAdded;
ServiceManager.SourceManager.SourceRemoved += OnSourceRemoved;
foreach (Source source in ServiceManager.SourceManager.Sources) {
MonitorLibrary (source as LibrarySource);
}
}
public void Dispose ()
{
while (libraries.Count > 0) {
UnmonitorLibrary (libraries[0]);
}
}
void ICollectionIndexerService.Hello ()
{
Hyena.Log.DebugFormat ("Hello called on {0}", GetType ());
}
public void Shutdown ()
{
lock (this) {
if (open_indexers == 0 && shutdown_handler != null) {
shutdown_handler ();
}
}
}
public void ForceShutdown ()
{
Dispose ();
if (shutdown_handler != null) {
shutdown_handler ();
}
}
public ICollectionIndexer CreateIndexer ()
{
lock (this) {
return new CollectionIndexer (null);
}
}
internal void DisposeIndexer (CollectionIndexer indexer)
{
lock (this) {
ServiceManager.DBusServiceManager.UnregisterObject (indexer);
open_indexers--;
}
}
ObjectPath ICollectionIndexerService.CreateIndexer ()
{
lock (this) {
ObjectPath path = ServiceManager.DBusServiceManager.RegisterObject (new CollectionIndexer (this));
open_indexers++;
return path;
}
}
public bool HasCollectionCountChanged (int count)
{
lock (this) {
int total_count = 0;
foreach (LibrarySource library in libraries) {
total_count += library.Count;
}
return count != total_count;
}
}
public bool HasCollectionLastModifiedChanged (long time)
{
lock (this) {
long last_updated = 0;
foreach (LibrarySource library in libraries) {
last_updated = Math.Max (last_updated, ServiceManager.DbConnection.Query<long> (
String.Format ("SELECT MAX(CoreTracks.DateUpdatedStamp) {0}",
library.DatabaseTrackModel.UnfilteredQuery)));
}
return last_updated > time;
}
}
public string [] GetAvailableExportFields ()
{
lock (this) {
if (available_export_fields != null) {
return available_export_fields;
}
List<string> fields = new List<string> ();
foreach (KeyValuePair<string, System.Reflection.PropertyInfo> field in TrackInfo.GetExportableProperties (
typeof (DatabaseTrackInfo))) {
fields.Add (field.Key);
}
available_export_fields = fields.ToArray ();
return available_export_fields;
}
}
private void MonitorLibrary (LibrarySource library)
{
if (library == null || !library.Indexable || libraries.Contains (library)) {
return;
}
libraries.Add (library);
library.TracksAdded += OnLibraryChanged;
library.TracksDeleted += OnLibraryChanged;
library.TracksChanged += OnLibraryChanged;
}
private void UnmonitorLibrary (LibrarySource library)
{
if (library == null || !libraries.Contains (library)) {
return;
}
library.TracksAdded -= OnLibraryChanged;
library.TracksDeleted -= OnLibraryChanged;
library.TracksChanged -= OnLibraryChanged;
libraries.Remove (library);
}
private void OnSourceAdded (SourceAddedArgs args)
{
MonitorLibrary (args.Source as LibrarySource);
}
private void OnSourceRemoved (SourceEventArgs args)
{
UnmonitorLibrary (args.Source as LibrarySource);
}
private void OnLibraryChanged (object o, TrackEventArgs args)
{
if (args.ChangedFields == null) {
OnCollectionChanged ();
return;
}
foreach (Hyena.Query.QueryField field in args.ChangedFields) {
if (field != Banshee.Query.BansheeQuery.LastPlayedField &&
field != Banshee.Query.BansheeQuery.LastSkippedField &&
field != Banshee.Query.BansheeQuery.PlayCountField &&
field != Banshee.Query.BansheeQuery.SkipCountField) {
OnCollectionChanged ();
return;
}
}
}
public void RequestCleanupAndShutdown ()
{
ActionHandler handler = CleanupAndShutdown;
if (handler != null) {
handler ();
}
}
private void OnCollectionChanged ()
{
ActionHandler handler = CollectionChanged;
if (handler != null) {
handler ();
}
}
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
string IService.ServiceName {
get { return "CollectionIndexerService"; }
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Portal.Runtime;
namespace Microsoft.Xrm.Portal.Web.UI.WebControls
{
/// <summary>
/// Coordinates loading of script dependencies for controls that request XRM inline editing support.
/// </summary>
[NonVisualControl, DefaultProperty("DependencyScripts"), ParseChildren(true), PersistChildren(false)]
public sealed class SiteEditingManager : WebControl
{
private ScriptReferenceCollection _dependencyScripts;
private StyleReferenceCollection _dependencyStyles;
private ScriptReferenceCollection _extensionScripts;
private StyleReferenceCollection _extensionStyles;
/// <summary>
/// Gets a collection of framework dependency <see cref="ScriptReference">script references</see> to be loaded prior
/// to the XRM inline editing scripts.
/// </summary>
/// <remarks>
/// These scripts will only be loaded if XRM inline editing support is requested by another control on the page.
/// </remarks>
[DefaultValue((string)null), PersistenceMode(PersistenceMode.InnerProperty), Category("Behavior"), MergableProperty(false)]
public ScriptReferenceCollection DependencyScripts
{
get
{
if (_dependencyScripts == null)
{
_dependencyScripts = new ScriptReferenceCollection();
}
return _dependencyScripts;
}
}
/// <summary>
/// Gets a collection of <see cref="StyleReference">style references</see> to be linked by the page if XRM inline
/// editing support is request by a control on the page.
/// </summary>
/// <remarks>
/// These styles will be loaded prior to any styles included by the framework.
/// </remarks>
[DefaultValue((string)null), PersistenceMode(PersistenceMode.InnerProperty), Category("Behavior"), MergableProperty(false)]
public StyleReferenceCollection DependencyStyles
{
get
{
if (_dependencyStyles == null)
{
_dependencyStyles = new StyleReferenceCollection();
}
return _dependencyStyles;
}
}
/// <summary>
/// Gets a collection of <see cref="ScriptReference">script references</see> to be loaded after the XRM inline
/// editing scripts.
/// </summary>
/// <remarks>
/// These scripts will only be loaded if XRM inline editing support is requested by another control on the page.
/// </remarks>
[DefaultValue((string)null), PersistenceMode(PersistenceMode.InnerProperty), Category("Behavior"), MergableProperty(false)]
public ScriptReferenceCollection ExtensionScripts
{
get
{
if (_extensionScripts == null)
{
_extensionScripts = new ScriptReferenceCollection();
}
return _extensionScripts;
}
}
/// <summary>
/// Gets a collection of <see cref="StyleReference">style references</see> to be linked by the page if XRM inline
/// editing support is request by a control on the page.
/// </summary>
/// <remarks>
/// These styles will be loaded after to any styles included by the framework.
/// </remarks>
[DefaultValue((string)null), PersistenceMode(PersistenceMode.InnerProperty), Category("Behavior"), MergableProperty(false)]
public StyleReferenceCollection ExtensionStyles
{
get
{
if (_extensionStyles == null)
{
_extensionStyles = new StyleReferenceCollection();
}
return _extensionStyles;
}
}
public string PortalName { get; set; }
public void RegisterClientSideDependencies(WebControl control)
{
RegisterScripts(control, DependencyScripts);
AddStyleReferencesToPage(control.Page, DependencyStyles);
var provider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<IRegisterClientSideDependenciesProvider>();
provider.Register(control);
RegisterScripts(control, ExtensionScripts);
AddStyleReferencesToPage(control.Page, ExtensionStyles);
}
private static void AddStyleReferencesToPage(Page page, StyleReferenceCollection styles)
{
if (page.Header == null)
{
return;
}
foreach (var style in styles)
{
if (string.IsNullOrEmpty(style.Path))
{
continue;
}
var path = style.Path;
if (ControlContainsStylesheetLink(page.Header, path))
{
continue;
}
var link = new HtmlLink { Href = path };
link.Attributes["rel"] = "stylesheet";
link.Attributes["type"] = "text/css";
if (!string.IsNullOrEmpty(style.Media))
{
link.Attributes["media"] = style.Media;
}
page.Header.Controls.Add(link);
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (DesignMode)
{
return;
}
var page = Page;
if (GetCurrent(page) != null)
{
throw new InvalidOperationException("Only one instance of a {0} can be added to the page.".FormatWith(typeof(SiteEditingManager).Name));
}
page.Items[typeof(SiteEditingManager)] = this;
}
public static SiteEditingManager GetCurrent(Page page)
{
page.ThrowOnNull("page");
return (page.Items[typeof(SiteEditingManager)] as SiteEditingManager);
}
private static void RegisterScripts(Control control, IEnumerable<ScriptReference> scripts)
{
if (!scripts.Any())
{
return;
}
var scriptManager = ScriptManager.GetCurrent(control.Page);
if (scriptManager == null)
{
throw new InvalidOperationException("{0} requires an instance of ScriptManager to exist on the page.".FormatWith(typeof(SiteEditingManager).Name));
}
foreach (var script in scripts)
{
scriptManager.Scripts.Add(script);
}
}
private static bool ControlContainsStylesheetLink(Control container, string stylesheetPath)
{
foreach (var control in container.Controls)
{
if (control is HtmlLink && (control as HtmlLink).Href == stylesheetPath)
{
return true;
}
}
return false;
}
}
[DefaultProperty("Path"), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public class StyleReference
{
private string _path;
[Category("Behavior"), DefaultValue("")]
public virtual string Media { get; set; }
[Category("Behavior"), UrlProperty("*.css"), DefaultValue("")]
public virtual string Path
{
get { return _path ?? string.Empty; }
set { _path = value; }
}
}
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public class StyleReferenceCollection : Collection<StyleReference> { }
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
private SafePipeHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _isAsync;
private bool _isMessageComplete;
private bool _isFromExistingHandle;
private bool _isHandleExposed;
private PipeTransmissionMode _readMode;
private PipeTransmissionMode _transmissionMode;
private PipeDirection _pipeDirection;
private int _outBufferSize;
private PipeState _state;
protected PipeStream(PipeDirection direction, int bufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, PipeTransmissionMode.Byte, bufferSize);
}
protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(transmissionMode), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (outBufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, transmissionMode, outBufferSize);
}
private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
// always defaults to this until overridden
_readMode = transmissionMode;
_transmissionMode = transmissionMode;
_pipeDirection = direction;
if ((_pipeDirection & PipeDirection.In) != 0)
{
_canRead = true;
}
if ((_pipeDirection & PipeDirection.Out) != 0)
{
_canWrite = true;
}
_outBufferSize = outBufferSize;
// This should always default to true
_isMessageComplete = true;
_state = PipeState.WaitingToConnect;
}
// Once a PipeStream has a handle ready, it should call this method to set up the PipeStream. If
// the pipe is in a connected state already, it should also set the IsConnected (protected) property.
// This method may also be called to uninitialize a handle, setting it to null.
[SecuritySafeCritical]
internal void InitializeHandle(SafePipeHandle handle, bool isExposed, bool isAsync)
{
if (isAsync && handle != null)
{
InitializeAsyncHandle(handle);
}
_handle = handle;
_isAsync = isAsync;
// track these separately; _isHandleExposed will get updated if accessed though the property
_isHandleExposed = isExposed;
_isFromExistingHandle = isExposed;
}
[SecurityCritical]
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (_isAsync)
{
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(buffer, offset, count);
}
[SecuritySafeCritical]
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckReadOperations();
if (!_isAsync)
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
UpdateMessageCompletion(false);
return s_zeroTask;
}
return ReadAsyncCore(buffer, offset, count, cancellationToken);
}
[SecurityCritical]
public override void Write(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
return;
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(buffer, offset, count);
}
[SecuritySafeCritical]
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (!_isAsync)
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
return Task.CompletedTask;
}
return WriteAsyncCore(buffer, offset, count, cancellationToken);
}
private void CheckReadWriteArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
[Conditional("DEBUG")]
private static void DebugAssertReadWriteArgs(byte[] buffer, int offset, int count, SafePipeHandle handle)
{
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(offset <= buffer.Length - count, "offset + count is too big");
Debug.Assert(handle != null, "handle is null");
Debug.Assert(!handle.IsClosed, "handle is closed");
}
[ThreadStatic]
private static byte[] t_singleByteArray;
private static byte[] SingleByteArray
{
get { return t_singleByteArray ?? (t_singleByteArray = new byte[1]); }
}
// Reads a byte from the pipe stream. Returns the byte cast to an int
// or -1 if the connection has been broken.
[SecurityCritical]
public override int ReadByte()
{
byte[] buffer = SingleByteArray;
return Read(buffer, 0, 1) > 0 ?
buffer[0] :
-1;
}
[SecurityCritical]
public override void WriteByte(byte value)
{
byte[] buffer = SingleByteArray;
buffer[0] = value;
Write(buffer, 0, 1);
}
// Does nothing on PipeStreams. We cannot call Interop.FlushFileBuffers here because we can deadlock
// if the other end of the pipe is no longer interested in reading from the pipe.
[SecurityCritical]
public override void Flush()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
}
[SecurityCritical]
protected override void Dispose(bool disposing)
{
try
{
// Nothing will be done differently based on whether we are
// disposing vs. finalizing.
if (_handle != null && !_handle.IsClosed)
{
_handle.Dispose();
}
UninitializeAsyncHandle();
}
finally
{
base.Dispose(disposing);
}
_state = PipeState.Closed;
}
// ********************** Public Properties *********************** //
// APIs use coarser definition of connected, but these map to internal
// Connected/Disconnected states. Note that setter is protected; only
// intended to be called by custom PipeStream concrete children
public bool IsConnected
{
get
{
return State == PipeState.Connected;
}
protected set
{
_state = (value) ? PipeState.Connected : PipeState.Disconnected;
}
}
public bool IsAsync
{
get { return _isAsync; }
}
// Set by the most recent call to Read or EndRead. Will be false if there are more buffer in the
// message, otherwise it is set to true.
public bool IsMessageComplete
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
// omitting pipe broken exception to allow reader to finish getting message
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
// don't need to check transmission mode; just care about read mode. Always use
// cached mode; otherwise could throw for valid message when other side is shutting down
if (_readMode != PipeTransmissionMode.Message)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeReadModeNotMessage);
}
return _isMessageComplete;
}
}
internal void UpdateMessageCompletion(bool completion)
{
// Set message complete to true because the pipe is broken as well.
// Need this to signal to readers to stop reading.
_isMessageComplete = (completion || _state == PipeState.Broken);
}
public SafePipeHandle SafePipeHandle
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if (_handle.IsClosed)
{
throw Error.GetPipeNotOpen();
}
_isHandleExposed = true;
return _handle;
}
}
internal SafePipeHandle InternalHandle
{
[SecurityCritical]
get
{
return _handle;
}
}
internal bool IsHandleExposed
{
get
{
return _isHandleExposed;
}
}
public override bool CanRead
{
[Pure]
get
{
return _canRead;
}
}
public override bool CanWrite
{
[Pure]
get
{
return _canWrite;
}
}
public override bool CanSeek
{
[Pure]
get
{
return false;
}
}
public override long Length
{
get
{
throw Error.GetSeekNotSupported();
}
}
public override long Position
{
get
{
throw Error.GetSeekNotSupported();
}
set
{
throw Error.GetSeekNotSupported();
}
}
public override void SetLength(long value)
{
throw Error.GetSeekNotSupported();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw Error.GetSeekNotSupported();
}
// anonymous pipe ends and named pipe server can get/set properties when broken
// or connected. Named client overrides
[SecurityCritical]
internal virtual void CheckPipePropertyOperations()
{
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Reads can be done in Connected and Broken. In the latter,
// read returns 0 bytes
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
internal void CheckReadOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Writes can only be done in connected state
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
internal void CheckWriteOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// IOException
if (_state == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
internal PipeState State
{
get
{
return _state;
}
set
{
_state = value;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.CognitiveServices
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for CognitiveServicesAccountsOperations.
/// </summary>
public static partial class CognitiveServicesAccountsOperationsExtensions
{
/// <summary>
/// Create Cognitive Services Account. Accounts is a resource group wide
/// resource type. It holds the keys for developer to access intelligent APIs.
/// It's also the resource type for billing.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
public static CognitiveServicesAccount Create(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CognitiveServicesAccountCreateParameters parameters)
{
return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create Cognitive Services Account. Accounts is a resource group wide
/// resource type. It holds the keys for developer to access intelligent APIs.
/// It's also the resource type for billing.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccount> CreateAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CognitiveServicesAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a Cognitive Services account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='sku'>
/// Gets or sets the SKU of the resource.
/// </param>
/// <param name='tags'>
/// Gets or sets a list of key value pairs that describe the resource. These
/// tags can be used in viewing and grouping this resource (across resource
/// groups). A maximum of 15 tags can be provided for a resource. Each tag must
/// have a key no greater than 128 characters and value no greater than 256
/// characters.
/// </param>
public static CognitiveServicesAccount Update(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, Sku sku = default(Sku), IDictionary<string, string> tags = default(IDictionary<string, string>))
{
return operations.UpdateAsync(resourceGroupName, accountName, sku, tags).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a Cognitive Services account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='sku'>
/// Gets or sets the SKU of the resource.
/// </param>
/// <param name='tags'>
/// Gets or sets a list of key value pairs that describe the resource. These
/// tags can be used in viewing and grouping this resource (across resource
/// groups). A maximum of 15 tags can be provided for a resource. Each tag must
/// have a key no greater than 128 characters and value no greater than 256
/// characters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccount> UpdateAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, Sku sku = default(Sku), IDictionary<string, string> tags = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, sku, tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a Cognitive Services account from the resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
public static void Delete(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName)
{
operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a Cognitive Services account from the resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Returns a Cognitive Services account specified by the parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
public static CognitiveServicesAccount GetProperties(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName)
{
return operations.GetPropertiesAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a Cognitive Services account specified by the parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccount> GetPropertiesAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the account keys for the specified Cognitive Services account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
public static CognitiveServicesAccountKeys ListKeys(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName)
{
return operations.ListKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the account keys for the specified Cognitive Services account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccountKeys> ListKeysAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the specified account key for the specified Cognitive Services
/// account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='keyName'>
/// key name to generate (Key1|Key2). Possible values include: 'Key1', 'Key2'
/// </param>
public static CognitiveServicesAccountKeys RegenerateKey(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, KeyName keyName)
{
return operations.RegenerateKeyAsync(resourceGroupName, accountName, keyName).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the specified account key for the specified Cognitive Services
/// account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='keyName'>
/// key name to generate (Key1|Key2). Possible values include: 'Key1', 'Key2'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccountKeys> RegenerateKeyAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, KeyName keyName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, keyName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List available SKUs for the requested Cognitive Services account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
public static CognitiveServicesAccountEnumerateSkusResult ListSkus(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName)
{
return operations.ListSkusAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// List available SKUs for the requested Cognitive Services account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccountEnumerateSkusResult> ListSkusAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListSkusWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
// Federico Di Gregorio <fog@initd.org>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
// Copyright (C) 2009 Federico Di Gregorio.
//
// 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.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
// ReSharper disable CheckNamespace
namespace Mono.Options
// ReSharper restore CheckNamespace
#endif
{
internal static class StringCoda
{
public static IEnumerable<string> WrappedLines(string self, params int[] widths)
{
IEnumerable<int> w = widths;
return WrappedLines(self, w);
}
public static IEnumerable<string> WrappedLines(string self, IEnumerable<int> widths)
{
if (widths == null)
{
throw new ArgumentNullException("widths");
}
return CreateWrappedLinesIterator(self, widths);
}
private static IEnumerable<string> CreateWrappedLinesIterator(string self, IEnumerable<int> widths)
{
if (string.IsNullOrEmpty(self))
{
yield return string.Empty;
yield break;
}
using (var ewidths = widths.GetEnumerator())
{
bool? hw = null;
var width = GetNextWidth(ewidths, int.MaxValue, ref hw);
int start = 0, end;
do
{
end = GetLineEnd(start, width, self);
var c = self[end - 1];
if (char.IsWhiteSpace(c))
{
--end;
}
var needContinuation = end != self.Length && !IsEolChar(c);
var continuation = "";
if (needContinuation)
{
--end;
continuation = "-";
}
var line = self.Substring(start, end - start) + continuation;
yield return line;
start = end;
if (char.IsWhiteSpace(c))
{
++start;
}
width = GetNextWidth(ewidths, width, ref hw);
} while (start < self.Length);
}
}
private static int GetNextWidth(IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
{
if (!eValid.HasValue || eValid.HasValue && eValid.Value)
{
curWidth = (eValid = ewidths.MoveNext()).Value ? ewidths.Current : curWidth;
// '.' is any character, - is for a continuation
const string minWidth = ".-";
if (curWidth < minWidth.Length)
{
throw new ArgumentOutOfRangeException("widths",
string.Format("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
}
return curWidth;
}
// no more elements, use the last element.
return curWidth;
}
private static bool IsEolChar(char c)
{
return !char.IsLetterOrDigit(c);
}
private static int GetLineEnd(int start, int length, string description)
{
var end = System.Math.Min(start + length, description.Length);
var sep = -1;
for (var i = start; i < end; ++i)
{
if (description[i] == '\n')
{
return i + 1;
}
if (IsEolChar(description[i]))
{
sep = i + 1;
}
}
if (sep == -1 || end == description.Length)
{
return end;
}
return sep;
}
}
public class OptionValueCollection : IList, IList<string>
{
private readonly List<string> values = new List<string>();
private readonly OptionContext c;
internal OptionValueCollection(OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo(Array array, int index)
{
(values as ICollection).CopyTo(array, index);
}
bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } }
object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } }
#endregion ICollection
#region ICollection<T>
public void Add(string item)
{
values.Add(item);
}
public void Clear()
{
values.Clear();
}
public bool Contains(string item)
{
return values.Contains(item);
}
public void CopyTo(string[] array, int arrayIndex)
{
values.CopyTo(array, arrayIndex);
}
public bool Remove(string item)
{
return values.Remove(item);
}
public int Count { get { return values.Count; } }
public bool IsReadOnly { get { return false; } }
#endregion ICollection<T>
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return values.GetEnumerator();
}
#endregion IEnumerable
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator()
{
return values.GetEnumerator();
}
#endregion IEnumerable<T>
#region IList
int IList.Add(object value)
{
return (values as IList).Add(value);
}
bool IList.Contains(object value)
{
return (values as IList).Contains(value);
}
int IList.IndexOf(object value)
{
return (values as IList).IndexOf(value);
}
void IList.Insert(int index, object value)
{
(values as IList).Insert(index, value);
}
void IList.Remove(object value)
{
(values as IList).Remove(value);
}
void IList.RemoveAt(int index)
{
(values as IList).RemoveAt(index);
}
bool IList.IsFixedSize { get { return false; } }
object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } }
#endregion IList
#region IList<T>
public int IndexOf(string item)
{
return values.IndexOf(item);
}
public void Insert(int index, string item)
{
values.Insert(index, item);
}
public void RemoveAt(int index)
{
values.RemoveAt(index);
}
private void AssertValid(int index)
{
if (c.Option == null)
{
throw new InvalidOperationException("OptionContext.Option is null.");
}
if (index >= c.Option.MaxValueCount)
{
throw new ArgumentOutOfRangeException("index");
}
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
{
throw new OptionException(string.Format(
c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
}
public string this[int index]
{
get
{
AssertValid(index);
return index >= values.Count ? null : values[index];
}
set
{
values[index] = value;
}
}
#endregion IList<T>
public List<string> ToList()
{
return new List<string>(values);
}
public string[] ToArray()
{
return values.ToArray();
}
public override string ToString()
{
return string.Join(", ", values.ToArray());
}
}
public class OptionContext
{
private Option option;
private string name;
private int index;
private readonly OptionSet set;
private readonly OptionValueCollection c;
public OptionContext(OptionSet set)
{
this.set = set;
c = new OptionValueCollection(this);
}
public Option Option
{
get { return option; }
set { option = value; }
}
public string OptionName
{
get { return name; }
set { name = value; }
}
public int OptionIndex
{
get { return index; }
set { index = value; }
}
public OptionSet OptionSet
{
get { return set; }
}
public OptionValueCollection OptionValues
{
get { return c; }
}
}
public enum OptionValueType
{
None,
Optional,
Required,
}
public abstract class Option
{
private readonly string prototype;
private readonly string description;
private readonly string[] names;
private readonly OptionValueType type;
private readonly int count;
private string[] separators;
protected Option(string prototype, string description)
: this(prototype, description, 1)
{
}
protected Option(string prototype, string description, int maxValueCount)
{
if (prototype == null)
{
throw new ArgumentNullException("prototype");
}
if (prototype.Length == 0)
{
throw new ArgumentException("Cannot be the empty string.", "prototype");
}
if (maxValueCount < 0)
{
throw new ArgumentOutOfRangeException("maxValueCount");
}
this.prototype = prototype;
this.description = description;
count = maxValueCount;
names = this is OptionSet.Category
// append GetHashCode() so that "duplicate" categories have distinct
// names, e.g. adding multiple "" categories should be valid.
? new[] { prototype + GetHashCode() }
: prototype.Split('|');
if (this is OptionSet.Category)
{
return;
}
type = ParsePrototype();
if (count == 0 && type != OptionValueType.None)
{
throw new ArgumentException(
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
}
if (type == OptionValueType.None && maxValueCount > 1)
{
throw new ArgumentException(
string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
}
if (Array.IndexOf(names, "<>") >= 0 &&
(names.Length == 1 && type != OptionValueType.None ||
names.Length > 1 && MaxValueCount > 1))
{
throw new ArgumentException(
"The default option handler '<>' cannot require values.",
"prototype");
}
}
public string Prototype { get { return prototype; } }
public string Description { get { return description; } }
public OptionValueType OptionValueType { get { return type; } }
public int MaxValueCount { get { return count; } }
public string[] GetNames()
{
return (string[])names.Clone();
}
public string[] GetValueSeparators()
{
if (separators == null)
{
return new string[0];
}
return (string[])separators.Clone();
}
protected static T Parse<T>(string value, OptionContext c)
{
var tt = typeof(T);
var nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition() == typeof(Nullable<>);
var targetType = nullable ? tt.GetGenericArguments()[0] : typeof(T);
var conv = TypeDescriptor.GetConverter(targetType);
var t = default(T);
try
{
if (value != null)
{
t = (T)conv.ConvertFromString(value);
}
}
catch (Exception e)
{
throw new OptionException(
string.Format(
c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names { get { return names; } }
internal string[] ValueSeparators { get { return separators; } }
private static readonly char[] NameTerminator = new char[] { '=', ':' };
private OptionValueType ParsePrototype()
{
var type = '\0';
var seps = new List<string>();
for (var i = 0; i < names.Length; ++i)
{
var name = names[i];
if (name.Length == 0)
{
throw new ArgumentException("Empty option names are not supported.", "prototype");
}
var end = name.IndexOfAny(NameTerminator);
if (end == -1)
{
continue;
}
names[i] = name.Substring(0, end);
if (type == '\0' || type == name[end])
{
type = name[end];
}
else
{
throw new ArgumentException(
string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]),
"prototype");
}
AddSeparators(name, end, seps);
}
if (type == '\0')
{
return OptionValueType.None;
}
if (count <= 1 && seps.Count != 0)
{
throw new ArgumentException(
string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
}
if (count > 1)
{
if (seps.Count == 0)
{
separators = new string[] { ":", "=" };
}
else if (seps.Count == 1 && seps[0].Length == 0)
{
separators = null;
}
else
{
separators = seps.ToArray();
}
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators(string name, int end, ICollection<string> seps)
{
var start = -1;
for (var i = end + 1; i < name.Length; ++i)
{
switch (name[i])
{
case '{':
if (start != -1)
{
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
start = i + 1;
break;
case '}':
if (start == -1)
{
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
seps.Add(name.Substring(start, i - start));
start = -1;
break;
default:
if (start == -1)
{
seps.Add(name[i].ToString());
}
break;
}
}
if (start != -1)
{
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
}
public void Invoke(OptionContext c)
{
OnParseComplete(c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear();
}
protected abstract void OnParseComplete(OptionContext c);
public override string ToString()
{
return Prototype;
}
}
public abstract class ArgumentSource
{
protected ArgumentSource()
{
}
public abstract string[] GetNames();
public abstract string Description { get; }
public abstract bool GetArguments(string value, out IEnumerable<string> replacement);
public static IEnumerable<string> GetArgumentsFromFile(string file)
{
return GetArguments(File.OpenText(file), true);
}
public static IEnumerable<string> GetArguments(TextReader reader)
{
return GetArguments(reader, false);
}
// Cribbed from mcs/driver.cs:LoadArgs(string)
private static IEnumerable<string> GetArguments(TextReader reader, bool close)
{
try
{
var arg = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
var t = line.Length;
for (var i = 0; i < t; i++)
{
var c = line[i];
if (c == '"' || c == '\'')
{
var end = c;
for (i++; i < t; i++)
{
c = line[i];
if (c == end)
{
break;
}
arg.Append(c);
}
}
else if (c == ' ')
{
if (arg.Length > 0)
{
yield return arg.ToString();
arg.Length = 0;
}
}
else
{
arg.Append(c);
}
}
if (arg.Length > 0)
{
yield return arg.ToString();
arg.Length = 0;
}
}
}
finally
{
if (close)
{
reader.Close();
}
}
}
}
public class ResponseFileSource : ArgumentSource
{
public override string[] GetNames()
{
return new string[] { "@file" };
}
public override string Description
{
get { return "Read response file for more options."; }
}
public override bool GetArguments(string value, out IEnumerable<string> replacement)
{
if (string.IsNullOrEmpty(value) || !value.StartsWith("@"))
{
replacement = null;
return false;
}
replacement = GetArgumentsFromFile(value.Substring(1));
return true;
}
}
[Serializable]
public class OptionException : Exception
{
private readonly string option;
public OptionException()
{
}
public OptionException(string message, string optionName)
: base(message)
{
option = optionName;
}
public OptionException(string message, string optionName, Exception innerException)
: base(message, innerException)
{
option = optionName;
}
protected OptionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
option = info.GetString("OptionName");
}
public string OptionName
{
get { return option; }
}
[SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue>(TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet()
: this(delegate (string f) { return f; })
{
}
public OptionSet(Converter<string, string> localizer)
{
this.localizer = localizer;
roSources = new ReadOnlyCollection<ArgumentSource>(sources);
}
private readonly Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer
{
get { return localizer; }
}
private readonly List<ArgumentSource> sources = new List<ArgumentSource>();
private readonly ReadOnlyCollection<ArgumentSource> roSources;
public ReadOnlyCollection<ArgumentSource> ArgumentSources
{
get { return roSources; }
}
protected override string GetKeyForItem(Option item)
{
if (item == null)
{
throw new ArgumentNullException("option");
}
if (item.Names != null && item.Names.Length > 0)
{
return item.Names[0];
}
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException("Option has no names!");
}
[Obsolete("Use KeyedCollection.this[string]")]
protected Option GetOptionForName(string option)
{
if (option == null)
{
throw new ArgumentNullException("option");
}
try
{
return base[option];
}
catch (KeyNotFoundException)
{
return null;
}
}
protected override void InsertItem(int index, Option item)
{
base.InsertItem(index, item);
AddImpl(item);
}
protected override void RemoveItem(int index)
{
var p = Items[index];
base.RemoveItem(index);
// KeyedCollection.RemoveItem() handles the 0th item
for (var i = 1; i < p.Names.Length; ++i)
{
Dictionary.Remove(p.Names[i]);
}
}
protected override void SetItem(int index, Option item)
{
base.SetItem(index, item);
AddImpl(item);
}
private void AddImpl(Option option)
{
if (option == null)
{
throw new ArgumentNullException("option");
}
var added = new List<string>(option.Names.Length);
try
{
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (var i = 1; i < option.Names.Length; ++i)
{
Dictionary.Add(option.Names[i], option);
added.Add(option.Names[i]);
}
}
catch (Exception)
{
foreach (var name in added)
{
Dictionary.Remove(name);
}
throw;
}
}
public OptionSet Add(string header)
{
if (header == null)
{
throw new ArgumentNullException("header");
}
Add(new Category(header));
return this;
}
internal sealed class Category : Option
{
// Prototype starts with '=' because this is an invalid prototype
// (see Option.ParsePrototype(), and thus it'll prevent Category
// instances from being accidentally used as normal options.
public Category(string description)
: base("=:Category:= " + description, description)
{
}
protected override void OnParseComplete(OptionContext c)
{
throw new NotSupportedException("Category.OnParseComplete should not be invoked.");
}
}
public new OptionSet Add(Option option)
{
base.Add(option);
return this;
}
private sealed class ActionOption : Option
{
private readonly Action<OptionValueCollection> action;
public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action)
: base(prototype, description, count)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(c.OptionValues);
}
}
public OptionSet Add(string prototype, Action<string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, Action<string> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
Option p = new ActionOption(prototype, description, 1,
delegate (OptionValueCollection v) { action(v[0]); });
base.Add(p);
return this;
}
public OptionSet Add(string prototype, OptionAction<string, string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
Option p = new ActionOption(prototype, description, 2,
delegate (OptionValueCollection v) { action(v[0], v[1]); });
base.Add(p);
return this;
}
private sealed class ActionOption<T> : Option
{
private readonly Action<T> action;
public ActionOption(string prototype, string description, Action<T> action)
: base(prototype, description, 1)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(Parse<T>(c.OptionValues[0], c));
}
}
private sealed class ActionOption<TKey, TValue> : Option
{
private readonly OptionAction<TKey, TValue> action;
public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action)
: base(prototype, description, 2)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(
Parse<TKey>(c.OptionValues[0], c),
Parse<TValue>(c.OptionValues[1], c));
}
}
public OptionSet Add<T>(string prototype, Action<T> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<T>(string prototype, string description, Action<T> action)
{
return Add(new ActionOption<T>(prototype, description, action));
}
public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add(new ActionOption<TKey, TValue>(prototype, description, action));
}
public OptionSet Add(ArgumentSource source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
sources.Add(source);
return this;
}
protected virtual OptionContext CreateOptionContext()
{
return new OptionContext(this);
}
public List<string> Parse(IEnumerable<string> arguments)
{
if (arguments == null)
{
throw new ArgumentNullException("arguments");
}
var c = CreateOptionContext();
c.OptionIndex = -1;
var process = true;
var unprocessed = new List<string>();
var def = Contains("<>") ? this["<>"] : null;
var ae = new ArgumentEnumerator(arguments);
foreach (var argument in ae)
{
++c.OptionIndex;
if (argument == "--")
{
process = false;
continue;
}
if (!process)
{
Unprocessed(unprocessed, def, c, argument);
continue;
}
if (AddSource(ae, argument))
{
continue;
}
if (!Parse(argument, c))
{
Unprocessed(unprocessed, def, c, argument);
}
}
if (c.Option != null)
{
c.Option.Invoke(c);
}
return unprocessed;
}
private class ArgumentEnumerator : IEnumerable<string>
{
private readonly List<IEnumerator<string>> sources = new List<IEnumerator<string>>();
public ArgumentEnumerator(IEnumerable<string> arguments)
{
sources.Add(arguments.GetEnumerator());
}
public void Add(IEnumerable<string> arguments)
{
sources.Add(arguments.GetEnumerator());
}
public IEnumerator<string> GetEnumerator()
{
do
{
var c = sources[sources.Count - 1];
if (c.MoveNext())
{
yield return c.Current;
}
else
{
c.Dispose();
sources.RemoveAt(sources.Count - 1);
}
} while (sources.Count > 0);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
private bool AddSource(ArgumentEnumerator ae, string argument)
{
foreach (var source in sources)
{
if (!source.GetArguments(argument, out IEnumerable<string> replacement))
{
continue;
}
ae.Add(replacement);
return true;
}
return false;
}
private static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null)
{
extra.Add(argument);
return false;
}
c.OptionValues.Add(argument);
c.Option = def;
c.Option.Invoke(c);
return false;
}
private readonly Regex ValueOption = new Regex(
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
{
throw new ArgumentNullException("argument");
}
flag = name = sep = value = null;
var m = ValueOption.Match(argument);
if (!m.Success)
{
return false;
}
flag = m.Groups["flag"].Value;
name = m.Groups["name"].Value;
if (m.Groups["sep"].Success && m.Groups["value"].Success)
{
sep = m.Groups["sep"].Value;
value = m.Groups["value"].Value;
}
return true;
}
protected virtual bool Parse(string argument, OptionContext c)
{
if (c.Option != null)
{
ParseValue(argument, c);
return true;
}
if (!GetOptionParts(argument, out string f, out string n, out string s, out string v))
{
return false;
}
Option p;
if (Contains(n))
{
p = this[n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType)
{
case OptionValueType.None:
c.OptionValues.Add(n);
c.Option.Invoke(c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue(v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool(argument, n, c))
{
return true;
}
// is it a bundled option?
if (ParseBundledValue(f, string.Concat(n + s + v), c))
{
return true;
}
return false;
}
private void ParseValue(string option, OptionContext c)
{
if (option != null)
{
foreach (var o in c.Option.ValueSeparators != null
? option.Split(c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
: new string[] { option })
{
c.OptionValues.Add(o);
}
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
{
c.Option.Invoke(c);
}
else if (c.OptionValues.Count > c.Option.MaxValueCount)
{
throw new OptionException(localizer(string.Format(
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool(string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') &&
Contains(rn = n.Substring(0, n.Length - 1)))
{
p = this[rn];
var v = n[n.Length - 1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add(v);
p.Invoke(c);
return true;
}
return false;
}
private bool ParseBundledValue(string f, string n, OptionContext c)
{
if (f != "-")
{
return false;
}
for (var i = 0; i < n.Length; ++i)
{
Option p;
var opt = f + n[i].ToString();
var rn = n[i].ToString();
if (!Contains(rn))
{
if (i == 0)
{
return false;
}
throw new OptionException(string.Format(localizer(
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this[rn];
switch (p.OptionValueType)
{
case OptionValueType.None:
Invoke(c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
{
var v = n.Substring(i + 1);
c.Option = p;
c.OptionName = opt;
ParseValue(v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke(OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add(value);
option.Invoke(c);
}
private const int OptionWidth = 29;
private const int Description_FirstWidth = 80 - OptionWidth;
private const int Description_RemWidth = 80 - OptionWidth - 2;
public void WriteOptionDescriptions(TextWriter o)
{
foreach (var p in this)
{
var written = 0;
var c = p as Category;
if (c != null)
{
WriteDescription(o, p.Description, "", 80, 80);
continue;
}
if (!WriteOptionPrototype(o, p, ref written))
{
continue;
}
if (written < OptionWidth)
{
o.Write(new string(' ', OptionWidth - written));
}
else
{
o.WriteLine();
o.Write(new string(' ', OptionWidth));
}
WriteDescription(o, p.Description, new string(' ', OptionWidth + 2),
Description_FirstWidth, Description_RemWidth);
}
foreach (var s in sources)
{
var names = s.GetNames();
if (names == null || names.Length == 0)
{
continue;
}
var written = 0;
Write(o, ref written, " ");
Write(o, ref written, names[0]);
for (var i = 1; i < names.Length; ++i)
{
Write(o, ref written, ", ");
Write(o, ref written, names[i]);
}
if (written < OptionWidth)
{
o.Write(new string(' ', OptionWidth - written));
}
else
{
o.WriteLine();
o.Write(new string(' ', OptionWidth));
}
WriteDescription(o, s.Description, new string(' ', OptionWidth + 2),
Description_FirstWidth, Description_RemWidth);
}
}
private void WriteDescription(TextWriter o, string value, string prefix, int firstWidth, int remWidth)
{
var indent = false;
foreach (var line in GetLines(localizer(GetDescription(value)), firstWidth, remWidth))
{
if (indent)
{
o.Write(prefix);
}
o.WriteLine(line);
indent = true;
}
}
private bool WriteOptionPrototype(TextWriter o, Option p, ref int written)
{
var names = p.Names;
var i = GetNextOptionIndex(names, 0);
if (i == names.Length)
{
return false;
}
if (names[i].Length == 1)
{
Write(o, ref written, " -");
Write(o, ref written, names[0]);
}
else
{
Write(o, ref written, " --");
Write(o, ref written, names[0]);
}
for (i = GetNextOptionIndex(names, i + 1);
i < names.Length; i = GetNextOptionIndex(names, i + 1))
{
Write(o, ref written, ", ");
Write(o, ref written, names[i].Length == 1 ? "-" : "--");
Write(o, ref written, names[i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required)
{
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("["));
}
Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description)));
var sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators[0]
: " ";
for (var c = 1; c < p.MaxValueCount; ++c)
{
Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("]"));
}
}
return true;
}
private static int GetNextOptionIndex(string[] names, int i)
{
while (i < names.Length && names[i] == "<>")
{
++i;
}
return i;
}
private static void Write(TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write(s);
}
private static string GetArgumentName(int index, int maxIndex, string description)
{
if (description == null)
{
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
string[] nameStart;
if (maxIndex == 1)
{
nameStart = new string[] { "{0:", "{" };
}
else
{
nameStart = new string[] { "{" + index + ":" };
}
for (var i = 0; i < nameStart.Length; ++i)
{
int start, j = 0;
do
{
start = description.IndexOf(nameStart[i], j);
} while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false);
if (start == -1)
{
continue;
}
var end = description.IndexOf("}", start);
if (end == -1)
{
continue;
}
return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription(string description)
{
if (description == null)
{
return string.Empty;
}
var sb = new StringBuilder(description.Length);
var start = -1;
for (var i = 0; i < description.Length; ++i)
{
switch (description[i])
{
case '{':
if (i == start)
{
sb.Append('{');
start = -1;
}
else if (start < 0)
{
start = i + 1;
}
break;
case '}':
if (start < 0)
{
if (i + 1 == description.Length || description[i + 1] != '}')
{
throw new InvalidOperationException("Invalid option description: " + description);
}
++i;
sb.Append("}");
}
else
{
sb.Append(description.Substring(start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
{
goto default;
}
start = i + 1;
break;
default:
if (start < 0)
{
sb.Append(description[i]);
}
break;
}
}
return sb.ToString();
}
private static IEnumerable<string> GetLines(string description, int firstWidth, int remWidth)
{
return StringCoda.WrappedLines(description, firstWidth, remWidth);
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for LabsOperations.
/// </summary>
public static partial class LabsOperationsExtensions
{
/// <summary>
/// List labs in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<Lab> ListBySubscription(this ILabsOperations operations, ODataQuery<Lab> odataQuery = default(ODataQuery<Lab>))
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).ListBySubscriptionAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List labs in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Lab>> ListBySubscriptionAsync(this ILabsOperations operations, ODataQuery<Lab> odataQuery = default(ODataQuery<Lab>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List labs in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<Lab> ListByResourceGroup(this ILabsOperations operations, ODataQuery<Lab> odataQuery = default(ODataQuery<Lab>))
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).ListByResourceGroupAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List labs in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Lab>> ListByResourceGroupAsync(this ILabsOperations operations, ODataQuery<Lab> odataQuery = default(ODataQuery<Lab>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example:
/// 'properties($select=defaultStorageAccount)'
/// </param>
public static Lab Get(this ILabsOperations operations, string name, string expand = default(string))
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).GetAsync(name, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example:
/// 'properties($select=defaultStorageAccount)'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Lab> GetAsync(this ILabsOperations operations, string name, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(name, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing lab. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
public static Lab CreateOrUpdate(this ILabsOperations operations, string name, Lab lab)
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).CreateOrUpdateAsync(name, lab), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing lab. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Lab> CreateOrUpdateAsync(this ILabsOperations operations, string name, Lab lab, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(name, lab, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing lab. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
public static Lab BeginCreateOrUpdate(this ILabsOperations operations, string name, Lab lab)
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).BeginCreateOrUpdateAsync(name, lab), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing lab. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Lab> BeginCreateOrUpdateAsync(this ILabsOperations operations, string name, Lab lab, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(name, lab, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete lab. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
public static void Delete(this ILabsOperations operations, string name)
{
Task.Factory.StartNew(s => ((ILabsOperations)s).DeleteAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete lab. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ILabsOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete lab. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
public static void BeginDelete(this ILabsOperations operations, string name)
{
Task.Factory.StartNew(s => ((ILabsOperations)s).BeginDeleteAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete lab. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this ILabsOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Modify properties of labs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
public static Lab Update(this ILabsOperations operations, string name, LabFragment lab)
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).UpdateAsync(name, lab), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Modify properties of labs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Lab> UpdateAsync(this ILabsOperations operations, string name, LabFragment lab, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(name, lab, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Claim a random claimable virtual machine in the lab. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
public static void ClaimAnyVm(this ILabsOperations operations, string name)
{
Task.Factory.StartNew(s => ((ILabsOperations)s).ClaimAnyVmAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Claim a random claimable virtual machine in the lab. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ClaimAnyVmAsync(this ILabsOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ClaimAnyVmWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Claim a random claimable virtual machine in the lab. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
public static void BeginClaimAnyVm(this ILabsOperations operations, string name)
{
Task.Factory.StartNew(s => ((ILabsOperations)s).BeginClaimAnyVmAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Claim a random claimable virtual machine in the lab. This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginClaimAnyVmAsync(this ILabsOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginClaimAnyVmWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create virtual machines in a lab. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='labVirtualMachineCreationParameter'>
/// Properties for creating a virtual machine.
/// </param>
public static void CreateEnvironment(this ILabsOperations operations, string name, LabVirtualMachineCreationParameter labVirtualMachineCreationParameter)
{
Task.Factory.StartNew(s => ((ILabsOperations)s).CreateEnvironmentAsync(name, labVirtualMachineCreationParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create virtual machines in a lab. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='labVirtualMachineCreationParameter'>
/// Properties for creating a virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateEnvironmentAsync(this ILabsOperations operations, string name, LabVirtualMachineCreationParameter labVirtualMachineCreationParameter, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.CreateEnvironmentWithHttpMessagesAsync(name, labVirtualMachineCreationParameter, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create virtual machines in a lab. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='labVirtualMachineCreationParameter'>
/// Properties for creating a virtual machine.
/// </param>
public static void BeginCreateEnvironment(this ILabsOperations operations, string name, LabVirtualMachineCreationParameter labVirtualMachineCreationParameter)
{
Task.Factory.StartNew(s => ((ILabsOperations)s).BeginCreateEnvironmentAsync(name, labVirtualMachineCreationParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create virtual machines in a lab. This operation can take a while to
/// complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='labVirtualMachineCreationParameter'>
/// Properties for creating a virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginCreateEnvironmentAsync(this ILabsOperations operations, string name, LabVirtualMachineCreationParameter labVirtualMachineCreationParameter, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginCreateEnvironmentWithHttpMessagesAsync(name, labVirtualMachineCreationParameter, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Exports the lab resource usage into a storage account This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='exportResourceUsageParameters'>
/// The parameters of the export operation.
/// </param>
public static void ExportResourceUsage(this ILabsOperations operations, string name, ExportResourceUsageParameters exportResourceUsageParameters)
{
Task.Factory.StartNew(s => ((ILabsOperations)s).ExportResourceUsageAsync(name, exportResourceUsageParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Exports the lab resource usage into a storage account This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='exportResourceUsageParameters'>
/// The parameters of the export operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ExportResourceUsageAsync(this ILabsOperations operations, string name, ExportResourceUsageParameters exportResourceUsageParameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ExportResourceUsageWithHttpMessagesAsync(name, exportResourceUsageParameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Exports the lab resource usage into a storage account This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='exportResourceUsageParameters'>
/// The parameters of the export operation.
/// </param>
public static void BeginExportResourceUsage(this ILabsOperations operations, string name, ExportResourceUsageParameters exportResourceUsageParameters)
{
Task.Factory.StartNew(s => ((ILabsOperations)s).BeginExportResourceUsageAsync(name, exportResourceUsageParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Exports the lab resource usage into a storage account This operation can
/// take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='exportResourceUsageParameters'>
/// The parameters of the export operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginExportResourceUsageAsync(this ILabsOperations operations, string name, ExportResourceUsageParameters exportResourceUsageParameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginExportResourceUsageWithHttpMessagesAsync(name, exportResourceUsageParameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Generate a URI for uploading custom disk images to a Lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='generateUploadUriParameter'>
/// Properties for generating an upload URI.
/// </param>
public static GenerateUploadUriResponse GenerateUploadUri(this ILabsOperations operations, string name, GenerateUploadUriParameter generateUploadUriParameter)
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).GenerateUploadUriAsync(name, generateUploadUriParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Generate a URI for uploading custom disk images to a Lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='generateUploadUriParameter'>
/// Properties for generating an upload URI.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GenerateUploadUriResponse> GenerateUploadUriAsync(this ILabsOperations operations, string name, GenerateUploadUriParameter generateUploadUriParameter, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GenerateUploadUriWithHttpMessagesAsync(name, generateUploadUriParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List disk images available for custom image creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
public static IPage<LabVhd> ListVhds(this ILabsOperations operations, string name)
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).ListVhdsAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List disk images available for custom image creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LabVhd>> ListVhdsAsync(this ILabsOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVhdsWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List labs in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Lab> ListBySubscriptionNext(this ILabsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).ListBySubscriptionNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List labs in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Lab>> ListBySubscriptionNextAsync(this ILabsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List labs in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Lab> ListByResourceGroupNext(this ILabsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List labs in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Lab>> ListByResourceGroupNextAsync(this ILabsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List disk images available for custom image creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<LabVhd> ListVhdsNext(this ILabsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ILabsOperations)s).ListVhdsNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List disk images available for custom image creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LabVhd>> ListVhdsNextAsync(this ILabsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVhdsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
#nullable enable
namespace Ignitor
{
public class BlazorClient : IAsyncDisposable
{
private const string MarkerPattern = ".*?<!--Blazor:(.*?)-->.*?";
private HubConnection? _hubConnection;
public BlazorClient()
{
CancellationTokenSource = new CancellationTokenSource();
CancellationToken = CancellationTokenSource.Token;
TaskCompletionSource = new TaskCompletionSource<object?>();
CancellationTokenSource.Token.Register(() =>
{
TaskCompletionSource.TrySetCanceled();
});
}
public TimeSpan? DefaultConnectionTimeout { get; set; } = Debugger.IsAttached ?
Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(20);
public TimeSpan? DefaultOperationTimeout { get; set; } = Debugger.IsAttached ?
Timeout.InfiniteTimeSpan : TimeSpan.FromMilliseconds(500);
/// <summary>
/// Gets or sets a value that determines whether the client will capture data such
/// as render batches, interop calls, and errors for later inspection.
/// </summary>
public bool CaptureOperations { get; set; }
/// <summary>
/// Gets the collections of operation results that are captured when <see cref="CaptureOperations"/>
/// is true.
/// </summary>
public Operations Operations { get; } = new Operations();
public Func<string, Exception>? FormatError { get; set; }
private CancellationTokenSource CancellationTokenSource { get; }
private CancellationToken CancellationToken { get; }
private TaskCompletionSource<object?> TaskCompletionSource { get; }
private CancellableOperation<CapturedAttachComponentCall>? NextAttachComponentReceived { get; set; }
private CancellableOperation<CapturedRenderBatch?>? NextBatchReceived { get; set; }
private CancellableOperation<string?>? NextErrorReceived { get; set; }
private CancellableOperation<Exception?>? NextDisconnect { get; set; }
private CancellableOperation<CapturedJSInteropCall?>? NextJSInteropReceived { get; set; }
private CancellableOperation<string?>? NextDotNetInteropCompletionReceived { get; set; }
public ILoggerProvider LoggerProvider { get; set; } = NullLoggerProvider.Instance;
public bool ConfirmRenderBatch { get; set; } = true;
public event Action<CapturedJSInteropCall>? JSInterop;
public event Action<CapturedRenderBatch>? RenderBatchReceived;
public event Action<string>? DotNetInteropCompletion;
public event Action<string>? OnCircuitError;
public string? CircuitId { get; private set; }
public ElementHive Hive { get; } = new ElementHive();
public bool ImplicitWait => DefaultOperationTimeout != null;
public HubConnection HubConnection => _hubConnection ?? throw new InvalidOperationException("HubConnection has not been initialized.");
public Task<CapturedRenderBatch?> PrepareForNextBatch(TimeSpan? timeout)
{
if (NextBatchReceived != null && !NextBatchReceived.Disposed)
{
throw new InvalidOperationException("Invalid state previous task not completed");
}
NextBatchReceived = new CancellableOperation<CapturedRenderBatch?>(timeout, CancellationToken);
return NextBatchReceived.Completion.Task;
}
public Task<CapturedJSInteropCall?> PrepareForNextJSInterop(TimeSpan? timeout)
{
if (NextJSInteropReceived != null && !NextJSInteropReceived.Disposed)
{
throw new InvalidOperationException("Invalid state previous task not completed");
}
NextJSInteropReceived = new CancellableOperation<CapturedJSInteropCall?>(timeout, CancellationToken);
return NextJSInteropReceived.Completion.Task;
}
public Task<string?> PrepareForNextDotNetInterop(TimeSpan? timeout)
{
if (NextDotNetInteropCompletionReceived != null && !NextDotNetInteropCompletionReceived.Disposed)
{
throw new InvalidOperationException("Invalid state previous task not completed");
}
NextDotNetInteropCompletionReceived = new CancellableOperation<string?>(timeout, CancellationToken);
return NextDotNetInteropCompletionReceived.Completion.Task;
}
public Task<string?> PrepareForNextCircuitError(TimeSpan? timeout)
{
if (NextErrorReceived != null && !NextErrorReceived.Disposed)
{
throw new InvalidOperationException("Invalid state previous task not completed");
}
NextErrorReceived = new CancellableOperation<string?>(timeout, CancellationToken);
return NextErrorReceived.Completion.Task;
}
public Task<Exception?> PrepareForNextDisconnect(TimeSpan? timeout)
{
if (NextDisconnect != null && !NextDisconnect.Disposed)
{
throw new InvalidOperationException("Invalid state previous task not completed");
}
NextDisconnect = new CancellableOperation<Exception?>(timeout, CancellationToken);
return NextDisconnect.Completion.Task;
}
public Task ClickAsync(string elementId, bool expectRenderBatch = true)
{
if (!Hive.TryFindElementById(elementId, out var elementNode))
{
throw new InvalidOperationException($"Could not find element with id {elementId}.");
}
if (expectRenderBatch)
{
return ExpectRenderBatch(() => elementNode.ClickAsync(this));
}
else
{
return elementNode.ClickAsync(this);
}
}
public Task SelectAsync(string elementId, string value)
{
if (!Hive.TryFindElementById(elementId, out var elementNode))
{
throw new InvalidOperationException($"Could not find element with id {elementId}.");
}
return ExpectRenderBatch(() => elementNode.SelectAsync(this, value));
}
public Task DispatchEventAsync(object descriptor, EventArgs eventArgs)
{
var attachWebRendererInteropCall = Operations.JSInteropCalls.FirstOrDefault(c => c.Identifier == "Blazor._internal.attachWebRendererInterop");
if (attachWebRendererInteropCall is null)
{
throw new InvalidOperationException("The server has not yet attached interop methods, so events cannot be dispatched.");
}
var args = JsonSerializer.Deserialize<JsonElement>(attachWebRendererInteropCall.ArgsJson);
var dotNetObjectRef = args.EnumerateArray().Skip(1).First();
var dotNetObjectId = dotNetObjectRef.GetProperty("__dotNetObject").GetInt32();
return InvokeDotNetMethod(
null,
null,
"DispatchEventAsync",
dotNetObjectId,
JsonSerializer.Serialize(new object[] { descriptor, eventArgs }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }));
}
public async Task<CapturedRenderBatch?> ExpectRenderBatch(Func<Task> action, TimeSpan? timeout = null)
{
var task = WaitForRenderBatch(timeout);
await action();
return await task;
}
public async Task<CapturedJSInteropCall?> ExpectJSInterop(Func<Task> action, TimeSpan? timeout = null)
{
var task = WaitForJSInterop(timeout);
await action();
return await task;
}
public async Task<string?> ExpectDotNetInterop(Func<Task> action, TimeSpan? timeout = null)
{
var task = WaitForDotNetInterop(timeout);
await action();
return await task;
}
public async Task<string?> ExpectCircuitError(Func<Task> action, TimeSpan? timeout = null)
{
var task = WaitForCircuitError(timeout);
await action();
return await task;
}
public async Task<Exception?> ExpectDisconnect(Func<Task> action, TimeSpan? timeout = null)
{
var task = WaitForDisconnect(timeout);
await action();
return await task;
}
public async Task<(string? error, Exception? exception)> ExpectCircuitErrorAndDisconnect(Func<Task> action, TimeSpan? timeout = null)
{
string? error = default;
// NOTE: timeout is used for each operation individually.
var exception = await ExpectDisconnect(async () =>
{
error = await ExpectCircuitError(action, timeout);
}, timeout);
return (error, exception);
}
private async Task<CapturedRenderBatch?> WaitForRenderBatch(TimeSpan? timeout = null)
{
if (ImplicitWait)
{
if (DefaultOperationTimeout == null && timeout == null)
{
throw new InvalidOperationException("Implicit wait without DefaultLatencyTimeout is not allowed.");
}
try
{
return await PrepareForNextBatch(timeout ?? DefaultOperationTimeout);
}
catch (TimeoutException) when (FormatError != null)
{
throw FormatError("Timed out while waiting for batch.");
}
}
return null;
}
private async Task<CapturedJSInteropCall?> WaitForJSInterop(TimeSpan? timeout = null)
{
if (ImplicitWait)
{
if (DefaultOperationTimeout == null && timeout == null)
{
throw new InvalidOperationException("Implicit wait without DefaultLatencyTimeout is not allowed.");
}
try
{
return await PrepareForNextJSInterop(timeout ?? DefaultOperationTimeout);
}
catch (TimeoutException) when (FormatError != null)
{
throw FormatError("Timed out while waiting for JS Interop.");
}
}
return null;
}
private async Task<string?> WaitForDotNetInterop(TimeSpan? timeout = null)
{
if (ImplicitWait)
{
if (DefaultOperationTimeout == null && timeout == null)
{
throw new InvalidOperationException("Implicit wait without DefaultLatencyTimeout is not allowed.");
}
try
{
return await PrepareForNextDotNetInterop(timeout ?? DefaultOperationTimeout);
}
catch (TimeoutException) when (FormatError != null)
{
throw FormatError("Timed out while waiting for .NET interop.");
}
}
return null;
}
private async Task<string?> WaitForCircuitError(TimeSpan? timeout = null)
{
if (ImplicitWait)
{
if (DefaultOperationTimeout == null && timeout == null)
{
throw new InvalidOperationException("Implicit wait without DefaultLatencyTimeout is not allowed.");
}
try
{
return await PrepareForNextCircuitError(timeout ?? DefaultOperationTimeout);
}
catch (TimeoutException) when (FormatError != null)
{
throw FormatError("Timed out while waiting for circuit error.");
}
}
return null;
}
private async Task<Exception?> WaitForDisconnect(TimeSpan? timeout = null)
{
if (ImplicitWait)
{
if (DefaultOperationTimeout == null && timeout == null)
{
throw new InvalidOperationException("Implicit wait without DefaultLatencyTimeout is not allowed.");
}
try
{
return await PrepareForNextDisconnect(timeout ?? DefaultOperationTimeout);
}
catch (TimeoutException) when (FormatError != null)
{
throw FormatError("Timed out while waiting for disconnect.");
}
}
return null;
}
public async Task<bool> ConnectAsync(Uri uri, bool connectAutomatically = true, Action<HubConnectionBuilder, Uri>? configure = null)
{
var builder = new HubConnectionBuilder();
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IHubProtocol, IgnitorMessagePackHubProtocol>());
var hubUrl = GetHubUrl(uri);
builder.WithUrl(hubUrl);
builder.ConfigureLogging(l =>
{
l.SetMinimumLevel(LogLevel.Trace);
if (LoggerProvider != null)
{
l.AddProvider(LoggerProvider);
}
});
configure?.Invoke(builder, hubUrl);
_hubConnection = builder.Build();
HubConnection.On<int, string>("JS.AttachComponent", OnAttachComponent);
HubConnection.On<int, string, string, int, long>("JS.BeginInvokeJS", OnBeginInvokeJS);
HubConnection.On<string>("JS.EndInvokeDotNet", OnEndInvokeDotNet);
HubConnection.On<int, byte[]>("JS.RenderBatch", OnRenderBatch);
HubConnection.On<string>("JS.Error", OnError);
HubConnection.Closed += OnClosedAsync;
for (var i = 0; i < 10; i++)
{
try
{
await HubConnection.StartAsync(CancellationToken);
break;
}
catch
{
await Task.Delay(500);
// Retry 10 times
}
}
if (!connectAutomatically)
{
return true;
}
var descriptors = await GetPrerenderDescriptors(uri);
await ExpectRenderBatch(
async () => CircuitId = await HubConnection.InvokeAsync<string>("StartCircuit", uri, uri, descriptors, null, CancellationToken),
DefaultConnectionTimeout);
return CircuitId != null;
}
private void OnEndInvokeDotNet(string message)
{
Operations?.DotNetCompletions.Enqueue(message);
DotNetInteropCompletion?.Invoke(message);
NextDotNetInteropCompletionReceived?.Completion?.TrySetResult(null);
}
private void OnAttachComponent(int componentId, string domSelector)
{
var call = new CapturedAttachComponentCall(componentId, domSelector);
Operations?.AttachComponent.Enqueue(call);
NextAttachComponentReceived?.Completion?.TrySetResult(call);
}
private void OnBeginInvokeJS(int asyncHandle, string identifier, string argsJson, int resultType, long targetInstanceId)
{
var call = new CapturedJSInteropCall(asyncHandle, identifier, argsJson, resultType, targetInstanceId);
Operations?.JSInteropCalls.Enqueue(call);
JSInterop?.Invoke(call);
NextJSInteropReceived?.Completion?.TrySetResult(null);
}
private void OnRenderBatch(int id, byte[] data)
{
var capturedBatch = new CapturedRenderBatch(id, data);
Operations?.Batches.Enqueue(capturedBatch);
RenderBatchReceived?.Invoke(capturedBatch);
var batch = RenderBatchReader.Read(data);
Hive.Update(batch);
if (ConfirmRenderBatch)
{
_ = ConfirmBatch(id);
}
NextBatchReceived?.Completion?.TrySetResult(null);
}
public Task ConfirmBatch(int batchId, string? error = null)
{
return HubConnection.InvokeAsync("OnRenderCompleted", batchId, error, CancellationToken);
}
private void OnError(string error)
{
Operations?.Errors.Enqueue(error);
OnCircuitError?.Invoke(error);
// If we get an error, forcibly terminate anything else we're waiting for. These
// tests should only encounter errors in specific situations, and this ensures that
// we fail with a good message.
var exception = FormatError?.Invoke(error) ?? new Exception(error);
NextBatchReceived?.Completion?.TrySetException(exception);
NextDotNetInteropCompletionReceived?.Completion.TrySetException(exception);
NextJSInteropReceived?.Completion.TrySetException(exception);
NextAttachComponentReceived?.Completion?.TrySetException(exception);
NextErrorReceived?.Completion?.TrySetResult(null);
}
private Task OnClosedAsync(Exception? ex)
{
NextDisconnect?.Completion?.TrySetResult(null);
if (ex == null)
{
TaskCompletionSource.TrySetResult(null);
}
else
{
TaskCompletionSource.TrySetException(ex);
}
return Task.CompletedTask;
}
private Uri GetHubUrl(Uri uri)
{
if (uri.Segments.Length == 1)
{
return new Uri(uri, "_blazor");
}
else
{
var builder = new UriBuilder(uri);
builder.Path += builder.Path.EndsWith("/", StringComparison.Ordinal) ? "_blazor" : "/_blazor";
return builder.Uri;
}
}
public async Task InvokeDotNetMethod(object? callId, string? assemblyName, string methodIdentifier, object dotNetObjectId, string argsJson)
{
await ExpectDotNetInterop(() => HubConnection.InvokeAsync(
"BeginInvokeDotNetFromJS",
callId?.ToString(),
assemblyName,
methodIdentifier,
dotNetObjectId ?? 0,
argsJson,
CancellationToken));
}
public async Task<string> GetPrerenderDescriptors(Uri uri)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", "__blazor_execution_mode=server");
var response = await httpClient.GetAsync(uri);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var match = ReadMarkers(content);
return $"[{string.Join(", ", match)}]";
}
public void Cancel()
{
if (!CancellationTokenSource.IsCancellationRequested)
{
CancellationTokenSource.Cancel();
CancellationTokenSource.Dispose();
}
}
public ElementNode FindElementById(string id)
{
if (!Hive.TryFindElementById(id, out var element))
{
throw new InvalidOperationException($"Element with id '{id}' was not found.");
}
return element;
}
private string[] ReadMarkers(string content)
{
content = content.Replace("\r\n", "").Replace("\n", "");
var matches = Regex.Matches(content, MarkerPattern);
var markers = matches.Select(s => (value: s.Groups[1].Value, parsed: JsonDocument.Parse(s.Groups[1].Value)))
.Where(s =>
{
return s.parsed.RootElement.TryGetProperty("type", out var markerType) &&
markerType.ValueKind != JsonValueKind.Undefined &&
markerType.GetString() == "server";
})
.OrderBy(p => p.parsed.RootElement.GetProperty("sequence").GetInt32())
.Select(p => p.value)
.ToArray();
return markers;
}
public async ValueTask DisposeAsync()
{
Cancel();
if (HubConnection != null)
{
await HubConnection.DisposeAsync();
}
}
}
}
#nullable restore
| |
/**
* @project JsonLight
*
* The MIT License (MIT)
*
* Copyright (c) 2013 Dmitry Ponomarev <demdxx@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace JsonLight
{
public class JObject : Dictionary<string, JValue>, JValue
{
#region Decode section
/**
* Decode json string to JArray or JObject
* @param content string
* @return JValue
*/
public static JValue Decode(string content)
{
if ('[' == content [0]) {
return JArray.Decode (content);
}
return DecodeObject (content);
}
/**
* Decode json string to JObject
* @param content string
* @return new JObject instance
*/
public static JObject DecodeObject (string content)
{
int index = 0, line = 0, simbol = 0;
return DecodeObject (content, ref index, ref line, ref simbol);
}
/**
* Decode json string to JObject
* @param content string
* @param ref index int
* @param red line int
* @param ref simbol int
* @return new JObject instance
*/
public static JObject DecodeObject (string content, ref int index, ref int line, ref int simbol)
{
if ('{' != content [index]) {
throw new ExceptionSyntaxError (0, 0);
}
JObject obj = new JObject ();
bool comma = true;
bool colon = false;
bool isValue = false;
string key = "";
index ++;
simbol ++;
for (; index<content.Length; index++, simbol++) {
char c = content [index];
if ('}' == c) {
if (colon) {
throw new ExceptionSyntaxError (line, simbol);
}
return obj;
}
else if (' ' == c || '\n' == c || '\t' == c) {
if ('\n' == c) {
line++;
simbol = -1;
}
continue;
} else if (!comma) {
if (',' != c) {
throw new ExceptionSyntaxError (line, simbol);
}
comma = true;
} else {
if (isValue && !colon) {
if (':' != c) {
throw new ExceptionSyntaxError (line, simbol);
}
colon = true;
} else {
if ('"' == c || '\'' == c) {
// Decode string value "String" or 'String'
try {
var pIndex = index;
index++;
if (isValue) {
obj.Add (key, JString.ValueOf (JUtils.DecodeEscapeString (content, ref index, c)));
} else {
key = JUtils.DecodeEscapeString (content, ref index, c);
if (null == key || key.Length < 1) {
throw new ExceptionSyntaxError (line, simbol);
}
}
simbol += index - pIndex;
} catch (FormatException e) {
throw new ExceptionSyntaxError (line, simbol);
}
} else if ('[' == c) {
// Parse Array
if (!isValue) {
throw new ExceptionSyntaxError (line, simbol);
}
obj.Add (key, JArray.DecodeArray (content, ref index, ref line, ref simbol));
} else if ('{' == c) {
// Parse Dictionary
if (!isValue) {
throw new ExceptionSyntaxError (line, simbol);
}
obj.Add (key, JObject.DecodeObject (content, ref index, ref line, ref simbol));
} else {
// Decode word value WORD or W0r6 ...
var pIndex = index;
if (isValue) {
var val = JUtils.DecodeWord (content, ref index);
if (null == val || val.Length < 1) {
throw new ExceptionSyntaxError (line, simbol);
}
if ("null" == val) {
obj.Add(key, null);
} else {
obj.Add(key, JUtils.ValueOfString(val));
}
} else {
key = JUtils.DecodeWord (content, ref index);
if (null == key || key.Length < 1) {
throw new ExceptionSyntaxError (line, simbol);
}
}
simbol += index - pIndex;
}
if (isValue) {
comma = false;
colon = false;
}
isValue = !isValue;
}
}
}
throw new ExceptionSyntaxError (line, simbol);
}
#endregion // Decode section
#region Value of
/**
* Decode json string to JObject
* @param content string
* @return new JObject instance
*/
public static JObject ValueOf (string content)
{
return DecodeObject (content);
}
/**
* Dictionary to JObject
* @param dict {key: value, ...}
* @return new JObject instance
*/
public static JObject ValueOf (IDictionary<string, object> dict)
{
return (new JObject ()).AddFromDict (dict);
}
#endregion // Value of
/**
* Add values from dict
* @param dict {key: value, ...}
* @return self
*/
public JObject AddFromDict (IDictionary<string, object> dict)
{
foreach (var it in dict) {
Add (it.Key, JUtils.ValueOf (it.Value));
}
return this;
}
/**
* Get/set dictionary value
* @return object
*/
public virtual object Value
{
get {
return this;
}
set {
Clear ();
if (null != value && value is IDictionary<string, object>) {
AddFromDict (value as IDictionary<string, object>);
} else {
throw new ArgumentException ();
}
}
}
#region Value convert to
/**
* Convert to dictionary
* @return dictionary
*/
public Dictionary<string, object> ToDictionary()
{
var result = new Dictionary<string, object> ();
foreach (var p in this) {
if (null != p.Value) {
if (p.Value is JObject)
{
result.Add(p.Key, (p.Value as JObject).ToDictionary());
}
else if (p.Value is JArray)
{
result.Add(p.Key, (p.Value as JArray).ToList());
}
else
{
result.Add (p.Key, p.Value.Value);
}
}
}
return result;
}
/**
* Convert to JSON string
* @return JSON string
*/
public override string ToString ()
{
var sb = new StringBuilder ();
bool started = false;
foreach (var p in this) {
if (null != p.Value) {
if (started) {
sb.Append (",");
} else {
started = true;
}
sb.AppendFormat ("\"{0}\":{1}", p.Key, p.Value.ToJsonString ());
}
}
return String.Format ("{{{0}}}", sb.ToString ());
}
/**
* Convert to JSON string
* @return JSON string
*/
public virtual string ToJsonString ()
{
return ToString ();
}
/**
* Get int value
* @return int
*/
public int IntValue
{
get {
return Count > 0 ? 1 : 0;
}
}
/**
* Get long value
* @return long
*/
public long LongValue
{
get {
return Count > 0 ? 1 : 0;
}
}
/**
* Get double value
* @return double
*/
public double DoubleValue
{
get {
return Count > 0 ? 1.0 : 0.0;
}
}
/**
* Get bool value
* @return bool
*/
public bool BoolValue
{
get {
return Count > 0;
}
}
#endregion // Value convert to
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Sql.Auditing.Model;
using Microsoft.Azure.Management.Internal.Resources;
using Microsoft.Azure.Management.Internal.Resources.Models;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Storage;
using Microsoft.WindowsAzure.Management.Storage;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.Commands.Sql.Common
{
/// <summary>
/// This class is responsible for all the REST communication with the management libraries
/// </summary>
public class AzureEndpointsCommunicator
{
/// <summary>
/// The storage management client used by this communicator
/// </summary>
private static Microsoft.Azure.Management.Storage.StorageManagementClient StorageV2Client { get; set; }
/// <summary>
/// Gets or sets the Azure subscription
/// </summary>
private static IAzureSubscription Subscription { get; set; }
/// <summary>
/// The resources management client used by this communicator
/// </summary>
private static ResourceManagementClient ResourcesClient { get; set; }
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public IAzureContext Context { get; set; }
/// <summary>
/// Default Constructor.
/// </summary>
/// <param name="context">The Azure context</param>
public AzureEndpointsCommunicator(IAzureContext context)
{
Context = context;
if (context.Subscription != Subscription)
{
Subscription = context.Subscription;
ResourcesClient = null;
StorageV2Client = null;
}
}
private static class StorageAccountType
{
public const string ClassicStorage = "Microsoft.ClassicStorage/storageAccounts";
public const string Storage = "Microsoft.Storage/storageAccounts";
}
/// <summary>
/// Provides the storage keys for the storage account within the given resource group
/// </summary>
/// <returns>A dictionary with two entries, one for each possible key type with the appropriate key</returns>
public async Task<Dictionary<StorageKeyKind, string>> GetStorageKeysAsync(string resourceGroupName, string storageAccountName)
{
Management.Storage.StorageManagementClient client = GetCurrentStorageV2Client(Context);
string url = Context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager).ToString();
if (!url.EndsWith("/"))
{
url = url + "/";
}
url = url + "subscriptions/" + (client.Credentials.SubscriptionId != null ? client.Credentials.SubscriptionId.Trim() : "");
url = url + "/resourceGroups/" + resourceGroupName;
url = url + "/providers/Microsoft.ClassicStorage/storageAccounts/" + storageAccountName;
url = url + "/listKeys?api-version=2014-06-01";
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
await client.Credentials.ProcessHttpRequestAsync(httpRequest, CancellationToken.None).ConfigureAwait(false);
HttpResponseMessage httpResponse = await client.HttpClient.SendAsync(httpRequest, CancellationToken.None).ConfigureAwait(false);
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Dictionary<StorageKeyKind, string> result = new Dictionary<StorageKeyKind, string>();
try
{
JToken responseDoc = JToken.Parse(responseContent);
string primaryKey = (string)responseDoc["primaryKey"];
string secondaryKey = (string)responseDoc["secondaryKey"];
if (string.IsNullOrEmpty(primaryKey) || string.IsNullOrEmpty(secondaryKey))
throw new Exception(); // this is caught by the synced wrapper
result.Add(StorageKeyKind.Primary, primaryKey);
result.Add(StorageKeyKind.Secondary, secondaryKey);
return result;
}
catch
{
return GetV2Keys(resourceGroupName, storageAccountName);
}
}
private Dictionary<StorageKeyKind, string> GetV2Keys(string resourceGroupName, string storageAccountName)
{
Microsoft.Azure.Management.Storage.StorageManagementClient storageClient = GetCurrentStorageV2Client(Context);
var r = storageClient.StorageAccounts.ListKeys(resourceGroupName, storageAccountName);
string k1 = r.StorageAccountKeys.Key1;
string k2 = r.StorageAccountKeys.Key2;
Dictionary<StorageKeyKind, String> result = new Dictionary<StorageKeyKind, String>();
result.Add(StorageKeyKind.Primary, k1);
result.Add(StorageKeyKind.Secondary, k2);
return result;
}
/// <summary>
/// Gets the storage keys for the given storage account.
/// </summary>
public Dictionary<StorageKeyKind, string> GetStorageKeys(string resourceGroupName, string storageAccountName)
{
try
{
return this.GetStorageKeysAsync(resourceGroupName, storageAccountName).GetAwaiter().GetResult();
}
catch (Exception e)
{
throw new Exception(string.Format(Properties.Resources.StorageAccountNotFound, storageAccountName), e);
}
}
/// <summary>
/// Returns the resource group of the provided storage account
/// </summary>
public string GetStorageResourceGroup(string storageAccountName)
{
ResourceManagementClient resourcesClient = GetCurrentResourcesClient(Context);
foreach (string storageAccountType in new[] { StorageAccountType.ClassicStorage, StorageAccountType.Storage })
{
string resourceGroup = GetStorageResourceGroup(
resourcesClient,
storageAccountName,
storageAccountType);
if (resourceGroup != null)
{
return resourceGroup;
}
}
throw new Exception(string.Format(Properties.Resources.StorageAccountNotFound, storageAccountName));
}
private string GetStorageResourceGroup(
ResourceManagementClient resourcesClient,
string storageAccountName,
string resourceType)
{
var query = new Rest.Azure.OData.ODataQuery<GenericResourceFilter>(r => r.ResourceType == resourceType);
Rest.Azure.IPage<GenericResource> res = resourcesClient.Resources.List(query);
var allResources = new List<GenericResource>(res);
GenericResource account = allResources.Find(r => r.Name == storageAccountName);
if (account != null)
{
string resId = account.Id;
string[] segments = resId.Split('/');
int indexOfResoureGroup = new List<string>(segments).IndexOf("resourceGroups") + 1;
return segments[indexOfResoureGroup];
}
else
{
return null;
}
}
public Dictionary<StorageKeyKind, string> GetStorageKeys(string storageName)
{
var resourceGroup = GetStorageResourceGroup(storageName);
return GetStorageKeys(resourceGroup, storageName);
}
/// <summary>
/// Lazy creation of a single instance of a storage client
/// </summary>
private Microsoft.Azure.Management.Storage.StorageManagementClient GetCurrentStorageV2Client(IAzureContext context)
{
if (StorageV2Client == null)
{
StorageV2Client = AzureSession.Instance.ClientFactory.CreateClient<Microsoft.Azure.Management.Storage.StorageManagementClient>(Context, AzureEnvironment.Endpoint.ResourceManager);
}
return StorageV2Client;
}
/// <summary>
/// Lazy creation of a single instance of a resoures client
/// </summary>
private ResourceManagementClient GetCurrentResourcesClient(IAzureContext context)
{
if (ResourcesClient == null)
{
ResourcesClient = AzureSession.Instance.ClientFactory.CreateArmClient<ResourceManagementClient>(Context, AzureEnvironment.Endpoint.ResourceManager);
}
return ResourcesClient;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHapi.Base.Model;
using NHapi.Model.V22.Group;
using NHapi.Model.V22.Message;
using NHapi.Model.V22.Segment;
using NHapi.Model.V22.Datatype;
using NHapiTools.Base;
namespace NHapiTools.Model.V22.Group
{
/// <summary>
/// Extention methods
/// </summary>
public static class GroupExtensions
{
#region Extension methods
/// <summary>
/// Get NK1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetNK1Records(this ADR_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("NK1RepetitionsUsed", "GetNK1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NK1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static List<NK1> GetAllNK1Records(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<NK1>("NK1RepetitionsUsed", "GetNK1");
}
/// <summary>
/// Add a new ADR_A19_QUERY_RESPONSE to NK1
/// </summary>
public static NK1 AddNK1(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetNK1(message.NK1RepetitionsUsed);
}
/// <summary>
/// Get OBX Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetOBXRecords(this ADR_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("OBXRepetitionsUsed", "GetOBX");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all OBX Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static List<OBX> GetAllOBXRecords(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<OBX>("OBXRepetitionsUsed", "GetOBX");
}
/// <summary>
/// Add a new ADR_A19_QUERY_RESPONSE to OBX
/// </summary>
public static OBX AddOBX(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetOBX(message.OBXRepetitionsUsed);
}
/// <summary>
/// Get AL1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetAL1Records(this ADR_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("AL1RepetitionsUsed", "GetAL1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all AL1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static List<AL1> GetAllAL1Records(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<AL1>("AL1RepetitionsUsed", "GetAL1");
}
/// <summary>
/// Add a new ADR_A19_QUERY_RESPONSE to AL1
/// </summary>
public static AL1 AddAL1(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetAL1(message.AL1RepetitionsUsed);
}
/// <summary>
/// Get DG1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetDG1Records(this ADR_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("DG1RepetitionsUsed", "GetDG1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all DG1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static List<DG1> GetAllDG1Records(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<DG1>("DG1RepetitionsUsed", "GetDG1");
}
/// <summary>
/// Add a new ADR_A19_QUERY_RESPONSE to DG1
/// </summary>
public static DG1 AddDG1(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetDG1(message.DG1RepetitionsUsed);
}
/// <summary>
/// Get PR1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetPR1Records(this ADR_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("PR1RepetitionsUsed", "GetPR1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all PR1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static List<PR1> GetAllPR1Records(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<PR1>("PR1RepetitionsUsed", "GetPR1");
}
/// <summary>
/// Add a new ADR_A19_QUERY_RESPONSE to PR1
/// </summary>
public static PR1 AddPR1(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetPR1(message.PR1RepetitionsUsed);
}
/// <summary>
/// Get GT1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetGT1Records(this ADR_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("GT1RepetitionsUsed", "GetGT1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all GT1 Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static List<GT1> GetAllGT1Records(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<GT1>("GT1RepetitionsUsed", "GetGT1");
}
/// <summary>
/// Add a new ADR_A19_QUERY_RESPONSE to GT1
/// </summary>
public static GT1 AddGT1(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetGT1(message.GT1RepetitionsUsed);
}
/// <summary>
/// Get INSURANCE Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetINSURANCERecords(this ADR_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("INSURANCERepetitionsUsed", "GetINSURANCE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all INSURANCE Records from ADR_A19_QUERY_RESPONSE
/// </summary>
public static List<ADR_A19_INSURANCE> GetAllINSURANCERecords(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<ADR_A19_INSURANCE>("INSURANCERepetitionsUsed", "GetINSURANCE");
}
/// <summary>
/// Add a new ADR_A19_QUERY_RESPONSE to INSURANCE
/// </summary>
public static ADR_A19_INSURANCE AddINSURANCE(this ADR_A19_QUERY_RESPONSE message)
{
return message.GetINSURANCE(message.INSURANCERepetitionsUsed);
}
/// <summary>
/// Get NK1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetNK1Records(this ARD_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("NK1RepetitionsUsed", "GetNK1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NK1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static List<NK1> GetAllNK1Records(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<NK1>("NK1RepetitionsUsed", "GetNK1");
}
/// <summary>
/// Add a new ARD_A19_QUERY_RESPONSE to NK1
/// </summary>
public static NK1 AddNK1(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetNK1(message.NK1RepetitionsUsed);
}
/// <summary>
/// Get OBX Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetOBXRecords(this ARD_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("OBXRepetitionsUsed", "GetOBX");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all OBX Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static List<OBX> GetAllOBXRecords(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<OBX>("OBXRepetitionsUsed", "GetOBX");
}
/// <summary>
/// Add a new ARD_A19_QUERY_RESPONSE to OBX
/// </summary>
public static OBX AddOBX(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetOBX(message.OBXRepetitionsUsed);
}
/// <summary>
/// Get AL1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetAL1Records(this ARD_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("AL1RepetitionsUsed", "GetAL1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all AL1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static List<AL1> GetAllAL1Records(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<AL1>("AL1RepetitionsUsed", "GetAL1");
}
/// <summary>
/// Add a new ARD_A19_QUERY_RESPONSE to AL1
/// </summary>
public static AL1 AddAL1(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetAL1(message.AL1RepetitionsUsed);
}
/// <summary>
/// Get DG1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetDG1Records(this ARD_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("DG1RepetitionsUsed", "GetDG1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all DG1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static List<DG1> GetAllDG1Records(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<DG1>("DG1RepetitionsUsed", "GetDG1");
}
/// <summary>
/// Add a new ARD_A19_QUERY_RESPONSE to DG1
/// </summary>
public static DG1 AddDG1(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetDG1(message.DG1RepetitionsUsed);
}
/// <summary>
/// Get PR1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetPR1Records(this ARD_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("PR1RepetitionsUsed", "GetPR1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all PR1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static List<PR1> GetAllPR1Records(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<PR1>("PR1RepetitionsUsed", "GetPR1");
}
/// <summary>
/// Add a new ARD_A19_QUERY_RESPONSE to PR1
/// </summary>
public static PR1 AddPR1(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetPR1(message.PR1RepetitionsUsed);
}
/// <summary>
/// Get GT1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetGT1Records(this ARD_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("GT1RepetitionsUsed", "GetGT1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all GT1 Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static List<GT1> GetAllGT1Records(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<GT1>("GT1RepetitionsUsed", "GetGT1");
}
/// <summary>
/// Add a new ARD_A19_QUERY_RESPONSE to GT1
/// </summary>
public static GT1 AddGT1(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetGT1(message.GT1RepetitionsUsed);
}
/// <summary>
/// Get INSURANCE Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetINSURANCERecords(this ARD_A19_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("INSURANCERepetitionsUsed", "GetINSURANCE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all INSURANCE Records from ARD_A19_QUERY_RESPONSE
/// </summary>
public static List<ARD_A19_INSURANCE> GetAllINSURANCERecords(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetAllRecords<ARD_A19_INSURANCE>("INSURANCERepetitionsUsed", "GetINSURANCE");
}
/// <summary>
/// Add a new ARD_A19_QUERY_RESPONSE to INSURANCE
/// </summary>
public static ARD_A19_INSURANCE AddINSURANCE(this ARD_A19_QUERY_RESPONSE message)
{
return message.GetINSURANCE(message.INSURANCERepetitionsUsed);
}
/// <summary>
/// Get OBX Records from BAR_P01_VISIT
/// </summary>
public static IEnumerable GetOBXRecords(this BAR_P01_VISIT message)
{
object[] result = message.GetRecords("OBXRepetitionsUsed", "GetOBX");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all OBX Records from BAR_P01_VISIT
/// </summary>
public static List<OBX> GetAllOBXRecords(this BAR_P01_VISIT message)
{
return message.GetAllRecords<OBX>("OBXRepetitionsUsed", "GetOBX");
}
/// <summary>
/// Add a new BAR_P01_VISIT to OBX
/// </summary>
public static OBX AddOBX(this BAR_P01_VISIT message)
{
return message.GetOBX(message.OBXRepetitionsUsed);
}
/// <summary>
/// Get AL1 Records from BAR_P01_VISIT
/// </summary>
public static IEnumerable GetAL1Records(this BAR_P01_VISIT message)
{
object[] result = message.GetRecords("AL1RepetitionsUsed", "GetAL1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all AL1 Records from BAR_P01_VISIT
/// </summary>
public static List<AL1> GetAllAL1Records(this BAR_P01_VISIT message)
{
return message.GetAllRecords<AL1>("AL1RepetitionsUsed", "GetAL1");
}
/// <summary>
/// Add a new BAR_P01_VISIT to AL1
/// </summary>
public static AL1 AddAL1(this BAR_P01_VISIT message)
{
return message.GetAL1(message.AL1RepetitionsUsed);
}
/// <summary>
/// Get DG1 Records from BAR_P01_VISIT
/// </summary>
public static IEnumerable GetDG1Records(this BAR_P01_VISIT message)
{
object[] result = message.GetRecords("DG1RepetitionsUsed", "GetDG1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all DG1 Records from BAR_P01_VISIT
/// </summary>
public static List<DG1> GetAllDG1Records(this BAR_P01_VISIT message)
{
return message.GetAllRecords<DG1>("DG1RepetitionsUsed", "GetDG1");
}
/// <summary>
/// Add a new BAR_P01_VISIT to DG1
/// </summary>
public static DG1 AddDG1(this BAR_P01_VISIT message)
{
return message.GetDG1(message.DG1RepetitionsUsed);
}
/// <summary>
/// Get PR1 Records from BAR_P01_VISIT
/// </summary>
public static IEnumerable GetPR1Records(this BAR_P01_VISIT message)
{
object[] result = message.GetRecords("PR1RepetitionsUsed", "GetPR1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all PR1 Records from BAR_P01_VISIT
/// </summary>
public static List<PR1> GetAllPR1Records(this BAR_P01_VISIT message)
{
return message.GetAllRecords<PR1>("PR1RepetitionsUsed", "GetPR1");
}
/// <summary>
/// Add a new BAR_P01_VISIT to PR1
/// </summary>
public static PR1 AddPR1(this BAR_P01_VISIT message)
{
return message.GetPR1(message.PR1RepetitionsUsed);
}
/// <summary>
/// Get GT1 Records from BAR_P01_VISIT
/// </summary>
public static IEnumerable GetGT1Records(this BAR_P01_VISIT message)
{
object[] result = message.GetRecords("GT1RepetitionsUsed", "GetGT1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all GT1 Records from BAR_P01_VISIT
/// </summary>
public static List<GT1> GetAllGT1Records(this BAR_P01_VISIT message)
{
return message.GetAllRecords<GT1>("GT1RepetitionsUsed", "GetGT1");
}
/// <summary>
/// Add a new BAR_P01_VISIT to GT1
/// </summary>
public static GT1 AddGT1(this BAR_P01_VISIT message)
{
return message.GetGT1(message.GT1RepetitionsUsed);
}
/// <summary>
/// Get NK1 Records from BAR_P01_VISIT
/// </summary>
public static IEnumerable GetNK1Records(this BAR_P01_VISIT message)
{
object[] result = message.GetRecords("NK1RepetitionsUsed", "GetNK1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NK1 Records from BAR_P01_VISIT
/// </summary>
public static List<NK1> GetAllNK1Records(this BAR_P01_VISIT message)
{
return message.GetAllRecords<NK1>("NK1RepetitionsUsed", "GetNK1");
}
/// <summary>
/// Add a new BAR_P01_VISIT to NK1
/// </summary>
public static NK1 AddNK1(this BAR_P01_VISIT message)
{
return message.GetNK1(message.NK1RepetitionsUsed);
}
/// <summary>
/// Get INSURANCE Records from BAR_P01_VISIT
/// </summary>
public static IEnumerable GetINSURANCERecords(this BAR_P01_VISIT message)
{
object[] result = message.GetRecords("INSURANCERepetitionsUsed", "GetINSURANCE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all INSURANCE Records from BAR_P01_VISIT
/// </summary>
public static List<BAR_P01_INSURANCE> GetAllINSURANCERecords(this BAR_P01_VISIT message)
{
return message.GetAllRecords<BAR_P01_INSURANCE>("INSURANCERepetitionsUsed", "GetINSURANCE");
}
/// <summary>
/// Add a new BAR_P01_VISIT to INSURANCE
/// </summary>
public static BAR_P01_INSURANCE AddINSURANCE(this BAR_P01_VISIT message)
{
return message.GetINSURANCE(message.INSURANCERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from NMD_N01_APP_STATS
/// </summary>
public static IEnumerable GetNTERecords(this NMD_N01_APP_STATS message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from NMD_N01_APP_STATS
/// </summary>
public static List<NTE> GetAllNTERecords(this NMD_N01_APP_STATS message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new NMD_N01_APP_STATS to NTE
/// </summary>
public static NTE AddNTE(this NMD_N01_APP_STATS message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from NMD_N01_APP_STATUS
/// </summary>
public static IEnumerable GetNTERecords(this NMD_N01_APP_STATUS message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from NMD_N01_APP_STATUS
/// </summary>
public static List<NTE> GetAllNTERecords(this NMD_N01_APP_STATUS message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new NMD_N01_APP_STATUS to NTE
/// </summary>
public static NTE AddNTE(this NMD_N01_APP_STATUS message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from NMD_N01_CLOCK
/// </summary>
public static IEnumerable GetNTERecords(this NMD_N01_CLOCK message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from NMD_N01_CLOCK
/// </summary>
public static List<NTE> GetAllNTERecords(this NMD_N01_CLOCK message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new NMD_N01_CLOCK to NTE
/// </summary>
public static NTE AddNTE(this NMD_N01_CLOCK message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT
/// </summary>
public static IEnumerable GetNTERecords(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT
/// </summary>
public static List<NTE> GetAllNTERecords(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT to NTE
/// </summary>
public static NTE AddNTE(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE2 Records from NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT
/// </summary>
public static IEnumerable GetNTE2Records(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
object[] result = message.GetRecords("NTE2RepetitionsUsed", "GetNTE2");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE2 Records from NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT
/// </summary>
public static List<NTE> GetAllNTE2Records(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
return message.GetAllRecords<NTE>("NTE2RepetitionsUsed", "GetNTE2");
}
/// <summary>
/// Add a new NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT to NTE2
/// </summary>
public static NTE AddNTE2(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
return message.GetNTE2(message.NTE2RepetitionsUsed);
}
/// <summary>
/// Get NTE3 Records from NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT
/// </summary>
public static IEnumerable GetNTE3Records(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
object[] result = message.GetRecords("NTE3RepetitionsUsed", "GetNTE3");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE3 Records from NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT
/// </summary>
public static List<NTE> GetAllNTE3Records(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
return message.GetAllRecords<NTE>("NTE3RepetitionsUsed", "GetNTE3");
}
/// <summary>
/// Add a new NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT to NTE3
/// </summary>
public static NTE AddNTE3(this NMR_N02_CLOCK_AND_STATS_WITH_NOTES_ALT message)
{
return message.GetNTE3(message.NTE3RepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORF_R04_OBSERVATION
/// </summary>
public static IEnumerable GetNTERecords(this ORF_R04_OBSERVATION message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORF_R04_OBSERVATION
/// </summary>
public static List<NTE> GetAllNTERecords(this ORF_R04_OBSERVATION message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORF_R04_OBSERVATION to NTE
/// </summary>
public static NTE AddNTE(this ORF_R04_OBSERVATION message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORF_R04_ORDER
/// </summary>
public static IEnumerable GetNTERecords(this ORF_R04_ORDER message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORF_R04_ORDER
/// </summary>
public static List<NTE> GetAllNTERecords(this ORF_R04_ORDER message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORF_R04_ORDER to NTE
/// </summary>
public static NTE AddNTE(this ORF_R04_ORDER message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get OBSERVATION Records from ORF_R04_ORDER
/// </summary>
public static IEnumerable GetOBSERVATIONRecords(this ORF_R04_ORDER message)
{
object[] result = message.GetRecords("OBSERVATIONRepetitionsUsed", "GetOBSERVATION");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all OBSERVATION Records from ORF_R04_ORDER
/// </summary>
public static List<ORF_R04_OBSERVATION> GetAllOBSERVATIONRecords(this ORF_R04_ORDER message)
{
return message.GetAllRecords<ORF_R04_OBSERVATION>("OBSERVATIONRepetitionsUsed", "GetOBSERVATION");
}
/// <summary>
/// Add a new ORF_R04_ORDER to OBSERVATION
/// </summary>
public static ORF_R04_OBSERVATION AddOBSERVATION(this ORF_R04_ORDER message)
{
return message.GetOBSERVATION(message.OBSERVATIONRepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORF_R04_QUERY_RESPONSE
/// </summary>
public static IEnumerable GetNTERecords(this ORF_R04_QUERY_RESPONSE message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORF_R04_QUERY_RESPONSE
/// </summary>
public static List<NTE> GetAllNTERecords(this ORF_R04_QUERY_RESPONSE message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORF_R04_QUERY_RESPONSE to NTE
/// </summary>
public static NTE AddNTE(this ORF_R04_QUERY_RESPONSE message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORM_O01_ORDER_DETAIL
/// </summary>
public static IEnumerable GetNTERecords(this ORM_O01_ORDER_DETAIL message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORM_O01_ORDER_DETAIL
/// </summary>
public static List<NTE> GetAllNTERecords(this ORM_O01_ORDER_DETAIL message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORM_O01_ORDER_DETAIL to NTE
/// </summary>
public static NTE AddNTE(this ORM_O01_ORDER_DETAIL message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get OBX Records from ORM_O01_ORDER_DETAIL
/// </summary>
public static IEnumerable GetOBXRecords(this ORM_O01_ORDER_DETAIL message)
{
object[] result = message.GetRecords("OBXRepetitionsUsed", "GetOBX");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all OBX Records from ORM_O01_ORDER_DETAIL
/// </summary>
public static List<OBX> GetAllOBXRecords(this ORM_O01_ORDER_DETAIL message)
{
return message.GetAllRecords<OBX>("OBXRepetitionsUsed", "GetOBX");
}
/// <summary>
/// Add a new ORM_O01_ORDER_DETAIL to OBX
/// </summary>
public static OBX AddOBX(this ORM_O01_ORDER_DETAIL message)
{
return message.GetOBX(message.OBXRepetitionsUsed);
}
/// <summary>
/// Get NTE2 Records from ORM_O01_ORDER_DETAIL
/// </summary>
public static IEnumerable GetNTE2Records(this ORM_O01_ORDER_DETAIL message)
{
object[] result = message.GetRecords("NTE2RepetitionsUsed", "GetNTE2");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE2 Records from ORM_O01_ORDER_DETAIL
/// </summary>
public static List<NTE> GetAllNTE2Records(this ORM_O01_ORDER_DETAIL message)
{
return message.GetAllRecords<NTE>("NTE2RepetitionsUsed", "GetNTE2");
}
/// <summary>
/// Add a new ORM_O01_ORDER_DETAIL to NTE2
/// </summary>
public static NTE AddNTE2(this ORM_O01_ORDER_DETAIL message)
{
return message.GetNTE2(message.NTE2RepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORM_O01_PATIENT
/// </summary>
public static IEnumerable GetNTERecords(this ORM_O01_PATIENT message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORM_O01_PATIENT
/// </summary>
public static List<NTE> GetAllNTERecords(this ORM_O01_PATIENT message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORM_O01_PATIENT to NTE
/// </summary>
public static NTE AddNTE(this ORM_O01_PATIENT message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORR_O02_ORDER
/// </summary>
public static IEnumerable GetNTERecords(this ORR_O02_ORDER message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORR_O02_ORDER
/// </summary>
public static List<NTE> GetAllNTERecords(this ORR_O02_ORDER message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORR_O02_ORDER to NTE
/// </summary>
public static NTE AddNTE(this ORR_O02_ORDER message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORR_O02_PATIENT
/// </summary>
public static IEnumerable GetNTERecords(this ORR_O02_PATIENT message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORR_O02_PATIENT
/// </summary>
public static List<NTE> GetAllNTERecords(this ORR_O02_PATIENT message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORR_O02_PATIENT to NTE
/// </summary>
public static NTE AddNTE(this ORR_O02_PATIENT message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get ORDER Records from ORR_O02_PATIENT
/// </summary>
public static IEnumerable GetORDERRecords(this ORR_O02_PATIENT message)
{
object[] result = message.GetRecords("ORDERRepetitionsUsed", "GetORDER");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all ORDER Records from ORR_O02_PATIENT
/// </summary>
public static List<ORR_O02_ORDER> GetAllORDERRecords(this ORR_O02_PATIENT message)
{
return message.GetAllRecords<ORR_O02_ORDER>("ORDERRepetitionsUsed", "GetORDER");
}
/// <summary>
/// Add a new ORR_O02_PATIENT to ORDER
/// </summary>
public static ORR_O02_ORDER AddORDER(this ORR_O02_PATIENT message)
{
return message.GetORDER(message.ORDERRepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORU_R01_OBSERVATION
/// </summary>
public static IEnumerable GetNTERecords(this ORU_R01_OBSERVATION message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORU_R01_OBSERVATION
/// </summary>
public static List<NTE> GetAllNTERecords(this ORU_R01_OBSERVATION message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORU_R01_OBSERVATION to NTE
/// </summary>
public static NTE AddNTE(this ORU_R01_OBSERVATION message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORU_R01_ORDER_OBSERVATION
/// </summary>
public static IEnumerable GetNTERecords(this ORU_R01_ORDER_OBSERVATION message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORU_R01_ORDER_OBSERVATION
/// </summary>
public static List<NTE> GetAllNTERecords(this ORU_R01_ORDER_OBSERVATION message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORU_R01_ORDER_OBSERVATION to NTE
/// </summary>
public static NTE AddNTE(this ORU_R01_ORDER_OBSERVATION message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get OBSERVATION Records from ORU_R01_ORDER_OBSERVATION
/// </summary>
public static IEnumerable GetOBSERVATIONRecords(this ORU_R01_ORDER_OBSERVATION message)
{
object[] result = message.GetRecords("OBSERVATIONRepetitionsUsed", "GetOBSERVATION");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all OBSERVATION Records from ORU_R01_ORDER_OBSERVATION
/// </summary>
public static List<ORU_R01_OBSERVATION> GetAllOBSERVATIONRecords(this ORU_R01_ORDER_OBSERVATION message)
{
return message.GetAllRecords<ORU_R01_OBSERVATION>("OBSERVATIONRepetitionsUsed", "GetOBSERVATION");
}
/// <summary>
/// Add a new ORU_R01_ORDER_OBSERVATION to OBSERVATION
/// </summary>
public static ORU_R01_OBSERVATION AddOBSERVATION(this ORU_R01_ORDER_OBSERVATION message)
{
return message.GetOBSERVATION(message.OBSERVATIONRepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORU_R01_PATIENT
/// </summary>
public static IEnumerable GetNTERecords(this ORU_R01_PATIENT message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORU_R01_PATIENT
/// </summary>
public static List<NTE> GetAllNTERecords(this ORU_R01_PATIENT message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORU_R01_PATIENT to NTE
/// </summary>
public static NTE AddNTE(this ORU_R01_PATIENT message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get ORDER_OBSERVATION Records from ORU_R01_PATIENT_RESULT
/// </summary>
public static IEnumerable GetORDER_OBSERVATIONRecords(this ORU_R01_PATIENT_RESULT message)
{
object[] result = message.GetRecords("ORDER_OBSERVATIONRepetitionsUsed", "GetORDER_OBSERVATION");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all ORDER_OBSERVATION Records from ORU_R01_PATIENT_RESULT
/// </summary>
public static List<ORU_R01_ORDER_OBSERVATION> GetAllORDER_OBSERVATIONRecords(this ORU_R01_PATIENT_RESULT message)
{
return message.GetAllRecords<ORU_R01_ORDER_OBSERVATION>("ORDER_OBSERVATIONRepetitionsUsed", "GetORDER_OBSERVATION");
}
/// <summary>
/// Add a new ORU_R01_PATIENT_RESULT to ORDER_OBSERVATION
/// </summary>
public static ORU_R01_ORDER_OBSERVATION AddORDER_OBSERVATION(this ORU_R01_PATIENT_RESULT message)
{
return message.GetORDER_OBSERVATION(message.ORDER_OBSERVATIONRepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORU_R03_OBSERVATION
/// </summary>
public static IEnumerable GetNTERecords(this ORU_R03_OBSERVATION message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORU_R03_OBSERVATION
/// </summary>
public static List<NTE> GetAllNTERecords(this ORU_R03_OBSERVATION message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORU_R03_OBSERVATION to NTE
/// </summary>
public static NTE AddNTE(this ORU_R03_OBSERVATION message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORU_R03_ORDER_OBSERVATION
/// </summary>
public static IEnumerable GetNTERecords(this ORU_R03_ORDER_OBSERVATION message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORU_R03_ORDER_OBSERVATION
/// </summary>
public static List<NTE> GetAllNTERecords(this ORU_R03_ORDER_OBSERVATION message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORU_R03_ORDER_OBSERVATION to NTE
/// </summary>
public static NTE AddNTE(this ORU_R03_ORDER_OBSERVATION message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get OBSERVATION Records from ORU_R03_ORDER_OBSERVATION
/// </summary>
public static IEnumerable GetOBSERVATIONRecords(this ORU_R03_ORDER_OBSERVATION message)
{
object[] result = message.GetRecords("OBSERVATIONRepetitionsUsed", "GetOBSERVATION");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all OBSERVATION Records from ORU_R03_ORDER_OBSERVATION
/// </summary>
public static List<ORU_R03_OBSERVATION> GetAllOBSERVATIONRecords(this ORU_R03_ORDER_OBSERVATION message)
{
return message.GetAllRecords<ORU_R03_OBSERVATION>("OBSERVATIONRepetitionsUsed", "GetOBSERVATION");
}
/// <summary>
/// Add a new ORU_R03_ORDER_OBSERVATION to OBSERVATION
/// </summary>
public static ORU_R03_OBSERVATION AddOBSERVATION(this ORU_R03_ORDER_OBSERVATION message)
{
return message.GetOBSERVATION(message.OBSERVATIONRepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORU_R03_PATIENT
/// </summary>
public static IEnumerable GetNTERecords(this ORU_R03_PATIENT message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORU_R03_PATIENT
/// </summary>
public static List<NTE> GetAllNTERecords(this ORU_R03_PATIENT message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORU_R03_PATIENT to NTE
/// </summary>
public static NTE AddNTE(this ORU_R03_PATIENT message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get ORDER_OBSERVATION Records from ORU_R03_PATIENT_RESULT
/// </summary>
public static IEnumerable GetORDER_OBSERVATIONRecords(this ORU_R03_PATIENT_RESULT message)
{
object[] result = message.GetRecords("ORDER_OBSERVATIONRepetitionsUsed", "GetORDER_OBSERVATION");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all ORDER_OBSERVATION Records from ORU_R03_PATIENT_RESULT
/// </summary>
public static List<ORU_R03_ORDER_OBSERVATION> GetAllORDER_OBSERVATIONRecords(this ORU_R03_PATIENT_RESULT message)
{
return message.GetAllRecords<ORU_R03_ORDER_OBSERVATION>("ORDER_OBSERVATIONRepetitionsUsed", "GetORDER_OBSERVATION");
}
/// <summary>
/// Add a new ORU_R03_PATIENT_RESULT to ORDER_OBSERVATION
/// </summary>
public static ORU_R03_ORDER_OBSERVATION AddORDER_OBSERVATION(this ORU_R03_PATIENT_RESULT message)
{
return message.GetORDER_OBSERVATION(message.ORDER_OBSERVATIONRepetitionsUsed);
}
#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.Threading;
using Xunit;
namespace System.Transactions.Tests
{
// Ported from Mono
public class AsyncTest : IDisposable
{
public AsyncTest()
{
s_delayedException = null;
s_called = false;
s_mr.Reset();
s_state = 0;
Transaction.Current = null;
}
public void Dispose()
{
Transaction.Current = null;
}
[Fact]
public void AsyncFail1()
{
Assert.Throws<InvalidOperationException>(() =>
{
IntResourceManager irm = new IntResourceManager(1);
CommittableTransaction ct = new CommittableTransaction();
/* Set ambient Tx */
Transaction.Current = ct;
/* Enlist */
irm.Value = 2;
IAsyncResult ar = ct.BeginCommit(null, null);
IAsyncResult ar2 = ct.BeginCommit(null, null);
});
}
[Fact]
public void AsyncFail2()
{
Assert.Throws<TransactionAbortedException>(() =>
{
IntResourceManager irm = new IntResourceManager(1);
CommittableTransaction ct = new CommittableTransaction();
/* Set ambient Tx */
Transaction.Current = ct;
/* Enlist */
irm.Value = 2;
irm.FailPrepare = true;
IAsyncResult ar = ct.BeginCommit(null, null);
ct.EndCommit(ar);
});
}
private AsyncCallback _callback = null;
private static int s_state = 0;
/* Callback called ? */
private static bool s_called = false;
private static ManualResetEvent s_mr = new ManualResetEvent(false);
private static Exception s_delayedException;
private static void CommitCallback(IAsyncResult ar)
{
s_called = true;
CommittableTransaction ct = ar as CommittableTransaction;
try
{
s_state = (int)ar.AsyncState;
ct.EndCommit(ar);
}
catch (Exception e)
{
s_delayedException = e;
}
finally
{
s_mr.Set();
}
}
[Fact]
public void AsyncFail3()
{
s_delayedException = null;
IntResourceManager irm = new IntResourceManager(1);
CommittableTransaction ct = new CommittableTransaction();
/* Set ambient Tx */
Transaction.Current = ct;
/* Enlist */
irm.Value = 2;
irm.FailPrepare = true;
_callback = new AsyncCallback(CommitCallback);
IAsyncResult ar = ct.BeginCommit(_callback, 5);
s_mr.WaitOne(new TimeSpan(0, 0, 60));
Assert.True(s_called, "callback not called");
Assert.Equal(5, s_state);
Assert.IsType<TransactionAbortedException>(s_delayedException);
}
[Fact]
public void Async1()
{
IntResourceManager irm = new IntResourceManager(1);
CommittableTransaction ct = new CommittableTransaction();
/* Set ambient Tx */
Transaction.Current = ct;
/* Enlist */
irm.Value = 2;
_callback = new AsyncCallback(CommitCallback);
IAsyncResult ar = ct.BeginCommit(_callback, 5);
s_mr.WaitOne(new TimeSpan(0, 2, 0));
Assert.True(s_called, "callback not called");
Assert.Equal(5, s_state);
if (s_delayedException != null)
throw new Exception("", s_delayedException);
}
[Fact]
public void Async2()
{
IntResourceManager irm = new IntResourceManager(1);
CommittableTransaction ct = new CommittableTransaction();
using (TransactionScope scope = new TransactionScope(ct))
{
irm.Value = 2;
//scope.Complete ();
IAsyncResult ar = ct.BeginCommit(null, null);
Assert.Throws<TransactionAbortedException>(() => ct.EndCommit(ar));
irm.Check(0, 0, 1, 0, "irm");
}
}
[Fact]
public void Async3()
{
IntResourceManager irm = new IntResourceManager(1);
CommittableTransaction ct = new CommittableTransaction();
/* Set ambient Tx */
Transaction.Current = ct;
/* Enlist */
irm.Value = 2;
IAsyncResult ar = ct.BeginCommit(null, null);
ct.EndCommit(ar);
irm.Check(1, 1, 0, 0, "irm");
}
[Fact]
public void Async4()
{
IntResourceManager irm = new IntResourceManager(1);
CommittableTransaction ct = new CommittableTransaction();
/* Set ambient Tx */
Transaction.Current = ct;
/* Enlist */
irm.Value = 2;
IAsyncResult ar = ct.BeginCommit(null, null);
ar.AsyncWaitHandle.WaitOne();
Assert.True(ar.IsCompleted);
irm.Check(1, 1, 0, 0, "irm");
}
[Fact]
public void Async5()
{
IntResourceManager irm = new IntResourceManager(1);
CommittableTransaction ct = new CommittableTransaction();
/* Set ambient Tx */
Transaction.Current = ct;
/* Enlist */
irm.Value = 2;
irm.FailPrepare = true;
IAsyncResult ar = ct.BeginCommit(null, null);
ar.AsyncWaitHandle.WaitOne();
Assert.True(ar.IsCompleted);
CommittableTransaction ctx = ar as CommittableTransaction;
Assert.Throws<TransactionAbortedException>(() => ctx.EndCommit(ar));
irm.Check(1, 0, 0, 0, "irm");
}
}
}
| |
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Interop;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System.Windows.Forms;
using SaveFileDialog = System.Windows.Forms.SaveFileDialog;
using DialogResult = System.Windows.Forms.DialogResult;
#endregion // Namespaces
namespace Etude
{
[Transaction( TransactionMode.Manual )]
public class Command : IExternalCommand
{
/// <summary>
/// Custom assembly resolver to find our support
/// DLL without being forced to place our entire
/// application in a subfolder of the Revit.exe
/// directory.
/// </summary>
System.Reflection.Assembly
CurrentDomain_AssemblyResolve(
object sender,
ResolveEventArgs args )
{
if( args.Name.Contains( "Newtonsoft" ) )
{
string filename = Path.GetDirectoryName(
System.Reflection.Assembly
.GetExecutingAssembly().Location );
filename = Path.Combine( filename,
"Newtonsoft.Json.dll" );
if( File.Exists( filename ) )
{
return System.Reflection.Assembly
.LoadFrom( filename );
}
}
return null;
}
/// <summary>
/// Export a given 3D view to JSON using
/// our custom exporter context.
/// </summary>
public void ExportView3D(
View3D view3d,
string filename )
{
AppDomain.CurrentDomain.AssemblyResolve
+= CurrentDomain_AssemblyResolve;
Document doc = view3d.Document;
ExportContext context
= new ExportContext( doc, filename );
CustomExporter exporter = new CustomExporter(
doc, context );
// Note: Excluding faces just suppresses the
// OnFaceBegin calls, not the actual processing
// of face tessellation. Meshes of the faces
// will still be received by the context.
//exporter.IncludeFaces = false;
exporter.ShouldStopOnError = false;
exporter.Export( view3d );
}
#region UI to Filter Parameters
public static ParameterFilter _filter;
public static TabControl _tabControl;
public static Dictionary<string, List<string>> _parameterDictionary;
public static Dictionary<string, List<string>> _toExportDictionary;
/// <summary>
/// Function to filter the parameters of the objects in the scene
/// </summary>
/// <param name="doc">Revit Document</param>
/// <param name="includeType">Include Type Parameters in the filter dialog</param>
public void filterElementParameters( Document doc, bool includeType )
{
_parameterDictionary = new Dictionary<string, List<string>>();
_toExportDictionary = new Dictionary<string, List<string>>();
FilteredElementCollector collector = new FilteredElementCollector( doc, doc.ActiveView.Id );
// Create a dictionary with all the properties for each category.
foreach( var fi in collector )
{
string category = fi.Category.Name;
if( category != "Title Blocks" && category != "Generic Annotations" && category != "Detail Items" && category != "Cameras" )
{
IList<Parameter> parameters = fi.GetOrderedParameters();
List<string> parameterNames = new List<string>();
foreach( Parameter p in parameters )
{
string pName = p.Definition.Name;
string tempVal = "";
if( StorageType.String == p.StorageType )
{
tempVal = p.AsString();
}
else
{
tempVal = p.AsValueString();
}
if( !string.IsNullOrEmpty( tempVal ) )
{
if( _parameterDictionary.ContainsKey( category ) )
{
if( !_parameterDictionary[category].Contains( pName ) )
{
_parameterDictionary[category].Add( pName );
}
}
else
{
parameterNames.Add( pName );
}
}
}
if( parameterNames.Count > 0 )
{
_parameterDictionary.Add( category, parameterNames );
}
if( includeType )
{
ElementId idType = fi.GetTypeId();
if( ElementId.InvalidElementId != idType )
{
Element typ = doc.GetElement( idType );
parameters = typ.GetOrderedParameters();
List<string> parameterTypes = new List<string>();
foreach( Parameter p in parameters )
{
string pName = "Type " + p.Definition.Name;
string tempVal = "";
if( !_parameterDictionary[category].Contains( pName ) )
{
if( StorageType.String == p.StorageType )
{
tempVal = p.AsString();
}
else
{
tempVal = p.AsValueString();
}
if( !string.IsNullOrEmpty( tempVal ) )
{
if( _parameterDictionary.ContainsKey( category ) )
{
if( !_parameterDictionary[category].Contains( pName ) )
{
_parameterDictionary[category].Add( pName );
}
}
else
{
parameterTypes.Add( pName );
}
}
}
}
if( parameterTypes.Count > 0 )
{
_parameterDictionary[category].AddRange( parameterTypes );
}
}
}
}
}
// Create filter UI.
_filter = new ParameterFilter();
_tabControl = new TabControl();
_tabControl.Size = new System.Drawing.Size( 600, 375 );
_tabControl.Location = new System.Drawing.Point( 0, 55 );
_tabControl.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom )
| System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
int j = 8;
// Populate the parameters as a checkbox in each tab
foreach( string c in _parameterDictionary.Keys )
{
//Create a checklist
CheckedListBox checkList = new CheckedListBox();
//set the properties of the checklist
checkList.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) );
checkList.FormattingEnabled = true;
checkList.HorizontalScrollbar = true;
checkList.Items.AddRange( _parameterDictionary[c].ToArray() );
checkList.MultiColumn = true;
checkList.Size = new System.Drawing.Size( 560, 360 );
checkList.ColumnWidth = 200;
checkList.CheckOnClick = true;
checkList.TabIndex = j;
j++;
for( int i = 0; i <= ( checkList.Items.Count - 1 ); i++ )
{
checkList.SetItemCheckState( i, CheckState.Checked );
}
//add a tab
TabPage tab = new TabPage( c );
tab.Name = c;
//attach the checklist to the tab
tab.Controls.Add( checkList );
// attach the tab to the tab control
_tabControl.TabPages.Add( tab );
}
// Attach the tab control to the filter form
_filter.Controls.Add( _tabControl );
// Display filter ui
_filter.ShowDialog();
// Loop thru each tab and get the parameters to export
foreach( TabPage tab in _tabControl.TabPages )
{
List<string> parametersToExport = new List<string>();
foreach( var checkedP in ( (CheckedListBox) tab.Controls[0] ).CheckedItems )
{
parametersToExport.Add( checkedP.ToString() );
}
_toExportDictionary.Add( tab.Name, parametersToExport );
}
}
#endregion // UI to Filter Parameters
#region SelectFile
/// <summary>
/// Store the last user selected output folder
/// in the current editing session.
/// </summary>
static string _output_folder_path = null;
/// <summary>
/// Return true is user selects and confirms
/// output file name and folder.
/// </summary>
static bool SelectFile(
ref string folder_path,
ref string filename )
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Select JSON Output File";
dlg.Filter = "JSON files|*.js";
if( null != folder_path
&& 0 < folder_path.Length )
{
dlg.InitialDirectory = folder_path;
}
dlg.FileName = filename;
bool rc = DialogResult.OK == dlg.ShowDialog();
if( rc )
{
filename = Path.Combine( dlg.InitialDirectory,
dlg.FileName );
folder_path = Path.GetDirectoryName(
filename );
}
return rc;
}
#endregion // SelectFile
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Autodesk.Revit.ApplicationServices.Application app
= uiapp.Application;
Document doc = uidoc.Document;
// Check that we are in a 3D view.
View3D view = doc.ActiveView as View3D;
if( null == view )
{
Util.ErrorMsg(
"You must be in a 3D view to export." );
return Result.Failed;
}
// Prompt for output filename selection.
string filename = doc.PathName;
if( 0 == filename.Length )
{
filename = doc.Title;
}
if( null == _output_folder_path )
{
// Sometimes the command fails if the file is
// detached from central and not saved locally
try
{
_output_folder_path = Path.GetDirectoryName(
filename );
}
catch
{
TaskDialog.Show( "Folder not found",
"Please save the file and run the command again." );
return Result.Failed;
}
}
filename = Path.GetFileName( filename ) + ".js";
if( !SelectFile( ref _output_folder_path,
ref filename ) )
{
return Result.Cancelled;
}
filename = Path.Combine( _output_folder_path,
filename );
// Ask user whether to interactively choose
// which parameters to export or just export
// them all.
TaskDialog td = new TaskDialog( "Ask user to filter parameters" );
td.Title = "Filter parameters";
td.CommonButtons = TaskDialogCommonButtons.No | TaskDialogCommonButtons.Yes;
td.MainInstruction = "Do you want to filter the parameters of the objects to be exported?";
td.MainContent = "Click Yes and you will be able to select parameters for each category in the next window";
td.AllowCancellation = true;
td.VerificationText = "Check this to include type properties";
if( TaskDialogResult.Yes == td.Show() )
{
filterElementParameters( doc, td.WasVerificationChecked() );
if( ParameterFilter.status == "cancelled" )
{
ParameterFilter.status = "";
return Result.Cancelled;
}
}
// Save file.
ExportView3D( doc.ActiveView as View3D,
filename );
return Result.Succeeded;
}
}
}
| |
namespace WebMConverter
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.buttonBrowseOut = new System.Windows.Forms.Button();
this.textBoxOut = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.textBoxIn = new System.Windows.Forms.TextBox();
this.buttonGo = new System.Windows.Forms.Button();
this.buttonBrowseIn = new System.Windows.Forms.Button();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel13 = new System.Windows.Forms.TableLayoutPanel();
this.label23 = new System.Windows.Forms.Label();
this.boxAudio = new System.Windows.Forms.CheckBox();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel11 = new System.Windows.Forms.TableLayoutPanel();
this.label19 = new System.Windows.Forms.Label();
this.boxMetadataTitle = new System.Windows.Forms.TextBox();
this.label20 = new System.Windows.Forms.Label();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel();
this.label25 = new System.Windows.Forms.Label();
this.boxHQ = new System.Windows.Forms.CheckBox();
this.label24 = new System.Windows.Forms.Label();
this.label22 = new System.Windows.Forms.Label();
this.tableLayoutPanel9 = new System.Windows.Forms.TableLayoutPanel();
this.boxCropTo = new System.Windows.Forms.TextBox();
this.boxCropFrom = new System.Windows.Forms.TextBox();
this.label17 = new System.Windows.Forms.Label();
this.tableLayoutPanel7 = new System.Windows.Forms.TableLayoutPanel();
this.boxLimit = new System.Windows.Forms.TextBox();
this.label16 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.tableLayoutPanel8 = new System.Windows.Forms.TableLayoutPanel();
this.boxBitrate = new System.Windows.Forms.TextBox();
this.label13 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.tableLayoutPanel6 = new System.Windows.Forms.TableLayoutPanel();
this.boxResH = new System.Windows.Forms.TextBox();
this.boxResW = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.tableLayoutPanel14 = new System.Windows.Forms.TableLayoutPanel();
this.buttonOpenCrop = new System.Windows.Forms.Button();
this.labelCrop = new System.Windows.Forms.Label();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel10 = new System.Windows.Forms.TableLayoutPanel();
this.label7 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.tableLayoutPanel12 = new System.Windows.Forms.TableLayoutPanel();
this.trackThreads = new System.Windows.Forms.TrackBar();
this.labelThreads = new System.Windows.Forms.Label();
this.label18 = new System.Windows.Forms.Label();
this.checkBox2Pass = new System.Windows.Forms.CheckBox();
this.label3 = new System.Windows.Forms.Label();
this.textBoxArguments = new System.Windows.Forms.TextBox();
this.label21 = new System.Windows.Forms.Label();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.tableLayoutPanel15 = new System.Windows.Forms.TableLayoutPanel();
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel16 = new System.Windows.Forms.TableLayoutPanel();
this.radioSubNone = new System.Windows.Forms.RadioButton();
this.radioSubInternal = new System.Windows.Forms.RadioButton();
this.radioSubExternal = new System.Windows.Forms.RadioButton();
this.label26 = new System.Windows.Forms.Label();
this.label27 = new System.Windows.Forms.Label();
this.tableLayoutPanel17 = new System.Windows.Forms.TableLayoutPanel();
this.buttonSubBrowse = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label28 = new System.Windows.Forms.Label();
this.label29 = new System.Windows.Forms.Label();
this.label30 = new System.Windows.Forms.Label();
this.label31 = new System.Windows.Forms.Label();
this.tableLayoutPanel1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this.groupBox2.SuspendLayout();
this.tableLayoutPanel13.SuspendLayout();
this.groupBox5.SuspendLayout();
this.tableLayoutPanel11.SuspendLayout();
this.groupBox4.SuspendLayout();
this.tableLayoutPanel5.SuspendLayout();
this.tableLayoutPanel9.SuspendLayout();
this.tableLayoutPanel7.SuspendLayout();
this.tableLayoutPanel8.SuspendLayout();
this.tableLayoutPanel6.SuspendLayout();
this.tableLayoutPanel14.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tableLayoutPanel4.SuspendLayout();
this.groupBox3.SuspendLayout();
this.tableLayoutPanel10.SuspendLayout();
this.tableLayoutPanel12.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trackThreads)).BeginInit();
this.tabPage3.SuspendLayout();
this.tableLayoutPanel15.SuspendLayout();
this.groupBox6.SuspendLayout();
this.tableLayoutPanel16.SuspendLayout();
this.tableLayoutPanel17.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.tabControl1, 0, 1);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 84F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(1067, 440);
this.tableLayoutPanel1.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.tableLayoutPanel2);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(3, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(1061, 78);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Main";
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.ColumnCount = 4;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 69F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 68F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 77F));
this.tableLayoutPanel2.Controls.Add(this.buttonBrowseOut, 2, 1);
this.tableLayoutPanel2.Controls.Add(this.textBoxOut, 1, 1);
this.tableLayoutPanel2.Controls.Add(this.label4, 0, 1);
this.tableLayoutPanel2.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.textBoxIn, 1, 0);
this.tableLayoutPanel2.Controls.Add(this.buttonGo, 3, 0);
this.tableLayoutPanel2.Controls.Add(this.buttonBrowseIn, 2, 0);
this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 2;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.Size = new System.Drawing.Size(1055, 59);
this.tableLayoutPanel2.TabIndex = 0;
//
// buttonBrowseOut
//
this.buttonBrowseOut.Dock = System.Windows.Forms.DockStyle.Fill;
this.buttonBrowseOut.Location = new System.Drawing.Point(913, 32);
this.buttonBrowseOut.Name = "buttonBrowseOut";
this.buttonBrowseOut.Size = new System.Drawing.Size(62, 24);
this.buttonBrowseOut.TabIndex = 5;
this.buttonBrowseOut.Text = "Browse";
this.buttonBrowseOut.UseVisualStyleBackColor = true;
this.buttonBrowseOut.Click += new System.EventHandler(this.buttonBrowseOut_Click);
//
// textBoxOut
//
this.textBoxOut.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.textBoxOut.Location = new System.Drawing.Point(72, 34);
this.textBoxOut.Name = "textBoxOut";
this.textBoxOut.Size = new System.Drawing.Size(835, 20);
this.textBoxOut.TabIndex = 4;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Dock = System.Windows.Forms.DockStyle.Fill;
this.label4.Location = new System.Drawing.Point(3, 29);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(63, 30);
this.label4.TabIndex = 3;
this.label4.Text = "Output file:";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(63, 29);
this.label1.TabIndex = 0;
this.label1.Text = "Input file:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textBoxIn
//
this.textBoxIn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.textBoxIn.Location = new System.Drawing.Point(72, 4);
this.textBoxIn.Name = "textBoxIn";
this.textBoxIn.Size = new System.Drawing.Size(835, 20);
this.textBoxIn.TabIndex = 1;
//
// buttonGo
//
this.buttonGo.Dock = System.Windows.Forms.DockStyle.Fill;
this.buttonGo.Location = new System.Drawing.Point(981, 3);
this.buttonGo.Name = "buttonGo";
this.tableLayoutPanel2.SetRowSpan(this.buttonGo, 2);
this.buttonGo.Size = new System.Drawing.Size(71, 53);
this.buttonGo.TabIndex = 6;
this.buttonGo.Text = "Convert";
this.buttonGo.UseVisualStyleBackColor = true;
this.buttonGo.Click += new System.EventHandler(this.buttonGo_Click);
//
// buttonBrowseIn
//
this.buttonBrowseIn.Dock = System.Windows.Forms.DockStyle.Fill;
this.buttonBrowseIn.Location = new System.Drawing.Point(913, 3);
this.buttonBrowseIn.Name = "buttonBrowseIn";
this.buttonBrowseIn.Size = new System.Drawing.Size(62, 23);
this.buttonBrowseIn.TabIndex = 2;
this.buttonBrowseIn.Text = "Browse";
this.buttonBrowseIn.UseVisualStyleBackColor = true;
this.buttonBrowseIn.Click += new System.EventHandler(this.buttonBrowseIn_Click);
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(3, 87);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(1061, 350);
this.tabControl1.TabIndex = 6;
//
// tabPage1
//
this.tabPage1.BackColor = System.Drawing.SystemColors.Control;
this.tabPage1.Controls.Add(this.tableLayoutPanel3);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(1053, 324);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Basic";
//
// tableLayoutPanel3
//
this.tableLayoutPanel3.ColumnCount = 1;
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel3.Controls.Add(this.groupBox2, 0, 2);
this.tableLayoutPanel3.Controls.Add(this.groupBox5, 0, 0);
this.tableLayoutPanel3.Controls.Add(this.groupBox4, 0, 1);
this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 3;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 22.55639F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 77.44361F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 51F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel3.Size = new System.Drawing.Size(1047, 318);
this.tableLayoutPanel3.TabIndex = 0;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.tableLayoutPanel13);
this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox2.Location = new System.Drawing.Point(3, 269);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(1041, 46);
this.groupBox2.TabIndex = 7;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Audio";
//
// tableLayoutPanel13
//
this.tableLayoutPanel13.ColumnCount = 3;
this.tableLayoutPanel13.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 76F));
this.tableLayoutPanel13.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 203F));
this.tableLayoutPanel13.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel13.Controls.Add(this.label23, 2, 0);
this.tableLayoutPanel13.Controls.Add(this.boxAudio, 0, 0);
this.tableLayoutPanel13.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel13.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel13.Name = "tableLayoutPanel13";
this.tableLayoutPanel13.RowCount = 1;
this.tableLayoutPanel13.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel13.Size = new System.Drawing.Size(1035, 27);
this.tableLayoutPanel13.TabIndex = 0;
//
// label23
//
this.label23.AutoSize = true;
this.label23.Dock = System.Windows.Forms.DockStyle.Fill;
this.label23.Location = new System.Drawing.Point(282, 0);
this.label23.Name = "label23";
this.label23.Size = new System.Drawing.Size(750, 27);
this.label23.TabIndex = 2;
this.label23.Text = "Keep this disabled until Moot allows audio.";
this.label23.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// boxAudio
//
this.boxAudio.AutoSize = true;
this.boxAudio.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.tableLayoutPanel13.SetColumnSpan(this.boxAudio, 2);
this.boxAudio.Dock = System.Windows.Forms.DockStyle.Fill;
this.boxAudio.Location = new System.Drawing.Point(6, 3);
this.boxAudio.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this.boxAudio.Name = "boxAudio";
this.boxAudio.Size = new System.Drawing.Size(267, 21);
this.boxAudio.TabIndex = 3;
this.boxAudio.Text = "Enable audio:";
this.boxAudio.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.boxAudio.UseVisualStyleBackColor = true;
this.boxAudio.CheckedChanged += new System.EventHandler(this.UpdateArguments);
//
// groupBox5
//
this.groupBox5.Controls.Add(this.tableLayoutPanel11);
this.groupBox5.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox5.Location = new System.Drawing.Point(3, 3);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(1041, 54);
this.groupBox5.TabIndex = 6;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Metadata";
//
// tableLayoutPanel11
//
this.tableLayoutPanel11.ColumnCount = 3;
this.tableLayoutPanel11.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 76F));
this.tableLayoutPanel11.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 413F));
this.tableLayoutPanel11.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel11.Controls.Add(this.label19, 0, 0);
this.tableLayoutPanel11.Controls.Add(this.boxMetadataTitle, 1, 0);
this.tableLayoutPanel11.Controls.Add(this.label20, 2, 0);
this.tableLayoutPanel11.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel11.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel11.Name = "tableLayoutPanel11";
this.tableLayoutPanel11.RowCount = 1;
this.tableLayoutPanel11.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel11.Size = new System.Drawing.Size(1035, 35);
this.tableLayoutPanel11.TabIndex = 0;
//
// label19
//
this.label19.AutoSize = true;
this.label19.Dock = System.Windows.Forms.DockStyle.Fill;
this.label19.Location = new System.Drawing.Point(3, 0);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(70, 35);
this.label19.TabIndex = 0;
this.label19.Text = "Title:";
this.label19.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// boxMetadataTitle
//
this.boxMetadataTitle.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.boxMetadataTitle.Location = new System.Drawing.Point(82, 7);
this.boxMetadataTitle.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this.boxMetadataTitle.Name = "boxMetadataTitle";
this.boxMetadataTitle.Size = new System.Drawing.Size(401, 20);
this.boxMetadataTitle.TabIndex = 1;
this.boxMetadataTitle.TextChanged += new System.EventHandler(this.UpdateArguments);
//
// label20
//
this.label20.AutoSize = true;
this.label20.Dock = System.Windows.Forms.DockStyle.Fill;
this.label20.Location = new System.Drawing.Point(492, 0);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(540, 35);
this.label20.TabIndex = 2;
this.label20.Text = "Adds a string of text to the metadata of the video, which can be used to indicate" +
" the source of a video, for example. Leave blank for no title.";
this.label20.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.tableLayoutPanel5);
this.groupBox4.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox4.Location = new System.Drawing.Point(3, 63);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(1041, 200);
this.groupBox4.TabIndex = 5;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Video";
//
// tableLayoutPanel5
//
this.tableLayoutPanel5.ColumnCount = 3;
this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 76F));
this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 202F));
this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel5.Controls.Add(this.label25, 2, 5);
this.tableLayoutPanel5.Controls.Add(this.boxHQ, 0, 5);
this.tableLayoutPanel5.Controls.Add(this.label24, 2, 2);
this.tableLayoutPanel5.Controls.Add(this.label22, 0, 2);
this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel9, 1, 1);
this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel7, 1, 4);
this.tableLayoutPanel5.Controls.Add(this.label15, 0, 4);
this.tableLayoutPanel5.Controls.Add(this.label6, 2, 4);
this.tableLayoutPanel5.Controls.Add(this.label14, 2, 3);
this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel8, 1, 3);
this.tableLayoutPanel5.Controls.Add(this.label12, 0, 3);
this.tableLayoutPanel5.Controls.Add(this.label11, 2, 1);
this.tableLayoutPanel5.Controls.Add(this.label10, 0, 1);
this.tableLayoutPanel5.Controls.Add(this.label5, 2, 0);
this.tableLayoutPanel5.Controls.Add(this.label2, 0, 0);
this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel6, 1, 0);
this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel14, 1, 2);
this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel5.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel5.Name = "tableLayoutPanel5";
this.tableLayoutPanel5.RowCount = 6;
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));
this.tableLayoutPanel5.Size = new System.Drawing.Size(1035, 181);
this.tableLayoutPanel5.TabIndex = 0;
//
// label25
//
this.label25.AutoSize = true;
this.label25.Dock = System.Windows.Forms.DockStyle.Fill;
this.label25.Location = new System.Drawing.Point(281, 150);
this.label25.Name = "label25";
this.label25.Size = new System.Drawing.Size(751, 31);
this.label25.TabIndex = 16;
this.label25.Text = "Will greatly increase the quality/size ratio. Be warned, this will make the conve" +
"rsion take forever.";
this.label25.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// boxHQ
//
this.boxHQ.AutoSize = true;
this.boxHQ.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.tableLayoutPanel5.SetColumnSpan(this.boxHQ, 2);
this.boxHQ.Dock = System.Windows.Forms.DockStyle.Fill;
this.boxHQ.Location = new System.Drawing.Point(6, 153);
this.boxHQ.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this.boxHQ.Name = "boxHQ";
this.boxHQ.Size = new System.Drawing.Size(266, 25);
this.boxHQ.TabIndex = 15;
this.boxHQ.Text = "Enable high quality mode:";
this.boxHQ.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.boxHQ.UseVisualStyleBackColor = true;
this.boxHQ.CheckedChanged += new System.EventHandler(this.UpdateArguments);
//
// label24
//
this.label24.AutoSize = true;
this.label24.Dock = System.Windows.Forms.DockStyle.Fill;
this.label24.Location = new System.Drawing.Point(281, 60);
this.label24.Name = "label24";
this.label24.Size = new System.Drawing.Size(751, 30);
this.label24.TabIndex = 13;
this.label24.Text = "Crop a region out of the video. Click the Crop... button to select the region to " +
"be cropped. Useful for reaction videos.";
this.label24.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label22
//
this.label22.AutoSize = true;
this.label22.Dock = System.Windows.Forms.DockStyle.Fill;
this.label22.Location = new System.Drawing.Point(3, 60);
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size(70, 30);
this.label22.TabIndex = 12;
this.label22.Text = "Crop size:";
this.label22.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// tableLayoutPanel9
//
this.tableLayoutPanel9.ColumnCount = 3;
this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 16F));
this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel9.Controls.Add(this.boxCropTo, 2, 0);
this.tableLayoutPanel9.Controls.Add(this.boxCropFrom, 0, 0);
this.tableLayoutPanel9.Controls.Add(this.label17, 1, 0);
this.tableLayoutPanel9.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel9.Location = new System.Drawing.Point(79, 30);
this.tableLayoutPanel9.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.tableLayoutPanel9.Name = "tableLayoutPanel9";
this.tableLayoutPanel9.RowCount = 1;
this.tableLayoutPanel9.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel9.Size = new System.Drawing.Size(196, 30);
this.tableLayoutPanel9.TabIndex = 4;
//
// boxCropTo
//
this.boxCropTo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.boxCropTo.Location = new System.Drawing.Point(109, 5);
this.boxCropTo.Name = "boxCropTo";
this.boxCropTo.Size = new System.Drawing.Size(84, 20);
this.boxCropTo.TabIndex = 2;
this.boxCropTo.TextChanged += new System.EventHandler(this.UpdateArguments);
//
// boxCropFrom
//
this.boxCropFrom.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.boxCropFrom.Location = new System.Drawing.Point(3, 5);
this.boxCropFrom.Name = "boxCropFrom";
this.boxCropFrom.Size = new System.Drawing.Size(84, 20);
this.boxCropFrom.TabIndex = 0;
this.boxCropFrom.TextChanged += new System.EventHandler(this.UpdateArguments);
//
// label17
//
this.label17.AutoSize = true;
this.label17.Dock = System.Windows.Forms.DockStyle.Fill;
this.label17.Location = new System.Drawing.Point(90, 0);
this.label17.Margin = new System.Windows.Forms.Padding(0);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(16, 30);
this.label17.TabIndex = 1;
this.label17.Text = "to";
this.label17.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// tableLayoutPanel7
//
this.tableLayoutPanel7.ColumnCount = 2;
this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 40F));
this.tableLayoutPanel7.Controls.Add(this.boxLimit, 0, 0);
this.tableLayoutPanel7.Controls.Add(this.label16, 1, 0);
this.tableLayoutPanel7.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel7.Location = new System.Drawing.Point(79, 120);
this.tableLayoutPanel7.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.tableLayoutPanel7.Name = "tableLayoutPanel7";
this.tableLayoutPanel7.RowCount = 1;
this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel7.Size = new System.Drawing.Size(196, 30);
this.tableLayoutPanel7.TabIndex = 10;
//
// boxLimit
//
this.boxLimit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.boxLimit.Location = new System.Drawing.Point(3, 5);
this.boxLimit.Name = "boxLimit";
this.boxLimit.Size = new System.Drawing.Size(150, 20);
this.boxLimit.TabIndex = 0;
this.boxLimit.TextChanged += new System.EventHandler(this.UpdateArguments);
//
// label16
//
this.label16.AutoSize = true;
this.label16.Dock = System.Windows.Forms.DockStyle.Fill;
this.label16.Location = new System.Drawing.Point(159, 0);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(34, 30);
this.label16.TabIndex = 1;
this.label16.Text = "MB";
this.label16.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label15
//
this.label15.AutoSize = true;
this.label15.Dock = System.Windows.Forms.DockStyle.Fill;
this.label15.Location = new System.Drawing.Point(3, 120);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(70, 30);
this.label15.TabIndex = 9;
this.label15.Text = "Size limit:";
this.label15.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Dock = System.Windows.Forms.DockStyle.Fill;
this.label6.Location = new System.Drawing.Point(281, 120);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(751, 30);
this.label6.TabIndex = 11;
this.label6.Text = "Will adjust the quality to attempt to stay below this limit, and cut off the end " +
"of a video if needed. Leave blank for no limit. The limit on 4chan is 3 MB. If e" +
"ntering decimals use dots, not commas.";
this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label14
//
this.label14.AutoSize = true;
this.label14.Dock = System.Windows.Forms.DockStyle.Fill;
this.label14.Location = new System.Drawing.Point(281, 90);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(751, 30);
this.label14.TabIndex = 8;
this.label14.Text = "Determines the quality of the video. Keep blank to let the program pick one based" +
" on size limit and duration.";
this.label14.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tableLayoutPanel8
//
this.tableLayoutPanel8.ColumnCount = 2;
this.tableLayoutPanel8.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel8.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 40F));
this.tableLayoutPanel8.Controls.Add(this.boxBitrate, 0, 0);
this.tableLayoutPanel8.Controls.Add(this.label13, 1, 0);
this.tableLayoutPanel8.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel8.Location = new System.Drawing.Point(79, 90);
this.tableLayoutPanel8.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.tableLayoutPanel8.Name = "tableLayoutPanel8";
this.tableLayoutPanel8.RowCount = 1;
this.tableLayoutPanel8.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel8.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F));
this.tableLayoutPanel8.Size = new System.Drawing.Size(196, 30);
this.tableLayoutPanel8.TabIndex = 7;
//
// boxBitrate
//
this.boxBitrate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.boxBitrate.Location = new System.Drawing.Point(3, 5);
this.boxBitrate.Name = "boxBitrate";
this.boxBitrate.Size = new System.Drawing.Size(150, 20);
this.boxBitrate.TabIndex = 0;
this.boxBitrate.TextChanged += new System.EventHandler(this.UpdateArguments);
//
// label13
//
this.label13.AutoSize = true;
this.label13.Dock = System.Windows.Forms.DockStyle.Fill;
this.label13.Location = new System.Drawing.Point(159, 0);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(34, 30);
this.label13.TabIndex = 1;
this.label13.Text = "Kb/s";
this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Dock = System.Windows.Forms.DockStyle.Fill;
this.label12.Location = new System.Drawing.Point(3, 90);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(70, 30);
this.label12.TabIndex = 6;
this.label12.Text = "Bitrate:";
this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Dock = System.Windows.Forms.DockStyle.Fill;
this.label11.Location = new System.Drawing.Point(281, 30);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(751, 30);
this.label11.TabIndex = 5;
this.label11.Text = resources.GetString("label11.Text");
this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Dock = System.Windows.Forms.DockStyle.Fill;
this.label10.Location = new System.Drawing.Point(3, 30);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(70, 30);
this.label10.TabIndex = 3;
this.label10.Text = "Trim video:";
this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Dock = System.Windows.Forms.DockStyle.Fill;
this.label5.Location = new System.Drawing.Point(281, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(751, 30);
this.label5.TabIndex = 2;
this.label5.Text = "Enter nothing to keep resolution intact. Enter -1 in one of the fields to scale a" +
"ccording to aspect ratio.";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
this.label2.Location = new System.Drawing.Point(3, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(70, 30);
this.label2.TabIndex = 0;
this.label2.Text = "Resolution:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// tableLayoutPanel6
//
this.tableLayoutPanel6.ColumnCount = 3;
this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 16F));
this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel6.Controls.Add(this.boxResH, 2, 0);
this.tableLayoutPanel6.Controls.Add(this.boxResW, 0, 0);
this.tableLayoutPanel6.Controls.Add(this.label8, 1, 0);
this.tableLayoutPanel6.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel6.Location = new System.Drawing.Point(79, 0);
this.tableLayoutPanel6.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.tableLayoutPanel6.Name = "tableLayoutPanel6";
this.tableLayoutPanel6.RowCount = 1;
this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F));
this.tableLayoutPanel6.Size = new System.Drawing.Size(196, 30);
this.tableLayoutPanel6.TabIndex = 1;
//
// boxResH
//
this.boxResH.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.boxResH.Location = new System.Drawing.Point(109, 5);
this.boxResH.Name = "boxResH";
this.boxResH.Size = new System.Drawing.Size(84, 20);
this.boxResH.TabIndex = 2;
this.boxResH.TextChanged += new System.EventHandler(this.UpdateArguments);
//
// boxResW
//
this.boxResW.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.boxResW.Location = new System.Drawing.Point(3, 5);
this.boxResW.Name = "boxResW";
this.boxResW.Size = new System.Drawing.Size(84, 20);
this.boxResW.TabIndex = 0;
this.boxResW.TextChanged += new System.EventHandler(this.UpdateArguments);
//
// label8
//
this.label8.AutoSize = true;
this.label8.Dock = System.Windows.Forms.DockStyle.Fill;
this.label8.Location = new System.Drawing.Point(90, 0);
this.label8.Margin = new System.Windows.Forms.Padding(0);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(16, 30);
this.label8.TabIndex = 1;
this.label8.Text = "x";
this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// tableLayoutPanel14
//
this.tableLayoutPanel14.ColumnCount = 2;
this.tableLayoutPanel14.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel14.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 56F));
this.tableLayoutPanel14.Controls.Add(this.buttonOpenCrop, 1, 0);
this.tableLayoutPanel14.Controls.Add(this.labelCrop, 0, 0);
this.tableLayoutPanel14.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel14.Location = new System.Drawing.Point(79, 60);
this.tableLayoutPanel14.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.tableLayoutPanel14.Name = "tableLayoutPanel14";
this.tableLayoutPanel14.RowCount = 1;
this.tableLayoutPanel14.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel14.Size = new System.Drawing.Size(196, 30);
this.tableLayoutPanel14.TabIndex = 14;
//
// buttonOpenCrop
//
this.buttonOpenCrop.Dock = System.Windows.Forms.DockStyle.Fill;
this.buttonOpenCrop.Location = new System.Drawing.Point(143, 3);
this.buttonOpenCrop.Name = "buttonOpenCrop";
this.buttonOpenCrop.Size = new System.Drawing.Size(50, 24);
this.buttonOpenCrop.TabIndex = 0;
this.buttonOpenCrop.Text = "Crop...";
this.buttonOpenCrop.UseVisualStyleBackColor = true;
this.buttonOpenCrop.Click += new System.EventHandler(this.buttonOpenCrop_Click);
//
// labelCrop
//
this.labelCrop.AutoSize = true;
this.labelCrop.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCrop.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelCrop.Location = new System.Drawing.Point(3, 0);
this.labelCrop.Name = "labelCrop";
this.labelCrop.Size = new System.Drawing.Size(134, 30);
this.labelCrop.TabIndex = 1;
this.labelCrop.Text = "Don\'t crop";
this.labelCrop.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// tabPage2
//
this.tabPage2.BackColor = System.Drawing.SystemColors.Control;
this.tabPage2.Controls.Add(this.tableLayoutPanel4);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(1053, 324);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Advanced";
//
// tableLayoutPanel4
//
this.tableLayoutPanel4.ColumnCount = 1;
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel4.Controls.Add(this.groupBox3, 0, 0);
this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel4.Name = "tableLayoutPanel4";
this.tableLayoutPanel4.RowCount = 2;
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 163F));
this.tableLayoutPanel4.Size = new System.Drawing.Size(1047, 318);
this.tableLayoutPanel4.TabIndex = 0;
//
// groupBox3
//
this.groupBox3.AutoSize = true;
this.groupBox3.Controls.Add(this.tableLayoutPanel10);
this.groupBox3.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox3.Location = new System.Drawing.Point(3, 3);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(1041, 149);
this.groupBox3.TabIndex = 8;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Advanced";
//
// tableLayoutPanel10
//
this.tableLayoutPanel10.ColumnCount = 3;
this.tableLayoutPanel10.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 79F));
this.tableLayoutPanel10.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 148F));
this.tableLayoutPanel10.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel10.Controls.Add(this.label7, 0, 1);
this.tableLayoutPanel10.Controls.Add(this.label9, 2, 1);
this.tableLayoutPanel10.Controls.Add(this.tableLayoutPanel12, 1, 1);
this.tableLayoutPanel10.Controls.Add(this.label18, 2, 2);
this.tableLayoutPanel10.Controls.Add(this.checkBox2Pass, 0, 2);
this.tableLayoutPanel10.Controls.Add(this.label3, 0, 3);
this.tableLayoutPanel10.Controls.Add(this.textBoxArguments, 1, 3);
this.tableLayoutPanel10.Controls.Add(this.label21, 0, 0);
this.tableLayoutPanel10.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel10.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel10.Name = "tableLayoutPanel10";
this.tableLayoutPanel10.RowCount = 4;
this.tableLayoutPanel10.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F));
this.tableLayoutPanel10.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel10.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel10.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel10.Size = new System.Drawing.Size(1035, 130);
this.tableLayoutPanel10.TabIndex = 0;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Dock = System.Windows.Forms.DockStyle.Fill;
this.label7.Location = new System.Drawing.Point(3, 28);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(73, 34);
this.label7.TabIndex = 28;
this.label7.Text = "Threads:";
this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Dock = System.Windows.Forms.DockStyle.Fill;
this.label9.Location = new System.Drawing.Point(230, 28);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(802, 34);
this.label9.TabIndex = 27;
this.label9.Text = "Determines amount of threads ffmpeg uses. Try setting this to 1 if ffmpeg.exe cra" +
"shes as soon as you click Convert.";
this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tableLayoutPanel12
//
this.tableLayoutPanel12.ColumnCount = 2;
this.tableLayoutPanel12.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 86.18421F));
this.tableLayoutPanel12.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 13.81579F));
this.tableLayoutPanel12.Controls.Add(this.trackThreads, 0, 0);
this.tableLayoutPanel12.Controls.Add(this.labelThreads, 1, 0);
this.tableLayoutPanel12.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel12.Location = new System.Drawing.Point(82, 31);
this.tableLayoutPanel12.Name = "tableLayoutPanel12";
this.tableLayoutPanel12.RowCount = 1;
this.tableLayoutPanel12.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel12.Size = new System.Drawing.Size(142, 28);
this.tableLayoutPanel12.TabIndex = 26;
//
// trackThreads
//
this.trackThreads.Dock = System.Windows.Forms.DockStyle.Fill;
this.trackThreads.Location = new System.Drawing.Point(0, 0);
this.trackThreads.Margin = new System.Windows.Forms.Padding(0);
this.trackThreads.Maximum = 16;
this.trackThreads.Minimum = 1;
this.trackThreads.Name = "trackThreads";
this.trackThreads.Size = new System.Drawing.Size(122, 28);
this.trackThreads.TabIndex = 0;
this.trackThreads.Value = 1;
this.trackThreads.Scroll += new System.EventHandler(this.trackThreads_Scroll);
//
// labelThreads
//
this.labelThreads.AutoSize = true;
this.labelThreads.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelThreads.Location = new System.Drawing.Point(122, 0);
this.labelThreads.Margin = new System.Windows.Forms.Padding(0);
this.labelThreads.Name = "labelThreads";
this.labelThreads.Size = new System.Drawing.Size(20, 28);
this.labelThreads.TabIndex = 1;
this.labelThreads.Text = "1";
this.labelThreads.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label18
//
this.label18.AutoSize = true;
this.label18.Dock = System.Windows.Forms.DockStyle.Fill;
this.label18.Location = new System.Drawing.Point(230, 62);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(802, 34);
this.label18.TabIndex = 16;
this.label18.Text = "Will make ffmpeg use two passes, which can increase the quality/size ratio, but a" +
"lso increases the time it takes to encode. Disable if you run into any issues.";
this.label18.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// checkBox2Pass
//
this.checkBox2Pass.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.tableLayoutPanel10.SetColumnSpan(this.checkBox2Pass, 2);
this.checkBox2Pass.Dock = System.Windows.Forms.DockStyle.Fill;
this.checkBox2Pass.Location = new System.Drawing.Point(6, 65);
this.checkBox2Pass.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this.checkBox2Pass.Name = "checkBox2Pass";
this.checkBox2Pass.Size = new System.Drawing.Size(215, 28);
this.checkBox2Pass.TabIndex = 12;
this.checkBox2Pass.Text = "Enable 2-pass encoding:";
this.checkBox2Pass.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.checkBox2Pass.UseVisualStyleBackColor = true;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Dock = System.Windows.Forms.DockStyle.Fill;
this.label3.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.label3.Location = new System.Drawing.Point(3, 96);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(73, 34);
this.label3.TabIndex = 29;
this.label3.Text = "Arguments:";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textBoxArguments
//
this.textBoxArguments.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel10.SetColumnSpan(this.textBoxArguments, 2);
this.textBoxArguments.Location = new System.Drawing.Point(85, 103);
this.textBoxArguments.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this.textBoxArguments.Name = "textBoxArguments";
this.textBoxArguments.Size = new System.Drawing.Size(944, 20);
this.textBoxArguments.TabIndex = 30;
//
// label21
//
this.label21.AutoSize = true;
this.tableLayoutPanel10.SetColumnSpan(this.label21, 3);
this.label21.Dock = System.Windows.Forms.DockStyle.Fill;
this.label21.Location = new System.Drawing.Point(3, 3);
this.label21.Margin = new System.Windows.Forms.Padding(3);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(1029, 22);
this.label21.TabIndex = 31;
this.label21.Text = "Don\'t modify these unless you know what you\'re doing!";
this.label21.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tabPage3
//
this.tabPage3.BackColor = System.Drawing.SystemColors.Control;
this.tabPage3.Controls.Add(this.tableLayoutPanel15);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
this.tabPage3.Size = new System.Drawing.Size(1053, 324);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Subtitles";
//
// tableLayoutPanel15
//
this.tableLayoutPanel15.ColumnCount = 1;
this.tableLayoutPanel15.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel15.Controls.Add(this.groupBox6, 0, 0);
this.tableLayoutPanel15.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel15.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel15.Name = "tableLayoutPanel15";
this.tableLayoutPanel15.RowCount = 2;
this.tableLayoutPanel15.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 38.99371F));
this.tableLayoutPanel15.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 61.00629F));
this.tableLayoutPanel15.Size = new System.Drawing.Size(1047, 318);
this.tableLayoutPanel15.TabIndex = 0;
//
// groupBox6
//
this.groupBox6.Controls.Add(this.tableLayoutPanel16);
this.groupBox6.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox6.Location = new System.Drawing.Point(3, 3);
this.groupBox6.Name = "groupBox6";
this.groupBox6.Size = new System.Drawing.Size(1041, 117);
this.groupBox6.TabIndex = 0;
this.groupBox6.TabStop = false;
this.groupBox6.Text = "Subtitles";
//
// tableLayoutPanel16
//
this.tableLayoutPanel16.ColumnCount = 3;
this.tableLayoutPanel16.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 79F));
this.tableLayoutPanel16.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 233F));
this.tableLayoutPanel16.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel16.Controls.Add(this.label31, 2, 3);
this.tableLayoutPanel16.Controls.Add(this.label30, 2, 2);
this.tableLayoutPanel16.Controls.Add(this.label29, 2, 1);
this.tableLayoutPanel16.Controls.Add(this.radioSubNone, 1, 0);
this.tableLayoutPanel16.Controls.Add(this.radioSubInternal, 1, 1);
this.tableLayoutPanel16.Controls.Add(this.radioSubExternal, 1, 2);
this.tableLayoutPanel16.Controls.Add(this.label26, 0, 0);
this.tableLayoutPanel16.Controls.Add(this.label27, 0, 3);
this.tableLayoutPanel16.Controls.Add(this.tableLayoutPanel17, 1, 3);
this.tableLayoutPanel16.Controls.Add(this.label28, 2, 0);
this.tableLayoutPanel16.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel16.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel16.Name = "tableLayoutPanel16";
this.tableLayoutPanel16.RowCount = 4;
this.tableLayoutPanel16.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel16.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel16.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.tableLayoutPanel16.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 27F));
this.tableLayoutPanel16.Size = new System.Drawing.Size(1035, 98);
this.tableLayoutPanel16.TabIndex = 0;
//
// radioSubNone
//
this.radioSubNone.AutoSize = true;
this.radioSubNone.Checked = true;
this.radioSubNone.Dock = System.Windows.Forms.DockStyle.Fill;
this.radioSubNone.Enabled = false;
this.radioSubNone.Location = new System.Drawing.Point(82, 0);
this.radioSubNone.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.radioSubNone.Name = "radioSubNone";
this.radioSubNone.Size = new System.Drawing.Size(227, 23);
this.radioSubNone.TabIndex = 0;
this.radioSubNone.TabStop = true;
this.radioSubNone.Text = "None";
this.radioSubNone.UseVisualStyleBackColor = true;
//
// radioSubInternal
//
this.radioSubInternal.AutoSize = true;
this.radioSubInternal.Dock = System.Windows.Forms.DockStyle.Fill;
this.radioSubInternal.Enabled = false;
this.radioSubInternal.Location = new System.Drawing.Point(82, 23);
this.radioSubInternal.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.radioSubInternal.Name = "radioSubInternal";
this.radioSubInternal.Size = new System.Drawing.Size(227, 23);
this.radioSubInternal.TabIndex = 1;
this.radioSubInternal.Text = "Use internal";
this.radioSubInternal.UseVisualStyleBackColor = true;
//
// radioSubExternal
//
this.radioSubExternal.AutoSize = true;
this.radioSubExternal.Dock = System.Windows.Forms.DockStyle.Fill;
this.radioSubExternal.Enabled = false;
this.radioSubExternal.Location = new System.Drawing.Point(82, 46);
this.radioSubExternal.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.radioSubExternal.Name = "radioSubExternal";
this.radioSubExternal.Size = new System.Drawing.Size(227, 23);
this.radioSubExternal.TabIndex = 2;
this.radioSubExternal.Text = "Use from file";
this.radioSubExternal.UseVisualStyleBackColor = true;
//
// label26
//
this.label26.AutoSize = true;
this.label26.Dock = System.Windows.Forms.DockStyle.Fill;
this.label26.Location = new System.Drawing.Point(3, 0);
this.label26.Name = "label26";
this.tableLayoutPanel16.SetRowSpan(this.label26, 3);
this.label26.Size = new System.Drawing.Size(73, 69);
this.label26.TabIndex = 3;
this.label26.Text = "Subtitles:";
this.label26.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label27
//
this.label27.AutoSize = true;
this.label27.Dock = System.Windows.Forms.DockStyle.Fill;
this.label27.Location = new System.Drawing.Point(3, 69);
this.label27.Name = "label27";
this.label27.Size = new System.Drawing.Size(73, 29);
this.label27.TabIndex = 4;
this.label27.Text = "Subtitle file:";
this.label27.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// tableLayoutPanel17
//
this.tableLayoutPanel17.ColumnCount = 2;
this.tableLayoutPanel17.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel17.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 59F));
this.tableLayoutPanel17.Controls.Add(this.buttonSubBrowse, 1, 0);
this.tableLayoutPanel17.Controls.Add(this.textBox1, 0, 0);
this.tableLayoutPanel17.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel17.Location = new System.Drawing.Point(82, 69);
this.tableLayoutPanel17.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.tableLayoutPanel17.Name = "tableLayoutPanel17";
this.tableLayoutPanel17.RowCount = 1;
this.tableLayoutPanel17.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel17.Size = new System.Drawing.Size(227, 29);
this.tableLayoutPanel17.TabIndex = 5;
//
// buttonSubBrowse
//
this.buttonSubBrowse.Dock = System.Windows.Forms.DockStyle.Fill;
this.buttonSubBrowse.Enabled = false;
this.buttonSubBrowse.Location = new System.Drawing.Point(171, 3);
this.buttonSubBrowse.Name = "buttonSubBrowse";
this.buttonSubBrowse.Size = new System.Drawing.Size(53, 23);
this.buttonSubBrowse.TabIndex = 0;
this.buttonSubBrowse.Text = "Browse";
this.buttonSubBrowse.UseVisualStyleBackColor = true;
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Enabled = false;
this.textBox1.Location = new System.Drawing.Point(3, 4);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(162, 20);
this.textBox1.TabIndex = 1;
//
// label28
//
this.label28.AutoSize = true;
this.label28.Dock = System.Windows.Forms.DockStyle.Fill;
this.label28.Location = new System.Drawing.Point(315, 0);
this.label28.Name = "label28";
this.label28.Size = new System.Drawing.Size(717, 23);
this.label28.TabIndex = 6;
this.label28.Text = "Don\'t add any subtitles to the video.";
this.label28.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label29
//
this.label29.AutoSize = true;
this.label29.Dock = System.Windows.Forms.DockStyle.Fill;
this.label29.Location = new System.Drawing.Point(315, 23);
this.label29.Name = "label29";
this.label29.Size = new System.Drawing.Size(717, 23);
this.label29.TabIndex = 7;
this.label29.Text = "Add subtitles which are taken from the input video.";
this.label29.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label30
//
this.label30.AutoSize = true;
this.label30.Dock = System.Windows.Forms.DockStyle.Fill;
this.label30.Location = new System.Drawing.Point(315, 46);
this.label30.Name = "label30";
this.label30.Size = new System.Drawing.Size(717, 23);
this.label30.TabIndex = 8;
this.label30.Text = "Add subtitles which are taken from an external file. Use the box below to select " +
"the file.";
this.label30.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label31
//
this.label31.AutoSize = true;
this.label31.Dock = System.Windows.Forms.DockStyle.Fill;
this.label31.Location = new System.Drawing.Point(315, 69);
this.label31.Name = "label31";
this.label31.Size = new System.Drawing.Size(717, 29);
this.label31.TabIndex = 9;
this.label31.Text = "Select the subtitle file to use for the video. Supports *.ass and *.srt format.";
this.label31.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// MainForm
//
this.AcceptButton = this.buttonGo;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1073, 446);
this.Controls.Add(this.tableLayoutPanel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimumSize = new System.Drawing.Size(975, 270);
this.Name = "MainForm";
this.Padding = new System.Windows.Forms.Padding(3);
this.Text = "WebM for Retards";
this.Load += new System.EventHandler(this.MainForm_Load);
this.tableLayoutPanel1.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tableLayoutPanel3.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.tableLayoutPanel13.ResumeLayout(false);
this.tableLayoutPanel13.PerformLayout();
this.groupBox5.ResumeLayout(false);
this.tableLayoutPanel11.ResumeLayout(false);
this.tableLayoutPanel11.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.tableLayoutPanel5.ResumeLayout(false);
this.tableLayoutPanel5.PerformLayout();
this.tableLayoutPanel9.ResumeLayout(false);
this.tableLayoutPanel9.PerformLayout();
this.tableLayoutPanel7.ResumeLayout(false);
this.tableLayoutPanel7.PerformLayout();
this.tableLayoutPanel8.ResumeLayout(false);
this.tableLayoutPanel8.PerformLayout();
this.tableLayoutPanel6.ResumeLayout(false);
this.tableLayoutPanel6.PerformLayout();
this.tableLayoutPanel14.ResumeLayout(false);
this.tableLayoutPanel14.PerformLayout();
this.tabPage2.ResumeLayout(false);
this.tableLayoutPanel4.ResumeLayout(false);
this.tableLayoutPanel4.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.tableLayoutPanel10.ResumeLayout(false);
this.tableLayoutPanel10.PerformLayout();
this.tableLayoutPanel12.ResumeLayout(false);
this.tableLayoutPanel12.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.trackThreads)).EndInit();
this.tabPage3.ResumeLayout(false);
this.tableLayoutPanel15.ResumeLayout(false);
this.groupBox6.ResumeLayout(false);
this.tableLayoutPanel16.ResumeLayout(false);
this.tableLayoutPanel16.PerformLayout();
this.tableLayoutPanel17.ResumeLayout(false);
this.tableLayoutPanel17.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.Button buttonBrowseOut;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button buttonGo;
private System.Windows.Forms.Button buttonBrowseIn;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel11;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.TextBox boxMetadataTitle;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel9;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel7;
private System.Windows.Forms.TextBox boxLimit;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel8;
private System.Windows.Forms.TextBox boxBitrate;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel6;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel10;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel12;
private System.Windows.Forms.TrackBar trackThreads;
private System.Windows.Forms.Label labelThreads;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.CheckBox checkBox2Pass;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBoxArguments;
private System.Windows.Forms.Label label21;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel13;
private System.Windows.Forms.Label label23;
private System.Windows.Forms.CheckBox boxAudio;
private System.Windows.Forms.Label label24;
private System.Windows.Forms.Label label22;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel14;
private System.Windows.Forms.Button buttonOpenCrop;
private System.Windows.Forms.Label labelCrop;
public System.Windows.Forms.TextBox textBoxIn;
public System.Windows.Forms.TextBox boxCropTo;
public System.Windows.Forms.TextBox boxCropFrom;
public System.Windows.Forms.TextBox boxResH;
public System.Windows.Forms.TextBox boxResW;
public System.Windows.Forms.TextBox textBoxOut;
private System.Windows.Forms.Label label25;
private System.Windows.Forms.CheckBox boxHQ;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel15;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel16;
private System.Windows.Forms.RadioButton radioSubNone;
private System.Windows.Forms.RadioButton radioSubInternal;
private System.Windows.Forms.RadioButton radioSubExternal;
private System.Windows.Forms.Label label26;
private System.Windows.Forms.Label label27;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel17;
private System.Windows.Forms.Button buttonSubBrowse;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label31;
private System.Windows.Forms.Label label30;
private System.Windows.Forms.Label label29;
private System.Windows.Forms.Label label28;
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
namespace Vanara.PInvoke
{
/// <summary>
/// Formal replacement for the Windows HRESULT definition. In windows.h, it is a defined UINT value. For .NET, this class strongly types
/// the value.
/// <para>The 32-bit value is organized as follows:</para>
/// <list type="table">
/// <item>
/// <term>Bit</term>
/// <description>31</description>
/// <description>30</description>
/// <description>29</description>
/// <description>28</description>
/// <description>27</description>
/// <description>26 - 16</description>
/// <description>15 - 0</description>
/// </item>
/// <item>
/// <term>Field</term>
/// <description>Severity</description>
/// <description>Severity</description>
/// <description>Customer</description>
/// <description>NT status</description>
/// <description>MsgID</description>
/// <description>Facility</description>
/// <description>Code</description>
/// </item>
/// </list>
/// </summary>
/// <seealso cref="System.IComparable"/>
/// <seealso cref="System.IComparable{HRESULT}"/>
/// <seealso cref="System.IEquatable{HRESULT}"/>
[StructLayout(LayoutKind.Sequential)]
[TypeConverter(typeof(HRESULTTypeConverter))]
[PInvokeData("winerr.h")]
public partial struct HRESULT : IComparable, IComparable<HRESULT>, IEquatable<HRESULT>, IEquatable<int>, IEquatable<uint>, IConvertible, IErrorProvider
{
internal readonly int _value;
private const int codeMask = 0xFFFF;
private const uint facilityMask = 0x7FF0000;
private const int facilityShift = 16;
private const uint severityMask = 0x80000000;
private const int severityShift = 31;
/// <summary>Initializes a new instance of the <see cref="HRESULT"/> structure.</summary>
/// <param name="rawValue">The raw HRESULT value.</param>
public HRESULT(int rawValue) => _value = rawValue;
/// <summary>Initializes a new instance of the <see cref="HRESULT"/> structure.</summary>
/// <param name="rawValue">The raw HRESULT value.</param>
public HRESULT(uint rawValue) => _value = unchecked((int)rawValue);
/// <summary>Enumeration of facility codes</summary>
[PInvokeData("winerr.h")]
public enum FacilityCode
{
/// <summary>The default facility code.</summary>
FACILITY_NULL = 0,
/// <summary>The source of the error code is an RPC subsystem.</summary>
FACILITY_RPC = 1,
/// <summary>The source of the error code is a COM Dispatch.</summary>
FACILITY_DISPATCH = 2,
/// <summary>The source of the error code is OLE Storage.</summary>
FACILITY_STORAGE = 3,
/// <summary>The source of the error code is COM/OLE Interface management.</summary>
FACILITY_ITF = 4,
/// <summary>This region is reserved to map undecorated error codes into HRESULTs.</summary>
FACILITY_WIN32 = 7,
/// <summary>The source of the error code is the Windows subsystem.</summary>
FACILITY_WINDOWS = 8,
/// <summary>The source of the error code is the Security API layer.</summary>
FACILITY_SECURITY = 9,
/// <summary>The source of the error code is the Security API layer.</summary>
FACILITY_SSPI = 9,
/// <summary>The source of the error code is the control mechanism.</summary>
FACILITY_CONTROL = 10,
/// <summary>The source of the error code is a certificate client or server?</summary>
FACILITY_CERT = 11,
/// <summary>The source of the error code is Wininet related.</summary>
FACILITY_INTERNET = 12,
/// <summary>The source of the error code is the Windows Media Server.</summary>
FACILITY_MEDIASERVER = 13,
/// <summary>The source of the error code is the Microsoft Message Queue.</summary>
FACILITY_MSMQ = 14,
/// <summary>The source of the error code is the Setup API.</summary>
FACILITY_SETUPAPI = 15,
/// <summary>The source of the error code is the Smart-card subsystem.</summary>
FACILITY_SCARD = 16,
/// <summary>The source of the error code is COM+.</summary>
FACILITY_COMPLUS = 17,
/// <summary>The source of the error code is the Microsoft agent.</summary>
FACILITY_AAF = 18,
/// <summary>The source of the error code is .NET CLR.</summary>
FACILITY_URT = 19,
/// <summary>The source of the error code is the audit collection service.</summary>
FACILITY_ACS = 20,
/// <summary>The source of the error code is Direct Play.</summary>
FACILITY_DPLAY = 21,
/// <summary>The source of the error code is the ubiquitous memoryintrospection service.</summary>
FACILITY_UMI = 22,
/// <summary>The source of the error code is Side-by-side servicing.</summary>
FACILITY_SXS = 23,
/// <summary>The error code is specific to Windows CE.</summary>
FACILITY_WINDOWS_CE = 24,
/// <summary>The source of the error code is HTTP support.</summary>
FACILITY_HTTP = 25,
/// <summary>The source of the error code is common Logging support.</summary>
FACILITY_USERMODE_COMMONLOG = 26,
/// <summary>The source of the error code is the user mode filter manager.</summary>
FACILITY_USERMODE_FILTER_MANAGER = 31,
/// <summary>The source of the error code is background copy control</summary>
FACILITY_BACKGROUNDCOPY = 32,
/// <summary>The source of the error code is configuration services.</summary>
FACILITY_CONFIGURATION = 33,
/// <summary>The source of the error code is state management services.</summary>
FACILITY_STATE_MANAGEMENT = 34,
/// <summary>The source of the error code is the Microsoft Identity Server.</summary>
FACILITY_METADIRECTORY = 35,
/// <summary>The source of the error code is a Windows update.</summary>
FACILITY_WINDOWSUPDATE = 36,
/// <summary>The source of the error code is Active Directory.</summary>
FACILITY_DIRECTORYSERVICE = 37,
/// <summary>The source of the error code is the graphics drivers.</summary>
FACILITY_GRAPHICS = 38,
/// <summary>The source of the error code is the user Shell.</summary>
FACILITY_SHELL = 39,
/// <summary>The source of the error code is the Trusted Platform Module services.</summary>
FACILITY_TPM_SERVICES = 40,
/// <summary>The source of the error code is the Trusted Platform Module applications.</summary>
FACILITY_TPM_SOFTWARE = 41,
/// <summary>The source of the error code is Performance Logs and Alerts</summary>
FACILITY_PLA = 48,
/// <summary>The source of the error code is Full volume encryption.</summary>
FACILITY_FVE = 49,
/// <summary>The source of the error code is the Firewall Platform.</summary>
FACILITY_FWP = 50,
/// <summary>The source of the error code is the Windows Resource Manager.</summary>
FACILITY_WINRM = 51,
/// <summary>The source of the error code is the Network Driver Interface.</summary>
FACILITY_NDIS = 52,
/// <summary>The source of the error code is the Usermode Hypervisor components.</summary>
FACILITY_USERMODE_HYPERVISOR = 53,
/// <summary>The source of the error code is the Configuration Management Infrastructure.</summary>
FACILITY_CMI = 54,
/// <summary>The source of the error code is the user mode virtualization subsystem.</summary>
FACILITY_USERMODE_VIRTUALIZATION = 55,
/// <summary>The source of the error code is the user mode volume manager</summary>
FACILITY_USERMODE_VOLMGR = 56,
/// <summary>The source of the error code is the Boot Configuration Database.</summary>
FACILITY_BCD = 57,
/// <summary>The source of the error code is user mode virtual hard disk support.</summary>
FACILITY_USERMODE_VHD = 58,
/// <summary>The source of the error code is System Diagnostics.</summary>
FACILITY_SDIAG = 60,
/// <summary>The source of the error code is the Web Services.</summary>
FACILITY_WEBSERVICES = 61,
/// <summary>The source of the error code is a Windows Defender component.</summary>
FACILITY_WINDOWS_DEFENDER = 80,
/// <summary>The source of the error code is the open connectivity service.</summary>
FACILITY_OPC = 81,
/// <summary/>
FACILITY_XPS = 82,
/// <summary/>
FACILITY_MBN = 84,
/// <summary/>
FACILITY_POWERSHELL = 84,
/// <summary/>
FACILITY_RAS = 83,
/// <summary/>
FACILITY_P2P_INT = 98,
/// <summary/>
FACILITY_P2P = 99,
/// <summary/>
FACILITY_DAF = 100,
/// <summary/>
FACILITY_BLUETOOTH_ATT = 101,
/// <summary/>
FACILITY_AUDIO = 102,
/// <summary/>
FACILITY_STATEREPOSITORY = 103,
/// <summary/>
FACILITY_VISUALCPP = 109,
/// <summary/>
FACILITY_SCRIPT = 112,
/// <summary/>
FACILITY_PARSE = 113,
/// <summary/>
FACILITY_BLB = 120,
/// <summary/>
FACILITY_BLB_CLI = 121,
/// <summary/>
FACILITY_WSBAPP = 122,
/// <summary/>
FACILITY_BLBUI = 128,
/// <summary/>
FACILITY_USN = 129,
/// <summary/>
FACILITY_USERMODE_VOLSNAP = 130,
/// <summary/>
FACILITY_TIERING = 131,
/// <summary/>
FACILITY_WSB_ONLINE = 133,
/// <summary/>
FACILITY_ONLINE_ID = 134,
/// <summary/>
FACILITY_DEVICE_UPDATE_AGENT = 135,
/// <summary/>
FACILITY_DRVSERVICING = 136,
/// <summary/>
FACILITY_DLS = 153,
/// <summary/>
FACILITY_DELIVERY_OPTIMIZATION = 208,
/// <summary/>
FACILITY_USERMODE_SPACES = 231,
/// <summary/>
FACILITY_USER_MODE_SECURITY_CORE = 232,
/// <summary/>
FACILITY_USERMODE_LICENSING = 234,
/// <summary/>
FACILITY_SOS = 160,
/// <summary/>
FACILITY_DEBUGGERS = 176,
/// <summary/>
FACILITY_SPP = 256,
/// <summary/>
FACILITY_RESTORE = 256,
/// <summary/>
FACILITY_DMSERVER = 256,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_SERVER = 257,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_IMAGING = 258,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_MANAGEMENT = 259,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_UTIL = 260,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_BINLSVC = 261,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_PXE = 263,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_TFTP = 264,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_TRANSPORT_MANAGEMENT = 272,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_DRIVER_PROVISIONING = 278,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_MULTICAST_SERVER = 289,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_MULTICAST_CLIENT = 290,
/// <summary/>
FACILITY_DEPLOYMENT_SERVICES_CONTENT_PROVIDER = 293,
/// <summary/>
FACILITY_LINGUISTIC_SERVICES = 305,
/// <summary/>
FACILITY_AUDIOSTREAMING = 1094,
/// <summary/>
FACILITY_ACCELERATOR = 1536,
/// <summary/>
FACILITY_WMAAECMA = 1996,
/// <summary/>
FACILITY_DIRECTMUSIC = 2168,
/// <summary/>
FACILITY_DIRECT3D10 = 2169,
/// <summary/>
FACILITY_DXGI = 2170,
/// <summary/>
FACILITY_DXGI_DDI = 2171,
/// <summary/>
FACILITY_DIRECT3D11 = 2172,
/// <summary/>
FACILITY_DIRECT3D11_DEBUG = 2173,
/// <summary/>
FACILITY_DIRECT3D12 = 2174,
/// <summary/>
FACILITY_DIRECT3D12_DEBUG = 2175,
/// <summary/>
FACILITY_LEAP = 2184,
/// <summary/>
FACILITY_AUDCLNT = 2185,
/// <summary/>
FACILITY_WINCODEC_DWRITE_DWM = 2200,
/// <summary/>
FACILITY_WINML = 2192,
/// <summary/>
FACILITY_DIRECT2D = 2201,
/// <summary/>
FACILITY_DEFRAG = 2304,
/// <summary/>
FACILITY_USERMODE_SDBUS = 2305,
/// <summary/>
FACILITY_JSCRIPT = 2306,
/// <summary/>
FACILITY_PIDGENX = 2561,
/// <summary/>
FACILITY_EAS = 85,
/// <summary/>
FACILITY_WEB = 885,
/// <summary/>
FACILITY_WEB_SOCKET = 886,
/// <summary/>
FACILITY_MOBILE = 1793,
/// <summary/>
FACILITY_SQLITE = 1967,
/// <summary/>
FACILITY_UTC = 1989,
/// <summary/>
FACILITY_WEP = 2049,
/// <summary/>
FACILITY_SYNCENGINE = 2050,
/// <summary/>
FACILITY_XBOX = 2339,
/// <summary/>
FACILITY_GAME = 2340,
/// <summary/>
FACILITY_PIX = 2748
}
/// <summary>A value indicating whether an <see cref="HRESULT"/> is a success (Severity bit 31 equals 0).</summary>
[PInvokeData("winerr.h")]
public enum SeverityLevel
{
/// <summary>Success</summary>
Success = 0,
/// <summary>Failure</summary>
Fail = 1
}
/// <summary>Gets the code portion of the <see cref="HRESULT"/>.</summary>
/// <value>The code value (bits 0-15).</value>
public int Code => GetCode(_value);
/// <summary>Gets the facility portion of the <see cref="HRESULT"/>.</summary>
/// <value>The facility value (bits 16-26).</value>
public FacilityCode Facility => GetFacility(_value);
/// <summary>Gets a value indicating whether this <see cref="HRESULT"/> is a failure (Severity bit 31 equals 1).</summary>
/// <value><c>true</c> if failed; otherwise, <c>false</c>.</value>
public bool Failed => _value < 0;
/// <summary>Gets the severity level of the <see cref="HRESULT"/>.</summary>
/// <value>The severity level.</value>
public SeverityLevel Severity => GetSeverity(_value);
/// <summary>Gets a value indicating whether this <see cref="HRESULT"/> is a success (Severity bit 31 equals 0).</summary>
/// <value><c>true</c> if succeeded; otherwise, <c>false</c>.</value>
public bool Succeeded => _value >= 0;
/// <summary>Performs an explicit conversion from <see cref="System.Boolean"/> to <see cref="HRESULT"/>.</summary>
/// <param name="value">if set to <see langword="true"/> returns S_OK; otherwise S_FALSE.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator HRESULT(bool value) => value ? S_OK : S_FALSE;
/// <summary>Performs an explicit conversion from <see cref="HRESULT"/> to <see cref="System.Int32"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator int(HRESULT value) => value._value;
/// <summary>Performs an explicit conversion from <see cref="HRESULT"/> to <see cref="System.UInt32"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator uint(HRESULT value) => unchecked((uint)value._value);
/// <summary>Tries to extract a HRESULT from an exception.</summary>
/// <param name="exception">The exception.</param>
/// <returns>The error. If undecipherable, E_FAIL is returned.</returns>
public static HRESULT FromException(Exception exception)
{
if (exception is Win32Exception we)
return new Win32Error(unchecked((uint)we.NativeErrorCode)).ToHRESULT();
if (exception.InnerException is Win32Exception iwe)
return new Win32Error(unchecked((uint)iwe.NativeErrorCode)).ToHRESULT();
#if !(NET20 || NET35 || NET40)
if (exception.HResult != 0)
return new HRESULT(exception.HResult);
else if (exception.InnerException != null && exception.InnerException.HResult != 0)
return new HRESULT(exception.InnerException.HResult);
#endif
return E_FAIL;
}
/// <summary>Gets the code value from a 32-bit value.</summary>
/// <param name="hresult">The 32-bit raw HRESULT value.</param>
/// <returns>The code value (bits 0-15).</returns>
public static int GetCode(int hresult) => hresult & codeMask;
/// <summary>Gets the facility value from a 32-bit value.</summary>
/// <param name="hresult">The 32-bit raw HRESULT value.</param>
/// <returns>The facility value (bits 16-26).</returns>
public static FacilityCode GetFacility(int hresult) => (FacilityCode)((hresult & facilityMask) >> facilityShift);
/// <summary>Gets the severity value from a 32-bit value.</summary>
/// <param name="hresult">The 32-bit raw HRESULT value.</param>
/// <returns>The severity value (bit 31).</returns>
public static SeverityLevel GetSeverity(int hresult)
=> (SeverityLevel)((hresult & severityMask) >> severityShift);
/// <summary>Performs an implicit conversion from <see cref="System.Int32"/> to <see cref="HRESULT"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator HRESULT(int value) => new HRESULT(value);
/// <summary>Performs an implicit conversion from <see cref="System.UInt32"/> to <see cref="HRESULT"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The resulting <see cref="HRESULT"/> instance from the conversion.</returns>
public static implicit operator HRESULT(uint value) => new HRESULT(value);
/// <summary>Maps an NT Status value to an HRESULT value.</summary>
/// <param name="err">The NT Status value.</param>
/// <returns>The HRESULT value.</returns>
public static HRESULT HRESULT_FROM_NT(NTStatus err) => err.ToHRESULT();
/// <summary>Maps a system error code to an HRESULT value.</summary>
/// <param name="err">The system error code.</param>
/// <returns>The HRESULT value.</returns>
public static HRESULT HRESULT_FROM_WIN32(Win32Error err) => err.ToHRESULT();
/// <summary>Creates a new <see cref="HRESULT"/> from provided values.</summary>
/// <param name="severe">if set to <c>false</c>, sets the severity bit to 1.</param>
/// <param name="facility">The facility.</param>
/// <param name="code">The code.</param>
/// <returns>The resulting <see cref="HRESULT"/>.</returns>
public static HRESULT Make(bool severe, FacilityCode facility, uint code) => Make(severe, (uint)facility, code);
/// <summary>Creates a new <see cref="HRESULT"/> from provided values.</summary>
/// <param name="severe">if set to <c>false</c>, sets the severity bit to 1.</param>
/// <param name="facility">The facility.</param>
/// <param name="code">The code.</param>
/// <returns>The resulting <see cref="HRESULT"/>.</returns>
public static HRESULT Make(bool severe, uint facility, uint code) =>
new HRESULT(unchecked((int)((severe ? severityMask : 0) | (facility << facilityShift) | code)));
/// <summary>Implements the operator !=.</summary>
/// <param name="hrLeft">The first <see cref="HRESULT"/>.</param>
/// <param name="hrRight">The second <see cref="HRESULT"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(HRESULT hrLeft, HRESULT hrRight) => !(hrLeft == hrRight);
/// <summary>Implements the operator !=.</summary>
/// <param name="hrLeft">The first <see cref="HRESULT"/>.</param>
/// <param name="hrRight">The second <see cref="int"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(HRESULT hrLeft, int hrRight) => !(hrLeft == hrRight);
/// <summary>Implements the operator !=.</summary>
/// <param name="hrLeft">The first <see cref="HRESULT"/>.</param>
/// <param name="hrRight">The second <see cref="uint"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(HRESULT hrLeft, uint hrRight) => !(hrLeft == hrRight);
/// <summary>Implements the operator ==.</summary>
/// <param name="hrLeft">The first <see cref="HRESULT"/>.</param>
/// <param name="hrRight">The second <see cref="HRESULT"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(HRESULT hrLeft, HRESULT hrRight) => hrLeft.Equals(hrRight);
/// <summary>Implements the operator ==.</summary>
/// <param name="hrLeft">The first <see cref="HRESULT"/>.</param>
/// <param name="hrRight">The second <see cref="int"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(HRESULT hrLeft, int hrRight) => hrLeft.Equals(hrRight);
/// <summary>Implements the operator ==.</summary>
/// <param name="hrLeft">The first <see cref="HRESULT"/>.</param>
/// <param name="hrRight">The second <see cref="uint"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(HRESULT hrLeft, uint hrRight) => hrLeft.Equals(hrRight);
/// <summary>
/// If the supplied raw HRESULT value represents a failure, throw the associated <see cref="Exception"/> with the optionally
/// supplied message.
/// </summary>
/// <param name="hresult">The 32-bit raw HRESULT value.</param>
/// <param name="message">The optional message to assign to the <see cref="Exception"/>.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void ThrowIfFailed(int hresult, string message = null) => new HRESULT(hresult).ThrowIfFailed(message);
/// <summary>Compares the current object with another object of the same type.</summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value
/// Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref
/// name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(HRESULT other) => _value.CompareTo(other._value);
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current
/// instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less
/// than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the
/// sort order as <paramref name="obj"/>. Greater than zero This instance follows <paramref name="obj"/> in the sort order.
/// </returns>
public int CompareTo(object obj)
{
var v = ValueFromObj(obj);
return v.HasValue
? _value.CompareTo(v.Value)
: throw new ArgumentException(@"Object cannot be converted to a UInt32 value for comparison.", nameof(obj));
}
/// <summary>Indicates whether the current object is equal to an <see cref="int"/>.</summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.</returns>
public bool Equals(int other) => other == _value;
/// <summary>Indicates whether the current object is equal to an <see cref="uint"/>.</summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.</returns>
public bool Equals(uint other) => unchecked((int)other) == _value;
/// <summary>Determines whether the specified <see cref="object"/>, is equal to this instance.</summary>
/// <param name="obj">The <see cref="object"/> to compare with this instance.</param>
/// <returns><c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj) => obj switch
{
null => false,
HRESULT h => Equals(h),
int i => Equals(i),
uint u => Equals(u),
_ => Equals(_value, ValueFromObj(obj)),
};
/// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.</returns>
public bool Equals(HRESULT other) => other._value == _value;
/// <summary>Gets the .NET <see cref="Exception"/> associated with the HRESULT value and optionally adds the supplied message.</summary>
/// <param name="message">The optional message to assign to the <see cref="Exception"/>.</param>
/// <returns>The associated <see cref="Exception"/> or <c>null</c> if this HRESULT is not a failure.</returns>
[SecurityCritical, SecuritySafeCritical]
public Exception GetException(string message = null)
{
if (!Failed) return null;
var exceptionForHR = Marshal.GetExceptionForHR(_value, new IntPtr(-1));
if (exceptionForHR.GetType() == typeof(COMException))
{
if (Facility == FacilityCode.FACILITY_WIN32)
return string.IsNullOrEmpty(message) ? new Win32Exception(Code) : new Win32Exception(Code, message);
return new COMException(message ?? exceptionForHR.Message, _value);
}
if (!string.IsNullOrEmpty(message))
{
Type[] types = { typeof(string) };
var constructor = exceptionForHR.GetType().GetConstructor(types);
if (null != constructor)
{
object[] parameters = { message };
exceptionForHR = constructor.Invoke(parameters) as Exception;
}
}
return exceptionForHR;
}
/// <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() => _value;
/// <summary>
/// If this <see cref="HRESULT"/> represents a failure, throw the associated <see cref="Exception"/> with the optionally supplied message.
/// </summary>
/// <param name="message">The optional message to assign to the <see cref="Exception"/>.</param>
[SecurityCritical, SecuritySafeCritical]
[System.Diagnostics.DebuggerStepThrough]
public void ThrowIfFailed(string message = null)
{
var exception = GetException(message);
if (exception != null)
throw exception;
}
/// <summary>Returns a <see cref="string"/> that represents this instance.</summary>
/// <returns>A <see cref="string"/> that represents this instance.</returns>
public override string ToString()
{
string err = null;
// Check for defined HRESULT value
if (!StaticFieldValueHash.TryGetFieldName<HRESULT, int>(_value, out err) && Facility == FacilityCode.FACILITY_WIN32)
{
foreach (var info2 in typeof(Win32Error).GetFields(BindingFlags.Public | BindingFlags.Static).Where(fi => fi.FieldType == typeof(uint)))
{
if ((HRESULT)(Win32Error)(uint)info2.GetValue(null) == this)
{
err = $"HRESULT_FROM_WIN32({info2.Name})";
break;
}
}
}
var msg = FormatMessage(unchecked((uint)_value));
return (err ?? string.Format(CultureInfo.InvariantCulture, "0x{0:X8}", _value)) + (msg == null ? "" : ": " + msg);
}
TypeCode IConvertible.GetTypeCode() => _value.GetTypeCode();
bool IConvertible.ToBoolean(IFormatProvider provider) => Succeeded;
byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)_value).ToByte(provider);
char IConvertible.ToChar(IFormatProvider provider) => throw new NotSupportedException();
DateTime IConvertible.ToDateTime(IFormatProvider provider) => throw new NotSupportedException();
decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)_value).ToDecimal(provider);
double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)_value).ToDouble(provider);
/// <summary>Converts this error to an <see cref="T:Vanara.PInvoke.HRESULT"/>.</summary>
/// <returns>An equivalent <see cref="T:Vanara.PInvoke.HRESULT"/>.</returns>
HRESULT IErrorProvider.ToHRESULT() => this;
short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)_value).ToInt16(provider);
int IConvertible.ToInt32(IFormatProvider provider) => _value;
long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)_value).ToInt64(provider);
sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)_value).ToSByte(provider);
float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)_value).ToSingle(provider);
string IConvertible.ToString(IFormatProvider provider) => ToString();
object IConvertible.ToType(Type conversionType, IFormatProvider provider) =>
((IConvertible)_value).ToType(conversionType, provider);
ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)unchecked((uint)_value)).ToUInt16(provider);
uint IConvertible.ToUInt32(IFormatProvider provider) => unchecked((uint)_value);
ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)unchecked((uint)_value)).ToUInt64(provider);
/// <summary>Formats the message.</summary>
/// <param name="id">The error.</param>
/// <returns>The string.</returns>
internal static string FormatMessage(uint id)
{
var flags = 0x1200U; // FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM
var buf = new System.Text.StringBuilder(1024);
do
{
if (0 != FormatMessage(flags, default, id, 0, buf, (uint)buf.Capacity, default))
return buf.ToString();
var lastError = Win32Error.GetLastError();
if (lastError == Win32Error.ERROR_MR_MID_NOT_FOUND || lastError == Win32Error.ERROR_MUI_FILE_NOT_FOUND)
break;
if (lastError != Win32Error.ERROR_INSUFFICIENT_BUFFER)
lastError.ThrowIfFailed();
buf.Capacity *= 2;
} while (true && buf.Capacity < 1024 * 16); // Don't go crazy
return string.Empty;
}
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
private static extern int FormatMessage(uint dwFlags, HINSTANCE lpSource, uint dwMessageId, uint dwLanguageId, System.Text.StringBuilder lpBuffer, uint nSize, IntPtr Arguments);
private static int? ValueFromObj(object obj)
{
switch (obj)
{
case null:
return null;
case int i:
return i;
case uint u:
return unchecked((int)u);
default:
var c = TypeDescriptor.GetConverter(obj);
return c.CanConvertTo(typeof(int)) ? (int?)c.ConvertTo(obj, typeof(int)) : null;
}
}
}
internal class HRESULTTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(Win32Error) || sourceType.IsPrimitive && sourceType != typeof(char))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string) || destinationType.IsPrimitive && destinationType != typeof(char))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is Win32Error e)
return e.ToHRESULT();
if (value != null && value.GetType().IsPrimitive)
{
if (value is bool b)
return b ? HRESULT.S_OK : HRESULT.S_FALSE;
if (!(value is char))
return new HRESULT((int)Convert.ChangeType(value, TypeCode.Int32));
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
Type destinationType)
{
if (!(value is HRESULT hr)) throw new NotSupportedException();
if (destinationType.IsPrimitive && destinationType != typeof(char))
return Convert.ChangeType(hr, destinationType);
if (destinationType == typeof(string))
return hr.ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
| |
/*
* Copyright (c) 2006-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
/// <summary>
/// Class for controlling various system settings.
/// </summary>
/// <remarks>Some values are readonly because they affect things that
/// happen when the GridClient object is initialized, so changing them at
/// runtime won't do any good. Non-readonly values may affect things that
/// happen at login or dynamically</remarks>
public class Settings
{
#region Login/Networking Settings
/// <summary>Main grid login server</summary>
public const string AGNI_LOGIN_SERVER = "https://login.agni.lindenlab.com/cgi-bin/login.cgi";
/// <summary>Beta grid login server</summary>
public const string ADITI_LOGIN_SERVER = "https://login.aditi.lindenlab.com/cgi-bin/login.cgi";
/// <summary>The relative directory where external resources are kept</summary>
public static string RESOURCE_DIR = "openmetaverse_data";
/// <summary>Login server to connect to</summary>
public string LOGIN_SERVER = AGNI_LOGIN_SERVER;
/// <summary>IP Address the client will bind to</summary>
public static System.Net.IPAddress BIND_ADDR = System.Net.IPAddress.Any;
/// <summary>Use XML-RPC Login or LLSD Login, default is XML-RPC Login</summary>
public bool USE_LLSD_LOGIN = false;
#endregion
#region Inventory
/// <summary>
/// InventoryManager requests inventory information on login,
/// GridClient initializes an Inventory store for main inventory.
/// </summary>
public const bool ENABLE_INVENTORY_STORE = true;
/// <summary>
/// InventoryManager requests library information on login,
/// GridClient initializes an Inventory store for the library.
/// </summary>
public const bool ENABLE_LIBRARY_STORE = true;
/// <summary>
/// Use Caps for fetching inventory where available
/// </summary>
public bool HTTP_INVENTORY = true;
#endregion
#region Timeouts and Intervals
/// <summary>Number of milliseconds before an asset transfer will time
/// out</summary>
public int TRANSFER_TIMEOUT = 90 * 1000;
/// <summary>Number of milliseconds before a teleport attempt will time
/// out</summary>
public int TELEPORT_TIMEOUT = 40 * 1000;
/// <summary>Number of milliseconds before NetworkManager.Logout() will
/// time out</summary>
public int LOGOUT_TIMEOUT = 5 * 1000;
/// <summary>Number of milliseconds before a CAPS call will time out</summary>
/// <remarks>Setting this too low will cause web requests time out and
/// possibly retry repeatedly</remarks>
public int CAPS_TIMEOUT = 60 * 1000;
/// <summary>Number of milliseconds for xml-rpc to timeout</summary>
public int LOGIN_TIMEOUT = 60 * 1000;
/// <summary>Milliseconds before a packet is assumed lost and resent</summary>
public int RESEND_TIMEOUT = 4000;
/// <summary>Milliseconds without receiving a packet before the
/// connection to a simulator is assumed lost</summary>
public int SIMULATOR_TIMEOUT = 30 * 1000;
/// <summary>Milliseconds to wait for a simulator info request through
/// the grid interface</summary>
public int MAP_REQUEST_TIMEOUT = 5 * 1000;
/// <summary>Number of milliseconds between sending pings to each sim</summary>
public const int PING_INTERVAL = 2200;
/// <summary>Number of milliseconds between sending camera updates</summary>
public const int DEFAULT_AGENT_UPDATE_INTERVAL = 500;
/// <summary>Number of milliseconds between updating the current
/// positions of moving, non-accelerating and non-colliding objects</summary>
public const int INTERPOLATION_INTERVAL = 250;
/// <summary>Millisecond interval between ticks, where all ACKs are
/// sent out and the age of unACKed packets is checked</summary>
public const int NETWORK_TICK_INTERVAL = 500;
#endregion
#region Sizes
/// <summary>The initial size of the packet inbox, where packets are
/// stored before processing</summary>
public const int PACKET_INBOX_SIZE = 100;
/// <summary>Maximum size of packet that we want to send over the wire</summary>
public const int MAX_PACKET_SIZE = 1200;
/// <summary>The maximum value of a packet sequence number before it
/// rolls over back to one</summary>
public const int MAX_SEQUENCE = 0xFFFFFF;
/// <summary>The maximum size of the sequence number archive, used to
/// check for resent and/or duplicate packets</summary>
public static int PACKET_ARCHIVE_SIZE = 1000;
/// <summary>Maximum number of queued ACKs to be sent before SendAcks()
/// is forced</summary>
public int MAX_PENDING_ACKS = 10;
/// <summary>Network stats queue length (seconds)</summary>
public int STATS_QUEUE_SIZE = 5;
#endregion
#region Experimental options
/// <summary>
/// Primitives will be reused when falling in/out of interest list (and shared between clients)
/// prims returning to interest list do not need re-requested
/// Helps also in not re-requesting prim.Properties for code that checks for a Properties == null per client
/// </summary>
public bool CACHE_PRIMITIVES = false;
/// <summary>
/// Pool parcel data between clients (saves on requesting multiple times when all clients may need it)
/// </summary>
public bool POOL_PARCEL_DATA = false;
/// <summary>
/// How long to preserve cached data when no client is connected to a simulator
/// The reason for setting it to something like 2 minutes is in case a client
/// is running back and forth between region edges or a sim is comming and going
/// </summary>
public static int SIMULATOR_POOL_TIMEOUT = 2 * 60 * 1000;
/// <summary>
/// Some people have been complaining that a prim's hashcode changes as it's data changes
/// Setting this to true allows their identity to be based off only their localID
/// </summary>
public static bool PRIMS_KEEP_HASHCODES = false;
#endregion
#region Configuration options (mostly booleans)
/// <summary>Enable/disable storing terrain heightmaps in the
/// TerrainManager</summary>
public bool STORE_LAND_PATCHES = false;
/// <summary>Enable/disable sending periodic camera updates</summary>
public bool SEND_AGENT_UPDATES = true;
/// <summary>Enable/disable automatically setting agent appearance at
/// login and after sim crossing</summary>
public bool SEND_AGENT_APPEARANCE = true;
/// <summary>Enable/disable automatically setting the bandwidth throttle
/// after connecting to each simulator</summary>
/// <remarks>The default throttle uses the equivalent of the maximum
/// bandwidth setting in the official client. If you do not set a
/// throttle your connection will by default be throttled well below
/// the minimum values and you may experience connection problems</remarks>
public bool SEND_AGENT_THROTTLE = true;
/// <summary>Enable/disable the sending of pings to monitor lag and
/// packet loss</summary>
public bool SEND_PINGS = true;
/// <summary>Should we connect to multiple sims? This will allow
/// viewing in to neighboring simulators and sim crossings
/// (Experimental)</summary>
public bool MULTIPLE_SIMS = true;
/// <summary>If true, all object update packets will be decoded in to
/// native objects. If false, only updates for our own agent will be
/// decoded. Registering an event handler will force objects for that
/// type to always be decoded. If this is disabled the object tracking
/// will have missing or partial prim and avatar information</summary>
public bool ALWAYS_DECODE_OBJECTS = true;
/// <summary>If true, when a cached object check is received from the
/// server the full object info will automatically be requested</summary>
public bool ALWAYS_REQUEST_OBJECTS = true;
/// <summary>Whether to establish connections to HTTP capabilities
/// servers for simulators</summary>
public bool ENABLE_CAPS = true;
/// <summary>Whether to decode sim stats</summary>
public bool ENABLE_SIMSTATS = true;
/// <summary>The capabilities servers are currently designed to
/// periodically return a 502 error which signals for the client to
/// re-establish a connection. Set this to true to log those 502 errors</summary>
public bool LOG_ALL_CAPS_ERRORS = false;
/// <summary>If true, any reference received for a folder or item
/// the library is not aware of will automatically be fetched</summary>
public bool FETCH_MISSING_INVENTORY = true;
/// <summary>If true, and <code>SEND_AGENT_UPDATES</code> is true,
/// AgentUpdate packets will continuously be sent out to give the bot
/// smoother movement and autopiloting</summary>
public bool DISABLE_AGENT_UPDATE_DUPLICATE_CHECK = true;
/// <summary>If true, currently visible avatars will be stored
/// in dictionaries inside <code>Simulator.ObjectAvatars</code>.
/// If false, a new Avatar or Primitive object will be created
/// each time an object update packet is received</summary>
public bool AVATAR_TRACKING = true;
/// <summary>If true, currently visible avatars will be stored
/// in dictionaries inside <code>Simulator.ObjectPrimitives</code>.
/// If false, a new Avatar or Primitive object will be created
/// each time an object update packet is received</summary>
public bool OBJECT_TRACKING = true;
/// <summary>If true, position and velocity will periodically be
/// interpolated (extrapolated, technically) for objects and
/// avatars that are being tracked by the library. This is
/// necessary to increase the accuracy of speed and position
/// estimates for simulated objects</summary>
public bool USE_INTERPOLATION_TIMER = true;
/// <summary>
/// If true, utilization statistics will be tracked. There is a minor penalty
/// in CPU time for enabling this option.
/// </summary>
public bool TRACK_UTILIZATION = false;
#endregion
#region Parcel Tracking
/// <summary>If true, parcel details will be stored in the
/// <code>Simulator.Parcels</code> dictionary as they are received</summary>
public bool PARCEL_TRACKING = true;
/// <summary>
/// If true, an incoming parcel properties reply will automatically send
/// a request for the parcel access list
/// </summary>
public bool ALWAYS_REQUEST_PARCEL_ACL = true;
/// <summary>
/// if true, an incoming parcel properties reply will automatically send
/// a request for the traffic count.
/// </summary>
public bool ALWAYS_REQUEST_PARCEL_DWELL = true;
#endregion
#region Asset Cache
/// <summary>
/// If true, images, and other assets downloaded from the server
/// will be cached in a local directory
/// </summary>
public bool USE_ASSET_CACHE = true;
/// <summary>Path to store cached texture data</summary>
public string ASSET_CACHE_DIR = RESOURCE_DIR + "/cache";
/// <summary>Maximum size cached files are allowed to take on disk (bytes)</summary>
public long ASSET_CACHE_MAX_SIZE = 1024 * 1024 * 1024; // 1GB
#endregion
#region Misc
/// <summary>Default color used for viewer particle effects</summary>
public Color4 DEFAULT_EFFECT_COLOR = new Color4(255, 0, 0, 255);
/// <summary>Cost of uploading an asset</summary>
/// <remarks>Read-only since this value is dynamically fetched at login</remarks>
public int UPLOAD_COST { get { return priceUpload; } }
/// <summary>Maximum number of times to resend a failed packet</summary>
public int MAX_RESEND_COUNT = 3;
/// <summary>Throttle outgoing packet rate</summary>
public bool THROTTLE_OUTGOING_PACKETS = true;
/// <summary>UUID of a texture used by some viewers to indentify type of client used</summary>
public UUID CLIENT_IDENTIFICATION_TAG = UUID.Zero;
#endregion
#region Texture Pipeline
/// <summary>
/// Download textures using GetTexture capability when available
/// </summary>
public bool USE_HTTP_TEXTURES = true;
/// <summary>The maximum number of concurrent texture downloads allowed</summary>
/// <remarks>Increasing this number will not necessarily increase texture retrieval times due to
/// simulator throttles</remarks>
public int MAX_CONCURRENT_TEXTURE_DOWNLOADS = 4;
/// <summary>
/// The Refresh timer inteval is used to set the delay between checks for stalled texture downloads
/// </summary>
/// <remarks>This is a static variable which applies to all instances</remarks>
public static float PIPELINE_REFRESH_INTERVAL = 500.0f;
/// <summary>
/// Textures taking longer than this value will be flagged as timed out and removed from the pipeline
/// </summary>
public int PIPELINE_REQUEST_TIMEOUT = 45*1000;
#endregion
#region Logging Configuration
/// <summary>
/// Get or set the minimum log level to output to the console by default
///
/// If the library is not compiled with DEBUG defined and this level is set to DEBUG
/// You will get no output on the console. This behavior can be overriden by creating
/// a logger configuration file for log4net
/// </summary>
public static Helpers.LogLevel LOG_LEVEL = Helpers.LogLevel.Debug;
public static Helpers.LogLevel INVENTORY_LOG_LEVEL = Helpers.LogLevel.Debug;
/// <summary>Attach avatar names to log messages</summary>
public bool LOG_NAMES = true;
/// <summary>Log packet retransmission info</summary>
public bool LOG_RESENDS = true;
/// <summary>Log disk cache misses and other info</summary>
public bool LOG_DISKCACHE = true;
#endregion
#region Private Fields
private GridClient Client;
private int priceUpload = 0;
public static bool SORT_INVENTORY = false;
/// <summary>Constructor</summary>
/// <param name="client">Reference to a GridClient object</param>
public Settings(GridClient client)
{
Client = client;
Client.Network.RegisterCallback(Packets.PacketType.EconomyData, EconomyDataHandler);
}
#endregion
#region Packet Callbacks
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void EconomyDataHandler(object sender, PacketReceivedEventArgs e)
{
EconomyDataPacket econ = (EconomyDataPacket)e.Packet;
priceUpload = econ.Info.PriceUpload;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using RLToolkit;
using RLToolkit.Basic;
using NUnit.Framework;
namespace RLToolkit.UnitTests.Modules
{
[TestFixture]
public class IniParserTest : TestHarness, ITestBase
{
#region Local Variables
private IniParser parser;
// files contents
private List<string> File1ContentRaw = new List<string>();
private List<string> File2ContentRaw = new List<string>();
private List<string> File3ContentRaw = new List<string>();
// DicConfig setup
private DicConfiguration dicoTest1 = new DicConfiguration();
private DicConfiguration dicoTest2 = new DicConfiguration();
// paths and filename
private string file_1 = "file1.ini";
private string file_1_out = "file1_out.ini";
private string file_2_out = "file2_out.ini";
#endregion
#region Interface Override
public string ModuleName()
{
return "IniParser";
}
public override void SetFolderPaths()
{
localFolder = AppDomain.CurrentDomain.BaseDirectory;
SetPaths (localFolder, ModuleName());
}
public override void DataPrepare()
{
// copy the data locally
AddInputFile(Path.Combine(folder_testdata, file_1), true, false);
// prepare the content of File1
File1ContentRaw.Add ("#comment");
File1ContentRaw.Add ("");
File1ContentRaw.Add ("[head]");
File1ContentRaw.Add ("var=val");
File1ContentRaw.Add ("testvar1=value1");
File1ContentRaw.Add ("");
File1ContentRaw.Add ("[head2]");
File1ContentRaw.Add ("var=val2");
File1ContentRaw.Add ("testvar2=value2");
// prepare the content of File2 from File1 (bad headers)
File2ContentRaw = new List<string>(File1ContentRaw);
File2ContentRaw[2] = "head]";
File2ContentRaw[6] = "[head2";
// prepare the content of File3 from File1 (bad variables)
File3ContentRaw = new List<string>(File1ContentRaw);
File3ContentRaw[3] = "var val";
File3ContentRaw[8] = "foobar";
// prepare the dicoConfig stuff
dicoTest1.header = "head";
dicoTest1.dicto.Add("var", "val");
dicoTest1.dicto.Add("testvar1", "value1");
dicoTest2.header = "head2";
dicoTest2.dicto.Add("var", "val2");
dicoTest2.dicto.Add("testvar2", "value2");
}
public override void DataCleanup()
{
// move the result files if there
AddOutputFile(Path.Combine(localFolder, file_1_out), false);
AddOutputFile(Path.Combine(localFolder, file_2_out), false);
}
#endregion
#region Tests-Read
[Test]
public void Ini_Read_Local()
{
parser = new IniParser(file_1);
string result = parser.GetValue("head", "testvar1");
Assert.AreEqual(result, "value1", "Value is not as expected");
Assert.IsFalse(parser.isEmpty, "isEmpty flag should be false");
}
[Test]
public void Ini_Read_FullPath()
{
parser = new IniParser(file_1, localFolder);
string result = parser.GetValue("head", "testvar1");
Assert.AreEqual(result, "value1", "Value is not as expected");
Assert.IsFalse(parser.isEmpty, "isEmpty flag should be false");
}
[Test]
public void Ini_Read_FromList()
{
parser = new IniParser(File1ContentRaw);
string result = parser.GetValue("head", "testvar1");
Assert.AreEqual("value1",result, "Value is not as expected");
Assert.IsFalse(parser.isEmpty, "isEmpty flag should be false");
}
[Test]
public void Ini_Read_EmptyList()
{
// empty file, try to fetch from it
parser = new IniParser(new List<string>());
Assert.IsTrue(parser.isEmpty, "isEmpty flag should be true");
}
[Test]
public void Ini_Read_EmptyConstructor()
{
// empty file, try to fetch from it
parser = new IniParser();
Assert.IsTrue(parser.isEmpty, "isEmpty flag should be true");
}
[Test]
public void Ini_Read_SameName_DiffHead()
{
// fetch from both header and make sure it is the right thing
parser = new IniParser(File1ContentRaw);
string result1 = parser.GetValue("head", "var"); // Val
string result2 = parser.GetValue("head2", "var"); // Val2
Assert.AreNotEqual(result1, result2, "Result from both header same variable are the same.");
}
[Test]
public void Ini_Read_WrongHeader()
{
// try t fetch from a header that doesn't have the variable
parser = new IniParser(File1ContentRaw);
string result1 = parser.GetValue("head3", "var");
Assert.AreEqual(result1, "", "Value is not as expected");
}
[Test]
public void Ini_Read_WrongVariable()
{
// try t fetch from a header that doesn't have the variable
parser = new IniParser(File1ContentRaw);
string result1 = parser.GetValue("head", "varX");
Assert.AreEqual(result1, "", "Value is not as expected");
}
#endregion
#region Tests-Add
[Test]
public void Ini_Add_AddDico()
{
// try t fetch from a header that doesn't have the variable
parser = new IniParser();
Assert.IsTrue(parser.isEmpty, "isEmpty flag should be true");
bool add = parser.AddDicConf(dicoTest1);
Assert.IsTrue(add, "Adding the dicConfig should return true");
Assert.IsFalse(parser.isEmpty, "isEmpty flag should be false");
string result1 = parser.GetValue("head", "var");
Assert.AreEqual(result1, "val", "Value is not as expected");
}
[Test]
public void Ini_Add_AddBadDico()
{
// try t fetch from a header that doesn't have the variable
parser = new IniParser();
Assert.IsTrue(parser.isEmpty, "isEmpty flag should be true");
bool add = parser.AddDicConf(new DicConfiguration());
Assert.IsFalse(add, "Should return false for this add");
Assert.IsTrue(parser.isEmpty, "isEmpty flag should still be true");
}
[Test]
public void Ini_Add_AddSameDico()
{
// try t fetch from a header that doesn't have the variable
parser = new IniParser();
Assert.IsTrue(parser.isEmpty, "isEmpty flag should be true");
bool add = parser.AddDicConf(dicoTest1);
Assert.IsTrue(add, "Adding the dicConfig should return true");
Assert.IsFalse(parser.isEmpty, "isEmpty flag should be false");
// try to readd the same DicConfig
bool add2 = parser.AddDicConf(dicoTest1);
Assert.IsFalse(add2, "Adding the second dicConfig should return false");
// fetch should still work
string result1 = parser.GetValue("head", "var");
Assert.AreEqual(result1, "val", "Value is not as expected");
}
[Test]
public void Ini_Add_AddDicEntry_New()
{
parser = new IniParser(File1ContentRaw);
bool add = parser.AddDicEntry ("head", "varX", "valueX");
Assert.IsTrue(add, "Adding the dicEntry should return true");
// fetch should work
string result1 = parser.GetValue("head", "varX");
Assert.AreEqual(result1, "valueX", "Value is not as expected");
}
[Test]
public void Ini_Add_AddDicEntry_ExistingVar()
{
parser = new IniParser(File1ContentRaw);
bool add = parser.AddDicEntry ("head", "var", "valueX");
Assert.IsFalse(add, "Adding the dicEntry should return false");
// fetch should work with the old value
string result1 = parser.GetValue("head", "var");
Assert.AreEqual(result1, "val", "Value is not as expected");
}
[Test]
public void Ini_Add_AddDicEntry_NonExistingHeader()
{
parser = new IniParser(File1ContentRaw);
bool add = parser.AddDicEntry ("headX", "var", "val");
Assert.IsFalse(add, "Adding the dicEntry should return false");
// fetch should return empty since the header doesn't exist
string result1 = parser.GetValue("head3", "var");
Assert.AreEqual(result1, "", "Value is not as expected");
}
#endregion
#region Tests-Write
[Test]
public void Ini_Write_NormalContent()
{
parser = new IniParser ();
parser.AddDicConf (dicoTest1);
parser.AddDicConf (dicoTest2);
bool success = parser.WriteContent (file_1_out, AppDomain.CurrentDomain.BaseDirectory);
Assert.IsTrue (success, "The write should have been successful");
}
public void Ini_Write_EmptyContent()
{
parser = new IniParser ();
bool success = parser.WriteContent (file_2_out, AppDomain.CurrentDomain.BaseDirectory);
Assert.IsTrue (success, "The write should have been unsuccessful");
}
#endregion
}
}
| |
using SharpFlame.Mapping.Tiles;
using SharpFlame.Mapping.Tools;
using SharpFlame.Painters;
namespace SharpFlame.Mapping
{
public class clsUpdateAutotexture : clsAction
{
public bool MakeInvalidTiles;
private Painter painter;
private TileDirection resultDirection;
private TileOrientationChance resultTexture;
private TileList resultTiles;
private Road road;
private bool roadBottom;
private bool roadLeft;
private bool roadRight;
private bool roadTop;
private clsTerrain terrain;
private Terrain terrainInner;
private Terrain terrainOuter;
public override void ActionPerform()
{
terrain = Map.Terrain;
painter = Map.Painter;
resultTiles = null;
resultDirection = TileUtil.None;
//apply centre brushes
if ( !terrain.Tiles[PosNum.X, PosNum.Y].Terrain_IsCliff )
{
for ( var brushNum = 0; brushNum <= painter.TerrainCount - 1; brushNum++ )
{
terrainInner = painter.Terrains[brushNum];
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//i i i i
resultTiles = terrainInner.Tiles;
resultDirection = TileUtil.None;
}
}
}
}
}
}
//apply transition brushes
if ( !terrain.Tiles[PosNum.X, PosNum.Y].Terrain_IsCliff )
{
for ( var brushNum = 0; brushNum <= painter.TransitionBrushCount - 1; brushNum++ )
{
terrainInner = painter.TransitionBrushes[brushNum].TerrainInner;
terrainOuter = painter.TransitionBrushes[brushNum].TerrainOuter;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//i i i i
//nothing to do here
break;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
//i i i o
resultTiles = painter.TransitionBrushes[brushNum].TilesCornerIn;
resultDirection = TileUtil.BottomRight;
break;
}
}
else if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//i i o i
resultTiles = painter.TransitionBrushes[brushNum].TilesCornerIn;
resultDirection = TileUtil.BottomLeft;
break;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
//i i o o
resultTiles = painter.TransitionBrushes[brushNum].TilesStraight;
resultDirection = TileUtil.Bottom;
break;
}
}
}
else if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter )
{
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//i o i i
resultTiles = painter.TransitionBrushes[brushNum].TilesCornerIn;
resultDirection = TileUtil.TopRight;
break;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
//i o i o
resultTiles = painter.TransitionBrushes[brushNum].TilesStraight;
resultDirection = TileUtil.Right;
break;
}
}
else if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//i o o i
resultTiles = null;
resultDirection = TileUtil.None;
break;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
//i o o o
resultTiles = painter.TransitionBrushes[brushNum].TilesCornerOut;
resultDirection = TileUtil.BottomRight;
break;
}
}
}
}
else if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//o i i i
resultTiles = painter.TransitionBrushes[brushNum].TilesCornerIn;
resultDirection = TileUtil.TopLeft;
break;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
//o i i o
resultTiles = null;
resultDirection = TileUtil.None;
break;
}
}
else if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//o i o i
resultTiles = painter.TransitionBrushes[brushNum].TilesStraight;
resultDirection = TileUtil.Left;
break;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
//o i o o
resultTiles = painter.TransitionBrushes[brushNum].TilesCornerOut;
resultDirection = TileUtil.BottomLeft;
break;
}
}
}
else if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter )
{
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//o o i i
resultTiles = painter.TransitionBrushes[brushNum].TilesStraight;
resultDirection = TileUtil.Top;
break;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
//o o i o
resultTiles = painter.TransitionBrushes[brushNum].TilesCornerOut;
resultDirection = TileUtil.TopRight;
break;
}
}
else if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
//o o o i
resultTiles = painter.TransitionBrushes[brushNum].TilesCornerOut;
resultDirection = TileUtil.TopLeft;
break;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
//o o o o
//nothing to do here
break;
}
}
}
}
}
}
//set cliff tiles
if ( terrain.Tiles[PosNum.X, PosNum.Y].Tri )
{
if ( terrain.Tiles[PosNum.X, PosNum.Y].TriTopLeftIsCliff )
{
if ( terrain.Tiles[PosNum.X, PosNum.Y].TriBottomRightIsCliff )
{
var brushNum = 0;
for ( brushNum = 0; brushNum <= painter.CliffBrushCount - 1; brushNum++ )
{
terrainInner = painter.CliffBrushes[brushNum].Terrain_Inner;
terrainOuter = painter.CliffBrushes[brushNum].Terrain_Outer;
if ( terrainInner == terrainOuter )
{
var a = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( a >= 3 )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = terrain.Tiles[PosNum.X, PosNum.Y].DownSide;
break;
}
}
if ( ((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner && terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner) &&
(terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter ||
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter)) ||
((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner || terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner) &&
(terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter &&
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter)) )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = TileUtil.Bottom;
break;
}
if ( ((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter &&
terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter) &&
(terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner ||
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner)) ||
((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter ||
terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter) &&
(terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner &&
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner)) )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = TileUtil.Left;
break;
}
if ( ((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter &&
terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter) &&
(terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner ||
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner)) ||
((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter ||
terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter) &&
(terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner &&
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner)) )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = TileUtil.Top;
break;
}
if ( ((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner &&
terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner) &&
(terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter ||
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter)) ||
((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner ||
terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner) &&
(terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter &&
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter)) )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = TileUtil.Right;
break;
}
}
if ( brushNum == painter.CliffBrushCount )
{
resultTiles = null;
resultDirection = TileUtil.None;
}
}
else
{
var brushNum = 0;
for ( brushNum = 0; brushNum <= painter.CliffBrushCount - 1; brushNum++ )
{
terrainInner = painter.CliffBrushes[brushNum].Terrain_Inner;
terrainOuter = painter.CliffBrushes[brushNum].Terrain_Outer;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter )
{
var a = 0;
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( a >= 2 )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Corner_In;
resultDirection = TileUtil.TopLeft;
break;
}
}
else if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner )
{
var A = 0;
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter )
{
A++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
A++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
A++;
}
if ( A >= 2 )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Corner_Out;
resultDirection = TileUtil.BottomRight;
break;
}
}
}
if ( brushNum == painter.CliffBrushCount )
{
resultTiles = null;
resultDirection = TileUtil.None;
}
}
}
else if ( terrain.Tiles[PosNum.X, PosNum.Y].TriBottomRightIsCliff )
{
var brushNum = 0;
for ( brushNum = 0; brushNum <= painter.CliffBrushCount - 1; brushNum++ )
{
terrainInner = painter.CliffBrushes[brushNum].Terrain_Inner;
terrainOuter = painter.CliffBrushes[brushNum].Terrain_Outer;
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
var a = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( a >= 2 )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Corner_In;
resultDirection = TileUtil.BottomRight;
break;
}
}
else if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
var a = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter )
{
a++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
a++;
}
if ( a >= 2 )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Corner_Out;
resultDirection = TileUtil.TopLeft;
break;
}
}
}
if ( brushNum == painter.CliffBrushCount )
{
resultTiles = null;
resultDirection = TileUtil.None;
}
}
}
else
{
//default tri orientation
if ( terrain.Tiles[PosNum.X, PosNum.Y].TriTopRightIsCliff )
{
if ( terrain.Tiles[PosNum.X, PosNum.Y].TriBottomLeftIsCliff )
{
var brushNum = 0;
for ( brushNum = 0; brushNum <= painter.CliffBrushCount - 1; brushNum++ )
{
terrainInner = painter.CliffBrushes[brushNum].Terrain_Inner;
terrainOuter = painter.CliffBrushes[brushNum].Terrain_Outer;
if ( terrainInner == terrainOuter )
{
var a = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( a >= 3 )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = terrain.Tiles[PosNum.X, PosNum.Y].DownSide;
break;
}
}
if ( ((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner && terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner) &&
(terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter ||
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter)) ||
((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner || terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner) &&
(terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter &&
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter)) )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = TileUtil.Bottom;
break;
}
if ( ((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter &&
terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter) &&
(terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner ||
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner)) ||
((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter ||
terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter) &&
(terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner &&
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner)) )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = TileUtil.Left;
break;
}
if ( ((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter &&
terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter) &&
(terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner ||
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner)) ||
((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter ||
terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter) &&
(terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner &&
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner)) )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = TileUtil.Top;
break;
}
if ( ((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner &&
terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner) &&
(terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter ||
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter)) ||
((terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner ||
terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner) &&
(terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter &&
terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter)) )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Straight;
resultDirection = TileUtil.Right;
break;
}
}
if ( brushNum == painter.CliffBrushCount )
{
resultTiles = null;
resultDirection = TileUtil.None;
}
}
else
{
var brushNum = 0;
for ( brushNum = 0; brushNum <= painter.CliffBrushCount - 1; brushNum++ )
{
terrainInner = painter.CliffBrushes[brushNum].Terrain_Inner;
terrainOuter = painter.CliffBrushes[brushNum].Terrain_Outer;
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter )
{
var a = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
a++;
}
if ( a >= 2 )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Corner_In;
resultDirection = TileUtil.TopRight;
break;
}
}
else if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
var a = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter )
{
a++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
a++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
a++;
}
if ( a >= 2 )
{
resultTiles = painter.CliffBrushes[brushNum].Tiles_Corner_Out;
resultDirection = TileUtil.BottomLeft;
break;
}
}
}
if ( brushNum == painter.CliffBrushCount )
{
resultTiles = null;
resultDirection = TileUtil.None;
}
}
}
else if ( terrain.Tiles[PosNum.X, PosNum.Y].TriBottomLeftIsCliff )
{
var BrushNum = 0;
for ( BrushNum = 0; BrushNum <= painter.CliffBrushCount - 1; BrushNum++ )
{
terrainInner = painter.CliffBrushes[BrushNum].Terrain_Inner;
terrainOuter = painter.CliffBrushes[BrushNum].Terrain_Outer;
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
var A = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainInner )
{
A++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainInner )
{
A++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainInner )
{
A++;
}
if ( A >= 2 )
{
resultTiles = painter.CliffBrushes[BrushNum].Tiles_Corner_In;
resultDirection = TileUtil.BottomLeft;
break;
}
}
else if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainInner )
{
var A = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter )
{
A++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter )
{
A++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
A++;
}
if ( A >= 2 )
{
resultTiles = painter.CliffBrushes[BrushNum].Tiles_Corner_Out;
resultDirection = TileUtil.TopRight;
break;
}
}
}
if ( BrushNum == painter.CliffBrushCount )
{
resultTiles = null;
resultDirection = TileUtil.None;
}
}
}
//apply roads
road = null;
if ( terrain.SideH[PosNum.X, PosNum.Y].Road != null )
{
road = terrain.SideH[PosNum.X, PosNum.Y].Road;
}
else if ( terrain.SideH[PosNum.X, PosNum.Y + 1].Road != null )
{
road = terrain.SideH[PosNum.X, PosNum.Y + 1].Road;
}
else if ( terrain.SideV[PosNum.X + 1, PosNum.Y].Road != null )
{
road = terrain.SideV[PosNum.X + 1, PosNum.Y].Road;
}
else if ( terrain.SideV[PosNum.X, PosNum.Y].Road != null )
{
road = terrain.SideV[PosNum.X, PosNum.Y].Road;
}
if ( road != null )
{
var BrushNum = 0;
for ( BrushNum = 0; BrushNum <= painter.RoadBrushCount - 1; BrushNum++ )
{
if ( painter.RoadBrushes[BrushNum].Road == road )
{
terrainOuter = painter.RoadBrushes[BrushNum].Terrain;
var A = 0;
if ( terrain.Vertices[PosNum.X, PosNum.Y].Terrain == terrainOuter )
{
A++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y].Terrain == terrainOuter )
{
A++;
}
if ( terrain.Vertices[PosNum.X, PosNum.Y + 1].Terrain == terrainOuter )
{
A++;
}
if ( terrain.Vertices[PosNum.X + 1, PosNum.Y + 1].Terrain == terrainOuter )
{
A++;
}
if ( A >= 2 )
{
break;
}
}
}
resultTiles = null;
resultDirection = TileUtil.None;
if ( BrushNum < painter.RoadBrushCount )
{
roadTop = terrain.SideH[PosNum.X, PosNum.Y].Road == road;
roadLeft = terrain.SideV[PosNum.X, PosNum.Y].Road == road;
roadRight = terrain.SideV[PosNum.X + 1, PosNum.Y].Road == road;
roadBottom = terrain.SideH[PosNum.X, PosNum.Y + 1].Road == road;
//do cross intersection
if ( roadTop && roadLeft && roadRight && roadBottom )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_CrossIntersection;
resultDirection = TileUtil.None;
//do T intersection
}
else if ( roadTop && roadLeft && roadRight )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_TIntersection;
resultDirection = TileUtil.Top;
}
else if ( roadTop && roadLeft && roadBottom )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_TIntersection;
resultDirection = TileUtil.Left;
}
else if ( roadTop && roadRight && roadBottom )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_TIntersection;
resultDirection = TileUtil.Right;
}
else if ( roadLeft && roadRight && roadBottom )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_TIntersection;
resultDirection = TileUtil.Bottom;
//do straight
}
else if ( roadTop && roadBottom )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_Straight;
if ( App.Random.Next() >= 0.5F )
{
resultDirection = TileUtil.Top;
}
else
{
resultDirection = TileUtil.Bottom;
}
}
else if ( roadLeft && roadRight )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_Straight;
if ( App.Random.Next() >= 0.5F )
{
resultDirection = TileUtil.Left;
}
else
{
resultDirection = TileUtil.Right;
}
//do corner
}
else if ( roadTop && roadLeft )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_Corner_In;
resultDirection = TileUtil.TopLeft;
}
else if ( roadTop && roadRight )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_Corner_In;
resultDirection = TileUtil.TopRight;
}
else if ( roadLeft && roadBottom )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_Corner_In;
resultDirection = TileUtil.BottomLeft;
}
else if ( roadRight && roadBottom )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_Corner_In;
resultDirection = TileUtil.BottomRight;
//do end
}
else if ( roadTop )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_End;
resultDirection = TileUtil.Top;
}
else if ( roadLeft )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_End;
resultDirection = TileUtil.Left;
}
else if ( roadRight )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_End;
resultDirection = TileUtil.Right;
}
else if ( roadBottom )
{
resultTiles = painter.RoadBrushes[BrushNum].Tile_End;
resultDirection = TileUtil.Bottom;
}
}
}
if ( resultTiles == null )
{
resultTexture.TextureNum = -1;
resultTexture.Direction = TileUtil.None;
}
else
{
resultTexture = resultTiles.GetRandom();
}
if ( resultTexture.TextureNum < 0 )
{
if ( MakeInvalidTiles )
{
terrain.Tiles[PosNum.X, PosNum.Y].Texture = TileUtil.OrientateTile(ref resultTexture, resultDirection);
}
}
else
{
terrain.Tiles[PosNum.X, PosNum.Y].Texture = TileUtil.OrientateTile(ref resultTexture, resultDirection);
}
Map.SectorGraphicsChanges.TileChanged(PosNum);
Map.SectorTerrainUndoChanges.TileChanged(PosNum);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2007 Novell Inc., www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
// Authors:
// Thomas Wiest (twiest@novell.com)
// Rusty Howell (rhowell@novell.com)
//
// (C) Novell Inc.
using System;
using System.Collections;
using System.Text;
using System.Management.Internal.BaseDataTypes;
namespace System.Management.Internal
{
/// <summary>
/// A list CimParameter objects
/// </summary>
internal class CimParameterList : BaseDataTypeList<CimParameter>
{
#region Constructors
/// <summary>
/// Creates an empty CimParameterList
/// </summary>
public CimParameterList()
{
}
/// <summary>
/// Creates a new CimParameterList with the given CimParameters
/// </summary>
/// <param name="parameters"></param>
public CimParameterList(params CimParameter[] parameters)
: base(parameters)
{
}
#endregion
#region Properties
/// <summary>
/// Gets a CimParameter based on the name
/// </summary>
/// <param name="name">Name of the CimParameter</param>
/// <returns>CimParameter or null if not found</returns>
public CimParameter this[CimName name]
{
get { return FindItem(name); }
}
#endregion
#region Methods
/// <summary>
/// Removes a CimParameter from the collection, based the the name
/// </summary>
/// <param name="name">Name of the parameter to remove</param>
public bool Remove(CimName name)
{
CimParameter param = FindItem(name);
if (param != null)
{
items.Remove(param);
return true;
}
return false;
}
private CimParameter FindItem(CimName name)
{
//use predicates to optimize?
foreach (CimParameter curParam in items)
{
if (curParam.Name == name)
return curParam;
}
return null;
}
#region Equals, operator== , operator!=
public override bool Equals(object obj)
{
if ((obj == null) || !(obj is CimParameterList))
{
return false;
}
return (this == (CimParameterList)obj);
}
/// <summary>
/// Shallow compare two CimPropertyLists
/// </summary>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns>Returns true if both lists have the same elements with the same names</returns>
public static bool operator ==(CimParameterList list1, CimParameterList list2)
{
if (((object)list1 == null) || ((object)list2 == null))
{
if (((object)list1 == null) && ((object)list2 == null))
{
return true;
}
return false;
}
if (list1.Count != list2.Count)
return false;
//check that all A's exist are in B
//Changed for MONO
for (int i = 0; i < list1.Count; ++i)
{
if (list2.FindItem(list1[i].Name) == null)
return false;
}
//check that all B's exist in A
for (int i = 0; i < list2.Count; ++i)
{
if (list1.FindItem(list2[i].Name) == null)
return false;
}
return true;
}
/// <summary>
/// Shallow compare of two CimPropertyLists
/// </summary>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns>Returns true if the lists do not have the same elements</returns>
public static bool operator !=(CimParameterList list1, CimParameterList list2)
{
return !(list1 == list2);
}
#endregion
#region Operator <,>,<=,>=
/* I don't think <,> are necessary...
/// <summary>
/// Determines whether a list is a subset of another list (shallow compare)
/// </summary>
/// <param name="list1">Subset list</param>
/// <param name="list2">Superset list</param>
/// <returns>Returns true if list1 is a subset of list2</returns>
public static bool operator <(CimParameterList list1, CimParameterList list2)
{
if (!(list1 <= list2))
return false;
//list1 is a subset of list2
return !(list1 == list2);//return true if the two lists are not equal
}
/// <summary>
/// Determines whether a list is a superset of another list (shallow compare)
/// </summary>
/// <param name="list1">Superset list</param>
/// <param name="list2">subset list</param>
/// <returns>Returns true if list1 is a superset of list2</returns>
public static bool operator >(CimParameterList list1, CimParameterList list2)
{
return (list2 < list1);
}
* */
/// <summary>
/// Determines whether a list is a subset of another list (shallow compare)
/// </summary>
/// <param name="list1">Superset list</param>
/// <param name="list2">subset list</param>
/// <returns>Returns true if list1 is a superset of list2</returns>
public static bool operator <=(CimParameterList list1, CimParameterList list2)
{
//return ((list1 < list2) || (list1 == list2));
if (((object)list1 == null) || ((object)list2 == null))
{
if (((object)list1 == null) && ((object)list2 == null))
{
return true;
}
return false;
}
if (list1.Count > list2.Count)
return false;
//Changed for MONO
for(int i = 0; i < list1.Count; ++i)
{
if (list2.FindItem(list1[i].Name) == null)
return false;
}
return true;
}
/// <summary>
/// Determines whether a list is a superset of another list (shallow compare)
/// </summary>
/// <param name="list1">Superset list</param>
/// <param name="list2">subset list</param>
/// <returns>Returns true if list1 is a superset of list2</returns>
public static bool operator >=(CimParameterList list1, CimParameterList list2)
{
return (list2 <= list1);
}
#endregion
/// <summary>
/// Performes a deep compare of two CimPropertyLists
/// </summary>
/// <param name="list">CimPropertyList to compare</param>
/// <returns>Returns true if the lists have the same properties and values</returns>
public bool IsEqualTo(CimParameterList list)
{
if (this != list)//do shallow compare first
return false;
//Changed for MONO
for (int i = 0; i < this.Count; i++)
{
CimParameter p = list.FindItem(this[i].Name);
if ((p == null) || (p != this[i]))
return false;
}
return true;
}
#endregion
}
}
| |
using System;
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// ConstructionManagement
/// </summary>
public sealed partial class ConstructionManagement : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _additionalDisbursementsConditions;
private DirtyValue<DateTime?>? _architectsCertificateDate;
private DirtyValue<bool?>? _architectsCertificateIndicator;
private DirtyValue<decimal?>? _asCompletedAppraisedValue;
private DirtyValue<decimal?>? _asCompletedPurchasePrice;
private DirtyValue<DateTime?>? _budgetDate;
private DirtyValue<bool?>? _budgetIndicator;
private DirtyValue<DateTime?>? _commitmentExpirationDate;
private DirtyValue<DateTime?>? _commitmentLetterDate;
private DirtyValue<DateTime?>? _constCompletionDate;
private DirtyValue<StringEnumValue<ConstOnlyAmortizationType>>? _constOnlyAmortizationType;
private DirtyValue<bool?>? _constructionContractIndicator;
private DirtyValue<DateTime?>? _constructionContractIssuedDate;
private DirtyValue<DateTime?>? _constructionContractReceivedDate;
private DirtyValue<bool?>? _constructionPeriodIncludedInLoanTermFlag;
private DirtyValue<DateTime?>? _contractorsAgreementDate;
private DirtyValue<bool?>? _contractorsAgreementIndicator;
private DirtyValue<bool?>? _costImprovementsIncluded;
private DirtyValue<DateTime?>? _environmentalAssessmentDate;
private DirtyValue<bool?>? _environmentalAssessmentIndicator;
private DirtyValue<DateTime?>? _floodHazardDeterminationDate;
private DirtyValue<bool?>? _floodHazardDeterminationIndicator;
private DirtyValue<int?>? _futureAdvancePeriod;
private DirtyValue<decimal?>? _holdbackAmount;
private DirtyValue<decimal?>? _holdbackPercent;
private DirtyValue<DateTime?>? _lienAgentNorthCarolinaDate;
private DirtyValue<bool?>? _lienAgentNorthCarolinaIndicator;
private DirtyValue<DateTime?>? _listOfConstructionAgreementsDate;
private DirtyValue<bool?>? _listOfConstructionAgreementsIndicator;
private DirtyValue<decimal?>? _maxLTVPercent;
private DirtyValue<int?>? _minimumDaysBetweenDisbursements;
private DirtyValue<DateTime?>? _otherDate;
private DirtyValue<string?>? _otherDescription;
private DirtyValue<bool?>? _otherIndicator;
private DirtyValue<StringEnumValue<PartialPrepaymentsElection>>? _partialPrepaymentsElection;
private DirtyValue<DateTime?>? _paymentAndPerformanceBondsDate;
private DirtyValue<bool?>? _paymentAndPerformanceBondsIndicator;
private DirtyValue<DateTime?>? _percolationTestDate;
private DirtyValue<bool?>? _percolationTestIndicator;
private DirtyValue<DateTime?>? _permitsDate;
private DirtyValue<bool?>? _permitsIndicator;
private DirtyValue<DateTime?>? _plansAndSpecificationsDate;
private DirtyValue<bool?>? _plansAndSpecificationsIndicator;
private DirtyValue<decimal?>? _projectDelaySurchargePercent;
private DirtyValue<int?>? _returnLendersCopyCommitmentDays;
private DirtyValue<bool?>? _securedBySeparateProperty;
private DirtyValue<DateTime?>? _soilReportDate;
private DirtyValue<bool?>? _soilReportIndicator;
private DirtyValue<DateTime?>? _surveyDate;
private DirtyValue<bool?>? _surveyIndicator;
private DirtyValue<DateTime?>? _takeOutCommitmentDate;
private DirtyValue<bool?>? _takeOutCommitmentIndicator;
private DirtyValue<DateTime?>? _takeOutCommitmentIssuedDate;
private DirtyValue<string?>? _takeOutLenderAddress;
private DirtyValue<string?>? _takeOutLenderCity;
private DirtyValue<string?>? _takeOutLenderContactName;
private DirtyValue<string?>? _takeOutLenderContactTitle;
private DirtyValue<string?>? _takeOutLenderEmail;
private DirtyValue<string?>? _takeOutLenderFax;
private DirtyValue<string?>? _takeOutLenderLicenseNumber;
private DirtyValue<string?>? _takeOutLenderName;
private DirtyValue<string?>? _takeOutLenderNMLSNumber;
private DirtyValue<string?>? _takeOutLenderPhone;
private DirtyValue<string?>? _takeOutLenderState;
private DirtyValue<string?>? _takeOutLenderZip;
private DirtyValue<DateTime?>? _titleInsuranceDate;
private DirtyValue<bool?>? _titleInsuranceIndicator;
private DirtyValue<DateTime?>? _utilityLettersDate;
private DirtyValue<bool?>? _utilityLettersIndicator;
private DirtyValue<DateTime?>? _waterTestDate;
private DirtyValue<bool?>? _waterTestIndicator;
/// <summary>
/// Construction Management Project Data - Additional Disbursements Conditions [CONST.X56]
/// </summary>
public string? AdditionalDisbursementsConditions { get => _additionalDisbursementsConditions; set => SetField(ref _additionalDisbursementsConditions, value); }
/// <summary>
/// Construction Management Project Data - Architect's Certificate Date [CONST.X34]
/// </summary>
public DateTime? ArchitectsCertificateDate { get => _architectsCertificateDate; set => SetField(ref _architectsCertificateDate, value); }
/// <summary>
/// Construction Management Project Data - Architect's Certificate Indicator [CONST.X33]
/// </summary>
public bool? ArchitectsCertificateIndicator { get => _architectsCertificateIndicator; set => SetField(ref _architectsCertificateIndicator, value); }
/// <summary>
/// As Completed Appraised Value [CONST.X59]
/// </summary>
public decimal? AsCompletedAppraisedValue { get => _asCompletedAppraisedValue; set => SetField(ref _asCompletedAppraisedValue, value); }
/// <summary>
/// As Completed Purchase Price [CONST.X58]
/// </summary>
public decimal? AsCompletedPurchasePrice { get => _asCompletedPurchasePrice; set => SetField(ref _asCompletedPurchasePrice, value); }
/// <summary>
/// Construction Management Project Data - Budget Date [CONST.X30]
/// </summary>
public DateTime? BudgetDate { get => _budgetDate; set => SetField(ref _budgetDate, value); }
/// <summary>
/// Construction Management Project Data - Budget Indicator [CONST.X29]
/// </summary>
public bool? BudgetIndicator { get => _budgetIndicator; set => SetField(ref _budgetIndicator, value); }
/// <summary>
/// Construction Management Project Data - Commitment Expiration Date [CONST.X12]
/// </summary>
public DateTime? CommitmentExpirationDate { get => _commitmentExpirationDate; set => SetField(ref _commitmentExpirationDate, value); }
/// <summary>
/// Construction Management Project Data - Commitment Letter Date [CONST.X11]
/// </summary>
public DateTime? CommitmentLetterDate { get => _commitmentLetterDate; set => SetField(ref _commitmentLetterDate, value); }
/// <summary>
/// Construction Management Loan Info - Const. Completion Date [CONST.X3]
/// </summary>
public DateTime? ConstCompletionDate { get => _constCompletionDate; set => SetField(ref _constCompletionDate, value); }
/// <summary>
/// Construction Management Loan Info - Construction Only Amortization Type [CONST.X13]
/// </summary>
public StringEnumValue<ConstOnlyAmortizationType> ConstOnlyAmortizationType { get => _constOnlyAmortizationType; set => SetField(ref _constOnlyAmortizationType, value); }
/// <summary>
/// Construction Management Project Data - Construction Contract Indicator [CONST.X27]
/// </summary>
public bool? ConstructionContractIndicator { get => _constructionContractIndicator; set => SetField(ref _constructionContractIndicator, value); }
/// <summary>
/// Construction Management Project Data - Construction Contract Issued Date [CONST.X10]
/// </summary>
public DateTime? ConstructionContractIssuedDate { get => _constructionContractIssuedDate; set => SetField(ref _constructionContractIssuedDate, value); }
/// <summary>
/// Construction Management Project Data - Construction Contract Received Date [CONST.X28]
/// </summary>
public DateTime? ConstructionContractReceivedDate { get => _constructionContractReceivedDate; set => SetField(ref _constructionContractReceivedDate, value); }
/// <summary>
/// Construction period included in the Loan Terms Flag [CONST.X1]
/// </summary>
public bool? ConstructionPeriodIncludedInLoanTermFlag { get => _constructionPeriodIncludedInLoanTermFlag; set => SetField(ref _constructionPeriodIncludedInLoanTermFlag, value); }
/// <summary>
/// Construction Management Project Data - Contractor's Agreement Date [CONST.X32]
/// </summary>
public DateTime? ContractorsAgreementDate { get => _contractorsAgreementDate; set => SetField(ref _contractorsAgreementDate, value); }
/// <summary>
/// Construction Management Project Data - Contractor's Agreement Indicator [CONST.X31]
/// </summary>
public bool? ContractorsAgreementIndicator { get => _contractorsAgreementIndicator; set => SetField(ref _contractorsAgreementIndicator, value); }
/// <summary>
/// Cost of Improvements Included in Liabilities [CONST.X73]
/// </summary>
public bool? CostImprovementsIncluded { get => _costImprovementsIncluded; set => SetField(ref _costImprovementsIncluded, value); }
/// <summary>
/// Construction Management Project Data - Environmental Assessment Date [CONST.X36]
/// </summary>
public DateTime? EnvironmentalAssessmentDate { get => _environmentalAssessmentDate; set => SetField(ref _environmentalAssessmentDate, value); }
/// <summary>
/// Construction Management Project Data - Environmental Assessment Indicator [CONST.X35]
/// </summary>
public bool? EnvironmentalAssessmentIndicator { get => _environmentalAssessmentIndicator; set => SetField(ref _environmentalAssessmentIndicator, value); }
/// <summary>
/// Construction Management Project Data - Flood Hazard Determination Date [CONST.X48]
/// </summary>
public DateTime? FloodHazardDeterminationDate { get => _floodHazardDeterminationDate; set => SetField(ref _floodHazardDeterminationDate, value); }
/// <summary>
/// Construction Management Project Data - Flood Hazard Determination Indicator [CONST.X47]
/// </summary>
public bool? FloodHazardDeterminationIndicator { get => _floodHazardDeterminationIndicator; set => SetField(ref _floodHazardDeterminationIndicator, value); }
/// <summary>
/// Construction Management Project Data - Future Advance Period (mths) [CONST.X54]
/// </summary>
public int? FutureAdvancePeriod { get => _futureAdvancePeriod; set => SetField(ref _futureAdvancePeriod, value); }
/// <summary>
/// Construction Management Loan Info - Holdback $ [CONST.X8]
/// </summary>
public decimal? HoldbackAmount { get => _holdbackAmount; set => SetField(ref _holdbackAmount, value); }
/// <summary>
/// Construction Management Loan Info - Holdback % [CONST.X7]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? HoldbackPercent { get => _holdbackPercent; set => SetField(ref _holdbackPercent, value); }
/// <summary>
/// Construction Management Project Data - Lien Agent (North Carolina) Date [CONST.X46]
/// </summary>
public DateTime? LienAgentNorthCarolinaDate { get => _lienAgentNorthCarolinaDate; set => SetField(ref _lienAgentNorthCarolinaDate, value); }
/// <summary>
/// Construction Management Project Data - Lien Agent (North Carolina) Indicator [CONST.X45]
/// </summary>
public bool? LienAgentNorthCarolinaIndicator { get => _lienAgentNorthCarolinaIndicator; set => SetField(ref _lienAgentNorthCarolinaIndicator, value); }
/// <summary>
/// Construction Management Project Data - List of Construction Agreements Date [CONST.X50]
/// </summary>
public DateTime? ListOfConstructionAgreementsDate { get => _listOfConstructionAgreementsDate; set => SetField(ref _listOfConstructionAgreementsDate, value); }
/// <summary>
/// Construction Management Project Data - List of Construction Agreements Indicator [CONST.X49]
/// </summary>
public bool? ListOfConstructionAgreementsIndicator { get => _listOfConstructionAgreementsIndicator; set => SetField(ref _listOfConstructionAgreementsIndicator, value); }
/// <summary>
/// Construction Management Loan Info - Max LTV % [CONST.X5]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? MaxLTVPercent { get => _maxLTVPercent; set => SetField(ref _maxLTVPercent, value); }
/// <summary>
/// Construction Management Project Data - Minimum days between disbursements [CONST.X55]
/// </summary>
public int? MinimumDaysBetweenDisbursements { get => _minimumDaysBetweenDisbursements; set => SetField(ref _minimumDaysBetweenDisbursements, value); }
/// <summary>
/// Construction Management Project Data - Other Date [CONST.X52]
/// </summary>
public DateTime? OtherDate { get => _otherDate; set => SetField(ref _otherDate, value); }
/// <summary>
/// Construction Management Project Data - Other Description [CONST.X53]
/// </summary>
public string? OtherDescription { get => _otherDescription; set => SetField(ref _otherDescription, value); }
/// <summary>
/// Construction Management Project Data - Other Indicator [CONST.X51]
/// </summary>
public bool? OtherIndicator { get => _otherIndicator; set => SetField(ref _otherIndicator, value); }
/// <summary>
/// Partial Prepayments Election [CONST.X57]
/// </summary>
public StringEnumValue<PartialPrepaymentsElection> PartialPrepaymentsElection { get => _partialPrepaymentsElection; set => SetField(ref _partialPrepaymentsElection, value); }
/// <summary>
/// Construction Management Project Data - Payment and Performance Bonds Date [CONST.X44]
/// </summary>
public DateTime? PaymentAndPerformanceBondsDate { get => _paymentAndPerformanceBondsDate; set => SetField(ref _paymentAndPerformanceBondsDate, value); }
/// <summary>
/// Construction Management Project Data - Payment and Performance Bonds Indicator [CONST.X43]
/// </summary>
public bool? PaymentAndPerformanceBondsIndicator { get => _paymentAndPerformanceBondsIndicator; set => SetField(ref _paymentAndPerformanceBondsIndicator, value); }
/// <summary>
/// Construction Management Project Data - Percolation Test Date [CONST.X42]
/// </summary>
public DateTime? PercolationTestDate { get => _percolationTestDate; set => SetField(ref _percolationTestDate, value); }
/// <summary>
/// Construction Management Project Data - Percolation Test Indicator [CONST.X41]
/// </summary>
public bool? PercolationTestIndicator { get => _percolationTestIndicator; set => SetField(ref _percolationTestIndicator, value); }
/// <summary>
/// Construction Management Project Data - Permits Date [CONST.X22]
/// </summary>
public DateTime? PermitsDate { get => _permitsDate; set => SetField(ref _permitsDate, value); }
/// <summary>
/// Construction Management Project Data - Permits Indicator [CONST.X21]
/// </summary>
public bool? PermitsIndicator { get => _permitsIndicator; set => SetField(ref _permitsIndicator, value); }
/// <summary>
/// Construction Management Project Data - Plans and Specifications Date [CONST.X26]
/// </summary>
public DateTime? PlansAndSpecificationsDate { get => _plansAndSpecificationsDate; set => SetField(ref _plansAndSpecificationsDate, value); }
/// <summary>
/// Construction Management Project Data - Plans and Specifications Indicator [CONST.X25]
/// </summary>
public bool? PlansAndSpecificationsIndicator { get => _plansAndSpecificationsIndicator; set => SetField(ref _plansAndSpecificationsIndicator, value); }
/// <summary>
/// Construction Management Loan Info - Project Delay Surcharge % [CONST.X9]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? ProjectDelaySurchargePercent { get => _projectDelaySurchargePercent; set => SetField(ref _projectDelaySurchargePercent, value); }
/// <summary>
/// Construction Management Project Data - Return Lender's copy of this commitment within days [CONST.X14]
/// </summary>
public int? ReturnLendersCopyCommitmentDays { get => _returnLendersCopyCommitmentDays; set => SetField(ref _returnLendersCopyCommitmentDays, value); }
/// <summary>
/// Construction Management Loan Info - Secured by Separate Property [CONST.X2]
/// </summary>
public bool? SecuredBySeparateProperty { get => _securedBySeparateProperty; set => SetField(ref _securedBySeparateProperty, value); }
/// <summary>
/// Construction Management Project Data - Soil Report Date [CONST.X38]
/// </summary>
public DateTime? SoilReportDate { get => _soilReportDate; set => SetField(ref _soilReportDate, value); }
/// <summary>
/// Construction Management Project Data - Soil Report Indicator [CONST.X37]
/// </summary>
public bool? SoilReportIndicator { get => _soilReportIndicator; set => SetField(ref _soilReportIndicator, value); }
/// <summary>
/// Construction Management Project Data - Survey Date [CONST.X20]
/// </summary>
public DateTime? SurveyDate { get => _surveyDate; set => SetField(ref _surveyDate, value); }
/// <summary>
/// Construction Management Project Data - Survey Indicator [CONST.X19]
/// </summary>
public bool? SurveyIndicator { get => _surveyIndicator; set => SetField(ref _surveyIndicator, value); }
/// <summary>
/// Construction Management Project Data - Take-out Commitment Date [CONST.X16]
/// </summary>
public DateTime? TakeOutCommitmentDate { get => _takeOutCommitmentDate; set => SetField(ref _takeOutCommitmentDate, value); }
/// <summary>
/// Construction Management Project Data - Take-out Commitment Indicator [CONST.X15]
/// </summary>
public bool? TakeOutCommitmentIndicator { get => _takeOutCommitmentIndicator; set => SetField(ref _takeOutCommitmentIndicator, value); }
/// <summary>
/// Take-Out Commitment Letter Date [CONST.X67]
/// </summary>
public DateTime? TakeOutCommitmentIssuedDate { get => _takeOutCommitmentIssuedDate; set => SetField(ref _takeOutCommitmentIssuedDate, value); }
/// <summary>
/// Take-Out Lender Address [CONST.X63]
/// </summary>
public string? TakeOutLenderAddress { get => _takeOutLenderAddress; set => SetField(ref _takeOutLenderAddress, value); }
/// <summary>
/// Take-Out Lender City [CONST.X64]
/// </summary>
public string? TakeOutLenderCity { get => _takeOutLenderCity; set => SetField(ref _takeOutLenderCity, value); }
/// <summary>
/// Take-Out Lender Contact Name [CONST.X68]
/// </summary>
public string? TakeOutLenderContactName { get => _takeOutLenderContactName; set => SetField(ref _takeOutLenderContactName, value); }
/// <summary>
/// Take-Out Lender Contact Title [CONST.X69]
/// </summary>
public string? TakeOutLenderContactTitle { get => _takeOutLenderContactTitle; set => SetField(ref _takeOutLenderContactTitle, value); }
/// <summary>
/// Take-Out Lender Email [CONST.X71]
/// </summary>
public string? TakeOutLenderEmail { get => _takeOutLenderEmail; set => SetField(ref _takeOutLenderEmail, value); }
/// <summary>
/// Take-Out Lender Fax [CONST.X72]
/// </summary>
public string? TakeOutLenderFax { get => _takeOutLenderFax; set => SetField(ref _takeOutLenderFax, value); }
/// <summary>
/// Take-Out Lender License # [CONST.X62]
/// </summary>
public string? TakeOutLenderLicenseNumber { get => _takeOutLenderLicenseNumber; set => SetField(ref _takeOutLenderLicenseNumber, value); }
/// <summary>
/// Take-Out Lender Name [CONST.X60]
/// </summary>
public string? TakeOutLenderName { get => _takeOutLenderName; set => SetField(ref _takeOutLenderName, value); }
/// <summary>
/// Take-Out Lender NMLS # [CONST.X61]
/// </summary>
public string? TakeOutLenderNMLSNumber { get => _takeOutLenderNMLSNumber; set => SetField(ref _takeOutLenderNMLSNumber, value); }
/// <summary>
/// Take-Out Lender Phone [CONST.X70]
/// </summary>
public string? TakeOutLenderPhone { get => _takeOutLenderPhone; set => SetField(ref _takeOutLenderPhone, value); }
/// <summary>
/// Take-Out Lender State [CONST.X65]
/// </summary>
public string? TakeOutLenderState { get => _takeOutLenderState; set => SetField(ref _takeOutLenderState, value); }
/// <summary>
/// Take-Out Lender Zipcode [CONST.X66]
/// </summary>
public string? TakeOutLenderZip { get => _takeOutLenderZip; set => SetField(ref _takeOutLenderZip, value); }
/// <summary>
/// Construction Management Project Data - Title Insurance Date [CONST.X18]
/// </summary>
public DateTime? TitleInsuranceDate { get => _titleInsuranceDate; set => SetField(ref _titleInsuranceDate, value); }
/// <summary>
/// Construction Management Project Data - Title Insurance Indicator [CONST.X17]
/// </summary>
public bool? TitleInsuranceIndicator { get => _titleInsuranceIndicator; set => SetField(ref _titleInsuranceIndicator, value); }
/// <summary>
/// Construction Management Project Data - Utility Letters Date [CONST.X24]
/// </summary>
public DateTime? UtilityLettersDate { get => _utilityLettersDate; set => SetField(ref _utilityLettersDate, value); }
/// <summary>
/// Construction Management Project Data - Utility Letters Indicator [CONST.X23]
/// </summary>
public bool? UtilityLettersIndicator { get => _utilityLettersIndicator; set => SetField(ref _utilityLettersIndicator, value); }
/// <summary>
/// Construction Management Project Data - Water Test Date [CONST.X40]
/// </summary>
public DateTime? WaterTestDate { get => _waterTestDate; set => SetField(ref _waterTestDate, value); }
/// <summary>
/// Construction Management Project Data - Water Test Indicator [CONST.X39]
/// </summary>
public bool? WaterTestIndicator { get => _waterTestIndicator; set => SetField(ref _waterTestIndicator, value); }
}
}
| |
using ATL.AudioData.IO;
using System;
using System.Collections.Generic;
using System.IO;
namespace ATL.AudioData
{
/// <summary>
/// Wrapper for reading multiple tags according to a priority
///
/// Rule : The first non-empty field of the most prioritized tag becomes the "cross-detected" field
/// There is no "field blending" across collections (pictures, additional fields) : the first non-empty collection is kept
/// </summary>
internal class CrossMetadataReader : IMetaDataIO
{
// Contains all IMetaDataIO objects to be read, in priority order (index [0] is the most important)
private IList<IMetaDataIO> metaReaders = null;
public CrossMetadataReader(AudioDataManager audioManager, int[] tagPriority)
{
metaReaders = new List<IMetaDataIO>();
for (int i=0; i<tagPriority.Length; i++)
{
if ((MetaDataIOFactory.TAG_NATIVE == tagPriority[i]) && (audioManager.HasNativeMeta()) && (audioManager.NativeTag != null))
{
metaReaders.Add(audioManager.NativeTag);
}
if ( (MetaDataIOFactory.TAG_ID3V1 == tagPriority[i]) && (audioManager.ID3v1.Exists) )
{
metaReaders.Add(audioManager.ID3v1);
}
if ( (MetaDataIOFactory.TAG_ID3V2 == tagPriority[i]) && (audioManager.ID3v2.Exists) )
{
metaReaders.Add(audioManager.ID3v2);
}
if ( (MetaDataIOFactory.TAG_APE == tagPriority[i]) && (audioManager.APEtag.Exists) )
{
metaReaders.Add(audioManager.APEtag);
}
}
}
/// <summary>
/// Returns true if this kind of metadata exists in the file, false if not
/// </summary>
public bool Exists
{
get { return (metaReaders.Count > 0); }
}
/// <summary>
/// Title of the track
/// </summary>
public String Title
{
get
{
String title = "";
foreach(IMetaDataIO reader in metaReaders)
{
title = reader.Title;
if (title != "") break;
}
return title;
}
}
/// <summary>
/// Artist
/// </summary>
public String Artist
{
get
{
String artist = "";
foreach(IMetaDataIO reader in metaReaders)
{
artist = reader.Artist;
if (artist != "") break;
}
return artist;
}
}
/// <summary>
/// Composer
/// </summary>
public String Composer
{
get
{
String composer = "";
foreach (IMetaDataIO reader in metaReaders)
{
composer = reader.Composer;
if (composer != "") break;
}
return composer;
}
}
/// <summary>
/// Comments
/// </summary>
public String Comment
{
get
{
String comment = "";
foreach(IMetaDataIO reader in metaReaders)
{
comment = reader.Comment;
if (comment != "") break;
}
return comment;
}
}
/// <summary>
/// Genre
/// </summary>
public String Genre
{
get
{
String genre = "";
foreach(IMetaDataIO reader in metaReaders)
{
genre = reader.Genre;
if (genre != "") break;
}
return genre;
}
}
/// <summary>
/// Track number
/// </summary>
public ushort Track
{
get
{
ushort track = 0;
foreach(IMetaDataIO reader in metaReaders)
{
track = reader.Track;
if (track != 0) break;
}
return track;
}
}
/// <summary>
/// Total track number
/// </summary>
public ushort TrackTotal
{
get
{
ushort trackTotal = 0;
foreach (IMetaDataIO reader in metaReaders)
{
trackTotal = reader.TrackTotal;
if (trackTotal != 0) break;
}
return trackTotal;
}
}
/// <summary>
/// Disc number
/// </summary>
public ushort Disc
{
get
{
ushort disc = 0;
foreach (IMetaDataIO reader in metaReaders)
{
disc = reader.Disc;
if (disc != 0) break;
}
return disc;
}
}
/// <summary>
/// Total disc number
/// </summary>
public ushort DiscTotal
{
get
{
ushort discTotal = 0;
foreach (IMetaDataIO reader in metaReaders)
{
discTotal = reader.DiscTotal;
if (discTotal != 0) break;
}
return discTotal;
}
}
/// <summary>
/// Year
/// </summary>
public String Year
{
get
{
String year = "";
foreach(IMetaDataIO reader in metaReaders)
{
year = reader.Year;
if (year != "") break;
}
return year;
}
}
/// <summary>
/// Title of the album
/// </summary>
public String Album
{
get
{
String album = "";
foreach(IMetaDataIO reader in metaReaders)
{
album = reader.Album;
if (album != "") break;
}
return album;
}
}
/// <summary>
/// Copyright
/// </summary>
public String Copyright
{
get
{
String result = "";
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.Copyright;
if (result != "") break;
}
return result;
}
}
/// <summary>
/// Album Arist
/// </summary>
public String AlbumArtist
{
get
{
String result = "";
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.AlbumArtist;
if (result != "") break;
}
return result;
}
}
/// <summary>
/// Conductor
/// </summary>
public String Conductor
{
get
{
String result = "";
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.Conductor;
if (result != "") break;
}
return result;
}
}
/// <summary>
/// Publisher
/// </summary>
public String Publisher
{
get
{
String result = "";
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.Publisher;
if (result != "") break;
}
return result;
}
}
/// <summary>
/// General description
/// </summary>
public String GeneralDescription
{
get
{
String result = "";
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.GeneralDescription;
if (result != "") break;
}
return result;
}
}
/// <summary>
/// Original artist
/// </summary>
public String OriginalArtist
{
get
{
String result = "";
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.OriginalArtist;
if (result != "") break;
}
return result;
}
}
/// <summary>
/// Original album
/// </summary>
public String OriginalAlbum
{
get
{
String result = "";
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.OriginalAlbum;
if (result != "") break;
}
return result;
}
}
public ushort Rating
{
get
{
ushort rating = 0;
foreach (IMetaDataIO reader in metaReaders)
{
rating = reader.Rating;
if (rating != 0) break;
}
return rating;
}
}
public float Popularity
{
get
{
float result = 0;
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.Popularity;
if (result != 0) break;
}
return result;
}
}
public string ChaptersTableDescription
{
get
{
string result = "";
foreach (IMetaDataIO reader in metaReaders)
{
result = reader.ChaptersTableDescription;
if (result != "") break;
}
return result;
}
}
/// <summary>
/// List of picture IDs stored in the tag
/// </summary>
public IList<PictureInfo> PictureTokens
{
get
{
IList<PictureInfo> pictures = new List<PictureInfo>();
foreach (IMetaDataIO reader in metaReaders)
{
if (reader.PictureTokens.Count > 0)
{
pictures = reader.PictureTokens;
break;
}
}
return pictures;
}
}
/// <summary>
/// Any other metadata field that is not represented among above getters
/// </summary>
public IDictionary<string,string> AdditionalFields
{
get
{
IDictionary<string,string> result = new Dictionary<string, string>();
foreach (IMetaDataIO reader in metaReaders)
{
IDictionary<string, string> readerAdditionalFields = reader.AdditionalFields;
if (readerAdditionalFields.Count > 0)
{
foreach (string s in readerAdditionalFields.Keys)
{
if (!result.ContainsKey(s)) result.Add(s, readerAdditionalFields[s]);
}
}
}
return result;
}
}
/// <summary>
/// Chapters
/// </summary>
public IList<ChapterInfo> Chapters
{
get
{
IList<ChapterInfo> chapters = new List<ChapterInfo>();
foreach (IMetaDataIO reader in metaReaders)
{
if (reader.Chapters != null && reader.Chapters.Count > 0)
{
foreach(ChapterInfo chapter in reader.Chapters)
{
chapters.Add(chapter);
}
break;
}
}
return chapters;
}
}
/// <summary>
/// Embedded pictures
/// </summary>
public IList<PictureInfo> EmbeddedPictures
{
get
{
IList<PictureInfo> pictures = new List<PictureInfo>();
foreach (IMetaDataIO reader in metaReaders)
{
if (reader.EmbeddedPictures != null && reader.EmbeddedPictures.Count > 0)
{
foreach (PictureInfo picture in reader.EmbeddedPictures)
{
pictures.Add(picture);
}
break;
}
}
return pictures;
}
}
public int Size
{
get
{
throw new NotImplementedException();
}
}
public bool Read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams) { throw new NotImplementedException(); }
public bool Write(BinaryReader r, BinaryWriter w, TagData tag) { throw new NotImplementedException(); }
public bool Remove(BinaryWriter w) { throw new NotImplementedException(); }
public void SetEmbedder(IMetaDataEmbedder embedder)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
}
}
| |
// 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 InsertInt321()
{
var test = new SimpleUnaryOpTest__InsertInt321();
try
{
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
}
catch (PlatformNotSupportedException)
{
test.Succeeded = true;
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__InsertInt321
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static SimpleUnaryOpTest__InsertInt321()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)0; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__InsertInt321()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)0; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)0; }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.Insert(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(int)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.Insert(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(int)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.Insert(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(int)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int32>), typeof(Int32), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(int)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int32>), typeof(Int32), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(int)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Int32>), typeof(Int32), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(int)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.Insert(
_clsVar,
(int)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Sse41.Insert(firstOp, (int)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, (int)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, (int)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__InsertInt321();
var result = Sse41.Insert(test._fld, (int)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.Insert(_fld, (int)2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
for (var i = 0; i < RetElementCount; i++)
{
if ((i == 1 ? result[i] != 2 : result[i] != 0))
{
Succeeded = false;
break;
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Int32>(Vector128<Int32><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon 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 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.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using KellermanSoftware.CompareNetObjects;
using System.Threading;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.FrameworkTests
{
[TestFixture]
class SurroundingRegionManagerTests
{
private Scene mockScene;
private SurroundingRegionManager srm;
private Dictionary<NeighborStateChangeType, int> stateChangeCounts = new Dictionary<NeighborStateChangeType, int>();
[SetUp]
public void Setup()
{
mockScene = InWorldz.Testing.SceneHelper.CreateScene(9000, 1000, 1000);
srm = mockScene.SurroundingRegions;
srm.OnNeighborStateChange += srm_OnNeighborStateChange;
}
void srm_OnNeighborStateChange(SimpleRegionInfo neighbor, NeighborStateChangeType changeType)
{
if (stateChangeCounts.ContainsKey(changeType))
{
stateChangeCounts[changeType]++;
}
else
{
stateChangeCounts[changeType] = 1;
}
}
[TearDown]
public void TearDown()
{
InWorldz.Testing.SceneHelper.TearDownScene(mockScene);
}
public static void SendCreateRegionMessage(uint xloc, uint yloc, ushort receiverServerPort, ushort regionServerport)
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = regionServerport,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = xloc,
RegionLocY = yloc,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:" + receiverServerPort + "/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
response.Dispose();
}
public static void SendRegionDownMessage(uint xloc, uint yloc, ushort receiverServerPort, ushort regionServerport)
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = regionServerport,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = xloc,
RegionLocY = yloc,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:" + receiverServerPort + "/region2/regiondown");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
response.Dispose();
}
[Test]
public void TestAddRegion()
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = 9000,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = 1100,
RegionLocY = 1000,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
Assert.AreEqual(2, response.ContentLength);
StreamReader sr = new StreamReader(response.GetResponseStream());
Assert.AreEqual("OK", sr.ReadToEnd());
var neighbors = srm.GetNeighborsSnapshot();
Assert.AreEqual(1, neighbors.Count);
CompareObjects.Equals((SimpleRegionInfo)info, neighbors[0].RegionInfo);
Assert.AreEqual(1, stateChangeCounts[NeighborStateChangeType.NeighborUp]);
stateChangeCounts.Clear();
}
[Test]
public void TestRemoveRegion()
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = 9000,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = 1100,
RegionLocY = 1000,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
Assert.AreEqual(2, response.ContentLength);
StreamReader sr = new StreamReader(response.GetResponseStream());
Assert.AreEqual("OK", sr.ReadToEnd());
var neighbors = srm.GetNeighborsSnapshot();
Assert.AreEqual(1, neighbors.Count);
CompareObjects.Equals((SimpleRegionInfo)info, neighbors[0].RegionInfo);
response.Dispose();
req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regiondown");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
response = req.GetResponse();
Assert.AreEqual(2, response.ContentLength);
sr = new StreamReader(response.GetResponseStream());
Assert.AreEqual("OK", sr.ReadToEnd());
neighbors = srm.GetNeighborsSnapshot();
Assert.AreEqual(0, neighbors.Count);
response.Dispose();
Assert.AreEqual(1, stateChangeCounts[NeighborStateChangeType.NeighborDown]);
stateChangeCounts.Clear();
}
[Test]
public void TestRegionPing()
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = 9000,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = 1100,
RegionLocY = 1000,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
var response = req.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
response.Dispose();
var neighbors = srm.GetNeighborsSnapshot();
var firstPing = neighbors[0].LastPingReceivedOn;
Thread.Sleep(1000);
req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/heartbeat");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("key");
req.Timeout = 10000;
req.Method = "POST";
serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
response = req.GetResponse();
Assert.AreEqual(2, response.ContentLength);
sr = new StreamReader(response.GetResponseStream());
Assert.AreEqual("OK", sr.ReadToEnd());
neighbors = srm.GetNeighborsSnapshot();
Assert.AreEqual(1, neighbors.Count);
Assert.Greater(neighbors[0].LastPingReceivedOn, firstPing);
response.Dispose();
Assert.AreEqual(1, stateChangeCounts[NeighborStateChangeType.NeighborPing]);
stateChangeCounts.Clear();
}
[Test]
public void TestUnauthorized()
{
RegionInfo info = new RegionInfo
{
ExternalHostName = "localhost",
InternalEndPoint = new System.Net.IPEndPoint(new System.Net.IPAddress(2130706433), 9001),
HttpPort = 9000,
OutsideIP = "127.0.0.1",
RegionID = UUID.Random(),
RegionLocX = 1100,
RegionLocY = 1000,
};
WebRequest req = HttpWebRequest.Create("http://127.0.0.1:9000/region2/regionup");
req.Headers["authorization"] = Util.GenerateHttpAuthorization("BADPASSWORD");
req.Timeout = 10000;
req.Method = "POST";
byte[] serRegInfo = OSDParser.SerializeLLSDBinary(info.PackRegionInfoData());
var rs = req.GetRequestStream();
rs.Write(serRegInfo, 0, serRegInfo.Length);
rs.Flush();
Assert.Throws<System.Net.WebException>(() =>
{
var response = req.GetResponse();
});
}
[Test]
public void TestQuerySurroundingRegions256()
{
// U = us at 1000, 1000
// N N N
// N U N
// N N N
//top row
SendCreateRegionMessage(999, 999, 9000, 9001);
SendCreateRegionMessage(1000, 999, 9000, 9001);
SendCreateRegionMessage(1001, 999, 9000, 9001);
//middle row
SendCreateRegionMessage(999, 1000, 9000, 9001);
SendCreateRegionMessage(1001, 1000, 9000, 9001);
//bottom row
SendCreateRegionMessage(999, 1001, 9000, 9001);
SendCreateRegionMessage(1000, 1001, 9000, 9001);
SendCreateRegionMessage(1001, 1001, 9000, 9001);
Assert.NotNull(srm.GetKnownNeighborAt(999, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 999));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1001));
//try a surrounding query
Assert.AreEqual(8, srm.GetKnownNeighborsWithinClientDD(1, 2).Count);
Assert.AreEqual(8, srm.GetKnownNeighborsWithinClientDD(256, 2).Count);
}
[Test]
public void TestQuerySurroundingRegions512()
{
// U = us at 1000, 1000
// X X X X X
// X N N N X
// X N U N X
// X N N N X
// X X X X X
//top row
SendCreateRegionMessage(998, 998, 9000, 9001);
SendCreateRegionMessage(999, 998, 9000, 9001);
SendCreateRegionMessage(1000, 998, 9000, 9001);
SendCreateRegionMessage(1001, 998, 9000, 9001);
SendCreateRegionMessage(1002, 998, 9000, 9001);
//second row
SendCreateRegionMessage(998, 999, 9000, 9001);
SendCreateRegionMessage(999, 999, 9000, 9001);
SendCreateRegionMessage(1000, 999, 9000, 9001);
SendCreateRegionMessage(1001, 999, 9000, 9001);
SendCreateRegionMessage(1002, 999, 9000, 9001);
//middle row
SendCreateRegionMessage(998, 1000, 9000, 9001);
SendCreateRegionMessage(999, 1000, 9000, 9001);
SendCreateRegionMessage(1001, 1000, 9000, 9001);
SendCreateRegionMessage(1002, 1000, 9000, 9001);
//an extra to try to trip up the limiter
SendCreateRegionMessage(1003, 1000, 9000, 9001);
//second to last row
SendCreateRegionMessage(998, 1001, 9000, 9001);
SendCreateRegionMessage(999, 1001, 9000, 9001);
SendCreateRegionMessage(1000, 1001, 9000, 9001);
SendCreateRegionMessage(1001, 1001, 9000, 9001);
SendCreateRegionMessage(1002, 1001, 9000, 9001);
//last row
SendCreateRegionMessage(998, 1002, 9000, 9001);
SendCreateRegionMessage(999, 1002, 9000, 9001);
SendCreateRegionMessage(1000, 1002, 9000, 9001);
SendCreateRegionMessage(1001, 1002, 9000, 9001);
SendCreateRegionMessage(1002, 1002, 9000, 9001);
//top row
Assert.NotNull(srm.GetKnownNeighborAt(998, 998));
Assert.NotNull(srm.GetKnownNeighborAt(999, 998));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 998));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 998));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 998));
//second row
Assert.NotNull(srm.GetKnownNeighborAt(998, 999));
Assert.NotNull(srm.GetKnownNeighborAt(999, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 999));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 999));
//middle row
Assert.NotNull(srm.GetKnownNeighborAt(998, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1000));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 1000));
//second to last row
Assert.NotNull(srm.GetKnownNeighborAt(998, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1001));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 1001));
//last row
Assert.NotNull(srm.GetKnownNeighborAt(998, 1002));
Assert.NotNull(srm.GetKnownNeighborAt(999, 1002));
Assert.NotNull(srm.GetKnownNeighborAt(1000, 1002));
Assert.NotNull(srm.GetKnownNeighborAt(1001, 1002));
Assert.NotNull(srm.GetKnownNeighborAt(1002, 1002));
//try a surrounding query
Assert.AreEqual(8, srm.GetKnownNeighborsWithinClientDD(1, 2).Count);
Assert.AreEqual(8, srm.GetKnownNeighborsWithinClientDD(256, 2).Count);
Assert.AreEqual(24, srm.GetKnownNeighborsWithinClientDD(257, 2).Count);
Assert.AreEqual(24, srm.GetKnownNeighborsWithinClientDD(512, 2).Count);
Assert.AreEqual(24, srm.GetKnownNeighborsWithinClientDD(1024, 2).Count);
}
}
}
| |
// 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;
/// <summary>
/// System.Array.Sort(System.Array,System.Array,System.Collections.IComparer)
/// </summary>
public class ArrayIndexOf1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array using default comparer ");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
"Tom",
"Allin"};
int[] i1 = new int[6] { 24, 30, 28, 26, 32, 23 };
string[] s2 = new string[6]{"Allin",
"Jack",
"Mary",
"Mike",
"Peter",
"Tom"};
int[] i2 = new int[6] { 23, 24, 30, 28, 26, 32 };
Array.Sort(s1, i1, null);
for (int i = 0; i < 6; i++)
{
if (s1[i] != s2[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("002", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using comparer ");
try
{
int length = TestLibrary.Generator.GetByte(-55);
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetInt32(-55);
i1[i] = value;
i2[i] = value;
}
IComparer a1 = new A();
Array.Sort(i1, i2, a1);
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("004", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using reverse comparer ");
try
{
char[] c1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10] { 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a' };
char[] d1 = new char[10];
char[] d2 = new char[10];
c1.CopyTo(d2, 0);
c2.CopyTo(d1, 0);
IComparer b = new B();
Array.Sort(c1, c2, b);
for (int i = 0; i < 10; i++)
{
if (c1[i] != d1[i])
{
TestLibrary.TestFramework.LogError("006", "The result is not the value as expected");
retVal = false;
}
if (c2[i] != d2[i])
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Sort a customized array ");
try
{
C c1 = new C(100);
C c2 = new C(16);
C c3 = new C(11);
C c4 = new C(9);
C c5 = new C(7);
C c6 = new C(2);
int[] i1 = new int[6] { 1, 2, 3, 4, 5, 6 };
int[] i2 = new int[6] { 6, 5, 4, 3, 2, 1 };
Array myarray = Array.CreateInstance(typeof(C), 6);
myarray.SetValue(c1, 0);
myarray.SetValue(c2, 1);
myarray.SetValue(c3, 2);
myarray.SetValue(c4, 3);
myarray.SetValue(c5, 4);
myarray.SetValue(c6, 5);
Array.Sort(myarray, i1, (IComparer)myarray.GetValue(0));
for (int i = 0; i < 6; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The first argument is null reference ");
try
{
string[] s1 = null;
int[] i1 = { 1, 2, 3, 4, 5 };
Array.Sort(s1, i1, null);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The keys array is not one dimension ");
try
{
int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } };
int[] i2 = { 1, 2, 3, 4, 5 };
Array.Sort(i1, i2, null);
TestLibrary.TestFramework.LogError("103", "The RankException is not throw as expected ");
retVal = false;
}
catch (RankException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The items array is not one dimension ");
try
{
int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } };
int[] i2 = { 1, 2, 3, 4, 5 };
Array.Sort(i2, i1, null);
TestLibrary.TestFramework.LogError("105", "The RankException is not throw as expected ");
retVal = false;
}
catch (RankException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: The length of items array is not equal to the length of keys array");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
"Tom",
"Allin"};
int[] i1 = new int[5] { 24, 30, 28, 26, 32 };
Array.Sort(s1, i1, null);
TestLibrary.TestFramework.LogError("107", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: The Icomparer is null and keys array does not implement the IComparer interface ");
try
{
D d1 = new D();
D d2 = new D();
D d3 = new D();
D d4 = new D();
int[] i2 = { 1, 2, 3, 4 };
D[] d = new D[4] { d1, d2, d3, d4 };
Array.Sort(d, i2, null);
TestLibrary.TestFramework.LogError("109", "The InvalidOperationException is not throw as expected ");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArrayIndexOf1 test = new ArrayIndexOf1();
TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
class A : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return ((int)x).CompareTo((int)y);
}
#endregion
}
class B : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
if (((char)x).CompareTo((char)y) > 0)
return -1;
else
{
if (x == y)
{
return 0;
}
else
{
return 1;
}
}
}
#endregion
}
class C : IComparer
{
protected int c_value;
public C(int a)
{
this.c_value = a;
}
#region IComparer Members
public int Compare(object x, object y)
{
return (x as C).c_value.CompareTo((y as C).c_value);
}
#endregion
}
class D : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return 0;
}
#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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Asn1;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Tests.Asn1
{
public sealed class ReadBitString : Asn1ReaderTests
{
[Theory]
[InlineData("Uncleared unused bit", PublicEncodingRules.BER, "030201FF")]
[InlineData("Constructed Payload", PublicEncodingRules.BER, "2302030100")]
[InlineData("Constructed Payload-Indefinite", PublicEncodingRules.BER, "238003010000")]
// This value is actually invalid CER, but it returns false since it's not primitive and
// it isn't worth preempting the descent to find out it was invalid.
[InlineData("Constructed Payload-Indefinite", PublicEncodingRules.CER, "238003010000")]
public static void TryGetBitStringBytes_Fails(
string description,
PublicEncodingRules ruleSet,
string inputHex)
{
_ = description;
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
bool didRead = reader.TryReadPrimitiveBitStringValue(
out int unusedBitCount,
out ReadOnlyMemory<byte> contents);
Assert.False(didRead, "reader.TryReadBitStringBytes");
Assert.Equal(0, unusedBitCount);
Assert.Equal(0, contents.Length);
}
[Theory]
[InlineData(PublicEncodingRules.BER, 0, 0, "030100")]
[InlineData(PublicEncodingRules.BER, 1, 1, "030201FE")]
[InlineData(PublicEncodingRules.CER, 2, 4, "030502FEEFF00C")]
[InlineData(PublicEncodingRules.DER, 7, 1, "03020780")]
[InlineData(PublicEncodingRules.DER, 0, 4, "030500FEEFF00D" + "0500")]
public static void TryGetBitStringBytes_Success(
PublicEncodingRules ruleSet,
int expectedUnusedBitCount,
int expectedLength,
string inputHex)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
bool didRead = reader.TryReadPrimitiveBitStringValue(
out int unusedBitCount,
out ReadOnlyMemory<byte> contents);
Assert.True(didRead, "reader.TryReadBitStringBytes");
Assert.Equal(expectedUnusedBitCount, unusedBitCount);
Assert.Equal(expectedLength, contents.Length);
}
[Theory]
[InlineData("Wrong Tag", PublicEncodingRules.BER, "0500")]
[InlineData("Wrong Tag", PublicEncodingRules.CER, "0500")]
[InlineData("Wrong Tag", PublicEncodingRules.DER, "0500")]
[InlineData("Zero Length", PublicEncodingRules.BER, "0300")]
[InlineData("Zero Length", PublicEncodingRules.CER, "0300")]
[InlineData("Zero Length", PublicEncodingRules.DER, "0300")]
[InlineData("Bad Length", PublicEncodingRules.BER, "030200")]
[InlineData("Bad Length", PublicEncodingRules.CER, "030200")]
[InlineData("Bad Length", PublicEncodingRules.DER, "030200")]
[InlineData("Constructed Form", PublicEncodingRules.DER, "2303030100")]
public static void TryGetBitStringBytes_Throws(
string description,
PublicEncodingRules ruleSet,
string inputHex)
{
_ = description;
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
Assert.Throws<CryptographicException>(
() =>
{
reader.TryReadPrimitiveBitStringValue(
out int unusedBitCount,
out ReadOnlyMemory<byte> contents);
});
}
[Fact]
public static void TryGetBitStringBytes_Throws_CER_TooLong()
{
// CER says that the maximum encoding length for a BitString primitive is
// 1000 (999 value bytes and 1 unused bit count byte).
//
// So we need 03 [1001] { 1001 0x00s }
// 1001 => 0x3E9, so the length encoding is 82 03 E9.
// 1001 + 3 + 1 == 1005
byte[] input = new byte[1005];
input[0] = 0x03;
input[1] = 0x82;
input[2] = 0x03;
input[3] = 0xE9;
AsnReader reader = new AsnReader(input, AsnEncodingRules.CER);
Assert.Throws<CryptographicException>(
() =>
{
reader.TryReadPrimitiveBitStringValue(
out int unusedBitCount,
out ReadOnlyMemory<byte> contents);
});
}
[Fact]
public static void TryGetBitStringBytes_Success_CER_MaxLength()
{
// CER says that the maximum encoding length for a BitString primitive is
// 1000 (999 value bytes and 1 unused bit count byte).
//
// So we need 03 [1000] [0x00-0x07] { 998 anythings } [a byte that's legal for the bitmask]
// 1000 => 0x3E8, so the length encoding is 82 03 E8.
// 1000 + 3 + 1 == 1004
byte[] input = new byte[1004];
input[0] = 0x03;
input[1] = 0x82;
input[2] = 0x03;
input[3] = 0xE8;
// Unused bits
input[4] = 0x02;
// Payload
input[5] = 0xA0;
input[1002] = 0xA5;
input[1003] = 0xFC;
AsnReader reader = new AsnReader(input, AsnEncodingRules.CER);
bool success = reader.TryReadPrimitiveBitStringValue(
out int unusedBitCount,
out ReadOnlyMemory<byte> contents);
Assert.True(success, "reader.TryReadBitStringBytes");
Assert.Equal(input[4], unusedBitCount);
Assert.Equal(999, contents.Length);
// Check that it is, in fact, the same memory. No copies with this API.
Assert.True(
Unsafe.AreSame(
ref MemoryMarshal.GetReference(contents.Span),
ref input[5]));
}
[Theory]
[InlineData(PublicEncodingRules.BER, "03020780")]
[InlineData(PublicEncodingRules.BER, "030207FF")]
[InlineData(PublicEncodingRules.CER, "03020780")]
[InlineData(PublicEncodingRules.DER, "03020780")]
[InlineData(
PublicEncodingRules.BER,
"2380" +
"2380" +
"0000" +
"03020000" +
"0000")]
public static void TryCopyBitStringBytes_Fails(PublicEncodingRules ruleSet, string inputHex)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
bool didRead = reader.TryCopyBitStringBytes(
Span<byte>.Empty,
out int unusedBitCount,
out int bytesWritten);
Assert.False(didRead, "reader.TryCopyBitStringBytes");
Assert.Equal(0, unusedBitCount);
Assert.Equal(0, bytesWritten);
}
[Theory]
[InlineData(PublicEncodingRules.BER, "03020780", "80", 7)]
[InlineData(PublicEncodingRules.BER, "030207FF", "80", 7)]
[InlineData(PublicEncodingRules.CER, "03020780", "80", 7)]
[InlineData(PublicEncodingRules.DER, "03020680", "80", 6)]
[InlineData(PublicEncodingRules.BER, "23800000", "", 0)]
[InlineData(PublicEncodingRules.BER, "2300", "", 0)]
[InlineData(PublicEncodingRules.BER, "2300" + "0500", "", 0)]
[InlineData(PublicEncodingRules.BER, "0303010203" + "0500", "0202", 1)]
[InlineData(
PublicEncodingRules.BER,
"2380" +
"2380" +
"0000" +
"03020000" +
"0000",
"00",
0)]
[InlineData(
PublicEncodingRules.BER,
"230C" +
"2380" +
"2380" +
"0000" +
"03020000" +
"0000",
"00",
0)]
[InlineData(
PublicEncodingRules.BER,
"2380" +
"2308" +
"030200FA" +
"030200CE" +
"2380" +
"2380" +
"2380" +
"030300F00D" +
"0000" +
"0000" +
"03020001" +
"0000" +
"0303000203" +
"030203FF" +
"2380" +
"0000" +
"0000",
"FACEF00D010203F8",
3)]
public static void TryCopyBitStringBytes_Success(
PublicEncodingRules ruleSet,
string inputHex,
string expectedHex,
int expectedUnusedBitCount)
{
byte[] inputData = inputHex.HexToByteArray();
byte[] output = new byte[expectedHex.Length / 2];
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
bool didRead = reader.TryCopyBitStringBytes(
output,
out int unusedBitCount,
out int bytesWritten);
Assert.True(didRead, "reader.TryCopyBitStringBytes");
Assert.Equal(expectedUnusedBitCount, unusedBitCount);
Assert.Equal(expectedHex, output.AsSpan(0, bytesWritten).ByteArrayToHex());
}
private static void TryCopyBitStringBytes_Throws(
PublicEncodingRules ruleSet,
byte[] input)
{
AsnReader reader = new AsnReader(input, (AsnEncodingRules)ruleSet);
Assert.Throws<CryptographicException>(
() =>
{
reader.TryCopyBitStringBytes(
Span<byte>.Empty,
out int unusedBitCount,
out int bytesWritten);
});
}
[Theory]
[InlineData("Wrong Tag", PublicEncodingRules.BER, "0500")]
[InlineData("Wrong Tag", PublicEncodingRules.CER, "0500")]
[InlineData("Wrong Tag", PublicEncodingRules.DER, "0500")]
[InlineData("Zero Length", PublicEncodingRules.BER, "0300")]
[InlineData("Zero Length", PublicEncodingRules.CER, "0300")]
[InlineData("Zero Length", PublicEncodingRules.DER, "0300")]
[InlineData("Bad Length", PublicEncodingRules.BER, "030200")]
[InlineData("Bad Length", PublicEncodingRules.CER, "030200")]
[InlineData("Bad Length", PublicEncodingRules.DER, "030200")]
[InlineData("Constructed Form", PublicEncodingRules.DER, "2303030100")]
[InlineData("Bad unused bits", PublicEncodingRules.BER, "03020800")]
[InlineData("Bad unused bits", PublicEncodingRules.CER, "03020800")]
[InlineData("Bad unused bits", PublicEncodingRules.DER, "03020800")]
[InlineData("Bad unused bits-nodata", PublicEncodingRules.BER, "030101")]
[InlineData("Bad unused bits-nodata", PublicEncodingRules.CER, "030101")]
[InlineData("Bad unused bits-nodata", PublicEncodingRules.DER, "030101")]
[InlineData("Bad nested unused bits", PublicEncodingRules.BER, "230403020800")]
[InlineData("Bad nested unused bits-indef", PublicEncodingRules.BER, "2380030208000000")]
[InlineData("Bad nested unused bits-indef", PublicEncodingRules.CER, "2380030208000000")]
[InlineData("Bad nested unused bits-nodata", PublicEncodingRules.BER, "2303030101")]
[InlineData("Bad nested unused bits-nodata-indef", PublicEncodingRules.BER, "23800301010000")]
[InlineData("Bad nested unused bits-nodata-indef", PublicEncodingRules.CER, "23800301010000")]
[InlineData("Bad mask", PublicEncodingRules.CER, "030201FF")]
[InlineData("Bad mask", PublicEncodingRules.DER, "030201FF")]
[InlineData("Bad nested mask", PublicEncodingRules.CER, "2380030201FF0000")]
[InlineData("Nested context-specific", PublicEncodingRules.BER, "2304800300FACE")]
[InlineData("Nested context-specific (indef)", PublicEncodingRules.BER, "2380800300FACE0000")]
[InlineData("Nested context-specific (indef)", PublicEncodingRules.CER, "2380800300FACE0000")]
[InlineData("Nested boolean", PublicEncodingRules.BER, "2303010100")]
[InlineData("Nested boolean (indef)", PublicEncodingRules.BER, "23800101000000")]
[InlineData("Nested boolean (indef)", PublicEncodingRules.CER, "23800101000000")]
[InlineData("Nested constructed form", PublicEncodingRules.CER, "2380" + "2380" + "03010" + "000000000")]
[InlineData("No terminator", PublicEncodingRules.BER, "2380" + "03020000" + "")]
[InlineData("No terminator", PublicEncodingRules.CER, "2380" + "03020000" + "")]
[InlineData("No content", PublicEncodingRules.BER, "2380")]
[InlineData("No content", PublicEncodingRules.CER, "2380")]
[InlineData("No nested content", PublicEncodingRules.CER, "23800000")]
[InlineData("Nested value too long", PublicEncodingRules.BER, "2380030A00")]
[InlineData("Nested value too long - constructed", PublicEncodingRules.BER, "2380230A00")]
[InlineData("Nested value too long - simple", PublicEncodingRules.BER, "2303" + "03050000000000")]
[InlineData(
"Unused bits in intermediate segment",
PublicEncodingRules.BER,
"2380" +
"0303000102" +
"0303020304" +
"0303010506" +
"0000")]
[InlineData("Constructed EndOfContents", PublicEncodingRules.BER, "238020000000")]
[InlineData("Constructed EndOfContents", PublicEncodingRules.CER, "238020000000")]
[InlineData("NonEmpty EndOfContents", PublicEncodingRules.BER, "2380000100")]
[InlineData("NonEmpty EndOfContents", PublicEncodingRules.CER, "2380000100")]
[InlineData("LongLength EndOfContents", PublicEncodingRules.BER, "2380008100")]
[InlineData("Constructed Payload-TooShort", PublicEncodingRules.CER, "23800301000000")]
public static void TryCopyBitStringBytes_Throws(
string description,
PublicEncodingRules ruleSet,
string inputHex)
{
_ = description;
byte[] inputData = inputHex.HexToByteArray();
TryCopyBitStringBytes_Throws(ruleSet, inputData);
}
[Fact]
public static void TryCopyBitStringBytes_Throws_CER_TooLong()
{
// CER says that the maximum encoding length for a BitString primitive is
// 1000 (999 value bytes and 1 unused bit count byte).
//
// So we need 03 [1001] { 1001 0x00s }
// 1001 => 0x3E9, so the length encoding is 82 03 E9.
// 1001 + 3 + 1 == 1004
byte[] input = new byte[1004];
input[0] = 0x03;
input[1] = 0x82;
input[2] = 0x03;
input[3] = 0xE9;
TryCopyBitStringBytes_Throws(PublicEncodingRules.CER, input);
}
[Fact]
public static void TryCopyBitStringBytes_Throws_CER_NestedTooLong()
{
// CER says that the maximum encoding length for a BitString primitive is
// 1000 (999 value bytes and 1 unused bit count byte).
//
// This test checks it for a primitive contained within a constructed.
//
// So we need 03 [1001] { 1001 0x00s }
// 1001 => 0x3E9, so the length encoding is 82 03 E9.
// 1001 + 3 + 1 == 1005
//
// Plus a leading 23 80 (indefinite length constructed)
// and a trailing 00 00 (End of contents)
// == 1009
byte[] input = new byte[1009];
// CONSTRUCTED BIT STRING (indefinite)
input[0] = 0x23;
input[1] = 0x80;
// BIT STRING (1001)
input[2] = 0x03;
input[3] = 0x82;
input[4] = 0x03;
input[5] = 0xE9;
// EOC implicit since the byte[] initializes to zeros
TryCopyBitStringBytes_Throws(PublicEncodingRules.CER, input);
}
[Fact]
public static void TryCopyBitStringBytes_Throws_CER_NestedTooShortIntermediate()
{
// CER says that the maximum encoding length for a BitString primitive is
// 1000 (999 value bytes and 1 unused bit count byte), and in the constructed
// form the lengths must be
// [ 1000, 1000, 1000, ..., len%1000 ]
//
// So 1000, 2, 2 is illegal.
//
// 23 80 (indefinite constructed bit string)
// 03 82 03 08 (bit string, 1000 bytes)
// [1000 content bytes]
// 03 02 (bit string, 2 bytes)
// [2 content bytes]
// 03 02 (bit string, 2 bytes)
// [2 content bytes]
// 00 00 (end of contents)
// Looks like 1,016 bytes.
byte[] input = new byte[1016];
// CONSTRUCTED BIT STRING (indefinite)
input[0] = 0x23;
input[1] = 0x80;
// BIT STRING (1000)
input[2] = 0x03;
input[3] = 0x82;
input[4] = 0x03;
input[5] = 0xE8;
// BIT STRING (2)
input[1006] = 0x03;
input[1007] = 0x02;
// BIT STRING (2)
input[1010] = 0x03;
input[1011] = 0x02;
// EOC implicit since the byte[] initializes to zeros
TryCopyBitStringBytes_Throws(PublicEncodingRules.CER, input);
}
[Fact]
public static void TryCopyBitStringBytes_Success_CER_MaxPrimitiveLength()
{
// CER says that the maximum encoding length for a BitString primitive is
// 1000 (999 value bytes and 1 unused bit count byte).
//
// So we need 03 [1000] [0x00-0x07] { 998 anythings } [a byte that's legal for the bitmask]
// 1000 => 0x3E8, so the length encoding is 82 03 E8.
// 1000 + 3 + 1 == 1003
byte[] input = new byte[1004];
input[0] = 0x03;
input[1] = 0x82;
input[2] = 0x03;
input[3] = 0xE8;
// Unused bits
input[4] = 0x02;
// Payload
input[5] = 0xA0;
input[1002] = 0xA5;
input[1003] = 0xFC;
byte[] output = new byte[999];
AsnReader reader = new AsnReader(input, AsnEncodingRules.CER);
bool success = reader.TryCopyBitStringBytes(
output,
out int unusedBitCount,
out int bytesWritten);
Assert.True(success, "reader.TryCopyBitStringBytes");
Assert.Equal(input[4], unusedBitCount);
Assert.Equal(999, bytesWritten);
Assert.Equal(
input.AsSpan(5).ByteArrayToHex(),
output.ByteArrayToHex());
}
[Fact]
public static void TryCopyBitStringBytes_Success_CER_MinConstructedLength()
{
// CER says that the maximum encoding length for a BitString primitive is
// 1000 (999 value bytes and 1 unused bit count byte), and that a constructed
// form must be used for values greater than 1000 bytes, with segments dividing
// up for each thousand [1000, 1000, ..., len%1000].
//
// Bit string primitives are one byte of "unused bits" and the rest are payload,
// so the minimum constructed payload has total content length 1002:
// [1000 (1+999), 2 (1+1)]
//
// 23 80 (indefinite constructed bit string)
// 03 82 03 E9 (primitive bit string, 1000 bytes)
// 00 [999 more payload bytes]
// 03 02 (primitive bit string, 2 bytes)
// uu pp
// 00 00 (end of contents, 0 bytes)
// 1010 total.
byte[] input = new byte[1012];
int offset = 0;
// CONSTRUCTED BIT STRING (Indefinite)
input[offset++] = 0x23;
input[offset++] = 0x80;
// BIT STRING (1000)
input[offset++] = 0x03;
input[offset++] = 0x82;
input[offset++] = 0x03;
input[offset++] = 0xE8;
// Primitive 1: Unused bits MUST be 0.
input[offset++] = 0x00;
// Payload (A0 :: A5 FC) (999)
input[offset] = 0xA0;
offset += 997;
input[offset++] = 0xA5;
input[offset++] = 0xFC;
// BIT STRING (2)
input[offset++] = 0x03;
input[offset++] = 0x02;
// Primitive 2: Unused bits 0-7
input[offset++] = 0x3;
// Payload (must have the three least significant bits unset)
input[offset] = 0b0000_1000;
byte[] expected = new byte[1000];
offset = 0;
expected[offset] = 0xA0;
offset += 997;
expected[offset++] = 0xA5;
expected[offset++] = 0xFC;
expected[offset] = 0b0000_1000;
byte[] output = new byte[1000];
AsnReader reader = new AsnReader(input, AsnEncodingRules.CER);
bool success = reader.TryCopyBitStringBytes(
output,
out int unusedBitCount,
out int bytesWritten);
Assert.True(success, "reader.TryCopyBitStringBytes");
Assert.Equal(input[1006], unusedBitCount);
Assert.Equal(1000, bytesWritten);
Assert.Equal(
expected.ByteArrayToHex(),
output.ByteArrayToHex());
}
[Theory]
[InlineData(PublicEncodingRules.BER)]
[InlineData(PublicEncodingRules.CER)]
[InlineData(PublicEncodingRules.DER)]
public static void TagMustBeCorrect_Universal(PublicEncodingRules ruleSet)
{
byte[] inputData = { 3, 2, 1, 0x7E };
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
AssertExtensions.Throws<ArgumentException>(
"expectedTag",
() => reader.TryReadPrimitiveBitStringValue(Asn1Tag.Null, out _, out _));
Assert.True(reader.HasData, "HasData after bad universal tag");
Assert.Throws<CryptographicException>(
() => reader.TryReadPrimitiveBitStringValue(new Asn1Tag(TagClass.ContextSpecific, 0), out _, out _));
Assert.True(reader.HasData, "HasData after wrong tag");
Assert.True(reader.TryReadPrimitiveBitStringValue(out int unusedBitCount, out ReadOnlyMemory<byte> contents));
Assert.Equal("7E", contents.ByteArrayToHex());
Assert.Equal(1, unusedBitCount);
Assert.False(reader.HasData, "HasData after read");
}
[Theory]
[InlineData(PublicEncodingRules.BER)]
[InlineData(PublicEncodingRules.CER)]
[InlineData(PublicEncodingRules.DER)]
public static void TagMustBeCorrect_Custom(PublicEncodingRules ruleSet)
{
byte[] inputData = { 0x87, 2, 0, 0x80 };
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
AssertExtensions.Throws<ArgumentException>(
"expectedTag",
() => reader.TryReadPrimitiveBitStringValue(Asn1Tag.Null, out _, out _));
Assert.True(reader.HasData, "HasData after bad universal tag");
Assert.Throws<CryptographicException>(() => reader.TryReadPrimitiveBitStringValue(out _, out _));
Assert.True(reader.HasData, "HasData after default tag");
Assert.Throws<CryptographicException>(
() => reader.TryReadPrimitiveBitStringValue(new Asn1Tag(TagClass.Application, 0), out _, out _));
Assert.True(reader.HasData, "HasData after wrong custom class");
Assert.Throws<CryptographicException>(
() => reader.TryReadPrimitiveBitStringValue(new Asn1Tag(TagClass.ContextSpecific, 1), out _, out _));
Assert.True(reader.HasData, "HasData after wrong custom tag value");
Assert.True(
reader.TryReadPrimitiveBitStringValue(
new Asn1Tag(TagClass.ContextSpecific, 7),
out int unusedBitCount,
out ReadOnlyMemory<byte> contents));
Assert.Equal("80", contents.ByteArrayToHex());
Assert.Equal(0, unusedBitCount);
Assert.False(reader.HasData, "HasData after reading value");
}
[Theory]
[InlineData(PublicEncodingRules.BER, "030400010203", PublicTagClass.Universal, 3)]
[InlineData(PublicEncodingRules.CER, "030400010203", PublicTagClass.Universal, 3)]
[InlineData(PublicEncodingRules.DER, "030400010203", PublicTagClass.Universal, 3)]
[InlineData(PublicEncodingRules.BER, "800200FF", PublicTagClass.ContextSpecific, 0)]
[InlineData(PublicEncodingRules.CER, "4C0200FF", PublicTagClass.Application, 12)]
[InlineData(PublicEncodingRules.DER, "DF8A460200FF", PublicTagClass.Private, 1350)]
public static void ExpectedTag_IgnoresConstructed(
PublicEncodingRules ruleSet,
string inputHex,
PublicTagClass tagClass,
int tagValue)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
Assert.True(
reader.TryReadPrimitiveBitStringValue(
new Asn1Tag((TagClass)tagClass, tagValue, true),
out int ubc1,
out ReadOnlyMemory<byte> val1));
Assert.False(reader.HasData);
reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
Assert.True(
reader.TryReadPrimitiveBitStringValue(
new Asn1Tag((TagClass)tagClass, tagValue, false),
out int ubc2,
out ReadOnlyMemory<byte> val2));
Assert.False(reader.HasData);
Assert.Equal(val1.ByteArrayToHex(), val2.ByteArrayToHex());
Assert.Equal(ubc1, ubc2);
}
[Fact]
public static void TryCopyBitStringBytes_ExtremelyNested()
{
byte[] dataBytes = new byte[4 * 16384];
// This will build 2^14 nested indefinite length values.
// In the end, none of them contain any content.
//
// For what it's worth, the initial algorithm succeeded at 1017, and StackOverflowed with 1018.
int end = dataBytes.Length / 2;
// UNIVERSAL BIT STRING [Constructed]
const byte Tag = 0x20 | (byte)UniversalTagNumber.BitString;
for (int i = 0; i < end; i += 2)
{
dataBytes[i] = Tag;
// Indefinite length
dataBytes[i + 1] = 0x80;
}
AsnReader reader = new AsnReader(dataBytes, AsnEncodingRules.BER);
int bytesWritten;
int unusedBitCount;
Assert.True(
reader.TryCopyBitStringBytes(Span<byte>.Empty, out unusedBitCount, out bytesWritten));
Assert.Equal(0, bytesWritten);
Assert.Equal(0, unusedBitCount);
}
}
}
| |
// 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation
{
public class SmartTokenFormatterFormatTokenTests : FormatterTestsBase
{
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmptyFile1()
{
var code = @"{";
await ExpectException_SmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 0,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmptyFile2()
{
var code = @"}";
await ExpectException_SmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 0,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace1()
{
var code = @"namespace NS
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 1,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace2()
{
var code = @"namespace NS
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 1,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace3()
{
var code = @"namespace NS
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 2,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class1()
{
var code = @"namespace NS
{
class Class
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 3,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class2()
{
var code = @"namespace NS
{
class Class
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 3,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class3()
{
var code = @"namespace NS
{
class Class
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 4,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method2()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Property1()
{
var code = @"namespace NS
{
class Class
{
int Foo
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Property2()
{
var code = @"namespace NS
{
class Class
{
int Foo
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Event1()
{
var code = @"namespace NS
{
class Class
{
event EventHandler Foo
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Event2()
{
var code = @"namespace NS
{
class Class
{
event EventHandler Foo
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Indexer1()
{
var code = @"namespace NS
{
class Class
{
int this[int index]
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Indexer2()
{
var code = @"namespace NS
{
class Class
{
int this[int index]
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 6,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block2()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
}
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 7,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block4()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 7,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new [] {
}";
var expected = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new [] {
}";
await AssertSmartTokenFormatterOpenBraceAsync(
expected,
code,
indentationLine: 6);
}
[Fact]
[WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
int[,] arr =
{
{1,1}, {2,2}
}
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 9,
expectedSpace: 12);
}
[Fact]
[WorkItem(543142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543142")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EnterWithTrailingWhitespace()
{
var code = @"class Class
{
void Method(int i)
{
var a = new {
};
";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[WorkItem(9216, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task OpenBraceWithBaseIndentation()
{
var markup = @"
class C
{
void M()
{
[|#line ""Default.aspx"", 273
if (true)
$${
}
#line default
#line hidden|]
}
}";
await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation: 7, expectedIndentation: 11);
}
[WorkItem(9216, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void CloseBraceWithBaseIndentation()
{
var markup = @"
class C
{
void M()
{
[|#line ""Default.aspx"", 273
if (true)
{
$$}
#line default
#line hidden|]
}
}";
AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation: 7, expectedIndentation: 11);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestPreprocessor()
{
var code = @"
class C
{
void M()
{
#
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: '#');
Assert.Equal(0, actualIndentation);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestRegion()
{
var code = @"
class C
{
void M()
{
#region
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n');
Assert.Equal(8, actualIndentation);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestEndRegion()
{
var code = @"
class C
{
void M()
{
#region
#endregion
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n');
Assert.Equal(8, actualIndentation);
}
[WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestSelect()
{
var code = @"
using System;
using System.Linq;
class Program
{
static IEnumerable<int> Foo()
{
return from a in new[] { 1, 2, 3 }
select
}
}
";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 't');
Assert.Equal(15, actualIndentation);
}
[WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestWhere()
{
var code = @"
using System;
using System.Linq;
class Program
{
static IEnumerable<int> Foo()
{
return from a in new[] { 1, 2, 3 }
where
}
}
";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 'e');
Assert.Equal(15, actualIndentation);
}
private Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation)
{
string code;
int position;
TextSpan span;
MarkupTestFile.GetPositionAndSpan(markup, out code, out position, out span);
return AssertSmartTokenFormatterOpenBraceAsync(
code,
SourceText.From(code).Lines.IndexOf(position),
expectedIndentation,
baseIndentation,
span);
}
private async Task AssertSmartTokenFormatterOpenBraceAsync(
string code,
int indentationLine,
int expectedSpace,
int? baseIndentation = null,
TextSpan span = default(TextSpan))
{
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '{', baseIndentation, span);
Assert.Equal(expectedSpace, actualIndentation);
}
private async Task AssertSmartTokenFormatterOpenBraceAsync(
string expected,
string code,
int indentationLine)
{
// create tree service
using (var workspace = await TestWorkspace.CreateCSharpAsync(code))
{
var buffer = workspace.Documents.First().GetTextBuffer();
var actual = await TokenFormatAsync(workspace, buffer, indentationLine, '{');
Assert.Equal(expected, actual);
}
}
private Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation)
{
string code;
int position;
TextSpan span;
MarkupTestFile.GetPositionAndSpan(markup, out code, out position, out span);
return AssertSmartTokenFormatterCloseBraceAsync(
code,
SourceText.From(code).Lines.IndexOf(position),
expectedIndentation,
baseIndentation,
span);
}
private async Task AssertSmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
int expectedSpace,
int? baseIndentation = null,
TextSpan span = default(TextSpan))
{
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', baseIndentation, span);
Assert.Equal(expectedSpace, actualIndentation);
}
private async Task ExpectException_SmartTokenFormatterOpenBraceAsync(
string code,
int indentationLine,
int expectedSpace)
{
Assert.NotNull(await Record.ExceptionAsync(async () => await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '{')));
}
private async Task ExpectException_SmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
int expectedSpace)
{
Assert.NotNull(await Record.ExceptionAsync(async () => await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}')));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using CoreFoundation;
using CoreGraphics;
using Foundation;
using Photos;
using PhotosUI;
using UIKit;
namespace SamplePhotoApp
{
public partial class AssetGridViewController : UICollectionViewController, IPHPhotoLibraryChangeObserver
{
const string cellReuseIdentifier = "GridViewCell";
public PHFetchResult FetchResult { get; set; }
public PHAssetCollection AssetCollection { get; set; }
readonly PHCachingImageManager imageManager = new PHCachingImageManager ();
CGSize thumbnailSize;
CGRect previousPreheatRect;
[Export ("initWithCoder:")]
public AssetGridViewController (NSCoder coder)
: base (coder)
{
}
public AssetGridViewController (IntPtr handle)
: base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
ResetCachedAssets ();
PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver (this);
// If we get here without a segue, it's because we're visible at app launch,
// so match the behavior of segue from the default "All Photos" view.
if (FetchResult == null)
{
var allPhotosOptions = new PHFetchOptions
{
SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor ("creationDate", true) }
};
FetchResult = PHAsset.FetchAssets (allPhotosOptions);
}
}
protected override void Dispose (bool disposing)
{
PHPhotoLibrary.SharedPhotoLibrary.UnregisterChangeObserver (this);
base.Dispose (disposing);
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
// Add button to the navigation bar if the asset collection supports adding content.
if (AssetCollection == null || AssetCollection.CanPerformEditOperation (PHCollectionEditOperation.AddContent))
NavigationItem.RightBarButtonItem = AddButtonItem;
else
NavigationItem.RightBarButtonItem = null;
UpdateItemSize ();
}
public override void ViewWillLayoutSubviews ()
{
base.ViewWillLayoutSubviews ();
UpdateItemSize ();
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
UpdateCachedAssets ();
}
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
// Configure the destination AssetViewController.
var assetViewController = segue.DestinationViewController as AssetViewController;
if (assetViewController == null)
throw new InvalidProgramException ("unexpected view controller for segue");
var indexPath = CollectionView.IndexPathForCell ((UICollectionViewCell)sender);
assetViewController.Asset = (PHAsset)FetchResult[indexPath.Item];
assetViewController.AssetCollection = AssetCollection;
}
void UpdateItemSize ()
{
var viewWidth = View.Bounds.Width;
var desiredItemWidth = 100f;
var columns = Math.Max (Math.Floor (viewWidth / desiredItemWidth), 4f);
var padding = 1f;
var itemWidth = Math.Floor ((viewWidth - (columns - 1f) * padding) / columns);
var itemSize = new CGSize (itemWidth, itemWidth);
if (Layout is UICollectionViewFlowLayout layout)
{
layout.ItemSize = itemSize;
layout.MinimumInteritemSpacing = padding;
layout.MinimumLineSpacing = padding;
}
// Determine the size of the thumbnails to request from the PHCachingImageManager
var scale = UIScreen.MainScreen.Scale;
thumbnailSize = new CGSize (itemSize.Width * scale, itemSize.Height * scale);
}
#region UICollectionView
public override nint GetItemsCount (UICollectionView collectionView, nint section)
{
return FetchResult.Count;
}
public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath)
{
var asset = (PHAsset)FetchResult[indexPath.Item];
// Dequeue an GridViewCell.
var cell = (GridViewCell)collectionView.DequeueReusableCell (cellReuseIdentifier, indexPath);
// Add a badge to the cell if the PHAsset represents a Live Photo.
if (asset.MediaSubtypes.HasFlag (PHAssetMediaSubtype.PhotoLive))
cell.LivePhotoBadgeImage = PHLivePhotoView.GetLivePhotoBadgeImage (PHLivePhotoBadgeOptions.OverContent);
// Request an image for the asset from the PHCachingImageManager.
cell.RepresentedAssetIdentifier = asset.LocalIdentifier;
imageManager.RequestImageForAsset (asset, thumbnailSize, PHImageContentMode.AspectFill, null, (image, info) =>
{
// The cell may have been recycled by the time this handler gets called;
// Set the cell's thumbnail image if it's still showing the same asset.
if (cell.RepresentedAssetIdentifier == asset.LocalIdentifier && image != null)
cell.ThumbnailImage = image;
});
return cell;
}
#endregion
#region UIScrollView
#if __TVOS__
[Export ("scrollViewDidScroll:")]
public void Scrolled (UIScrollView scrollView)
#elif __IOS__
public override void Scrolled (UIScrollView scrollView)
#endif
{
UpdateCachedAssets ();
}
#endregion
#region Asset Caching
void ResetCachedAssets ()
{
imageManager.StopCaching ();
previousPreheatRect = CGRect.Empty;
}
void UpdateCachedAssets ()
{
// Update only if the view is visible.
bool isViewVisible = IsViewLoaded && View.Window != null;
if (!isViewVisible)
return;
// The preheat window is twice the height of the visible rect.
var visibleRect = new CGRect (CollectionView.ContentOffset, CollectionView.Bounds.Size);
var preheatRect = visibleRect.Inset (0f, -0.5f * visibleRect.Height);
// Update only if the visible area is significantly different from the last preheated area.
nfloat delta = NMath.Abs (preheatRect.GetMidY () - previousPreheatRect.GetMidY ());
if (delta <= CollectionView.Bounds.Height / 3f)
return;
// Compute the assets to start caching and to stop caching.
var rects = ComputeDifferenceBetweenRect (previousPreheatRect, preheatRect);
var addedAssets = rects.added
.SelectMany (rect => CollectionView.GetIndexPaths (rect))
.Select (indexPath => FetchResult.ObjectAt (indexPath.Item))
.Cast<PHAsset> ()
.ToArray ();
var removedAssets = rects.removed
.SelectMany (rect => CollectionView.GetIndexPaths (rect))
.Select (indexPath => FetchResult.ObjectAt (indexPath.Item))
.Cast<PHAsset> ()
.ToArray ();
// Update the assets the PHCachingImageManager is caching.
imageManager.StartCaching (addedAssets, thumbnailSize, PHImageContentMode.AspectFill, null);
imageManager.StopCaching (removedAssets, thumbnailSize, PHImageContentMode.AspectFill, null);
// Store the preheat rect to compare against in the future.
previousPreheatRect = preheatRect;
}
(IEnumerable<CGRect> added, IEnumerable<CGRect> removed) ComputeDifferenceBetweenRect (CGRect oldRect, CGRect newRect)
{
if (!oldRect.IntersectsWith (newRect))
{
return (new CGRect[] { newRect }, new CGRect[] { oldRect });
}
var oldMaxY = oldRect.GetMaxY ();
var oldMinY = oldRect.GetMinY ();
var newMaxY = newRect.GetMaxY ();
var newMinY = newRect.GetMinY ();
var added = new List<CGRect> ();
var removed = new List<CGRect> ();
if (newMaxY > oldMaxY)
added.Add (new CGRect (newRect.X, oldMaxY, newRect.Width, newMaxY - oldMaxY));
if (oldMinY > newMinY)
added.Add (new CGRect (newRect.X, newMinY, newRect.Width, oldMinY - newMinY));
if (newMaxY < oldMaxY)
removed.Add (new CGRect (newRect.X, newMaxY, newRect.Width, oldMaxY - newMaxY));
if (oldMinY < newMinY)
removed.Add (new CGRect (newRect.X, oldMinY, newRect.Width, newMinY - oldMinY));
return (added, removed);
}
#endregion
#region UI Actions
partial void AddAsset (NSObject sender)
{
var rnd = new Random ();
// Create a random dummy image.
var size = (rnd.Next (0, 2) == 0)
? new CGSize (400f, 300f)
: new CGSize (300f, 400f);
var renderer = new UIGraphicsImageRenderer (size);
var image = renderer.CreateImage (context =>
{
UIColor.FromHSBA ((float)rnd.NextDouble (), 1, 1, 1).SetFill ();
context.FillRect (context.Format.Bounds);
});
// Add it to the photo library
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() =>
{
PHAssetChangeRequest creationRequest = PHAssetChangeRequest.FromImage (image);
if (AssetCollection != null)
{
var addAssetRequest = PHAssetCollectionChangeRequest.ChangeRequest (AssetCollection);
addAssetRequest.AddAssets (new PHObject[] {
creationRequest.PlaceholderForCreatedAsset
});
}
}, (success, error) =>
{
if (!success)
Console.WriteLine (error.LocalizedDescription);
});
}
#endregion
#region IPHPhotoLibraryChangeObserver
public void PhotoLibraryDidChange (PHChange changeInstance)
{
var changes = changeInstance.GetFetchResultChangeDetails (FetchResult);
if (changes == null)
return;
DispatchQueue.MainQueue.DispatchSync (() =>
{
// Hang on to the new fetch result.
FetchResult = changes.FetchResultAfterChanges;
if (changes.HasIncrementalChanges)
{
// If we have incremental diffs, animate them in the collection view.
CollectionView.PerformBatchUpdates (() =>
{
// For indexes to make sense, updates must be in this order:
// delete, insert, reload, move
var removed = changes.RemovedIndexes;
if (removed != null && removed.Count > 0)
CollectionView.DeleteItems (ToNSIndexPaths (removed));
var inserted = changes.InsertedIndexes;
if (inserted != null && inserted.Count > 0)
CollectionView.InsertItems (ToNSIndexPaths (inserted));
var changed = changes.ChangedIndexes;
if (changed != null && changed.Count > 0)
CollectionView.ReloadItems (ToNSIndexPaths (changed));
changes.EnumerateMoves ((fromIndex, toIndex) =>
{
var start = NSIndexPath.FromItemSection ((nint)fromIndex, 0);
var end = NSIndexPath.FromItemSection ((nint)toIndex, 0);
CollectionView.MoveItem (start, end);
});
}, null);
}
else
{
// Reload the collection view if incremental diffs are not available.
CollectionView.ReloadData ();
}
ResetCachedAssets ();
});
}
static NSIndexPath[] ToNSIndexPaths (NSIndexSet indexSet)
{
var cnt = indexSet.Count;
var result = new NSIndexPath[(int)cnt];
int i = 0;
indexSet.EnumerateIndexes ((nuint idx, ref bool stop) =>
{
stop = false;
result[i++] = NSIndexPath.FromItemSection ((nint)idx, 0);
});
return result;
}
#endregion
}
}
| |
//
// PlaylistFileUtil.cs
//
// Authors:
// Trey Ethridge <tale@juno.com>
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
// Ting Z Zhou <ting.z.zhou@intel.com>
//
// Copyright (C) 2007 Trey Ethridge
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2010 Intel Corp
//
// 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.Threading;
using Mono.Unix;
using Hyena;
using Hyena.Data.Sqlite;
using Banshee.Configuration;
using Banshee.ServiceStack;
using Banshee.Database;
using Banshee.Sources;
using Banshee.Playlists.Formats;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Streaming;
namespace Banshee.Playlist
{
public class PlaylistImportCanceledException : ApplicationException
{
public PlaylistImportCanceledException (string message) : base (message)
{
}
public PlaylistImportCanceledException () : base ()
{
}
}
public static class PlaylistFileUtil
{
public static readonly SchemaEntry<string> DefaultExportFormat = new SchemaEntry<string> (
"player_window", "default_export_format",
String.Empty,
"Export Format",
"The default playlist export format"
);
private static PlaylistFormatDescription [] export_formats = new PlaylistFormatDescription [] {
M3uPlaylistFormat.FormatDescription,
PlsPlaylistFormat.FormatDescription,
XspfPlaylistFormat.FormatDescription
};
public static readonly string [] PlaylistExtensions = new string [] {
M3uPlaylistFormat.FormatDescription.FileExtension,
PlsPlaylistFormat.FormatDescription.FileExtension,
XspfPlaylistFormat.FormatDescription.FileExtension
};
public static PlaylistFormatDescription [] ExportFormats {
get { return export_formats; }
}
public static bool IsSourceExportSupported (Source source)
{
bool supported = true;
if (source == null || !(source is AbstractPlaylistSource)) {
supported = false;
}
return supported;
}
public static PlaylistFormatDescription GetDefaultExportFormat ()
{
PlaylistFormatDescription default_format = null;
try {
string exportFormat = DefaultExportFormat.Get ();
PlaylistFormatDescription [] formats = PlaylistFileUtil.ExportFormats;
foreach (PlaylistFormatDescription format in formats) {
if (format.FileExtension.Equals (exportFormat)) {
default_format = format;
break;
}
}
} catch {
// Ignore errors, return our default if we encounter an error.
} finally {
if (default_format == null) {
default_format = M3uPlaylistFormat.FormatDescription;
}
}
return default_format;
}
public static void SetDefaultExportFormat (PlaylistFormatDescription format)
{
try {
DefaultExportFormat.Set (format.FileExtension);
} catch (Exception) {
}
}
public static int GetFormatIndex (PlaylistFormatDescription [] formats, PlaylistFormatDescription playlist)
{
int default_export_index = -1;
foreach (PlaylistFormatDescription format in formats) {
default_export_index++;
if (format.FileExtension.Equals (playlist.FileExtension)) {
break;
}
}
return default_export_index;
}
public static bool PathHasPlaylistExtension (string playlistUri)
{
if (System.IO.Path.HasExtension (playlistUri)) {
string extension = System.IO.Path.GetExtension (playlistUri).ToLower ();
foreach (PlaylistFormatDescription format in PlaylistFileUtil.ExportFormats) {
if (extension.Equals ("." + format.FileExtension)) {
return true;
}
}
}
return false;
}
public static IPlaylistFormat Load (string playlistUri, Uri baseUri, Uri rootPath)
{
PlaylistFormatDescription [] formats = PlaylistFileUtil.ExportFormats;
// If the file has an extenstion, rearrange the format array so that the
// appropriate format is tried first.
if (System.IO.Path.HasExtension (playlistUri)) {
string extension = System.IO.Path.GetExtension (playlistUri);
extension = extension.ToLower ();
int index = -1;
foreach (PlaylistFormatDescription format in formats) {
index++;
if (extension.Equals ("." + format.FileExtension)) {
break;
}
}
if (index != -1 && index != 0 && index < formats.Length) {
// Move to first position in array.
PlaylistFormatDescription preferredFormat = formats[index];
formats[index] = formats[0];
formats[0] = preferredFormat;
}
}
foreach (PlaylistFormatDescription format in formats) {
try {
IPlaylistFormat playlist = (IPlaylistFormat)Activator.CreateInstance (format.Type);
playlist.BaseUri = baseUri;
playlist.RootPath = rootPath;
playlist.Load (Banshee.IO.File.OpenRead (new SafeUri (playlistUri)), true);
return playlist;
} catch (InvalidPlaylistException) {
}
}
return null;
}
public static void ImportPlaylistToLibrary (string path)
{
ImportPlaylistToLibrary (path, null, null);
}
public static void ImportPlaylistToLibrary (string path, PrimarySource source, DatabaseImportManager importer)
{
try {
Log.InformationFormat ("Importing playlist {0} to library", path);
SafeUri uri = new SafeUri (path);
string relative_dir = System.IO.Path.GetDirectoryName (uri.LocalPath);
if (relative_dir[relative_dir.Length - 1] != System.IO.Path.DirectorySeparatorChar) {
relative_dir = relative_dir + System.IO.Path.DirectorySeparatorChar;
}
var parsed_playlist = PlaylistParser.Parse (uri, new Uri (relative_dir));
if (parsed_playlist != null) {
List<string> uris = new List<string> ();
foreach (PlaylistElement element in parsed_playlist.Elements) {
if (element.Uri.IsFile) {
uris.Add (element.Uri.LocalPath);
} else {
Log.InformationFormat ("Ignoring invalid playlist element: {0}", element.Uri.OriginalString);
}
}
if (source == null) {
if (uris.Count > 0) {
// Get the media attribute of the 1st Uri in Playlist
// and then determine whether the playlist belongs to Video or Music
SafeUri uri1 = new SafeUri (uris[0]);
var track = new TrackInfo ();
StreamTagger.TrackInfoMerge (track, uri1);
if (track.HasAttribute (TrackMediaAttributes.VideoStream))
source = ServiceManager.SourceManager.VideoLibrary;
else
source = ServiceManager.SourceManager.MusicLibrary;
}
}
// Give source a fallback value - MusicLibrary when it's null
if (source == null) {
source = ServiceManager.SourceManager.MusicLibrary;
}
// Only import an non-empty playlist
if (uris.Count > 0) {
ImportPlaylistWorker worker = new ImportPlaylistWorker (
parsed_playlist.Title,
uris.ToArray (), source, importer);
worker.Import ();
}
}
} catch (Exception e) {
Log.Error (e);
}
}
}
public class ImportPlaylistWorker
{
private string [] uris;
private string name;
private PrimarySource source;
private DatabaseImportManager importer;
private bool finished;
public ImportPlaylistWorker (string name, string [] uris, PrimarySource source, DatabaseImportManager importer)
{
this.name = name;
this.uris = uris;
this.source = source;
this.importer = importer;
}
public void Import ()
{
try {
if (importer == null) {
importer = new Banshee.Library.LibraryImportManager ();
}
finished = false;
importer.Finished += CreatePlaylist;
importer.Enqueue (uris);
} catch (PlaylistImportCanceledException e) {
Log.Warning (e);
}
}
private void CreatePlaylist (object o, EventArgs args)
{
if (finished) {
return;
}
finished = true;
try {
PlaylistSource playlist = new PlaylistSource (name, source);
playlist.Save ();
source.AddChildSource (playlist);
HyenaSqliteCommand insert_command = new HyenaSqliteCommand (String.Format (
@"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES ({0}, ?)", playlist.DbId));
//ServiceManager.DbConnection.BeginTransaction ();
foreach (string uri in uris) {
// FIXME: Does the following call work if the source is just a PrimarySource (not LibrarySource)?
long track_id = source.GetTrackIdForUri (uri);
if (track_id > 0) {
ServiceManager.DbConnection.Execute (insert_command, track_id);
}
}
playlist.Reload ();
playlist.NotifyUser ();
} catch (Exception e) {
Log.Error (e);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.Reflection;
namespace Falken
{
/// <summary>
/// <c>RotationQuaternion</c> defines the rotation of an object as
/// a quaternion.
/// </summary>
[Serializable]
public sealed class RotationQuaternion
{
/// <summary>
/// X component of the quaternion.
/// </summary>
public float X
{
get
{
return _internalRotation.x;
}
set
{
_internalRotation.x = value;
}
}
/// <summary>
/// Y component of the quaternion.
/// </summary>
public float Y
{
get
{
return _internalRotation.y;
}
set
{
_internalRotation.y = value;
}
}
/// <summary>
/// Z component of the quaternion.
/// </summary>
public float Z
{
get
{
return _internalRotation.z;
}
set
{
_internalRotation.z = value;
}
}
/// <summary>
/// W component of the quaternion.
/// </summary>
public float W
{
get
{
return _internalRotation.w;
}
set
{
_internalRotation.w = value;
}
}
/// <summary>
/// Default constructor. Set every component to 0.0f.
/// </summary>
public RotationQuaternion()
{
_internalRotation = new FalkenInternal.falken.Rotation();
}
/// <summary>
/// Initialize every component to the same value.
/// </summary>
public RotationQuaternion(float initializationValue) : this()
{
X = initializationValue;
Y = initializationValue;
Z = initializationValue;
W = 1.0f;
}
#if UNITY_5_3_OR_NEWER
/// <summary>
/// Initialize the quaternion using a Unity's quaternion.
/// </summary>
public RotationQuaternion(UnityEngine.Quaternion unityQuaternion) : this()
{
X = unityQuaternion.x;
Y = unityQuaternion.y;
Z = unityQuaternion.z;
W = unityQuaternion.w;
}
#endif // UNITY_5_3_OR_NEWER
/// <summary>
/// Construct a Quaternion with the given component values.
/// </summary>
public RotationQuaternion(float newX, float newY, float newZ, float newW) : this()
{
X = newX;
Y = newY;
Z = newZ;
W = newW;
}
/// <summary>
/// Initialize the rotation with the internal Falken rotation class.
/// </summary>
internal RotationQuaternion(FalkenInternal.falken.Rotation rotation) : this()
{
X = rotation.x;
Y = rotation.y;
Z = rotation.z;
W = rotation.w;
}
/// <summary>
/// Modify a falken internal rotation with the instance's attributes.
/// </summary>
/// <returns> Internal Rotation object.</returns>
internal FalkenInternal.falken.Rotation ToInPlaceInternalRotation(
FalkenInternal.falken.Rotation rotation)
{
rotation.x = X;
rotation.y = Y;
rotation.z = Z;
rotation.w = W;
return rotation;
}
/// <summary>
/// Convert to internal rotation.
/// </summary>
/// <returns> Internal Rotation object.</returns>
internal FalkenInternal.falken.Rotation ToInternalRotation()
{
return _internalRotation;
}
#if UNITY_5_3_OR_NEWER
/// <summary>
/// Convert a Falken.RotationQuaternion to a UnityEngine.Quaternion.
/// </summary>
public static implicit operator UnityEngine.Quaternion(
Falken.RotationQuaternion value) =>
new UnityEngine.Quaternion(value.X, value.Y, value.Z, value.W);
/// <summary>
/// Convert a UnityEngine.Quaternion to a Falken.RotationQuaternion.
/// </summary>
public static implicit operator Falken.RotationQuaternion(
UnityEngine.Quaternion value) =>
new Falken.RotationQuaternion(value);
#endif // UNITY_5_3_OR_NEWER
/// <summary>
/// Construct a Quaternion from a direction vector. This vector must be normalized.
/// </summary>
/// <param name="vector"> Vector3 to convet. Values must be normalized.</param>
public static RotationQuaternion FromDirectionVector(Vector3 vector)
{
// Call internal method to generate rotation.
var rotation =
FalkenInternal.falken.Rotation.FromDirectionVector(vector.ToInternalVector3());
return new RotationQuaternion(rotation);
}
/// <summary>
/// Construct a Quaternion from a direction vector. This vector must be normalized.
/// </summary>
/// <param name="x"> X component of the vector.</param>
/// <param name="y"> Y component of the vector.</param>
/// <param name="z"> Z component of the vector.</param>
public static RotationQuaternion FromDirectionVector(float x, float y, float z)
{
// Call internal method to generate rotation.
var rotation =
FalkenInternal.falken.Rotation.FromDirectionVector(x, y, z);
return new RotationQuaternion(rotation);
}
/// <summary>
/// Construct a Quaternion from Euler angles vector. The conversion follows Body 2-1-3
/// sequence convention (rotate Pitch, then Roll and last Yaw). The type of
/// rotation is extrinsic.
/// </summary>
/// <param name="eulerAngles"> EulerAngles to convert.</param>
public static RotationQuaternion FromEulerAngles(EulerAngles eulerAngles)
{
// Call internal method to generate rotation.
var rotation =
FalkenInternal.falken.Rotation.FromEulerAngles(eulerAngles.ToInternalEulerAngles());
return new RotationQuaternion(rotation);
}
/// <summary>
/// Construct a Quaternion from Euler angles. The conversion follows Body 2-1-3
/// sequence convention (rotate Pitch, then Roll and last Yaw). The type of
/// rotation is extrinsic.
/// </summary>
/// <param name="roll"> Roll component of the vector in degrees.</param>
/// <param name="pitch"> Pitch component of the vector in degrees.</param>
/// <param name="yaw"> Yaw component of the vector in degrees.</param>
public static RotationQuaternion FromEulerAngles(float roll, float pitch, float yaw)
{
// Call internal method to generate rotation.
var rotation =
FalkenInternal.falken.Rotation.FromDirectionVector(
Utils.DegreesToRadians(roll),
Utils.DegreesToRadians(pitch),
Utils.DegreesToRadians(yaw));
return new RotationQuaternion(rotation);
}
/// <summary>
/// Convert quaternion to euler angles. Values are in degrees.
/// </summary>
/// <returns> Internal Rotation object.</returns>
public static EulerAngles ToEulerAngles(RotationQuaternion rotation)
{
var internalRotation = rotation.ToInternalRotation();
return new EulerAngles(FalkenInternal.falken.Rotation.ToEulerAngles(internalRotation));
}
private FalkenInternal.falken.Rotation _internalRotation;
}
/// <summary>
/// <c>Rotation</c> Establishes a connection with a Falken's RotationAttribute.
/// A rotation attribute is embedded in Entity's class and there's no
/// support for more than rotation attribute.
/// </summary>
public sealed class Rotation : Falken.AttributeBase
{
/// <summary>
/// Verify that the given object can be converted/assigned
/// to a RotationQuaternion.
/// </summary>
static private bool CanConvertToQuaternionType(object obj)
{
return CanConvertToGivenType(typeof(Falken.RotationQuaternion), obj);
}
#if UNITY_5_3_OR_NEWER
/// <summary>
/// Verify that the given object can be converted/assigned
/// to a UnityEngine.Quaternion
/// </summary>
static private bool CanConvertToUnityQuaternionType(object obj)
{
return CanConvertToGivenType(typeof(UnityEngine.Quaternion), obj);
}
#endif // UNITY_5_3_OR_NEWER
/// <summary>
/// Verify that the given object can be converted/assigned
/// to any supported position type.
/// </summary>
static internal bool CanConvertToRotationType(object obj)
{
bool canConvert = CanConvertToQuaternionType(obj);
#if UNITY_5_3_OR_NEWER
canConvert |= CanConvertToUnityQuaternionType(obj);
#endif // UNITY_5_3_OR_NEWER
return canConvert;
}
// Type of the rotation field.
// Useful to distinguish between UnityEngine.Quaternion and Falken's
// RotationQuaternion
private Type _rotationType = typeof(Falken.RotationQuaternion);
/// <summary>
/// Get Falken's rotation attribute value.
/// <exception> AttributeNotBoundException if attribute is
/// not bound. </exception>
/// <returns> Value stored in Falken's attribute. </returns>
/// </summary>
public Falken.RotationQuaternion Value
{
get
{
if (Bound)
{
Read();
return new Falken.RotationQuaternion(_attribute.rotation());
}
throw new AttributeNotBoundException(
"Can't retrieve the value if the attribute is not bound.");
}
set
{
if (Bound)
{
_attribute.set_rotation(CastTo<Falken.RotationQuaternion>(value)
.ToInPlaceInternalRotation(_attribute.rotation()));
Write();
return;
}
throw new AttributeNotBoundException(
"Can't set value if the attribute is not bound.");
}
}
/// <summary>
/// Establish a connection between a C# attribute and a Falken's attribute.
/// </summary>
/// <param name="fieldInfo">Metadata information of the field this is being bound
/// to.</param>
/// <param name="fieldContainer">Object that contains the value of the field.</param>
/// <param name="container">Internal container to add the attribute to.</param>
/// <exception>AlreadyBoundException thrown when trying to bind the attribute when it was
/// bound already.</exception>
internal override void BindAttribute(FieldInfo fieldInfo, object fieldContainer,
FalkenInternal.falken.AttributeContainer container)
{
ThrowIfBound(fieldInfo);
SetNameToFieldName(fieldInfo, fieldContainer);
if (fieldInfo != null && fieldContainer != null)
{
object value = fieldInfo.GetValue(fieldContainer);
if (value != this)
{
// Attribute represents a field with non-Falken value.
_rotationType = null;
#if UNITY_5_3_OR_NEWER
if (CanConvertToUnityQuaternionType(value))
{
_rotationType = typeof(UnityEngine.Quaternion);
}
#endif // UNITY_5_3_OR_NEWER
if (_rotationType == null && CanConvertToQuaternionType(value))
{
_rotationType = typeof(Falken.RotationQuaternion);
}
if (_rotationType == null)
{
ClearBindings();
throw new UnsupportedFalkenTypeException(
$"Field '{fieldInfo.Name}' is not a Falken.RotationQuaternion" +
" or a UnityEngine.Quaternion or it does not have the" +
" necessary implicit conversions to support it.");
}
}
}
else
{
// Attribute does not represent a field.
_name = "rotation";
ClearBindings();
}
FalkenInternal.falken.AttributeBase attributeBase;
if (fieldInfo == null ||
System.Attribute.GetCustomAttribute(fieldInfo,
typeof(FalkenInheritedAttribute)) == null)
{
attributeBase = new FalkenInternal.falken.AttributeBase(
container, _name, FalkenInternal.falken.AttributeBase.Type.kTypeRotation);
}
else
{
attributeBase = container.attribute(_name);
if (attributeBase == null)
{
ClearBindings();
throw new InheritedAttributeNotFoundException(
$"Inherited field '{_name}' was not found in the container.");
}
else if (attributeBase.type() !=
FalkenInternal.falken.AttributeBase.Type.kTypeRotation)
{
ClearBindings();
throw new InheritedAttributeNotFoundException(
$"Inherited field '{_name}' has a rotation type but the " +
$"attribute type is '{attributeBase.type()}'");
}
}
SetFalkenInternalAttribute(attributeBase, fieldInfo, fieldContainer);
Read();
InvalidateNonFalkenFieldValue();
}
/// <summary>
/// Clear all field and attribute bindings.
/// </summary>
protected override void ClearBindings()
{
base.ClearBindings();
_rotationType = typeof(Falken.RotationQuaternion);
}
/// <summary>
/// Read a field and check if the value is valid.
/// </summary>
/// <returns>
/// Object boxed version of the attribute value.
/// or null if invalid or unable to readValue stored in Falken's attribute.
/// </returns>
internal override object ReadFieldIfValid()
{
object value = base.ReadField();
RotationQuaternion rotation = null;
if (value != null)
{
if (_rotationType == typeof(RotationQuaternion))
{
rotation = CastTo<RotationQuaternion>(value);
}
#if UNITY_5_3_OR_NEWER
if (_rotationType == typeof(UnityEngine.Quaternion))
{
rotation = CastTo<UnityEngine.Quaternion>(value);
}
#endif // UNITY_5_3_OR_NEWER
if (Single.IsNaN(rotation.X) || Single.IsNaN(rotation.Y)
|| Single.IsNaN(rotation.Z) || Single.IsNaN(rotation.W)) {
return null;
}
}
return rotation;
}
/// <summary>
/// Update Falken's attribute value to reflect C# field's value.
/// </summary>
internal override void Read()
{
var value = ReadFieldIfValid();
if (value != null)
{
_attribute.set_rotation(
((RotationQuaternion)value).ToInPlaceInternalRotation(_attribute.rotation()));
}
}
/// <summary>
/// Update C# field's value to match Falken's attribute value.
/// </summary>
internal override void Write()
{
if (Bound && HasForeignFieldValue)
{
WriteField(CastFrom<RotationQuaternion>(
new RotationQuaternion(_attribute.rotation())));
}
}
/// <summary>
/// Invalidates the value of any non-Falken field represented by this attribute.
/// </summary>
internal override void InvalidateNonFalkenFieldValue()
{
if (HasForeignFieldValue) {
RotationQuaternion rotation = new RotationQuaternion
{
X = Single.NaN,
Y = Single.NaN,
Z = Single.NaN,
W = Single.NaN
};
WriteField(CastFrom<RotationQuaternion>(rotation));
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Starfield.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
#endregion
namespace NetRumble
{
/// <summary>
/// The starfield that renders behind the game, including a parallax effect.
/// </summary>
public class Starfield : IDisposable
{
#region Constants
/// <summary>
/// The number of stars in the starfield.
/// </summary>
const int numberOfStars = 256;
/// <summary>
/// The number of layers in the starfield.
/// </summary>
const int numberOfLayers = 8;
/// <summary>
/// The colors for each layer of stars.
/// </summary>
static readonly Color[] layerColors = new Color[numberOfLayers]
{
new Color(255, 255, 255, 255),
new Color(255, 255, 255, 216),
new Color(255, 255, 255, 192),
new Color(255, 255, 255, 160),
new Color(255, 255, 255, 128),
new Color(255, 255, 255, 96),
new Color(255, 255, 255, 64),
new Color(255, 255, 255, 32)
};
/// <summary>
/// The movement factor for each layer of stars, used in the parallax effect.
/// </summary>
static readonly float[] movementFactors = new float[numberOfLayers]
{
0.9f, 0.8f, 0.7f, 0.6f, 0.5f, 0.4f, 0.3f, 0.2f
};
/// <summary>
/// The maximum amount of movement allowed per update.
/// </summary>
/// <remarks>
/// Any per-update movement values that exceed this will trigger a
/// starfield reset.
/// </remarks>
const float maximumMovementPerUpdate = 128f;
/// <summary>
/// The background color of the starfield.
/// </summary>
static readonly Color backgroundColor = new Color(0, 0, 32);
/// <summary>
/// The size of each star, in pixels.
/// </summary>
const int starSize = 2;
#endregion
#region Gameplay Data
/// <summary>
/// The last position, used for the parallax effect.
/// </summary>
private Vector2 lastPosition;
/// <summary>
/// The current position, used for the parallax effect.
/// </summary>
private Vector2 position;
/// <summary>
/// The stars in the starfield.
/// </summary>
private Vector2[] stars;
#endregion
#region Graphics Data
/// <summary>
/// The graphics device used to render the starfield.
/// </summary>
private GraphicsDevice graphicsDevice;
/// <summary>
/// The content manager used to manage the textures in the starfield.
/// </summary>
private ContentManager contentManager;
/// <summary>
/// The SpriteBatch used to render the starfield.
/// </summary>
private SpriteBatch spriteBatch;
/// <summary>
/// The texture used for each star, typically one white pixel.
/// </summary>
private Texture2D starTexture;
/// <summary>
/// The cloud texture that appears behind the stars.
/// </summary>
private Texture2D cloudTexture;
/// <summary>
/// The effect used to draw the clouds.
/// </summary>
private Effect cloudEffect;
/// <summary>
/// The parameter on the cloud effect that receives the current position
/// </summary>
private EffectParameter cloudEffectPosition;
#endregion
#region Initialization Methods
/// <summary>
/// Create a new Starfield object.
/// </summary>
/// <param name="position"></param>
/// <param name="graphicsDevice">The graphics device used to render.</param>
/// <param name="contentManager">The content manager for this object.</param>
public Starfield(Vector2 position, GraphicsDevice graphicsDevice,
ContentManager contentManager)
{
// safety-check the parameters, as they must be valid
if (graphicsDevice == null)
{
throw new ArgumentNullException("graphicsDevice");
}
if (contentManager == null)
{
throw new ArgumentNullException("contentManager");
}
// assign the parameters
this.graphicsDevice = graphicsDevice;
this.contentManager = contentManager;
// initialize the stars
stars = new Vector2[numberOfStars];
Reset(position);
}
/// <summary>
/// Load graphics data from the system.
/// </summary>
public void LoadContent()
{
// load the cloud texture
cloudTexture = contentManager.Load<Texture2D>("Textures/Clouds");
// load the cloud effect
cloudEffect = contentManager.Load<Effect>("Effects/Clouds");
cloudEffectPosition = cloudEffect.Parameters["Position"];
// create the star texture
starTexture = new Texture2D(graphicsDevice, 1, 1, false, SurfaceFormat.Color);
starTexture.SetData<Color>(new Color[] { Color.White });
// create the SpriteBatch object
spriteBatch = new SpriteBatch(graphicsDevice);
}
/// <summary>
/// Release graphics data.
/// </summary>
public void UnloadContent()
{
cloudTexture = null;
cloudEffect = null;
cloudEffectPosition = null;
if (starTexture != null)
{
starTexture.Dispose();
starTexture = null;
}
if (spriteBatch != null)
{
spriteBatch.Dispose();
spriteBatch = null;
}
}
/// <summary>
/// Reset the stars and the parallax effect.
/// </summary>
/// <param name="position">The new origin point for the parallax effect.</param>
public void Reset(Vector2 position)
{
// recreate the stars
int viewportWidth = graphicsDevice.Viewport.Width;
int viewportHeight = graphicsDevice.Viewport.Height;
for (int i = 0; i < stars.Length; ++i)
{
stars[i] = new Vector2(RandomMath.Random.Next(0, viewportWidth),
RandomMath.Random.Next(0, viewportHeight));
}
// reset the position
this.lastPosition = this.position = position;
}
#endregion
#region Draw Methods
/// <summary>
/// Update and draw the starfield.
/// </summary>
/// <remarks>
/// This function updates and draws the starfield,
/// so that the per-star loop is only run once per frame.
/// </remarks>
/// <param name="position">The new position for the parallax effect.</param>
public void Draw(Vector2 position)
{
// update the current position
this.lastPosition = this.position;
this.position = position;
// determine the movement vector of the stars
// -- for the purposes of the parallax effect,
// this is the opposite direction as the position movement.
Vector2 movement = -1.0f * (position - lastPosition);
// create a rectangle representing the screen dimensions of the starfield
Rectangle starfieldRectangle = new Rectangle(0, 0,
graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height);
// draw a background color for the starfield
spriteBatch.Begin();
spriteBatch.Draw(starTexture, starfieldRectangle, backgroundColor);
spriteBatch.End();
// draw the cloud texture
cloudEffectPosition.SetValue(this.position);
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied,
null, null, null, cloudEffect);
spriteBatch.Draw(cloudTexture, starfieldRectangle, null, Color.White, 0.0f,
Vector2.Zero, SpriteEffects.None, 1.0f);
spriteBatch.End();
// if we've moved too far, then reset, as the stars will be moving too fast
if (movement.Length() > maximumMovementPerUpdate)
{
Reset(position);
return;
}
// draw all of the stars
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
for (int i = 0; i < stars.Length; i++)
{
// move the star based on the depth
int depth = i % movementFactors.Length;
stars[i] += movement * movementFactors[depth];
// wrap the stars around
if (stars[i].X < starfieldRectangle.X)
{
stars[i].X = starfieldRectangle.X + starfieldRectangle.Width;
stars[i].Y = starfieldRectangle.Y +
RandomMath.Random.Next(starfieldRectangle.Height);
}
if (stars[i].X > (starfieldRectangle.X + starfieldRectangle.Width))
{
stars[i].X = starfieldRectangle.X;
stars[i].Y = starfieldRectangle.Y +
RandomMath.Random.Next(starfieldRectangle.Height);
}
if (stars[i].Y < starfieldRectangle.Y)
{
stars[i].X = starfieldRectangle.X +
RandomMath.Random.Next(starfieldRectangle.Width);
stars[i].Y = starfieldRectangle.Y + starfieldRectangle.Height;
}
if (stars[i].Y >
(starfieldRectangle.Y + graphicsDevice.Viewport.Height))
{
stars[i].X = starfieldRectangle.X +
RandomMath.Random.Next(starfieldRectangle.Width);
stars[i].Y = starfieldRectangle.Y;
}
// draw the star
spriteBatch.Draw(starTexture,
new Rectangle((int)stars[i].X, (int)stars[i].Y, starSize, starSize),
null, layerColors[depth]);
}
spriteBatch.End();
}
#endregion
#region IDisposable Implementation
/// <summary>
/// Finalizes the Starfield object, calls Dispose(false)
/// </summary>
~Starfield()
{
Dispose(false);
}
/// <summary>
/// Disposes the Starfield object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes this object.
/// </summary>
/// <param name="disposing">
/// True if this method was called as part of the Dispose method.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (this)
{
if (starTexture != null)
{
starTexture.Dispose();
starTexture = null;
}
if (spriteBatch != null)
{
spriteBatch.Dispose();
spriteBatch = null;
}
}
}
}
#endregion
}
}
| |
/*
* PortAudioSharp - PortAudio bindings for .NET
* Copyright 2006-2011 Riccardo Gerosa and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.Runtime.InteropServices;
namespace PortAudioSharp {
/**
<summary>
PortAudio v.19 bindings for .NET
</summary>
*/
public partial class PortAudio
{
#region **** PORTAUDIO CALLBACKS ****
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate PaStreamCallbackResult PaStreamCallbackDelegate(
IntPtr input,
IntPtr output,
uint frameCount,
ref PaStreamCallbackTimeInfo timeInfo,
PaStreamCallbackFlags statusFlags,
IntPtr userData);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void PaStreamFinishedCallbackDelegate(IntPtr userData);
#endregion
#region **** PORTAUDIO DATA STRUCTURES ****
[StructLayout (LayoutKind.Sequential)]
public struct PaDeviceInfo {
public int structVersion;
[MarshalAs (UnmanagedType.LPStr)]
public string name;
public int hostApi;
public int maxInputChannels;
public int maxOutputChannels;
public double defaultLowInputLatency;
public double defaultLowOutputLatency;
public double defaultHighInputLatency;
public double defaultHighOutputLatency;
public double defaultSampleRate;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "name: " + name + "\n"
+ "hostApi: " + hostApi + "\n"
+ "maxInputChannels: " + maxInputChannels + "\n"
+ "maxOutputChannels: " + maxOutputChannels + "\n"
+ "defaultLowInputLatency: " + defaultLowInputLatency + "\n"
+ "defaultLowOutputLatency: " + defaultLowOutputLatency + "\n"
+ "defaultHighInputLatency: " + defaultHighInputLatency + "\n"
+ "defaultHighOutputLatency: " + defaultHighOutputLatency + "\n"
+ "defaultSampleRate: " + defaultSampleRate;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaHostApiInfo {
public int structVersion;
public PaHostApiTypeId type;
[MarshalAs (UnmanagedType.LPStr)]
public string name;
public int deviceCount;
public int defaultInputDevice;
public int defaultOutputDevice;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "structVersion: " + structVersion + "\n"
+ "type: " + type + "\n"
+ "name: " + name + "\n"
+ "deviceCount: " + deviceCount + "\n"
+ "defaultInputDevice: " + defaultInputDevice + "\n"
+ "defaultOutputDevice: " + defaultOutputDevice;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaHostErrorInfo {
public PaHostApiTypeId hostApiType;
public int errorCode;
[MarshalAs (UnmanagedType.LPStr)]
public string errorText;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "hostApiType: " + hostApiType + "\n"
+ "errorCode: " + errorCode + "\n"
+ "errorText: " + errorText;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaStreamCallbackTimeInfo {
public double inputBufferAdcTime;
public double currentTime;
public double outputBufferDacTime;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "currentTime: " + currentTime + "\n"
+ "inputBufferAdcTime: " + inputBufferAdcTime + "\n"
+ "outputBufferDacTime: " + outputBufferDacTime;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaStreamInfo {
public int structVersion;
public double inputLatency;
public double outputLatency;
public double sampleRate;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "structVersion: " + structVersion + "\n"
+ "inputLatency: " + inputLatency + "\n"
+ "outputLatency: " + outputLatency + "\n"
+ "sampleRate: " + sampleRate;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaStreamParameters {
public int device;
public int channelCount;
public PaSampleFormat sampleFormat;
public double suggestedLatency;
public IntPtr hostApiSpecificStreamInfo;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "device: " + device + "\n"
+ "channelCount: " + channelCount + "\n"
+ "sampleFormat: " + sampleFormat + "\n"
+ "suggestedLatency: " + suggestedLatency;
}
}
#endregion
#region **** PORTAUDIO DEFINES ****
public enum PaDeviceIndex: int
{
paNoDevice = -1,
paUseHostApiSpecificDeviceSpecification = -2
}
public enum PaSampleFormat: uint
{
paFloat32 = 0x00000001,
paInt32 = 0x00000002,
paInt24 = 0x00000004,
paInt16 = 0x00000008,
paInt8 = 0x00000010,
paUInt8 = 0x00000020,
paCustomFormat = 0x00010000,
paNonInterleaved = 0x80000000,
}
public const int paFormatIsSupported = 0;
public const int paFramesPerBufferUnspecified = 0;
public enum PaStreamFlags: uint
{
paNoFlag = 0,
paClipOff = 0x00000001,
paDitherOff = 0x00000002,
paNeverDropInput = 0x00000004,
paPrimeOutputBuffersUsingStreamCallback = 0x00000008,
paPlatformSpecificFlags = 0xFFFF0000
}
public enum PaStreamCallbackFlags: uint
{
paInputUnderflow = 0x00000001,
paInputOverflow = 0x00000002,
paOutputUnderflow = 0x00000004,
paOutputOverflow = 0x00000008,
paPrimingOutput = 0x00000010
}
#endregion
#region **** PORTAUDIO ENUMERATIONS ****
public enum PaError : int {
paNoError = 0,
paNotInitialized = -10000,
paUnanticipatedHostError,
paInvalidChannelCount,
paInvalidSampleRate,
paInvalidDevice,
paInvalidFlag,
paSampleFormatNotSupported,
paBadIODeviceCombination,
paInsufficientMemory,
paBufferTooBig,
paBufferTooSmall,
paNullCallback,
paBadStreamPtr,
paTimedOut,
paInternalError,
paDeviceUnavailable,
paIncompatibleHostApiSpecificStreamInfo,
paStreamIsStopped,
paStreamIsNotStopped,
paInputOverflowed,
paOutputUnderflowed,
paHostApiNotFound,
paInvalidHostApi,
paCanNotReadFromACallbackStream,
paCanNotWriteToACallbackStream,
paCanNotReadFromAnOutputOnlyStream,
paCanNotWriteToAnInputOnlyStream,
paIncompatibleStreamHostApi,
paBadBufferPtr
}
public enum PaHostApiTypeId : uint {
paInDevelopment=0,
paDirectSound=1,
paMME=2,
paASIO=3,
paSoundManager=4,
paCoreAudio=5,
paOSS=7,
paALSA=8,
paAL=9,
paBeOS=10,
paWDMKS=11,
paJACK=12,
paWASAPI=13,
paAudioScienceHPI=14
}
public enum PaStreamCallbackResult : uint {
paContinue = 0,
paComplete = 1,
paAbort = 2
}
#endregion
#region **** PORTAUDIO FUNCTIONS ****
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetVersion();
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetVersionText")]
private static extern IntPtr IntPtr_Pa_GetVersionText();
public static string Pa_GetVersionText() {
IntPtr strptr = IntPtr_Pa_GetVersionText();
return Marshal.PtrToStringAnsi(strptr);
}
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetErrorText")]
public static extern IntPtr IntPtr_Pa_GetErrorText(PaError errorCode);
public static string Pa_GetErrorText(PaError errorCode) {
IntPtr strptr = IntPtr_Pa_GetErrorText(errorCode);
return Marshal.PtrToStringAnsi(strptr);
}
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_Initialize();
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_Terminate();
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetHostApiCount();
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetDefaultHostApi();
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetHostApiInfo")]
public static extern IntPtr IntPtr_Pa_GetHostApiInfo(int hostApi);
public static PaHostApiInfo Pa_GetHostApiInfo(int hostApi) {
IntPtr structptr = IntPtr_Pa_GetHostApiInfo(hostApi);
return (PaHostApiInfo) Marshal.PtrToStructure(structptr, typeof(PaHostApiInfo));
}
[DllImport ("PortAudio.dll")]
public static extern int Pa_HostApiTypeIdToHostApiIndex(PaHostApiTypeId type);
[DllImport ("PortAudio.dll")]
public static extern int Pa_HostApiDeviceIndexToDeviceIndex(int hostApi, int hostApiDeviceIndex);
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetLastHostErrorInfo")]
public static extern IntPtr IntPtr_Pa_GetLastHostErrorInfo();
public static PaHostErrorInfo Pa_GetLastHostErrorInfo() {
IntPtr structptr = IntPtr_Pa_GetLastHostErrorInfo();
return (PaHostErrorInfo) Marshal.PtrToStructure(structptr, typeof(PaHostErrorInfo));
}
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetDeviceCount();
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetDefaultInputDevice();
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetDefaultOutputDevice();
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetDeviceInfo")]
public static extern IntPtr IntPtr_Pa_GetDeviceInfo(int device);
public static PaDeviceInfo Pa_GetDeviceInfo(int device) {
IntPtr structptr = IntPtr_Pa_GetDeviceInfo(device);
return (PaDeviceInfo) Marshal.PtrToStructure(structptr, typeof(PaDeviceInfo));
}
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_IsFormatSupported(
ref PaStreamParameters inputParameters,
ref PaStreamParameters outputParameters,
double sampleRate);
[DllImport("PortAudio.dll")]
public static extern PaError Pa_OpenStream(
out IntPtr stream,
ref PaStreamParameters inputParameters,
ref PaStreamParameters outputParameters,
double sampleRate,
uint framesPerBuffer,
PaStreamFlags streamFlags,
PaStreamCallbackDelegate streamCallback,
IntPtr userData);
[DllImport("PortAudio.dll")]
private static extern PaError Pa_OpenStream(
out IntPtr stream,
IntPtr inputParameters,
IntPtr outputParameters,
double sampleRate,
uint framesPerBuffer,
PaStreamFlags streamFlags,
PaStreamCallbackDelegate streamCallback,
IntPtr userData);
public static PaError Pa_OpenStream(
out IntPtr stream,
ref PaStreamParameters? inputParameters,
ref PaStreamParameters? outputParameters,
double sampleRate,
uint framesPerBuffer,
PaStreamFlags streamFlags,
PaStreamCallbackDelegate streamCallback,
IntPtr userData)
{
IntPtr inputParametersPtr;
if (inputParameters != null) {
inputParametersPtr = Marshal.AllocHGlobal(Marshal.SizeOf(inputParameters.Value));
Marshal.StructureToPtr(inputParameters.Value, inputParametersPtr, true);
} else {
inputParametersPtr = IntPtr.Zero;
}
IntPtr outputParametersPtr;
if (outputParameters != null) {
outputParametersPtr = Marshal.AllocHGlobal(Marshal.SizeOf(outputParameters.Value));
Marshal.StructureToPtr(outputParameters.Value, outputParametersPtr, true);
} else {
outputParametersPtr = IntPtr.Zero;
}
return Pa_OpenStream(out stream, inputParametersPtr, outputParametersPtr, sampleRate, framesPerBuffer, streamFlags, streamCallback, userData);
}
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_OpenDefaultStream(
out IntPtr stream,
int numInputChannels,
int numOutputChannels,
uint sampleFormat,
double sampleRate,
uint framesPerBuffer,
PaStreamCallbackDelegate streamCallback,
IntPtr userData);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_CloseStream(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_SetStreamFinishedCallback(
ref IntPtr stream,
[MarshalAs(UnmanagedType.FunctionPtr)]PaStreamFinishedCallbackDelegate streamFinishedCallback);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_StartStream(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_StopStream(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_AbortStream(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_IsStreamStopped(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_IsStreamActive(IntPtr stream);
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetStreamInfo")]
public static extern IntPtr IntPtr_Pa_GetStreamInfo(IntPtr stream);
public static PaStreamInfo Pa_GetStreamInfo(IntPtr stream) {
IntPtr structptr = IntPtr_Pa_GetStreamInfo(stream);
return (PaStreamInfo) Marshal.PtrToStructure(structptr,typeof(PaStreamInfo));
}
[DllImport ("PortAudio.dll")]
public static extern double Pa_GetStreamTime(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern double Pa_GetStreamCpuLoad(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]float[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]byte[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]sbyte[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]ushort[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]short[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]uint[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]int[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]float[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]byte[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]sbyte[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]ushort[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]short[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]uint[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]int[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetStreamReadAvailable(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetStreamWriteAvailable(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_GetSampleSize(PaSampleFormat format);
[DllImport ("PortAudio.dll")]
public static extern void Pa_Sleep(int msec);
#endregion
private PortAudio() {
// This is a static class
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source
{
public sealed class ExpressionBodiedPropertyTests : CSharpTestBase
{
[Fact(Skip = "973907")]
public void Syntax01()
{
// Language feature enabled by default
var comp = CreateCompilationWithMscorlib(@"
class C
{
public int P => 1;
}");
comp.VerifyDiagnostics();
}
[Fact]
public void Syntax02()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int P { get; } => 1;
}");
comp.VerifyDiagnostics(
// (4,5): error CS8056: Properties cannot combine accessor lists with expression bodies.
// public int P { get; } => 1;
Diagnostic(ErrorCode.ERR_AccessorListAndExpressionBody, "public int P { get; } => 1;").WithLocation(4, 5)
);
}
[Fact]
public void Syntax03()
{
var comp = CreateCompilationWithMscorlib45(@"
interface C
{
int P => 1;
}");
comp.VerifyDiagnostics(
// (4,14): error CS0531: 'C.P.get': interface members cannot have a definition
// int P => 1;
Diagnostic(ErrorCode.ERR_InterfaceMemberHasBody, "1").WithArguments("C.P.get").WithLocation(4, 14));
}
[Fact]
public void Syntax04()
{
var comp = CreateCompilationWithMscorlib45(@"
abstract class C
{
public abstract int P => 1;
}");
comp.VerifyDiagnostics(
// (4,28): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract
// public abstract int P => 1;
Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 28));
}
[Fact]
public void Syntax05()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public abstract int P => 1;
}");
comp.VerifyDiagnostics(
// (4,29): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract
// public abstract int P => 1;
Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 29),
// (4,29): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract class 'C'
// public abstract int P => 1;
Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "1").WithArguments("C.P.get", "C").WithLocation(4, 29));
}
[Fact]
public void Syntax06()
{
var comp = CreateCompilationWithMscorlib45(@"
abstract class C
{
abstract int P => 1;
}");
comp.VerifyDiagnostics(
// (4,17): error CS0621: 'C.P': virtual or abstract members cannot be private
// abstract int P => 1;
Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("C.P").WithLocation(4, 17),
// (4,22): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract
// abstract int P => 1;
Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 22));
}
[Fact]
public void Syntax07()
{
// The '=' here parses as part of the expression body, not the property
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int P => 1 = 2;
}");
comp.VerifyDiagnostics(
// (4,21): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// public int P => 1 = 2;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(4, 21));
}
[Fact]
public void Syntax08()
{
CreateCompilationWithMscorlib45(@"
interface I
{
int P { get; };
}").VerifyDiagnostics(
// (4,19): error CS1597: Semicolon after method or accessor block is not valid
// int P { get; };
Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 19));
}
[Fact]
public void Syntax09()
{
CreateCompilationWithMscorlib45(@"
class C
{
int P => 2
}").VerifyDiagnostics(
// (4,15): error CS1002: ; expected
// int P => 2
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15));
}
[Fact]
public void Syntax10()
{
CreateCompilationWithMscorlib45(@"
interface I
{
int this[int i]
}").VerifyDiagnostics(
// (4,20): error CS1514: { expected
// int this[int i]
Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(4, 20),
// (5,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2),
// (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor
// int this[int i]
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9));
}
[Fact]
public void Syntax11()
{
CreateCompilationWithMscorlib45(@"
interface I
{
int this[int i];
}").VerifyDiagnostics(
// (4,20): error CS1514: { expected
// int this[int i];
Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(4, 20),
// (4,20): error CS1014: A get or set accessor expected
// int this[int i];
Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(4, 20),
// (5,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2),
// (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor
// int this[int i];
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9));
}
[Fact]
public void Syntax12()
{
CreateCompilationWithMscorlib45(@"
interface I
{
int this[int i] { get; };
}").VerifyDiagnostics(
// (4,29): error CS1597: Semicolon after method or accessor block is not valid
// int this[int i] { get; };
Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 29));
}
[Fact]
public void Syntax13()
{
// End the property declaration at the semicolon after the accessor list
CreateCompilationWithMscorlib45(@"
class C
{
int P { get; set; }; => 2;
}").VerifyDiagnostics(
// (4,24): error CS1597: Semicolon after method or accessor block is not valid
// int P { get; set; }; => 2;
Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 24),
// (4,26): error CS1519: Invalid token '=>' in class, struct, or interface member declaration
// int P { get; set; }; => 2;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 26));
}
[Fact]
public void Syntax14()
{
CreateCompilationWithMscorlib45(@"
class C
{
int this[int i] => 2
}").VerifyDiagnostics(
// (4,25): error CS1002: ; expected
// int this[int i] => 2
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 25));
}
[Fact]
public void LambdaTest01()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public Func<int, Func<int, int>> P => x => y => x + y;
}");
comp.VerifyDiagnostics();
}
[Fact]
public void SimpleTest()
{
var text = @"
class C
{
public int P => 2 * 2;
public int this[int i, int j] => i * j * P;
}";
var comp = CreateCompilationWithMscorlib45(text);
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var c = global.GetTypeMember("C");
var p = c.GetMember<SourcePropertySymbol>("P");
Assert.Null(p.SetMethod);
Assert.NotNull(p.GetMethod);
Assert.False(p.GetMethod.IsImplicitlyDeclared);
Assert.True(p.IsExpressionBodied);
var indexer = c.GetMember<SourcePropertySymbol>("this[]");
Assert.Null(indexer.SetMethod);
Assert.NotNull(indexer.GetMethod);
Assert.False(indexer.GetMethod.IsImplicitlyDeclared);
Assert.True(indexer.IsExpressionBodied);
Assert.True(indexer.IsIndexer);
Assert.Equal(2, indexer.ParameterCount);
var i = indexer.Parameters[0];
Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType);
Assert.Equal("i", i.Name);
var j = indexer.Parameters[1];
Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType);
Assert.Equal("j", j.Name);
}
[Fact]
public void Override01()
{
var comp = CreateCompilationWithMscorlib45(@"
class B
{
public virtual int P { get; set; }
}
class C : B
{
public override int P => 1;
}").VerifyDiagnostics();
}
[Fact]
public void Override02()
{
CreateCompilationWithMscorlib45(@"
class B
{
public int P => 10;
public int this[int i] => i;
}
class C : B
{
public override int P => 20;
public override int this[int i] => i * 2;
}").VerifyDiagnostics(
// (10,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override
// public override int this[int i] => i * 2;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]").WithLocation(10, 25),
// (9,25): error CS0506: 'C.P': cannot override inherited member 'B.P' because it is not marked virtual, abstract, or override
// public override int P => 20;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("C.P", "B.P").WithLocation(9, 25));
}
[Fact]
public void Override03()
{
CreateCompilationWithMscorlib45(@"
class B
{
public virtual int P => 10;
public virtual int this[int i] => i;
}
class C : B
{
public override int P => 20;
public override int this[int i] => i * 2;
}").VerifyDiagnostics();
}
[Fact]
public void VoidExpression()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public void P => System.Console.WriteLine(""foo"");
}").VerifyDiagnostics(
// (4,17): error CS0547: 'C.P': property or indexer cannot have void type
// public void P => System.Console.WriteLine("foo");
Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "P").WithArguments("C.P").WithLocation(4, 17));
}
[Fact]
public void VoidExpression2()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int P => System.Console.WriteLine(""foo"");
}").VerifyDiagnostics(
// (4,21): error CS0029: Cannot implicitly convert type 'void' to 'int'
// public int P => System.Console.WriteLine("foo");
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"System.Console.WriteLine(""foo"")").WithArguments("void", "int").WithLocation(4, 21));
}
[Fact]
public void InterfaceImplementation01()
{
var comp = CreateCompilationWithMscorlib45(@"
interface I
{
int P { get; }
string Q { get; }
}
internal interface J
{
string Q { get; }
}
internal interface K
{
decimal D { get; }
}
class C : I, J, K
{
public int P => 10;
string I.Q { get { return ""foo""; } }
string J.Q { get { return ""bar""; } }
public decimal D { get { return P; } }
}");
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var i = global.GetTypeMember("I");
var j = global.GetTypeMember("J");
var k = global.GetTypeMember("K");
var c = global.GetTypeMember("C");
var iP = i.GetMember<SourcePropertySymbol>("P");
var prop = c.GetMember<SourcePropertySymbol>("P");
Assert.True(prop.IsReadOnly);
var implements = prop.ContainingType.FindImplementationForInterfaceMember(iP);
Assert.Equal(prop, implements);
prop = (SourcePropertySymbol)c.GetProperty("I.Q");
Assert.True(prop.IsReadOnly);
Assert.True(prop.IsExplicitInterfaceImplementation);
prop = (SourcePropertySymbol)c.GetProperty("J.Q");
Assert.True(prop.IsReadOnly);
Assert.True(prop.IsExplicitInterfaceImplementation);
prop = c.GetMember<SourcePropertySymbol>("D");
Assert.True(prop.IsReadOnly);
}
[ClrOnlyFact]
public void Emit01()
{
var comp = CreateCompilationWithMscorlib45(@"
abstract class A
{
protected abstract string Z { get; }
}
abstract class B : A
{
protected sealed override string Z => ""foo"";
protected abstract string Y { get; }
}
class C : B
{
public const int X = 2;
public static int P => C.X * C.X;
public int Q => X;
private int R => P * Q;
protected sealed override string Y => Z + R;
public int this[int i] => R + i;
public static void Main()
{
System.Console.WriteLine(C.X);
System.Console.WriteLine(C.P);
var c = new C();
System.Console.WriteLine(c.Q);
System.Console.WriteLine(c.R);
System.Console.WriteLine(c.Z);
System.Console.WriteLine(c.Y);
System.Console.WriteLine(c[10]);
}
}", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
var verifier = CompileAndVerify(comp, expectedOutput:
@"2
4
2
8
foo
foo8
18");
}
[ClrOnlyFact]
public void AccessorInheritsVisibility()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
private int P => 1;
private int this[int i] => i;
}", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
Action<ModuleSymbol> srcValidator = m =>
{
var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var p = c.GetMember<PropertySymbol>("P");
var indexer = c.Indexers[0];
Assert.Equal(Accessibility.Private, p.DeclaredAccessibility);
Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility);
};
var verifier = CompileAndVerify(comp, sourceSymbolValidator: srcValidator);
}
[Fact]
public void StaticIndexer()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
static int this[int i] => i;
}");
comp.VerifyDiagnostics(
// (4,16): error CS0106: The modifier 'static' is not valid for this item
// static int this[int i] => i;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16));
}
[Fact]
public void RefReturningExpressionBodiedProperty()
{
var comp = CreateExperimentalCompilationWithMscorlib45(@"
class C
{
int field = 0;
public ref int P => ref field;
}");
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var c = global.GetTypeMember("C");
var p = c.GetMember<SourcePropertySymbol>("P");
Assert.Null(p.SetMethod);
Assert.NotNull(p.GetMethod);
Assert.False(p.GetMethod.IsImplicitlyDeclared);
Assert.True(p.IsExpressionBodied);
Assert.Equal(RefKind.Ref, p.GetMethod.RefKind);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Diadoc.Api.Com;
using Diadoc.Api.Proto.Documents;
namespace Diadoc.Api.Proto.Events
{
[ComVisible(true)]
[Guid("ABF440A3-BC33-4DF4-80CF-6889F7B004A3")]
public interface IMessage
{
string MessageId { get; }
string FromBoxId { get; }
string FromTitle { get; }
string ToBoxId { get; }
string ToTitle { get; }
bool IsDraft { get; }
bool IsDeleted { get; }
bool IsTest { get; }
bool IsInternal { get; }
ReadonlyList EntitiesList { get; }
bool DraftIsLocked { get; }
bool DraftIsRecycled { get; }
string CreatedFromDraftId { get; }
string DraftIsTransformedToMessageId { get; }
DateTime Timestamp { get; }
DateTime LastPatchTimestamp { get; }
}
[ComVisible(true)]
[Guid("26C32890-61DE-4FB9-9EED-B815E41050B7")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IMessage))]
public partial class Message : SafeComObject, IMessage
{
public string DraftIsTransformedToMessageId
{
get { return DraftIsTransformedToMessageIdList.FirstOrDefault(); }
}
public DateTime Timestamp
{
get { return new DateTime(TimestampTicks, DateTimeKind.Utc); }
}
public DateTime LastPatchTimestamp
{
get { return new DateTime(LastPatchTimestampTicks, DateTimeKind.Utc); }
}
public ReadonlyList EntitiesList
{
get { return new ReadonlyList(Entities); }
}
}
[ComVisible(true)]
[Guid("DFF0AEBA-4DCC-4910-B34A-200F1B919F4E")]
public interface IEntity
{
string EntityId { get; }
string ParentEntityId { get; }
Com.EntityType EntityTypeValue { get; }
Com.AttachmentType AttachmentTypeValue { get; }
string FileName { get; }
bool NeedRecipientSignature { get; }
bool NeedReceipt { get; }
Content Content { get; }
Document DocumentInfo { get; }
ResolutionInfo ResolutionInfo { get; }
string SignerBoxId { get; }
string SignerDepartmentId { get; }
DateTime CreationTime { get; }
string NotDeliveredEventId { get; }
ResolutionRouteAssignmentInfo ResolutionRouteAssignmentInfo { get; }
ResolutionRouteRemovalInfo ResolutionRouteRemovalInfo { get; }
CancellationInfo CancellationInfo { get; }
}
[ComVisible(true)]
[Guid("E7D82A2C-A0BF-4D0B-9466-9E8DA15B99B7")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IEntity))]
public partial class Entity : SafeComObject, IEntity
{
public DateTime CreationTime
{
get { return new DateTime(RawCreationDate, DateTimeKind.Utc); }
}
public Com.EntityType EntityTypeValue
{
get { return (Com.EntityType) ((int) EntityType); }
}
public Com.AttachmentType AttachmentTypeValue
{
get { return (Com.AttachmentType) ((int) AttachmentType); }
}
}
[ComVisible(true)]
[Guid("D3BD7130-16A6-4202-B1CE-5FB1A9AFD4EF")]
public interface IEntityPatch
{
string EntityId { get; }
bool DocumentIsDeleted { get; }
string MovedToDepartment { get; }
bool DocumentIsRestored { get; }
bool ContentIsPatched { get; }
}
[ComVisible(true)]
[Guid("4C05AB1C-5385-41A2-8C04-8855FC7E8341")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IEntityPatch))]
public partial class EntityPatch : SafeComObject, IEntityPatch
{
}
[ComVisible(true)]
[Guid("AE4037C5-DA6E-4D69-A738-5E6B64490492")]
public interface IBoxEvent
{
string EventId { get; }
string MessageId { get; }
DateTime Timestamp { get; }
ReadonlyList EntitiesList { get; }
bool HasMessage { get; }
bool HasPatch { get; }
Message Message { get; }
MessagePatch Patch { get; }
}
[ComVisible(true)]
[Guid("C59A22CF-9744-457A-8359-3569B19A31C8")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IBoxEvent))]
public partial class BoxEvent : SafeComObject, IBoxEvent
{
public string MessageId
{
get
{
return (Message != null ? Message.MessageId : null)
?? (Patch != null ? Patch.MessageId : null);
}
}
public DateTime Timestamp
{
get
{
if (Message != null)
return Message.Timestamp;
if (Patch != null)
return Patch.Timestamp;
return default(DateTime);
}
}
public ReadonlyList EntitiesList
{
get
{
var entities = (Message != null ? Message.Entities : null)
?? (Patch != null ? Patch.Entities : null);
return entities != null
? new ReadonlyList(entities)
: null;
}
}
public List<Entity> Entities
{
get
{
var entities = (Message != null ? Message.Entities : null)
?? (Patch != null ? Patch.Entities : null);
return entities != null
? new List<Entity>(entities)
: new List<Entity>();
}
}
public bool HasMessage
{
get { return Message != null; }
}
public bool HasPatch
{
get { return Patch != null; }
}
}
[ComVisible(true)]
[Guid("581C269C-67A5-4CDF-AC77-CDB2D05E03A0")]
public interface IBoxEventList
{
int TotalCount { get; }
ReadonlyList EventsList { get; }
}
[ComVisible(true)]
[Guid("793E451E-3F4A-4A3E-BDBB-F47ED13305F5")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IBoxEventList))]
public partial class BoxEventList : SafeComObject, IBoxEventList
{
public ReadonlyList EventsList
{
get { return new ReadonlyList(Events); }
}
}
[ComVisible(true)]
[Guid("527CD64F-A219-4B45-8219-CC48586D521B")]
public interface IMessagePatch
{
string MessageId { get; }
ReadonlyList EntitiesList { get; }
ReadonlyList EntityPatchesList { get; }
DateTime Timestamp { get; }
bool ForDraft { get; }
bool DraftIsRecycled { get; }
string DraftIsTransformedToMessageId { get; }
bool DraftIsLocked { get; }
bool MessageIsDeleted { get; }
bool MessageIsRestored { get; }
bool MessageIsDelivered { get; }
string DeliveredPatchId { get; }
string PatchId { get; }
}
[ComVisible(true)]
[Guid("949C9C09-DD1A-4787-A5AD-94D8677A5439")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IMessagePatch))]
public partial class MessagePatch : SafeComObject, IMessagePatch
{
public DateTime Timestamp
{
get { return new DateTime(TimestampTicks, DateTimeKind.Utc); }
}
public string DraftIsTransformedToMessageId
{
get { return DraftIsTransformedToMessageIdList.FirstOrDefault(); }
}
public ReadonlyList EntitiesList
{
get { return new ReadonlyList(Entities); }
}
public ReadonlyList EntityPatchesList
{
get { return new ReadonlyList(EntityPatches); }
}
}
[ComVisible(true)]
[Guid("32176AA9-AF39-4E0C-A47B-0CEA3C1DA211")]
public interface IGeneratedFile
{
string FileName { get; }
byte[] Content { get; }
void SaveContentToFile(string path);
}
[ComVisible(true)]
[Guid("D4E7012E-1A64-42EC-AD5E-B27754AC24FE")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IGeneratedFile))]
public class GeneratedFile : SafeComObject, IGeneratedFile
{
private readonly string fileName;
private readonly byte[] content;
public GeneratedFile(string fileName, byte[] content)
{
this.fileName = fileName;
this.content = content;
}
public void SaveContentToFile(string path)
{
File.WriteAllBytes(path, Content);
}
public string FileName
{
get { return fileName; }
}
public byte[] Content
{
get { return content; }
}
}
[ComVisible(true)]
[Guid("34FD4B0B-CE38-41CE-AB76-4C6234A6C542")]
public interface IMessageToPost
{
string FromBoxId { get; set; }
string FromDepartmentId { get; set; }
string ToBoxId { get; set; }
string ToDepartmentId { get; set; }
bool IsInternal { get; set; }
bool IsDraft { get; set; }
bool LockDraft { get; set; }
bool LockPacket { get; set; }
bool StrictDraftValidation { get; set; }
bool DelaySend { get; set; }
TrustConnectionRequestAttachment TrustConnectionRequest { get; set; }
void AddInvoice([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddXmlTorg12SellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddXmlAcceptanceCertificateSellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddTorg12([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddAcceptanceCertificate([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddProformaInvoice([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddStructuredData([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddPriceList([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddPriceListAgreement([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddCertificateRegistry([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddReconciliationAct([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddContract([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddTorg13([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddServiceDetails([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddSupplementaryAgreement([MarshalAs(UnmanagedType.IDispatch)] object supplementaryAgreement);
void AddUniversalTransferDocumentSellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.MessageToPost")]
[Guid("6EABD544-6DDC-49b4-95A1-0D7936C08C31")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IMessageToPost))]
public partial class MessageToPost : SafeComObject, IMessageToPost
{
//That property was deletes from proto description, but we can't delete this property here because COM need continuous sequence of methods
public TrustConnectionRequestAttachment TrustConnectionRequest
{
get { return null; }
set { }
}
public void AddInvoice(object attachment)
{
Invoices.Add((XmlDocumentAttachment)attachment);
}
public void AddXmlTorg12SellerTitle(object attachment)
{
XmlTorg12SellerTitles.Add((XmlDocumentAttachment)attachment);
}
public void AddXmlAcceptanceCertificateSellerTitle(object attachment)
{
XmlAcceptanceCertificateSellerTitles.Add((XmlDocumentAttachment)attachment);
}
public void AddAttachment(object attachment)
{
NonformalizedDocuments.Add((NonformalizedAttachment)attachment);
}
public void AddTorg12(object attachment)
{
Torg12Documents.Add((BasicDocumentAttachment)attachment);
}
public void AddAcceptanceCertificate(object attachment)
{
AcceptanceCertificates.Add((AcceptanceCertificateAttachment) attachment);
}
public void AddProformaInvoice(object attachment)
{
ProformaInvoices.Add((BasicDocumentAttachment) attachment);
}
public void AddStructuredData(object attachment)
{
StructuredDataAttachments.Add((StructuredDataAttachment) attachment);
}
public void AddPriceList(object attachment)
{
PriceLists.Add((PriceListAttachment) attachment);
}
public void AddPriceListAgreement(object attachment)
{
PriceListAgreements.Add((NonformalizedAttachment) attachment);
}
public void AddCertificateRegistry(object attachment)
{
CertificateRegistries.Add((NonformalizedAttachment) attachment);
}
public void AddReconciliationAct(object attachment)
{
ReconciliationActs.Add((ReconciliationActAttachment) attachment);
}
public void AddContract(object attachment)
{
Contracts.Add((ContractAttachment) attachment);
}
public void AddTorg13(object attachment)
{
Torg13Documents.Add((Torg13Attachment) attachment);
}
public void AddServiceDetails(object attachment)
{
ServiceDetailsDocuments.Add((ServiceDetailsAttachment) attachment);
}
public void AddSupplementaryAgreement(object supplementaryAgreement)
{
SupplementaryAgreements.Add((SupplementaryAgreementAttachment)supplementaryAgreement);
}
public void AddUniversalTransferDocumentSellerTitle(object attachment)
{
UniversalTransferDocumentSellerTitles.Add((XmlDocumentAttachment)attachment);
}
}
[ComVisible(true)]
[Guid("A0C93B1F-5FD2-4738-B8F9-994AE05B5B63")]
public interface ISupplementaryAgreementAttachment
{
SignedContent SignedContent { get; set; }
string FileName { get; set; }
string Comment { get; set; }
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
string CustomDocumentId { get; set; }
string DocumentDate { get; set; }
string DocumentNumber { get; set; }
string Total { get; set; }
string ContractNumber { get; set; }
string ContractDate { get; set; }
string ContractType { get; set; }
bool NeedReceipt { get; set; }
void AddCustomDataItem([MarshalAs(UnmanagedType.IDispatch)] object customDataItem);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.SupplementaryAgreementAttachment")]
[Guid("9AA39127-85C9-4B40-A456-9C18D5BF8348")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ISupplementaryAgreementAttachment))]
public partial class SupplementaryAgreementAttachment : SafeComObject, ISupplementaryAgreementAttachment
{
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId)documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId)documentId);
}
public void AddCustomDataItem(object customDataItem)
{
CustomData.Add((CustomDataItem)customDataItem);
}
}
[ComVisible(true)]
[Guid("0D648002-53CC-4EAB-969B-68364BB4F3CE")]
public interface IMessagePatchToPost
{
string BoxId { get; set; }
string MessageId { get; set; }
void AddReceipt([MarshalAs(UnmanagedType.IDispatch)] object receipt);
void AddCorrectionRequest([MarshalAs(UnmanagedType.IDispatch)] object correctionRequest);
void AddSignature([MarshalAs(UnmanagedType.IDispatch)] object signature);
void AddRequestedSignatureRejection(
[MarshalAs(UnmanagedType.IDispatch)] object signatureRejection);
void AddXmlTorg12BuyerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddXmlAcceptanceCertificateBuyerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddResolution([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddRevocationRequestAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddXmlSignatureRejectionAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddUniversalTransferDocumentBuyerTitleAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddResolutionRouteAssignment([MarshalAs(UnmanagedType.IDispatch)] object attachment);
void AddResolutoinRouteRemoval([MarshalAs(UnmanagedType.IDispatch)] object attachment);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.MessagePatchToPost")]
[Guid("F917FD6D-AEE9-4b21-A79F-11981E805F5D")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IMessagePatchToPost))]
public partial class MessagePatchToPost : SafeComObject, IMessagePatchToPost
{
public void AddReceipt(object receipt)
{
Receipts.Add((ReceiptAttachment)receipt);
}
public void AddCorrectionRequest(object correctionRequest)
{
CorrectionRequests.Add((CorrectionRequestAttachment)correctionRequest);
}
public void AddSignature(object signature)
{
Signatures.Add((DocumentSignature)signature);
}
public void AddRequestedSignatureRejection(object signatureRejection)
{
RequestedSignatureRejections.Add((RequestedSignatureRejection)signatureRejection);
}
public void AddXmlTorg12BuyerTitle(object attachment)
{
XmlTorg12BuyerTitles.Add((ReceiptAttachment)attachment);
}
public void AddXmlAcceptanceCertificateBuyerTitle(object attachment)
{
XmlAcceptanceCertificateBuyerTitles.Add((ReceiptAttachment)attachment);
}
public void AddUniversalTransferDocumentBuyerTitle(object attachment)
{
UniversalTransferDocumentBuyerTitles.Add((ReceiptAttachment)attachment);
}
public void AddResolution(object attachment)
{
Resolutions.Add((ResolutionAttachment)attachment);
}
public void AddResolutionRequestAttachment(object attachment)
{
ResolutionRequests.Add((ResolutionRequestAttachment)attachment);
}
public void AddResolutionRequestCancellationAttachment(object attachment)
{
ResolutionRequestCancellations.Add((ResolutionRequestCancellationAttachment)attachment);
}
public void AddResolutionRequestDenialAttachment(object attachment)
{
ResolutionRequestDenials.Add((ResolutionRequestDenialAttachment)attachment);
}
public void AddResolutionRequestDenialCancellationAttachment(object attachment)
{
ResolutionRequestDenialCancellations.Add((ResolutionRequestDenialCancellationAttachment)attachment);
}
public void AddRevocationRequestAttachment(object attachment)
{
RevocationRequests.Add((RevocationRequestAttachment)attachment);
}
public void AddXmlSignatureRejectionAttachment(object attachment)
{
XmlSignatureRejections.Add((XmlSignatureRejectionAttachment)attachment);
}
public void AddUniversalTransferDocumentBuyerTitleAttachment(object attachment)
{
UniversalTransferDocumentBuyerTitles.Add((ReceiptAttachment)attachment);
}
public void AddResolutionRouteAssignment(object attachment)
{
ResolutionRouteAssignments.Add((ResolutionRouteAssignment)attachment);
}
public void AddResolutoinRouteRemoval(object attachment)
{
ResolutionRouteRemovals.Add((ResolutionRouteRemoval)attachment);
}
}
[ComVisible(true)]
[Guid("10AC1159-A121-4F3E-9437-7CF22A1B60A1")]
public interface IXmlDocumentAttachment
{
string CustomDocumentId { get; set; }
SignedContent SignedContent { get; set; }
string Comment { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.XmlDocumentAttachment")]
[Guid("E6B32174-37DE-467d-A947-B88AEDC2ECEC")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IXmlDocumentAttachment))]
public partial class XmlDocumentAttachment : SafeComObject, IXmlDocumentAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId)documentId);
}
}
[ComVisible(true)]
[Guid("B43D2BF4-E100-4F49-8F8F-D87EA3ECE453")]
public interface INonformalizedAttachment
{
string CustomDocumentId { get; set; }
string FileName { get; set; }
string DocumentNumber { get; set; }
string DocumentDate { get; set; }
bool NeedRecipientSignature { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.NonformalizedAttachment")]
[Guid("9904995A-1EF3-4182-8C3E-61DBEADC159C")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (INonformalizedAttachment))]
public partial class NonformalizedAttachment : SafeComObject, INonformalizedAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId) documentId);
}
}
[ComVisible(true)]
[Guid("8FC16D12-EEE7-44F1-AD9C-ACD907EF286D")]
public interface IBasicDocumentAttachment
{
string CustomDocumentId { get; set; }
string FileName { get; set; }
string DocumentNumber { get; set; }
string DocumentDate { get; set; }
string Total { get; set; }
string Vat { get; set; }
string Grounds { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[Guid("E7DA152C-B651-4F3A-B9D7-25F6E5BABC1D")]
public interface IAcceptanceCertificateAttachment
{
string CustomDocumentId { get; set; }
string FileName { get; set; }
string DocumentNumber { get; set; }
string DocumentDate { get; set; }
string Total { get; set; }
string Vat { get; set; }
string Grounds { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
bool NeedRecipientSignature { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.BasicDocumentAttachment")]
[Guid("776261C4-361D-42BF-929C-8B368DEE917D")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IBasicDocumentAttachment))]
public partial class BasicDocumentAttachment : SafeComObject, IBasicDocumentAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent)signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId)documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId)documentId);
}
}
[ComVisible(true)]
[ProgId("Diadoc.Api.AcceptanceCertificateAttachment")]
[Guid("9BCBE1E4-11C5-45BF-887A-FE63D074D71A")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IAcceptanceCertificateAttachment))]
public partial class AcceptanceCertificateAttachment : SafeComObject, IAcceptanceCertificateAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId) documentId);
}
}
[ComVisible(true)]
[Guid("2860C8D8-72C3-4D83-A3EB-DF36A2A8EB2E")]
public interface ITrustConnectionRequestAttachment
{
string FileName { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.TrustConnectionRequestAttachment")]
[Guid("139BB7DA-D92A-49F0-840A-3FB541323632")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (ITrustConnectionRequestAttachment))]
public partial class TrustConnectionRequestAttachment : SafeComObject, ITrustConnectionRequestAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
}
[ComVisible(true)]
[Guid("DA50195B-0B15-42DB-AFE3-35C1280C9EA6")]
public interface IStructuredDataAttachment
{
string ParentCustomDocumentId { get; set; }
string FileName { get; set; }
byte[] Content { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.StructuredDataAttachment")]
[Guid("E35327B6-F774-476A-93B4-CC68DE7432D1")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IStructuredDataAttachment))]
public partial class StructuredDataAttachment : SafeComObject, IStructuredDataAttachment
{
}
[ComVisible(true)]
[Guid("4D8D636A-91D8-4734-8371-913E144FED66")]
public interface ISignedContent
{
byte[] Content { get; set; }
byte[] Signature { get; set; }
[Obsolete]
bool SignByAttorney { get; set; }
bool SignWithTestSignature { get; set; }
string NameOnShelf { get; set; }
void LoadContentFromFile(string fileName);
void SaveContentToFile(string fileName);
void LoadSignatureFromFile(string fileName);
void SaveSignatureToFile(string fileName);
}
[ComVisible(true)]
[Guid("A42D43EB-C083-4765-86C2-A5BD7DE58C3E")]
public interface IPriceListAttachment
{
string CustomDocumentId { get; set; }
string FileName { get; set; }
string DocumentNumber { get; set; }
string DocumentDate { get; set; }
string PriceListEffectiveDate { get; set; }
string ContractDocumentDate { get; set; }
string ContractDocumentNumber { get; set; }
string Comment { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.PriceListAttachment")]
[Guid("2D0A054F-E3FA-4FBD-A64F-9C4EB73901BB")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IPriceListAttachment))]
public partial class PriceListAttachment : SafeComObject, IPriceListAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void AddInitialDocumentId(object documentId)
{
InitialDocumentIds.Add((DocumentId) documentId);
}
public void AddSubordinateDocumentId(object documentId)
{
SubordinateDocumentIds.Add((DocumentId) documentId);
}
}
[ComVisible(true)]
[ProgId("Diadoc.Api.SignedContent")]
[Guid("0EC71E3F-F203-4c49-B1D6-4DA6BFDD279B")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (ISignedContent))]
public partial class SignedContent : SafeComObject, ISignedContent
{
public bool SignByAttorney
{
get { return false; }
set { }
}
public void LoadContentFromFile(string fileName)
{
Content = File.ReadAllBytes(fileName);
}
public void SaveContentToFile(string fileName)
{
if (Content != null)
File.WriteAllBytes(fileName, Content);
}
public void LoadSignatureFromFile(string fileName)
{
Signature = File.ReadAllBytes(fileName);
}
public void SaveSignatureToFile(string fileName)
{
File.WriteAllBytes(fileName, Signature);
}
}
[ComVisible(true)]
[Guid("BD1E9A9B-E74C-41AD-94CE-199601346DDB")]
public interface IDocumentSignature
{
string ParentEntityId { get; set; }
byte[] Signature { get; set; }
[Obsolete]
bool SignByAttorney { get; set; }
bool SignWithTestSignature { get; set; }
void LoadFromFile(string fileName);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DocumentSignature")]
[Guid("28373DE6-3147-4d8b-B166-6D653F50EED3")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IDocumentSignature))]
public partial class DocumentSignature : SafeComObject, IDocumentSignature
{
public bool SignByAttorney
{
get { return false; }
set { }
}
public void LoadFromFile(string fileName)
{
Signature = File.ReadAllBytes(fileName);
}
}
[ComVisible(true)]
[Guid("F60296C5-6981-48A7-9E93-72B819B81172")]
public interface IRequestedSignatureRejection
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
void LoadComment(string commentFileName, string signatureFileName);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.RequestedSignatureRejection")]
[Guid("C0106095-AF9F-462A-AEC0-A3E0B1ACAC6B")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IRequestedSignatureRejection))]
public partial class RequestedSignatureRejection : SafeComObject, IRequestedSignatureRejection
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
public void LoadComment(string commentFileName, string signatureFileName)
{
SignedContent = new SignedContent
{
Content = File.ReadAllBytes(commentFileName),
Signature = File.ReadAllBytes(signatureFileName),
};
}
}
[ComVisible(true)]
[Guid("8E18ECC8-18B4-4A9C-B322-1CF03DB3E07F")]
public interface IReceiptAttachment
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ReceiptAttachment")]
[Guid("45053335-83C3-4e62-9973-D6CC1872A60A")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IReceiptAttachment))]
public partial class ReceiptAttachment : SafeComObject, IReceiptAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
}
[ComVisible(true)]
[Guid("5902A325-F31B-4B9B-978E-99C1CC7C9209")]
public interface IResolutionAttachment
{
string InitialDocumentId { get; set; }
Com.ResolutionType ResolutionTypeValue { get; set; }
string Comment { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionAttachment")]
[Guid("89D739B0-03F1-4E6C-8301-E3FEA9FD2AD6")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionAttachment))]
public partial class ResolutionAttachment : SafeComObject, IResolutionAttachment
{
public Com.ResolutionType ResolutionTypeValue
{
get { return (Com.ResolutionType) ResolutionType; }
set { ResolutionType = (ResolutionType) value; }
}
}
[ComVisible(true)]
[Guid("F19CEEBD-ECE5-49D2-A0FC-FE8C4B1B9E4C")]
public interface IResolutionRequestAttachment
{
string InitialDocumentId { get; set; }
Com.ResolutionRequestType RequestType { get; set; }
string TargetUserId { get; set; }
string TargetDepartmentId { get; set; }
string Comment { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRequest")]
[Guid("6043455B-3087-4A63-9870-66D54E8E34FB")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionRequestAttachment))]
public partial class ResolutionRequestAttachment : SafeComObject, IResolutionRequestAttachment
{
public Com.ResolutionRequestType RequestType
{
get { return (Com.ResolutionRequestType) Type; }
set { Type = (ResolutionRequestType) value; }
}
}
[ComVisible(true)]
[Guid("F23FCA9D-4FD3-4AE7-A431-275CAB51C7A1")]
public interface IResolutionRequestCancellationAttachment
{
string InitialResolutionRequestId { get; set; }
string Comment { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRequestCancellation")]
[Guid("E80B8699-9883-4259-AA67-B84B03DD5F09")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionRequestCancellationAttachment))]
public partial class ResolutionRequestCancellationAttachment : SafeComObject, IResolutionRequestCancellationAttachment
{
}
[ComVisible(true)]
[Guid("96F3613E-9DAA-4F2E-B8AB-7A8895D9E3AE")]
public interface IResolutionRequestDenialAttachment
{
string InitialResolutionRequestId { get; set; }
string Comment { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRequestDenial")]
[Guid("BD79962A-D6AC-4831-9498-162C36AFD6E1")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionRequestDenialAttachment))]
public partial class ResolutionRequestDenialAttachment : SafeComObject, IResolutionRequestDenialAttachment
{
}
[ComVisible(true)]
[Guid("39F44156-E889-4EFB-9368-350D1ED40B2F")]
public interface IResolutionRequestDenialCancellationAttachment
{
string InitialResolutionRequestDenialId { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRequestDenialCancellation")]
[Guid("4E8A0DEF-B6F7-4820-9CBE-D94A38E34DFC")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IResolutionRequestDenialCancellationAttachment))]
public partial class ResolutionRequestDenialCancellationAttachment : SafeComObject,
IResolutionRequestDenialCancellationAttachment
{
}
[ComVisible(true)]
[Guid("4BA8315A-FDAA-4D4F-BB14-9707E12DFA39")]
public interface ICorrectionRequestAttachment
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.CorrectionRequestAttachment")]
[Guid("D78FC023-2BEF-49a4-BDBE-3B791168CE98")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (ICorrectionRequestAttachment))]
public partial class CorrectionRequestAttachment : SafeComObject, ICorrectionRequestAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent)signedContent;
}
}
[ComVisible(true)]
[Guid("D9B32F6D-C203-49DB-B224-6B30BB1F2BAA")]
public interface IDocumentSenderSignature
{
string ParentEntityId { get; set; }
byte[] Signature { get; set; }
bool SignWithTestSignature { get; set; }
void LoadFromFile(string fileName);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DocumentSenderSignature")]
[Guid("19CB816D-F518-4E91-94A2-F19B0CF7CC71")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDocumentSenderSignature))]
public partial class DocumentSenderSignature : SafeComObject, IDocumentSenderSignature
{
public void LoadFromFile(string fileName)
{
Signature = File.ReadAllBytes(fileName);
}
}
[ComVisible(true)]
[Guid("BDCD849E-F6A9-4EA4-8B84-482E10173DED")]
public interface IDraftToSend
{
string BoxId { get; set; }
string DraftId { get; set; }
string ToBoxId { get; set; }
string ToDepartmentId { get; set; }
void AddDocumentSignature([MarshalAs(UnmanagedType.IDispatch)] object signature);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.DraftToSend")]
[Guid("37127975-95FC-4247-8393-052EF27D1575")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IDraftToSend))]
public partial class DraftToSend : SafeComObject, IDraftToSend
{
public void AddDocumentSignature(object signature)
{
DocumentSignatures.Add((DocumentSenderSignature) signature);
}
}
[ComVisible(true)]
[Guid("0A28FEDA-8108-49CE-AC56-31B16B2D036B")]
public interface IRevocationRequestAttachment
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.RevocationRequestAttachment")]
[Guid("D2616BCD-A691-42B5-9707-6CE12742C5D3")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IRevocationRequestAttachment))]
public partial class RevocationRequestAttachment : SafeComObject, IRevocationRequestAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent)signedContent;
}
}
[ComVisible(true)]
[Guid("4EED1BE6-7136-4B46-86C7-44F9A0FFD530")]
public interface IXmlSignatureRejectionAttachment
{
string ParentEntityId { get; set; }
SignedContent SignedContent { get; set; }
void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.XmlSignatureRejectionAttachment")]
[Guid("553DC13F-81B4-4010-886C-260DBD60D486")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof (IXmlSignatureRejectionAttachment))]
public partial class XmlSignatureRejectionAttachment : SafeComObject, IXmlSignatureRejectionAttachment
{
public void SetSignedContent(object signedContent)
{
SignedContent = (SignedContent) signedContent;
}
}
[ComVisible(true)]
[Guid("1B7169E9-455A-47C8-BD0F-5227B436CC61")]
public interface IResolutionRouteAssignment
{
string InitialDocumentId { get; set; }
string RouteId { get; set; }
string Comment { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRouteAssignment")]
[Guid("B4C90587-3DB9-4BFB-84A0-E1A8E082978D")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IResolutionRouteAssignment))]
public partial class ResolutionRouteAssignment : SafeComObject, IResolutionRouteAssignment
{
}
[ComVisible(true)]
[Guid("DBCE6766-25F7-4EAB-9C4F-C59AB0054E57")]
public interface IResolutionRouteRemoval
{
string ParentEntityId { get; set; }
string RouteId { get; set; }
string Comment { get; set; }
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ResolutionRouteRemoval")]
[Guid("F1356D51-625B-4A24-AF11-3402D72908C8")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IResolutionRouteRemoval))]
public partial class ResolutionRouteRemoval : SafeComObject, IResolutionRouteRemoval
{
}
[ComVisible(true)]
[Guid("12A46076-9F0F-4E89-8E49-68E3C5FC8C04")]
public interface IResolutionRouteAssignmentInfo
{
string RouteId { get; }
string Author { get; }
}
[ComVisible(true)]
[Guid("AF775D73-D1BB-40C7-9DF5-D0305B606DC7")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IResolutionRouteAssignmentInfo))]
public partial class ResolutionRouteAssignmentInfo : SafeComObject, IResolutionRouteAssignmentInfo
{
}
[ComVisible(true)]
[Guid("180C7D5E-7E8B-48ED-BAA4-AAA29D9467CC")]
public interface IResolutionRouteRemovalInfo
{
string RouteId { get; }
string Author { get; }
}
[ComVisible(true)]
[Guid("AAB466D3-6BF3-4DB4-B7C9-DA7BD8F74837")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IResolutionRouteRemovalInfo))]
public partial class ResolutionRouteRemovalInfo : SafeComObject, IResolutionRouteRemovalInfo
{
}
}
| |
//
// Lazy.cs
//
// Authors:
// Zoltan Varga (vargaz@gmail.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (C) 2009 Novell
//
// 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 NET20 || NET35
using System;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading;
using System.Diagnostics;
namespace System
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
[SerializableAttribute]
[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
[DebuggerDisplay ("ThreadSafetyMode={mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={exception != null}, Value={value}")]
internal class Lazy<T>
{
T value;
Func<T> factory;
readonly object monitor;
Exception exception;
readonly LazyThreadSafetyMode mode;
bool inited;
/// <summary>
///
/// </summary>
public Lazy ()
: this (LazyThreadSafetyMode.ExecutionAndPublication)
{
}
/// <summary>
///
/// </summary>
/// <param name="valueFactory"></param>
public Lazy (Func<T> valueFactory)
: this (valueFactory, LazyThreadSafetyMode.ExecutionAndPublication)
{
}
/// <summary>
///
/// </summary>
/// <param name="isThreadSafe"></param>
public Lazy (bool isThreadSafe)
: this (Activator.CreateInstance<T>, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
{
}
/// <summary>
///
/// </summary>
/// <param name="valueFactory"></param>
/// <param name="isThreadSafe"></param>
public Lazy (Func<T> valueFactory, bool isThreadSafe)
: this (valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
{
}
/// <summary>
///
/// </summary>
/// <param name="mode"></param>
public Lazy (LazyThreadSafetyMode mode)
: this (Activator.CreateInstance<T>, mode)
{
}
/// <summary>
///
/// </summary>
/// <param name="valueFactory"></param>
/// <param name="mode"></param>
public Lazy (Func<T> valueFactory, LazyThreadSafetyMode mode)
{
if (valueFactory == null)
throw new ArgumentNullException ("valueFactory");
this.factory = valueFactory;
if (mode != LazyThreadSafetyMode.None)
monitor = new object ();
this.mode = mode;
}
/// <summary>
///
/// </summary>
// Don't trigger expensive initialization
[DebuggerBrowsable (DebuggerBrowsableState.Never)]
public T Value {
get {
if (inited)
return value;
if (exception != null)
throw exception;
return InitValue ();
}
}
T InitValue ()
{
Func<T> init_factory;
T v;
switch (mode) {
case LazyThreadSafetyMode.None:
init_factory = factory;
if (init_factory == null) {
if (exception == null)
throw new InvalidOperationException ("The initialization function tries to access Value on this instance");
throw exception;
}
try {
factory = null;
v = init_factory ();
value = v;
Thread.MemoryBarrier ();
inited = true;
} catch (Exception ex) {
exception = ex;
throw;
}
break;
case LazyThreadSafetyMode.PublicationOnly:
init_factory = factory;
//exceptions are ignored
if (init_factory != null)
v = init_factory ();
else
v = default (T);
lock (monitor) {
if (inited)
return value;
value = v;
Thread.MemoryBarrier ();
inited = true;
factory = null;
}
break;
case LazyThreadSafetyMode.ExecutionAndPublication:
lock (monitor) {
if (inited)
return value;
if (factory == null) {
if (exception == null)
throw new InvalidOperationException ("The initialization function tries to access Value on this instance");
throw exception;
}
init_factory = factory;
try {
factory = null;
v = init_factory ();
value = v;
Thread.MemoryBarrier ();
inited = true;
} catch (Exception ex) {
exception = ex;
throw;
}
}
break;
default:
throw new InvalidOperationException ("Invalid LazyThreadSafetyMode " + mode);
}
return value;
}
/// <summary>
///
/// </summary>
public bool IsValueCreated {
get {
return inited;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString ()
{
if (inited)
return value.ToString ();
else
return "Value is not created";
}
}
}
#endif
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.fx.effect.core
{
/// <summary>
/// <para>Core effect “Scale”</para>
/// <para>This effect scales the specified element (and its content, optionally) by given percentages.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.fx.effect.core.Scale", OmitOptionalParameters = true, Export = false)]
public partial class Scale : qx.fx.Base
{
#region Properties
/// <summary>
/// <para>Array containing sizes which will instead of element’s dimensions, if filled.</para>
/// </summary>
[JsProperty(Name = "alternateDimensions", NativeField = true)]
public JsArray AlternateDimensions { get; set; }
/// <summary>
/// <para>Flag indicating if element’s original dimensions should be restored
/// after effect’s runtime.</para>
/// </summary>
[JsProperty(Name = "restoreAfterFinish", NativeField = true)]
public bool RestoreAfterFinish { get; set; }
/// <summary>
/// <para>Flag indicating if element’s content (font size) should be scaled.</para>
/// </summary>
[JsProperty(Name = "scaleContent", NativeField = true)]
public bool ScaleContent { get; set; }
/// <summary>
/// <para>Percentage the elements dimensions should be scaled from.</para>
/// </summary>
[JsProperty(Name = "scaleFrom", NativeField = true)]
public double ScaleFrom { get; set; }
/// <summary>
/// <para>Flag indicating if element should be scaled
/// from center (upper left corner otherwise).</para>
/// </summary>
[JsProperty(Name = "scaleFromCenter", NativeField = true)]
public bool ScaleFromCenter { get; set; }
/// <summary>
/// <para>Percentage the elements dimensions should be scaled to.</para>
/// </summary>
[JsProperty(Name = "scaleTo", NativeField = true)]
public double ScaleTo { get; set; }
/// <summary>
/// <para>Flag indicating if element’s width should be scaled.</para>
/// </summary>
[JsProperty(Name = "scaleX", NativeField = true)]
public bool ScaleX { get; set; }
/// <summary>
/// <para>Flag indicating if element’s height should be scaled.</para>
/// </summary>
[JsProperty(Name = "scaleY", NativeField = true)]
public bool ScaleY { get; set; }
#endregion Properties
#region Methods
public Scale() { throw new NotImplementedException(); }
public Scale(object element) { throw new NotImplementedException(); }
/// <summary>
/// <para>This internal function is called
/// when the effect has finished.</para>
/// <para>Fires “finish” event.</para>
/// </summary>
[JsMethod(Name = "finish")]
public void Finish() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property alternateDimensions.</para>
/// </summary>
[JsMethod(Name = "getAlternateDimensions")]
public JsArray GetAlternateDimensions() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property restoreAfterFinish.</para>
/// </summary>
[JsMethod(Name = "getRestoreAfterFinish")]
public bool GetRestoreAfterFinish() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property scaleContent.</para>
/// </summary>
[JsMethod(Name = "getScaleContent")]
public bool GetScaleContent() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property scaleFrom.</para>
/// </summary>
[JsMethod(Name = "getScaleFrom")]
public double GetScaleFrom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property scaleFromCenter.</para>
/// </summary>
[JsMethod(Name = "getScaleFromCenter")]
public bool GetScaleFromCenter() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property scaleTo.</para>
/// </summary>
[JsMethod(Name = "getScaleTo")]
public double GetScaleTo() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property scaleX.</para>
/// </summary>
[JsMethod(Name = "getScaleX")]
public bool GetScaleX() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property scaleY.</para>
/// </summary>
[JsMethod(Name = "getScaleY")]
public bool GetScaleY() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property alternateDimensions
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property alternateDimensions.</param>
[JsMethod(Name = "initAlternateDimensions")]
public void InitAlternateDimensions(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property restoreAfterFinish
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property restoreAfterFinish.</param>
[JsMethod(Name = "initRestoreAfterFinish")]
public void InitRestoreAfterFinish(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property scaleContent
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property scaleContent.</param>
[JsMethod(Name = "initScaleContent")]
public void InitScaleContent(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property scaleFrom
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property scaleFrom.</param>
[JsMethod(Name = "initScaleFrom")]
public void InitScaleFrom(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property scaleFromCenter
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property scaleFromCenter.</param>
[JsMethod(Name = "initScaleFromCenter")]
public void InitScaleFromCenter(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property scaleTo
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property scaleTo.</param>
[JsMethod(Name = "initScaleTo")]
public void InitScaleTo(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property scaleX
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property scaleX.</param>
[JsMethod(Name = "initScaleX")]
public void InitScaleX(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property scaleY
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property scaleY.</param>
[JsMethod(Name = "initScaleY")]
public void InitScaleY(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property restoreAfterFinish equals true.</para>
/// </summary>
[JsMethod(Name = "isRestoreAfterFinish")]
public void IsRestoreAfterFinish() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property scaleContent equals true.</para>
/// </summary>
[JsMethod(Name = "isScaleContent")]
public void IsScaleContent() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property scaleFromCenter equals true.</para>
/// </summary>
[JsMethod(Name = "isScaleFromCenter")]
public void IsScaleFromCenter() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property scaleX equals true.</para>
/// </summary>
[JsMethod(Name = "isScaleX")]
public void IsScaleX() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property scaleY equals true.</para>
/// </summary>
[JsMethod(Name = "isScaleY")]
public void IsScaleY() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property alternateDimensions.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetAlternateDimensions")]
public void ResetAlternateDimensions() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property restoreAfterFinish.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetRestoreAfterFinish")]
public void ResetRestoreAfterFinish() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property scaleContent.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetScaleContent")]
public void ResetScaleContent() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property scaleFrom.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetScaleFrom")]
public void ResetScaleFrom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property scaleFromCenter.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetScaleFromCenter")]
public void ResetScaleFromCenter() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property scaleTo.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetScaleTo")]
public void ResetScaleTo() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property scaleX.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetScaleX")]
public void ResetScaleX() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property scaleY.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetScaleY")]
public void ResetScaleY() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property alternateDimensions.</para>
/// </summary>
/// <param name="value">New value for property alternateDimensions.</param>
[JsMethod(Name = "setAlternateDimensions")]
public void SetAlternateDimensions(JsArray value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property restoreAfterFinish.</para>
/// </summary>
/// <param name="value">New value for property restoreAfterFinish.</param>
[JsMethod(Name = "setRestoreAfterFinish")]
public void SetRestoreAfterFinish(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property scaleContent.</para>
/// </summary>
/// <param name="value">New value for property scaleContent.</param>
[JsMethod(Name = "setScaleContent")]
public void SetScaleContent(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property scaleFrom.</para>
/// </summary>
/// <param name="value">New value for property scaleFrom.</param>
[JsMethod(Name = "setScaleFrom")]
public void SetScaleFrom(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property scaleFromCenter.</para>
/// </summary>
/// <param name="value">New value for property scaleFromCenter.</param>
[JsMethod(Name = "setScaleFromCenter")]
public void SetScaleFromCenter(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property scaleTo.</para>
/// </summary>
/// <param name="value">New value for property scaleTo.</param>
[JsMethod(Name = "setScaleTo")]
public void SetScaleTo(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property scaleX.</para>
/// </summary>
/// <param name="value">New value for property scaleX.</param>
[JsMethod(Name = "setScaleX")]
public void SetScaleX(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property scaleY.</para>
/// </summary>
/// <param name="value">New value for property scaleY.</param>
[JsMethod(Name = "setScaleY")]
public void SetScaleY(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>This internal function is called
/// before the effect starts to configure
/// the element or prepare other effects.</para>
/// <para>Fires “setup” event.</para>
/// </summary>
[JsMethod(Name = "setup")]
public void Setup() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property restoreAfterFinish.</para>
/// </summary>
[JsMethod(Name = "toggleRestoreAfterFinish")]
public void ToggleRestoreAfterFinish() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property scaleContent.</para>
/// </summary>
[JsMethod(Name = "toggleScaleContent")]
public void ToggleScaleContent() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property scaleFromCenter.</para>
/// </summary>
[JsMethod(Name = "toggleScaleFromCenter")]
public void ToggleScaleFromCenter() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property scaleX.</para>
/// </summary>
[JsMethod(Name = "toggleScaleX")]
public void ToggleScaleX() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property scaleY.</para>
/// </summary>
[JsMethod(Name = "toggleScaleY")]
public void ToggleScaleY() { throw new NotImplementedException(); }
/// <summary>
/// <para>This internal function is called
/// each time the effect performs an
/// step of the animation.</para>
/// <para>Sub classes will overwrite this to
/// perform the actual changes on element
/// properties.</para>
/// </summary>
/// <param name="position">Animation setup as Number between 0 and 1.</param>
[JsMethod(Name = "update")]
public void Update(double position) { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Lucene.Net.Index;
using Lucene.Net.Linq;
using Lucene.Net.Linq.Abstractions;
using Lucene.Net.Search;
using NuGet.Lucene.Util;
#if NET_4_5
using TaskEx=System.Threading.Tasks.Task;
#endif
namespace NuGet.Lucene
{
public class PackageIndexer : IPackageIndexer, IDisposable
{
public static ILog Log = LogManager.GetLogger<PackageIndexer>();
#if NET_4_5
private static readonly TimeSpan InfiniteTimeSpan = Timeout.InfiniteTimeSpan;
#else
private static readonly TimeSpan InfiniteTimeSpan = TimeSpan.FromMilliseconds(-1);
#endif
private enum UpdateType { Add, Remove, RemoveByPath, Increment }
private class Update
{
private readonly LucenePackage package;
private readonly UpdateType updateType;
private readonly TaskCompletionSource<object> signal = new TaskCompletionSource<object>();
public Update(LucenePackage package, UpdateType updateType)
{
this.package = package;
this.updateType = updateType;
}
public LucenePackage Package
{
get { return package; }
}
public UpdateType UpdateType
{
get { return updateType; }
}
public Task Task
{
get
{
return signal.Task;
}
}
public void SetComplete()
{
if (!signal.Task.IsCompleted)
{
signal.SetResult(null);
}
}
public void SetException(Exception exception)
{
signal.SetException(exception);
}
}
private volatile IndexingState indexingState = IndexingState.Idle;
private readonly object synchronizationStatusLock = new object();
private volatile SynchronizationStatus synchronizationStatus = new SynchronizationStatus(SynchronizationState.Idle);
private readonly BlockingCollection<Update> pendingUpdates = new BlockingCollection<Update>();
private Task indexUpdaterTask;
private readonly TaskPoolScheduler eventScheduler = TaskPoolScheduler.Default;
public IFileSystem FileSystem { get; set; }
public IIndexWriter Writer { get; set; }
public LuceneDataProvider Provider { get; set; }
public ILucenePackageRepository PackageRepository { get; set; }
private event EventHandler statusChanged;
public void Initialize()
{
indexUpdaterTask = Task.Factory.StartNew(IndexUpdateLoop, TaskCreationOptions.LongRunning);
}
public void Dispose()
{
pendingUpdates.CompleteAdding();
indexUpdaterTask.Wait();
}
/// <summary>
/// Gets status of index building activity.
/// </summary>
public IndexingStatus GetIndexingStatus()
{
return new IndexingStatus(indexingState, synchronizationStatus);
}
public IObservable<IndexingStatus> StatusChanged
{
get
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
eh => eh.Invoke,
eh => statusChanged += eh,
eh => statusChanged -= eh)
.Select(_ => GetIndexingStatus());
}
}
public void Optimize()
{
using (UpdateStatus(IndexingState.Optimizing))
{
Writer.Optimize();
}
}
public async Task SynchronizeIndexWithFileSystem(CancellationToken cancellationToken)
{
lock (synchronizationStatusLock)
{
if (synchronizationStatus.SynchronizationState != SynchronizationState.Idle)
{
throw new InvalidOperationException("Already running");
}
UpdateSynchronizationStatus(SynchronizationState.ScanningFiles);
}
try
{
IndexDifferences differences = null;
await TaskEx.Run(() => differences = IndexDifferenceCalculator.FindDifferences(
FileSystem, PackageRepository.LucenePackages, cancellationToken, UpdateSynchronizationStatus), cancellationToken);
await TaskEx.Run(() => SynchronizeIndexWithFileSystem(differences, cancellationToken));
}
finally
{
UpdateSynchronizationStatus(SynchronizationState.Idle);
}
}
public Task AddPackage(LucenePackage package)
{
var update = new Update(package, UpdateType.Add);
pendingUpdates.Add(update);
return update.Task;
}
public Task RemovePackage(IPackage package)
{
if (!(package is LucenePackage)) throw new ArgumentException("Package of type " + package.GetType() + " not supported.");
var update = new Update((LucenePackage)package, UpdateType.Remove);
pendingUpdates.Add(update);
return update.Task;
}
public Task IncrementDownloadCount(IPackage package)
{
if (!(package is LucenePackage)) throw new ArgumentException("Package of type " + package.GetType() + " not supported.");
if (string.IsNullOrWhiteSpace(package.Id))
{
throw new InvalidOperationException("Package Id must be specified.");
}
if (package.Version == null)
{
throw new InvalidOperationException("Package Version must be specified.");
}
var update = new Update((LucenePackage) package, UpdateType.Increment);
pendingUpdates.Add(update);
return update.Task;
}
internal void SynchronizeIndexWithFileSystem(IndexDifferences diff, CancellationToken cancellationToken)
{
if (diff.IsEmpty) return;
var tasks = new ConcurrentQueue<Task>();
Log.Info(string.Format("Updates to process: {0} packages added, {1} packages updated, {2} packages removed.", diff.NewPackages.Count(), diff.ModifiedPackages.Count(), diff.MissingPackages.Count()));
foreach (var path in diff.MissingPackages)
{
cancellationToken.ThrowIfCancellationRequested();
var package = new LucenePackage(FileSystem) { Path = path };
var update = new Update(package, UpdateType.RemoveByPath);
pendingUpdates.Add(update);
tasks.Enqueue(update.Task);
}
var pathsToIndex = diff.NewPackages.Union(diff.ModifiedPackages).OrderBy(p => p).ToArray();
var packagesToIndex = pathsToIndex.Length;
var i = 0;
Parallel.ForEach(pathsToIndex, new ParallelOptions {MaxDegreeOfParallelism = 4, CancellationToken = cancellationToken}, (p, s) =>
{
UpdateSynchronizationStatus(SynchronizationState.Indexing, Interlocked.Increment(ref i),
packagesToIndex);
tasks.Enqueue(SynchronizePackage(p));
});
Task.WaitAll(tasks.ToArray(), cancellationToken);
}
private Task SynchronizePackage(string path)
{
try
{
var package = PackageRepository.LoadFromFileSystem(path);
return AddPackage(package);
}
catch (Exception ex)
{
Log.Error("Failed to index package path: " + path, ex);
return TaskEx.FromResult(ex);
}
}
private void IndexUpdateLoop()
{
var items = new List<Update>();
while (!pendingUpdates.IsCompleted)
{
items.Clear();
try
{
pendingUpdates.TakeAvailable(items, InfiniteTimeSpan);
}
catch (OperationCanceledException)
{
}
if (items.Any())
{
ApplyUpdates(items);
}
}
Log.Info("Update task shutting down.");
}
private void ApplyUpdates(List<Update> items)
{
Log.Info(m => m("Processing {0} updates.", items.Count()));
using (var session = OpenSession())
{
using (UpdateStatus(IndexingState.Updating))
{
var removals =
items.Where(i => i.UpdateType == UpdateType.Remove).ToList();
removals.ForEach(pkg => RemovePackageInternal(pkg, session));
var removalsByPath =
items.Where(i => i.UpdateType == UpdateType.RemoveByPath).ToList();
RemovePackagesByPath(removalsByPath, session);
var additions = items.Where(i => i.UpdateType == UpdateType.Add).ToList();
ApplyPendingAdditions(additions, session);
var downloadUpdates =
items.Where(i => i.UpdateType == UpdateType.Increment).Select(i => i.Package).ToList();
ApplyPendingDownloadIncrements(downloadUpdates, session);
}
using (UpdateStatus(IndexingState.Committing))
{
session.Commit();
items.ForEach(i => i.SetComplete());
}
}
}
private static void RemovePackagesByPath(IEnumerable<Update> removalsByPath, ISession<LucenePackage> session)
{
var deleteQueries = removalsByPath.Select(p => (Query) new TermQuery(new Term("Path", p.Package.Path))).ToArray();
session.Delete(deleteQueries);
}
private void ApplyPendingAdditions(List<Update> additions, ISession<LucenePackage> session)
{
foreach (var grouping in additions.GroupBy(update => update.Package.Id))
{
try
{
AddPackagesInternal(grouping.Key, grouping.Select(p => p.Package).ToList(), session);
}
catch (Exception ex)
{
additions.ForEach(i => i.SetException(ex));
}
}
}
private void AddPackagesInternal(string packageId, IEnumerable<LucenePackage> packages, ISession<LucenePackage> session)
{
var currentPackages = (from p in session.Query()
where p.Id == packageId
orderby p.Version descending
select p).ToList();
var newest = currentPackages.FirstOrDefault();
var versionDownloadCount = newest != null ? newest.VersionDownloadCount : 0;
foreach (var package in packages)
{
var packageToReplace = currentPackages.Find(p => p.Version == package.Version);
package.VersionDownloadCount = versionDownloadCount;
package.DownloadCount = packageToReplace != null ? packageToReplace.DownloadCount : 0;
if (packageToReplace != null)
{
currentPackages.Remove(packageToReplace);
session.Delete(packageToReplace);
}
currentPackages.Add(package);
session.Add(package);
}
UpdatePackageVersionFlags(currentPackages.OrderByDescending(p => p.Version));
}
private void RemovePackageInternal(Update update, ISession<LucenePackage> session)
{
try
{
session.Delete(update.Package);
var remainingPackages = from p in session.Query()
where p.Id == update.Package.Id
orderby p.Version descending
select p;
UpdatePackageVersionFlags(remainingPackages);
}
catch (Exception e)
{
update.SetException(e);
}
}
private void UpdatePackageVersionFlags(IEnumerable<LucenePackage> packages)
{
var first = true;
var firstNonPreRelease = true;
foreach (var p in packages)
{
if (!p.IsPrerelease && firstNonPreRelease)
{
p.IsLatestVersion = true;
firstNonPreRelease = false;
}
else
{
p.IsLatestVersion = false;
}
p.IsAbsoluteLatestVersion = first;
if (first)
{
first = false;
}
}
}
public void ApplyPendingDownloadIncrements(IList<LucenePackage> increments, ISession<LucenePackage> session)
{
if (increments.Count == 0) return;
var byId = increments.ToLookup(p => p.Id);
foreach (var grouping in byId)
{
var packageId = grouping.Key;
var packages = from p in session.Query() where p.Id == packageId select p;
var byVersion = grouping.ToLookup(p => p.Version);
foreach (var lucenePackage in packages)
{
lucenePackage.DownloadCount += grouping.Count();
lucenePackage.VersionDownloadCount += byVersion[lucenePackage.Version].Count();
}
}
}
protected internal virtual ISession<LucenePackage> OpenSession()
{
return Provider.OpenSession(() => new LucenePackage(FileSystem));
}
private void UpdateSynchronizationStatus(SynchronizationState state)
{
UpdateSynchronizationStatus(state, 0, 0);
}
private void UpdateSynchronizationStatus(SynchronizationState state, int completedPackages, int packagesToIndex)
{
synchronizationStatus = new SynchronizationStatus(
state,
completedPackages,
packagesToIndex
);
RaiseStatusChanged();
}
private IDisposable UpdateStatus(IndexingState state)
{
var prev = indexingState;
indexingState = state;
RaiseStatusChanged();
return new DisposableAction(() =>
{
indexingState = prev;
RaiseStatusChanged();
});
}
private void RaiseStatusChanged()
{
var tmp = statusChanged;
if (tmp != null)
{
eventScheduler.Schedule(() => tmp(this, new EventArgs()));
}
}
}
}
| |
// 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 Microsoft.Xml
{
using System;
using System.IO;
using System.Resources;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
/// <devdoc>
/// <para>Returns detailed information about the last parse error, including the error
/// number, line number, character position, and a text description.</para>
/// </devdoc>
public class XmlException : System.Exception
{
private string _res;
private string[] _args; // this field is not used, it's here just V1.1 serialization compatibility
private int _lineNumber;
private int _linePosition;
private string _sourceUri;
// message != null for V1 exceptions deserialized in Whidbey
// message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message)
private string _message = null;
//provided to meet the ECMA standards
public XmlException() : this(null)
{
}
//provided to meet the ECMA standards
public XmlException(String message) : this(message, ((Exception)null), 0, 0)
{
#if DEBUG
Debug.Assert(message == null || !message.StartsWith("Xml_", StringComparison.Ordinal), "Do not pass a resource here!");
#endif
}
//provided to meet ECMA standards
public XmlException(String message, Exception innerException) : this(message, innerException, 0, 0)
{
}
//provided to meet ECMA standards
public XmlException(String message, Exception innerException, int lineNumber, int linePosition) :
this(message, innerException, lineNumber, linePosition, null)
{
}
internal XmlException(String message, Exception innerException, int lineNumber, int linePosition, string sourceUri) :
base(FormatUserMessage(message, lineNumber, linePosition), innerException)
{
HResult = HResults.Xml;
_res = (message == null ? ResXml.Xml_DefaultException : ResXml.Xml_UserException);
_args = new string[] { message };
_sourceUri = sourceUri;
_lineNumber = lineNumber;
_linePosition = linePosition;
}
internal XmlException(string res, string[] args) :
this(res, args, null, 0, 0, null)
{ }
internal XmlException(string res, string[] args, string sourceUri) :
this(res, args, null, 0, 0, sourceUri)
{ }
internal XmlException(string res, string arg) :
this(res, new string[] { arg }, null, 0, 0, null)
{ }
internal XmlException(string res, string arg, string sourceUri) :
this(res, new string[] { arg }, null, 0, 0, sourceUri)
{ }
internal XmlException(string res, String arg, IXmlLineInfo lineInfo) :
this(res, new string[] { arg }, lineInfo, null)
{ }
internal XmlException(string res, String arg, Exception innerException, IXmlLineInfo lineInfo) :
this(res, new string[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null)
{ }
internal XmlException(string res, String arg, IXmlLineInfo lineInfo, string sourceUri) :
this(res, new string[] { arg }, lineInfo, sourceUri)
{ }
internal XmlException(string res, string[] args, IXmlLineInfo lineInfo) :
this(res, args, lineInfo, null)
{ }
internal XmlException(string res, string[] args, IXmlLineInfo lineInfo, string sourceUri) :
this(res, args, null, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), sourceUri)
{
}
internal XmlException(string res, int lineNumber, int linePosition) :
this(res, (string[])null, null, lineNumber, linePosition)
{ }
internal XmlException(string res, string arg, int lineNumber, int linePosition) :
this(res, new string[] { arg }, null, lineNumber, linePosition, null)
{ }
internal XmlException(string res, string arg, int lineNumber, int linePosition, string sourceUri) :
this(res, new string[] { arg }, null, lineNumber, linePosition, sourceUri)
{ }
internal XmlException(string res, string[] args, int lineNumber, int linePosition) :
this(res, args, null, lineNumber, linePosition, null)
{ }
internal XmlException(string res, string[] args, int lineNumber, int linePosition, string sourceUri) :
this(res, args, null, lineNumber, linePosition, sourceUri)
{ }
internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition) :
this(res, args, innerException, lineNumber, linePosition, null)
{ }
internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition, string sourceUri) :
base(CreateMessage(res, args, lineNumber, linePosition), innerException)
{
HResult = HResults.Xml;
_res = res;
_args = args;
_sourceUri = sourceUri;
_lineNumber = lineNumber;
_linePosition = linePosition;
}
private static string FormatUserMessage(string message, int lineNumber, int linePosition)
{
if (message == null)
{
return CreateMessage(ResXml.Xml_DefaultException, null, lineNumber, linePosition);
}
else
{
if (lineNumber == 0 && linePosition == 0)
{
// do not reformat the message when not needed
return message;
}
else
{
// add line information
return CreateMessage(ResXml.Xml_UserException, new string[] { message }, lineNumber, linePosition);
}
}
}
private static string CreateMessage(string res, string[] args, int lineNumber, int linePosition)
{
try
{
string message;
// No line information -> get resource string and return
if (lineNumber == 0)
{
message = string.Format(res, args);
}
// Line information is available -> we need to append it to the error message
else
{
string lineNumberStr = lineNumber.ToString();
string linePositionStr = linePosition.ToString();
message = string.Format(res, args);
message = string.Format(ResXml.Xml_MessageWithErrorPosition, new string[] { message, lineNumberStr, linePositionStr });
}
return message;
}
catch (MissingManifestResourceException)
{
return "UNKNOWN(" + res + ")";
}
}
internal static string[] BuildCharExceptionArgs(string data, int invCharIndex)
{
return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < data.Length ? data[invCharIndex + 1] : '\0');
}
internal static string[] BuildCharExceptionArgs(char[] data, int invCharIndex)
{
return BuildCharExceptionArgs(data, data.Length, invCharIndex);
}
internal static string[] BuildCharExceptionArgs(char[] data, int length, int invCharIndex)
{
Debug.Assert(invCharIndex < data.Length);
Debug.Assert(invCharIndex < length);
Debug.Assert(length <= data.Length);
return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < length ? data[invCharIndex + 1] : '\0');
}
internal static string[] BuildCharExceptionArgs(char invChar, char nextChar)
{
string[] aStringList = new string[2];
// for surrogate characters include both high and low char in the message so that a full character is displayed
if (XmlCharType.IsHighSurrogate(invChar) && nextChar != 0)
{
int combinedChar = XmlCharType.CombineSurrogateChar(nextChar, invChar);
aStringList[0] = new string(new char[] { invChar, nextChar });
aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", combinedChar);
}
else
{
// don't include 0 character in the string - in means eof-of-string in native code, where this may bubble up to
if ((int)invChar == 0)
{
aStringList[0] = ".";
}
else
{
aStringList[0] = invChar.ToString();
}
aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", (int)invChar);
}
return aStringList;
}
public int LineNumber
{
get { return _lineNumber; }
}
public int LinePosition
{
get { return _linePosition; }
}
public string SourceUri
{
get { return _sourceUri; }
}
public override string Message
{
get
{
return (_message == null) ? base.Message : _message;
}
}
internal string ResString
{
get
{
return _res;
}
}
internal static bool IsCatchableException(Exception e)
{
Debug.Assert(e != null, "Unexpected null exception");
return !(
e is OutOfMemoryException ||
e is NullReferenceException
);
}
};
} // namespace Microsoft.Xml
| |
namespace XenAdmin.TabPages
{
partial class PerformancePage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PerformancePage));
this.panel1 = new System.Windows.Forms.Panel();
this.GraphList = new XenAdmin.Controls.CustomDataGraph.GraphList();
this.DataEventList = new XenAdmin.Controls.CustomDataGraph.DataEventList();
this.DataPlotNav = new XenAdmin.Controls.CustomDataGraph.DataPlotNav();
this.EventsLabel = new System.Windows.Forms.Label();
this.gradientPanel2 = new XenAdmin.Controls.GradientPanel.GradientPanel();
this.panel3 = new System.Windows.Forms.Panel();
this.zoomButton = new System.Windows.Forms.Button();
this.moveDownButton = new System.Windows.Forms.Button();
this.moveUpButton = new System.Windows.Forms.Button();
this.graphActionsButton = new System.Windows.Forms.Button();
this.graphActionsMenuStrip = new XenAdmin.Controls.NonReopeningContextMenuStrip(this.components);
this.newGraphToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editGraphToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteGraphToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.restoreDefaultGraphsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.zoomMenuStrip = new XenAdmin.Controls.NonReopeningContextMenuStrip(this.components);
this.lastYearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastMonthToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastWeekToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastDayToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastHourToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastTenMinutesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.moveUpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.moveDownToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.actionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newGraphToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editGraphToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteGraphToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.restoreDefaultGraphsToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.zoomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastYearToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastMonthToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastWeekToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastDayToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastHourToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastTenMinutesToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pageContainerPanel.SuspendLayout();
this.panel1.SuspendLayout();
this.gradientPanel2.SuspendLayout();
this.panel3.SuspendLayout();
this.graphActionsMenuStrip.SuspendLayout();
this.zoomMenuStrip.SuspendLayout();
this.contextMenuStrip.SuspendLayout();
this.SuspendLayout();
//
// pageContainerPanel
//
this.pageContainerPanel.Controls.Add(this.panel3);
resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel");
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.GraphList);
this.panel1.Name = "panel1";
//
// GraphList
//
this.GraphList.ArchiveMaintainer = null;
resources.ApplyResources(this.GraphList, "GraphList");
this.GraphList.BackColor = System.Drawing.SystemColors.Window;
this.GraphList.DataEventList = this.DataEventList;
this.GraphList.DataPlotNav = this.DataPlotNav;
this.GraphList.Name = "GraphList";
this.GraphList.SelectedGraph = null;
this.GraphList.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.GraphList_MouseDoubleClick);
//
// DataEventList
//
resources.ApplyResources(this.DataEventList, "DataEventList");
this.DataEventList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.DataEventList.FormattingEnabled = true;
this.DataEventList.Name = "DataEventList";
//
// DataPlotNav
//
resources.ApplyResources(this.DataPlotNav, "DataPlotNav");
this.DataPlotNav.ArchiveMaintainer = null;
this.DataPlotNav.DataEventList = this.DataEventList;
this.DataPlotNav.DisplayedUuids = ((System.Collections.Generic.List<string>)(resources.GetObject("DataPlotNav.DisplayedUuids")));
this.DataPlotNav.GraphOffset = System.TimeSpan.Parse("00:00:00");
this.DataPlotNav.GraphWidth = System.TimeSpan.Parse("00:09:59");
this.DataPlotNav.GridSpacing = System.TimeSpan.Parse("00:02:00");
this.DataPlotNav.MinimumSize = new System.Drawing.Size(410, 0);
this.DataPlotNav.Name = "DataPlotNav";
this.DataPlotNav.ScrollViewOffset = System.TimeSpan.Parse("00:00:00");
this.DataPlotNav.ScrollViewWidth = System.TimeSpan.Parse("02:00:00");
//
// EventsLabel
//
this.EventsLabel.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.EventsLabel, "EventsLabel");
this.EventsLabel.ForeColor = System.Drawing.SystemColors.HighlightText;
this.EventsLabel.Name = "EventsLabel";
//
// gradientPanel2
//
resources.ApplyResources(this.gradientPanel2, "gradientPanel2");
this.gradientPanel2.Controls.Add(this.EventsLabel);
this.gradientPanel2.Name = "gradientPanel2";
this.gradientPanel2.Scheme = XenAdmin.Controls.GradientPanel.GradientPanel.Schemes.Title;
//
// panel3
//
this.panel3.Controls.Add(this.zoomButton);
this.panel3.Controls.Add(this.moveDownButton);
this.panel3.Controls.Add(this.moveUpButton);
this.panel3.Controls.Add(this.graphActionsButton);
this.panel3.Controls.Add(this.gradientPanel2);
this.panel3.Controls.Add(this.DataPlotNav);
this.panel3.Controls.Add(this.panel1);
this.panel3.Controls.Add(this.DataEventList);
resources.ApplyResources(this.panel3, "panel3");
this.panel3.Name = "panel3";
//
// zoomButton
//
resources.ApplyResources(this.zoomButton, "zoomButton");
this.zoomButton.Image = global::XenAdmin.Properties.Resources.expanded_triangle;
this.zoomButton.Name = "zoomButton";
this.zoomButton.UseVisualStyleBackColor = true;
this.zoomButton.Click += new System.EventHandler(this.zoomButton_Click);
//
// moveDownButton
//
resources.ApplyResources(this.moveDownButton, "moveDownButton");
this.moveDownButton.Name = "moveDownButton";
this.moveDownButton.UseVisualStyleBackColor = true;
this.moveDownButton.Click += new System.EventHandler(this.moveDownButton_Click);
//
// moveUpButton
//
resources.ApplyResources(this.moveUpButton, "moveUpButton");
this.moveUpButton.Name = "moveUpButton";
this.moveUpButton.UseVisualStyleBackColor = true;
this.moveUpButton.Click += new System.EventHandler(this.moveUpButton_Click);
//
// graphActionsButton
//
this.graphActionsButton.Image = global::XenAdmin.Properties.Resources.expanded_triangle;
resources.ApplyResources(this.graphActionsButton, "graphActionsButton");
this.graphActionsButton.Name = "graphActionsButton";
this.graphActionsButton.UseVisualStyleBackColor = true;
this.graphActionsButton.Click += new System.EventHandler(this.graphActionsButton_Click);
//
// graphActionsMenuStrip
//
this.graphActionsMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newGraphToolStripMenuItem,
this.editGraphToolStripMenuItem,
this.deleteGraphToolStripMenuItem,
this.toolStripSeparator3,
this.restoreDefaultGraphsToolStripMenuItem});
this.graphActionsMenuStrip.Name = "saveMenuStrip";
resources.ApplyResources(this.graphActionsMenuStrip, "graphActionsMenuStrip");
this.graphActionsMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.graphActionsMenuStrip_Opening);
//
// newGraphToolStripMenuItem
//
this.newGraphToolStripMenuItem.Name = "newGraphToolStripMenuItem";
resources.ApplyResources(this.newGraphToolStripMenuItem, "newGraphToolStripMenuItem");
this.newGraphToolStripMenuItem.Click += new System.EventHandler(this.addGraphToolStripMenuItem_Click);
//
// editGraphToolStripMenuItem
//
this.editGraphToolStripMenuItem.Name = "editGraphToolStripMenuItem";
resources.ApplyResources(this.editGraphToolStripMenuItem, "editGraphToolStripMenuItem");
this.editGraphToolStripMenuItem.Click += new System.EventHandler(this.editGraphToolStripMenuItem_Click);
//
// deleteGraphToolStripMenuItem
//
this.deleteGraphToolStripMenuItem.Name = "deleteGraphToolStripMenuItem";
resources.ApplyResources(this.deleteGraphToolStripMenuItem, "deleteGraphToolStripMenuItem");
this.deleteGraphToolStripMenuItem.Click += new System.EventHandler(this.deleteGraphToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// restoreDefaultGraphsToolStripMenuItem
//
this.restoreDefaultGraphsToolStripMenuItem.Name = "restoreDefaultGraphsToolStripMenuItem";
resources.ApplyResources(this.restoreDefaultGraphsToolStripMenuItem, "restoreDefaultGraphsToolStripMenuItem");
this.restoreDefaultGraphsToolStripMenuItem.Click += new System.EventHandler(this.restoreDefaultGraphsToolStripMenuItem_Click);
//
// zoomMenuStrip
//
this.zoomMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lastYearToolStripMenuItem,
this.lastMonthToolStripMenuItem,
this.lastWeekToolStripMenuItem,
this.lastDayToolStripMenuItem,
this.lastHourToolStripMenuItem,
this.lastTenMinutesToolStripMenuItem});
this.zoomMenuStrip.Name = "saveMenuStrip";
resources.ApplyResources(this.zoomMenuStrip, "zoomMenuStrip");
//
// lastYearToolStripMenuItem
//
this.lastYearToolStripMenuItem.Name = "lastYearToolStripMenuItem";
resources.ApplyResources(this.lastYearToolStripMenuItem, "lastYearToolStripMenuItem");
this.lastYearToolStripMenuItem.Click += new System.EventHandler(this.lastYearToolStripMenuItem_Click);
//
// lastMonthToolStripMenuItem
//
this.lastMonthToolStripMenuItem.Name = "lastMonthToolStripMenuItem";
resources.ApplyResources(this.lastMonthToolStripMenuItem, "lastMonthToolStripMenuItem");
this.lastMonthToolStripMenuItem.Click += new System.EventHandler(this.lastMonthToolStripMenuItem_Click);
//
// lastWeekToolStripMenuItem
//
this.lastWeekToolStripMenuItem.Name = "lastWeekToolStripMenuItem";
resources.ApplyResources(this.lastWeekToolStripMenuItem, "lastWeekToolStripMenuItem");
this.lastWeekToolStripMenuItem.Click += new System.EventHandler(this.lastWeekToolStripMenuItem_Click);
//
// lastDayToolStripMenuItem
//
this.lastDayToolStripMenuItem.Name = "lastDayToolStripMenuItem";
resources.ApplyResources(this.lastDayToolStripMenuItem, "lastDayToolStripMenuItem");
this.lastDayToolStripMenuItem.Click += new System.EventHandler(this.lastDayToolStripMenuItem_Click);
//
// lastHourToolStripMenuItem
//
this.lastHourToolStripMenuItem.Name = "lastHourToolStripMenuItem";
resources.ApplyResources(this.lastHourToolStripMenuItem, "lastHourToolStripMenuItem");
this.lastHourToolStripMenuItem.Click += new System.EventHandler(this.lastHourToolStripMenuItem_Click);
//
// lastTenMinutesToolStripMenuItem
//
this.lastTenMinutesToolStripMenuItem.Name = "lastTenMinutesToolStripMenuItem";
resources.ApplyResources(this.lastTenMinutesToolStripMenuItem, "lastTenMinutesToolStripMenuItem");
this.lastTenMinutesToolStripMenuItem.Click += new System.EventHandler(this.lastTenMinutesToolStripMenuItem_Click);
//
// contextMenuStrip
//
this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.moveUpToolStripMenuItem,
this.moveDownToolStripMenuItem,
this.toolStripSeparator1,
this.actionsToolStripMenuItem,
this.toolStripSeparator2,
this.zoomToolStripMenuItem});
this.contextMenuStrip.Name = "contextMenuStrip";
resources.ApplyResources(this.contextMenuStrip, "contextMenuStrip");
this.contextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening);
//
// moveUpToolStripMenuItem
//
this.moveUpToolStripMenuItem.Name = "moveUpToolStripMenuItem";
resources.ApplyResources(this.moveUpToolStripMenuItem, "moveUpToolStripMenuItem");
this.moveUpToolStripMenuItem.Click += new System.EventHandler(this.moveUpToolStripMenuItem_Click);
//
// moveDownToolStripMenuItem
//
this.moveDownToolStripMenuItem.Name = "moveDownToolStripMenuItem";
resources.ApplyResources(this.moveDownToolStripMenuItem, "moveDownToolStripMenuItem");
this.moveDownToolStripMenuItem.Click += new System.EventHandler(this.moveDownToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// actionsToolStripMenuItem
//
this.actionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newGraphToolStripContextMenuItem,
this.editGraphToolStripContextMenuItem,
this.deleteGraphToolStripContextMenuItem,
this.toolStripSeparator4,
this.restoreDefaultGraphsToolStripContextMenuItem});
this.actionsToolStripMenuItem.Name = "actionsToolStripMenuItem";
resources.ApplyResources(this.actionsToolStripMenuItem, "actionsToolStripMenuItem");
//
// newGraphToolStripContextMenuItem
//
this.newGraphToolStripContextMenuItem.Name = "newGraphToolStripContextMenuItem";
resources.ApplyResources(this.newGraphToolStripContextMenuItem, "newGraphToolStripContextMenuItem");
this.newGraphToolStripContextMenuItem.Click += new System.EventHandler(this.newGraphToolStripContextMenuItem_Click);
//
// editGraphToolStripContextMenuItem
//
this.editGraphToolStripContextMenuItem.Name = "editGraphToolStripContextMenuItem";
resources.ApplyResources(this.editGraphToolStripContextMenuItem, "editGraphToolStripContextMenuItem");
this.editGraphToolStripContextMenuItem.Click += new System.EventHandler(this.editGraphToolStripContextMenuItem_Click);
//
// deleteGraphToolStripContextMenuItem
//
this.deleteGraphToolStripContextMenuItem.Name = "deleteGraphToolStripContextMenuItem";
resources.ApplyResources(this.deleteGraphToolStripContextMenuItem, "deleteGraphToolStripContextMenuItem");
this.deleteGraphToolStripContextMenuItem.Click += new System.EventHandler(this.deleteGraphToolStripContextMenuItem_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// restoreDefaultGraphsToolStripContextMenuItem
//
this.restoreDefaultGraphsToolStripContextMenuItem.Name = "restoreDefaultGraphsToolStripContextMenuItem";
resources.ApplyResources(this.restoreDefaultGraphsToolStripContextMenuItem, "restoreDefaultGraphsToolStripContextMenuItem");
this.restoreDefaultGraphsToolStripContextMenuItem.Click += new System.EventHandler(this.restoreDefaultGraphsToolStripContextMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// zoomToolStripMenuItem
//
this.zoomToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lastYearToolStripContextMenuItem,
this.lastMonthToolStripContextMenuItem,
this.lastWeekToolStripContextMenuItem,
this.lastDayToolStripContextMenuItem,
this.lastHourToolStripContextMenuItem,
this.lastTenMinutesToolStripContextMenuItem});
this.zoomToolStripMenuItem.Name = "zoomToolStripMenuItem";
resources.ApplyResources(this.zoomToolStripMenuItem, "zoomToolStripMenuItem");
//
// lastYearToolStripContextMenuItem
//
this.lastYearToolStripContextMenuItem.Name = "lastYearToolStripContextMenuItem";
resources.ApplyResources(this.lastYearToolStripContextMenuItem, "lastYearToolStripContextMenuItem");
this.lastYearToolStripContextMenuItem.Click += new System.EventHandler(this.lastYearToolStripContextMenuItem_Click);
//
// lastMonthToolStripContextMenuItem
//
this.lastMonthToolStripContextMenuItem.Name = "lastMonthToolStripContextMenuItem";
resources.ApplyResources(this.lastMonthToolStripContextMenuItem, "lastMonthToolStripContextMenuItem");
this.lastMonthToolStripContextMenuItem.Click += new System.EventHandler(this.lastMonthToolStripContextMenuItem_Click);
//
// lastWeekToolStripContextMenuItem
//
this.lastWeekToolStripContextMenuItem.Name = "lastWeekToolStripContextMenuItem";
resources.ApplyResources(this.lastWeekToolStripContextMenuItem, "lastWeekToolStripContextMenuItem");
this.lastWeekToolStripContextMenuItem.Click += new System.EventHandler(this.lastWeekToolStripContextMenuItem_Click);
//
// lastDayToolStripContextMenuItem
//
this.lastDayToolStripContextMenuItem.Name = "lastDayToolStripContextMenuItem";
resources.ApplyResources(this.lastDayToolStripContextMenuItem, "lastDayToolStripContextMenuItem");
this.lastDayToolStripContextMenuItem.Click += new System.EventHandler(this.lastDayToolStripContextMenuItem_Click);
//
// lastHourToolStripContextMenuItem
//
this.lastHourToolStripContextMenuItem.Name = "lastHourToolStripContextMenuItem";
resources.ApplyResources(this.lastHourToolStripContextMenuItem, "lastHourToolStripContextMenuItem");
this.lastHourToolStripContextMenuItem.Click += new System.EventHandler(this.lastHourToolStripContextMenuItem_Click);
//
// lastTenMinutesToolStripContextMenuItem
//
this.lastTenMinutesToolStripContextMenuItem.Name = "lastTenMinutesToolStripContextMenuItem";
resources.ApplyResources(this.lastTenMinutesToolStripContextMenuItem, "lastTenMinutesToolStripContextMenuItem");
this.lastTenMinutesToolStripContextMenuItem.Click += new System.EventHandler(this.lastTenMinutesToolStripContextMenuItem_Click);
//
// PerformancePage
//
resources.ApplyResources(this, "$this");
this.DoubleBuffered = true;
this.Name = "PerformancePage";
this.Controls.SetChildIndex(this.pageContainerPanel, 0);
this.pageContainerPanel.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.gradientPanel2.ResumeLayout(false);
this.panel3.ResumeLayout(false);
this.graphActionsMenuStrip.ResumeLayout(false);
this.zoomMenuStrip.ResumeLayout(false);
this.contextMenuStrip.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public XenAdmin.Controls.CustomDataGraph.DataEventList DataEventList;
public XenAdmin.Controls.CustomDataGraph.DataPlotNav DataPlotNav;
private XenAdmin.Controls.CustomDataGraph.GraphList GraphList;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label EventsLabel;
private XenAdmin.Controls.GradientPanel.GradientPanel gradientPanel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Button graphActionsButton;
private XenAdmin.Controls.NonReopeningContextMenuStrip graphActionsMenuStrip;
private System.Windows.Forms.ToolStripMenuItem newGraphToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editGraphToolStripMenuItem;
private System.Windows.Forms.Button moveDownButton;
private System.Windows.Forms.Button moveUpButton;
private XenAdmin.Controls.NonReopeningContextMenuStrip zoomMenuStrip;
private System.Windows.Forms.ToolStripMenuItem lastYearToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastMonthToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastWeekToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastDayToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastHourToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastTenMinutesToolStripMenuItem;
private System.Windows.Forms.Button zoomButton;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem moveUpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem moveDownToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem actionsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem zoomToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newGraphToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem editGraphToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastYearToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastMonthToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastWeekToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastDayToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastHourToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastTenMinutesToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteGraphToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem restoreDefaultGraphsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteGraphToolStripContextMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem restoreDefaultGraphsToolStripContextMenuItem;
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using log4net.Util;
using log4net.Core;
namespace log4net.Appender
{
/// <summary>
/// Abstract base class implementation of <see cref="IAppender"/> that
/// buffers events in a fixed size buffer.
/// </summary>
/// <remarks>
/// <para>
/// This base class should be used by appenders that need to buffer a
/// number of events before logging them. For example the <see cref="AdoNetAppender"/>
/// buffers events and then submits the entire contents of the buffer to
/// the underlying database in one go.
/// </para>
/// <para>
/// Subclasses should override the <see cref="M:SendBuffer(LoggingEvent[])"/>
/// method to deliver the buffered events.
/// </para>
/// <para>The BufferingAppenderSkeleton maintains a fixed size cyclic
/// buffer of events. The size of the buffer is set using
/// the <see cref="BufferSize"/> property.
/// </para>
/// <para>A <see cref="ITriggeringEventEvaluator"/> is used to inspect
/// each event as it arrives in the appender. If the <see cref="Evaluator"/>
/// triggers, then the current buffer is sent immediately
/// (see <see cref="M:SendBuffer(LoggingEvent[])"/>). Otherwise the event
/// is stored in the buffer. For example, an evaluator can be used to
/// deliver the events immediately when an ERROR event arrives.
/// </para>
/// <para>
/// The buffering appender can be configured in a <see cref="Lossy"/> mode.
/// By default the appender is NOT lossy. When the buffer is full all
/// the buffered events are sent with <see cref="M:SendBuffer(LoggingEvent[])"/>.
/// If the <see cref="Lossy"/> property is set to <c>true</c> then the
/// buffer will not be sent when it is full, and new events arriving
/// in the appender will overwrite the oldest event in the buffer.
/// In lossy mode the buffer will only be sent when the <see cref="Evaluator"/>
/// triggers. This can be useful behavior when you need to know about
/// ERROR events but not about events with a lower level, configure an
/// evaluator that will trigger when an ERROR event arrives, the whole
/// buffer will be sent which gives a history of events leading up to
/// the ERROR event.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public abstract class BufferingAppenderSkeleton : AppenderSkeleton
{
#region Protected Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BufferingAppenderSkeleton" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Protected default constructor to allow subclassing.
/// </para>
/// </remarks>
protected BufferingAppenderSkeleton() : this(true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingAppenderSkeleton" /> class.
/// </summary>
/// <param name="eventMustBeFixed">the events passed through this appender must be
/// fixed by the time that they arrive in the derived class' <c>SendBuffer</c> method.</param>
/// <remarks>
/// <para>
/// Protected constructor to allow subclassing.
/// </para>
/// <para>
/// The <paramref name="eventMustBeFixed"/> should be set if the subclass
/// expects the events delivered to be fixed even if the
/// <see cref="BufferSize"/> is set to zero, i.e. when no buffering occurs.
/// </para>
/// </remarks>
protected BufferingAppenderSkeleton(bool eventMustBeFixed) : base()
{
m_eventMustBeFixed = eventMustBeFixed;
}
#endregion Protected Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets a value that indicates whether the appender is lossy.
/// </summary>
/// <value>
/// <c>true</c> if the appender is lossy, otherwise <c>false</c>. The default is <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// This appender uses a buffer to store logging events before
/// delivering them. A triggering event causes the whole buffer
/// to be send to the remote sink. If the buffer overruns before
/// a triggering event then logging events could be lost. Set
/// <see cref="Lossy"/> to <c>false</c> to prevent logging events
/// from being lost.
/// </para>
/// <para>If <see cref="Lossy"/> is set to <c>true</c> then an
/// <see cref="Evaluator"/> must be specified.</para>
/// </remarks>
public bool Lossy
{
get { return m_lossy; }
set { m_lossy = value; }
}
/// <summary>
/// Gets or sets the size of the cyclic buffer used to hold the
/// logging events.
/// </summary>
/// <value>
/// The size of the cyclic buffer used to hold the logging events.
/// </value>
/// <remarks>
/// <para>
/// The <see cref="BufferSize"/> option takes a positive integer
/// representing the maximum number of logging events to collect in
/// a cyclic buffer. When the <see cref="BufferSize"/> is reached,
/// oldest events are deleted as new events are added to the
/// buffer. By default the size of the cyclic buffer is 512 events.
/// </para>
/// <para>
/// If the <see cref="BufferSize"/> is set to a value less than
/// or equal to 1 then no buffering will occur. The logging event
/// will be delivered synchronously (depending on the <see cref="Lossy"/>
/// and <see cref="Evaluator"/> properties). Otherwise the event will
/// be buffered.
/// </para>
/// </remarks>
public int BufferSize
{
get { return m_bufferSize; }
set { m_bufferSize = value; }
}
/// <summary>
/// Gets or sets the <see cref="ITriggeringEventEvaluator"/> that causes the
/// buffer to be sent immediately.
/// </summary>
/// <value>
/// The <see cref="ITriggeringEventEvaluator"/> that causes the buffer to be
/// sent immediately.
/// </value>
/// <remarks>
/// <para>
/// The evaluator will be called for each event that is appended to this
/// appender. If the evaluator triggers then the current buffer will
/// immediately be sent (see <see cref="M:SendBuffer(LoggingEvent[])"/>).
/// </para>
/// <para>If <see cref="Lossy"/> is set to <c>true</c> then an
/// <see cref="Evaluator"/> must be specified.</para>
/// </remarks>
public ITriggeringEventEvaluator Evaluator
{
get { return m_evaluator; }
set { m_evaluator = value; }
}
/// <summary>
/// Gets or sets the value of the <see cref="ITriggeringEventEvaluator"/> to use.
/// </summary>
/// <value>
/// The value of the <see cref="ITriggeringEventEvaluator"/> to use.
/// </value>
/// <remarks>
/// <para>
/// The evaluator will be called for each event that is discarded from this
/// appender. If the evaluator triggers then the current buffer will immediately
/// be sent (see <see cref="M:SendBuffer(LoggingEvent[])"/>).
/// </para>
/// </remarks>
public ITriggeringEventEvaluator LossyEvaluator
{
get { return m_lossyEvaluator; }
set { m_lossyEvaluator = value; }
}
/// <summary>
/// Gets or sets a value indicating if only part of the logging event data
/// should be fixed.
/// </summary>
/// <value>
/// <c>true</c> if the appender should only fix part of the logging event
/// data, otherwise <c>false</c>. The default is <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// Setting this property to <c>true</c> will cause only part of the
/// event data to be fixed and serialized. This will improve performance.
/// </para>
/// <para>
/// See <see cref="M:LoggingEvent.FixVolatileData(FixFlags)"/> for more information.
/// </para>
/// </remarks>
[Obsolete("Use Fix property. Scheduled removal in v10.0.0.")]
virtual public bool OnlyFixPartialEventData
{
get { return (Fix == FixFlags.Partial); }
set
{
if (value)
{
Fix = FixFlags.Partial;
}
else
{
Fix = FixFlags.All;
}
}
}
/// <summary>
/// Gets or sets a the fields that will be fixed in the event
/// </summary>
/// <value>
/// The event fields that will be fixed before the event is buffered
/// </value>
/// <remarks>
/// <para>
/// The logging event needs to have certain thread specific values
/// captured before it can be buffered. See <see cref="LoggingEvent.Fix"/>
/// for details.
/// </para>
/// </remarks>
/// <seealso cref="LoggingEvent.Fix"/>
virtual public FixFlags Fix
{
get { return m_fixFlags; }
set { m_fixFlags = value; }
}
#endregion Public Instance Properties
#region Public Methods
/// <summary>
/// Flushes any buffered log data.
/// </summary>
/// <param name="millisecondsTimeout">The maximum time to wait for logging events to be flushed.</param>
/// <returns><c>True</c> if all logging events were flushed successfully, else <c>false</c>.</returns>
public override bool Flush(int millisecondsTimeout)
{
Flush();
return true;
}
/// <summary>
/// Flush the currently buffered events
/// </summary>
/// <remarks>
/// <para>
/// Flushes any events that have been buffered.
/// </para>
/// <para>
/// If the appender is buffering in <see cref="Lossy"/> mode then the contents
/// of the buffer will NOT be flushed to the appender.
/// </para>
/// </remarks>
public virtual void Flush()
{
Flush(false);
}
/// <summary>
/// Flush the currently buffered events
/// </summary>
/// <param name="flushLossyBuffer">set to <c>true</c> to flush the buffer of lossy events</param>
/// <remarks>
/// <para>
/// Flushes events that have been buffered. If <paramref name="flushLossyBuffer" /> is
/// <c>false</c> then events will only be flushed if this buffer is non-lossy mode.
/// </para>
/// <para>
/// If the appender is buffering in <see cref="Lossy"/> mode then the contents
/// of the buffer will only be flushed if <paramref name="flushLossyBuffer" /> is <c>true</c>.
/// In this case the contents of the buffer will be tested against the
/// <see cref="LossyEvaluator"/> and if triggering will be output. All other buffered
/// events will be discarded.
/// </para>
/// <para>
/// If <paramref name="flushLossyBuffer" /> is <c>true</c> then the buffer will always
/// be emptied by calling this method.
/// </para>
/// </remarks>
public virtual void Flush(bool flushLossyBuffer)
{
// This method will be called outside of the AppenderSkeleton DoAppend() method
// therefore it needs to be protected by its own lock. This will block any
// Appends while the buffer is flushed.
lock(this)
{
if (m_cb != null && m_cb.Length > 0)
{
if (m_lossy)
{
// If we are allowed to eagerly flush from the lossy buffer
if (flushLossyBuffer)
{
if (m_lossyEvaluator != null)
{
// Test the contents of the buffer against the lossy evaluator
LoggingEvent[] bufferedEvents = m_cb.PopAll();
ArrayList filteredEvents = new ArrayList(bufferedEvents.Length);
foreach(LoggingEvent loggingEvent in bufferedEvents)
{
if (m_lossyEvaluator.IsTriggeringEvent(loggingEvent))
{
filteredEvents.Add(loggingEvent);
}
}
// Send the events that meet the lossy evaluator criteria
if (filteredEvents.Count > 0)
{
SendBuffer((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent)));
}
}
else
{
// No lossy evaluator, all buffered events are discarded
m_cb.Clear();
}
}
}
else
{
// Not lossy, send whole buffer
SendFromBuffer(null, m_cb);
}
}
}
}
#endregion Public Methods
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
base.ActivateOptions();
// If the appender is in Lossy mode then we will
// only send the buffer when the Evaluator triggers
// therefore check we have an evaluator.
if (m_lossy && m_evaluator == null)
{
ErrorHandler.Error("Appender ["+Name+"] is Lossy but has no Evaluator. The buffer will never be sent!");
}
if (m_bufferSize > 1)
{
m_cb = new CyclicBuffer(m_bufferSize);
}
else
{
m_cb = null;
}
}
#endregion Implementation of IOptionHandler
#region Override implementation of AppenderSkeleton
/// <summary>
/// Close this appender instance.
/// </summary>
/// <remarks>
/// <para>
/// Close this appender instance. If this appender is marked
/// as not <see cref="Lossy"/> then the remaining events in
/// the buffer must be sent when the appender is closed.
/// </para>
/// </remarks>
override protected void OnClose()
{
// Flush the buffer on close
Flush(true);
}
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">the event to log</param>
/// <remarks>
/// <para>
/// Stores the <paramref name="loggingEvent"/> in the cyclic buffer.
/// </para>
/// <para>
/// The buffer will be sent (i.e. passed to the <see cref="SendBuffer"/>
/// method) if one of the following conditions is met:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>The cyclic buffer is full and this appender is
/// marked as not lossy (see <see cref="Lossy"/>)</description>
/// </item>
/// <item>
/// <description>An <see cref="Evaluator"/> is set and
/// it is triggered for the <paramref name="loggingEvent"/>
/// specified.</description>
/// </item>
/// </list>
/// <para>
/// Before the event is stored in the buffer it is fixed
/// (see <see cref="M:LoggingEvent.FixVolatileData(FixFlags)"/>) to ensure that
/// any data referenced by the event will be valid when the buffer
/// is processed.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent loggingEvent)
{
// If the buffer size is set to 1 or less then the buffer will be
// sent immediately because there is not enough space in the buffer
// to buffer up more than 1 event. Therefore as a special case
// we don't use the buffer at all.
if (m_cb == null || m_bufferSize <= 1)
{
// Only send the event if we are in non lossy mode or the event is a triggering event
if ((!m_lossy) ||
(m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent)) ||
(m_lossyEvaluator != null && m_lossyEvaluator.IsTriggeringEvent(loggingEvent)))
{
if (m_eventMustBeFixed)
{
// Derive class expects fixed events
loggingEvent.Fix = this.Fix;
}
// Not buffering events, send immediately
SendBuffer(new LoggingEvent[] { loggingEvent } );
}
}
else
{
// Because we are caching the LoggingEvent beyond the
// lifetime of the Append() method we must fix any
// volatile data in the event.
loggingEvent.Fix = this.Fix;
// Add to the buffer, returns the event discarded from the buffer if there is no space remaining after the append
LoggingEvent discardedLoggingEvent = m_cb.Append(loggingEvent);
if (discardedLoggingEvent != null)
{
// Buffer is full and has had to discard an event
if (!m_lossy)
{
// Not lossy, must send all events
SendFromBuffer(discardedLoggingEvent, m_cb);
}
else
{
// Check if the discarded event should not be logged
if (m_lossyEvaluator == null || !m_lossyEvaluator.IsTriggeringEvent(discardedLoggingEvent))
{
// Clear the discarded event as we should not forward it
discardedLoggingEvent = null;
}
// Check if the event should trigger the whole buffer to be sent
if (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent))
{
SendFromBuffer(discardedLoggingEvent, m_cb);
}
else if (discardedLoggingEvent != null)
{
// Just send the discarded event
SendBuffer(new LoggingEvent[] { discardedLoggingEvent } );
}
}
}
else
{
// Buffer is not yet full
// Check if the event should trigger the whole buffer to be sent
if (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent))
{
SendFromBuffer(null, m_cb);
}
}
}
}
#endregion Override implementation of AppenderSkeleton
#region Protected Instance Methods
/// <summary>
/// Sends the contents of the buffer.
/// </summary>
/// <param name="firstLoggingEvent">The first logging event.</param>
/// <param name="buffer">The buffer containing the events that need to be send.</param>
/// <remarks>
/// <para>
/// The subclass must override <see cref="M:SendBuffer(LoggingEvent[])"/>.
/// </para>
/// </remarks>
virtual protected void SendFromBuffer(LoggingEvent firstLoggingEvent, CyclicBuffer buffer)
{
LoggingEvent[] bufferEvents = buffer.PopAll();
if (firstLoggingEvent == null)
{
SendBuffer(bufferEvents);
}
else if (bufferEvents.Length == 0)
{
SendBuffer(new LoggingEvent[] { firstLoggingEvent } );
}
else
{
// Create new array with the firstLoggingEvent at the head
LoggingEvent[] events = new LoggingEvent[bufferEvents.Length + 1];
Array.Copy(bufferEvents, 0, events, 1, bufferEvents.Length);
events[0] = firstLoggingEvent;
SendBuffer(events);
}
}
#endregion Protected Instance Methods
/// <summary>
/// Sends the events.
/// </summary>
/// <param name="events">The events that need to be send.</param>
/// <remarks>
/// <para>
/// The subclass must override this method to process the buffered events.
/// </para>
/// </remarks>
abstract protected void SendBuffer(LoggingEvent[] events);
#region Private Static Fields
/// <summary>
/// The default buffer size.
/// </summary>
/// <remarks>
/// The default size of the cyclic buffer used to store events.
/// This is set to 512 by default.
/// </remarks>
private const int DEFAULT_BUFFER_SIZE = 512;
#endregion Private Static Fields
#region Private Instance Fields
/// <summary>
/// The size of the cyclic buffer used to hold the logging events.
/// </summary>
/// <remarks>
/// Set to <see cref="DEFAULT_BUFFER_SIZE"/> by default.
/// </remarks>
private int m_bufferSize = DEFAULT_BUFFER_SIZE;
/// <summary>
/// The cyclic buffer used to store the logging events.
/// </summary>
private CyclicBuffer m_cb;
/// <summary>
/// The triggering event evaluator that causes the buffer to be sent immediately.
/// </summary>
/// <remarks>
/// The object that is used to determine if an event causes the entire
/// buffer to be sent immediately. This field can be <c>null</c>, which
/// indicates that event triggering is not to be done. The evaluator
/// can be set using the <see cref="Evaluator"/> property. If this appender
/// has the <see cref="m_lossy"/> (<see cref="Lossy"/> property) set to
/// <c>true</c> then an <see cref="Evaluator"/> must be set.
/// </remarks>
private ITriggeringEventEvaluator m_evaluator;
/// <summary>
/// Indicates if the appender should overwrite events in the cyclic buffer
/// when it becomes full, or if the buffer should be flushed when the
/// buffer is full.
/// </summary>
/// <remarks>
/// If this field is set to <c>true</c> then an <see cref="Evaluator"/> must
/// be set.
/// </remarks>
private bool m_lossy = false;
/// <summary>
/// The triggering event evaluator filters discarded events.
/// </summary>
/// <remarks>
/// The object that is used to determine if an event that is discarded should
/// really be discarded or if it should be sent to the appenders.
/// This field can be <c>null</c>, which indicates that all discarded events will
/// be discarded.
/// </remarks>
private ITriggeringEventEvaluator m_lossyEvaluator;
/// <summary>
/// Value indicating which fields in the event should be fixed
/// </summary>
/// <remarks>
/// By default all fields are fixed
/// </remarks>
private FixFlags m_fixFlags = FixFlags.All;
/// <summary>
/// The events delivered to the subclass must be fixed.
/// </summary>
private readonly bool m_eventMustBeFixed;
#endregion Private Instance Fields
}
}
| |
// ***********************************************************************
// 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
{
#if NETSTANDARD1_3 || NETSTANDARD1_6
private const string MOCK_ASSEMBLY_FILE = "mock-assembly.dll";
#else
private const string MOCK_ASSEMBLY_FILE = "mock-assembly.exe";
#endif
#if NETSTANDARD1_6
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]
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]
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]
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]
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]
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]
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
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
namespace UMA
{
/// <summary>
/// Utility class for generating texture atlases
/// </summary>
[Serializable]
public class UMAGeneratorCoroutine : WorkerCoroutine
{
private struct PackSize
{
public int Width;
public int Height;
public bool success;
}
private class GeneratedMaterialLookupKey : IEquatable<GeneratedMaterialLookupKey>
{
public List<OverlayData> overlayList;
public UMARendererAsset rendererAsset;
public bool Equals(GeneratedMaterialLookupKey other)
{
return (overlayList == other.overlayList && rendererAsset == other.rendererAsset);
}
}
TextureProcessBaseCoroutine textureProcessCoroutine;
MaxRectsBinPack packTexture;
UMAGeneratorBase umaGenerator;
UMAData umaData;
Texture[] backUpTexture;
bool updateMaterialList;
int scaleFactor;
MaterialDefinitionComparer comparer = new MaterialDefinitionComparer();
List<UMAData.GeneratedMaterial> generatedMaterials;
List<UMARendererAsset> uniqueRenderers = new List<UMARendererAsset>();
List<UMAData.GeneratedMaterial> atlassedMaterials = new List<UMAData.GeneratedMaterial>(20);
Dictionary<GeneratedMaterialLookupKey, UMAData.GeneratedMaterial> generatedMaterialLookup;
public void Prepare(UMAGeneratorBase _umaGenerator, UMAData _umaData, TextureProcessBaseCoroutine textureProcessCoroutine, bool updateMaterialList, int InitialScaleFactor)
{
umaGenerator = _umaGenerator;
umaData = _umaData;
this.textureProcessCoroutine = textureProcessCoroutine;
this.updateMaterialList = updateMaterialList;
scaleFactor = InitialScaleFactor;
}
private UMAData.GeneratedMaterial FindOrCreateGeneratedMaterial(UMAMaterial umaMaterial, UMARendererAsset renderer = null)
{
if (umaMaterial.materialType == UMAMaterial.MaterialType.Atlas)
{
foreach (var atlassedMaterial in atlassedMaterials)
{
if (atlassedMaterial.umaMaterial == umaMaterial && atlassedMaterial.rendererAsset == renderer)
{
return atlassedMaterial;
}
else
{
if (atlassedMaterial.umaMaterial.Equals(umaMaterial) && atlassedMaterial.rendererAsset == renderer)
{
return atlassedMaterial;
}
}
}
}
var res = new UMAData.GeneratedMaterial();
res.rendererAsset = renderer;
res.umaMaterial = umaMaterial;
res.material = UnityEngine.Object.Instantiate(umaMaterial.material) as Material;
res.material.name = umaMaterial.material.name;
#if UNITY_WEBGL
res.material.shader = Shader.Find(res.material.shader.name);
#endif
res.material.CopyPropertiesFromMaterial(umaMaterial.material);
atlassedMaterials.Add(res);
generatedMaterials.Add(res);
return res;
}
protected bool IsUVCoordinates(Rect r)
{
if (r.width == 0.0f || r.height == 0.0f)
return false;
if (r.width <= 1.0f && r.height <= 1.0f)
return true;
return false;
}
protected Rect ScaleToBase(Rect r, Texture BaseTexture)
{
if (!BaseTexture) return r;
float w = BaseTexture.width;
float h = BaseTexture.height;
return new Rect(r.x * w, r.y * h, r.width * w, r.height * h);
}
protected override void Start()
{
if (generatedMaterialLookup == null)
{
generatedMaterialLookup = new Dictionary<GeneratedMaterialLookupKey, UMAData.GeneratedMaterial>(20);
}
else
{
generatedMaterialLookup.Clear();
}
backUpTexture = umaData.backUpTextures();
umaData.CleanTextures();
generatedMaterials = new List<UMAData.GeneratedMaterial>(20);
atlassedMaterials.Clear();
uniqueRenderers.Clear();
SlotData[] slots = umaData.umaRecipe.slotDataList;
for (int i = 0; i < slots.Length; i++)
{
SlotData slot = slots[i];
if (slot == null)
continue;
if (slot.Suppressed)
continue;
//Keep a running list of unique RendererHashes from our slots
//Null rendererAsset gets added, which is good, it is the default renderer.
if (!uniqueRenderers.Contains(slot.rendererAsset))
uniqueRenderers.Add(slot.rendererAsset);
// Let's only add the default overlay if the slot has meshData and NO overlays
// This should be able to be removed if default overlay/textures are ever added to uma materials...
if ((slot.asset.meshData != null) && (slot.OverlayCount == 0))
{
if (umaGenerator.defaultOverlaydata != null)
slot.AddOverlay(umaGenerator.defaultOverlaydata);
}
OverlayData overlay0 = slot.GetOverlay(0);
if ((slot.material != null) && (overlay0 != null))
{
GeneratedMaterialLookupKey lookupKey = new GeneratedMaterialLookupKey
{
overlayList = slot.GetOverlayList(),
rendererAsset = slot.rendererAsset
};
UMAData.GeneratedMaterial generatedMaterial;
if (!generatedMaterialLookup.TryGetValue(lookupKey, out generatedMaterial))
{
generatedMaterial = FindOrCreateGeneratedMaterial(slot.material, slot.rendererAsset);
generatedMaterialLookup.Add(lookupKey, generatedMaterial);
}
int validOverlayCount = 0;
for (int j = 0; j < slot.OverlayCount; j++)
{
var overlay = slot.GetOverlay(j);
if (overlay != null)
{
validOverlayCount++;
#if (UNITY_STANDALONE || UNITY_IOS || UNITY_ANDROID || UNITY_PS4 || UNITY_XBOXONE) && !UNITY_2017_3_OR_NEWER //supported platforms for procedural materials
if (overlay.isProcedural)
overlay.GenerateProceduralTextures();
#endif
}
}
UMAData.MaterialFragment tempMaterialDefinition = new UMAData.MaterialFragment();
tempMaterialDefinition.baseOverlay = new UMAData.textureData();
tempMaterialDefinition.baseOverlay.textureList = overlay0.textureArray;
tempMaterialDefinition.baseOverlay.alphaTexture = overlay0.alphaMask;
tempMaterialDefinition.baseOverlay.overlayType = overlay0.overlayType;
tempMaterialDefinition.umaMaterial = slot.material;
if (overlay0.isEmpty)
{
tempMaterialDefinition.isNoTextures = true;
tempMaterialDefinition.overlayData[0] = slot.GetOverlay(0);
}
else
{
tempMaterialDefinition.baseColor = overlay0.colorData.color;
tempMaterialDefinition.size = overlay0.pixelCount;
tempMaterialDefinition.overlays = new UMAData.textureData[validOverlayCount - 1];
tempMaterialDefinition.overlayColors = new Color32[validOverlayCount - 1];
tempMaterialDefinition.rects = new Rect[validOverlayCount - 1];
tempMaterialDefinition.overlayData = new OverlayData[validOverlayCount];
tempMaterialDefinition.channelMask = new Color[validOverlayCount][];
tempMaterialDefinition.channelAdditiveMask = new Color[validOverlayCount][];
tempMaterialDefinition.overlayData[0] = slot.GetOverlay(0);
tempMaterialDefinition.channelMask[0] = slot.GetOverlay(0).colorData.channelMask;
tempMaterialDefinition.channelAdditiveMask[0] = slot.GetOverlay(0).colorData.channelAdditiveMask;
}
tempMaterialDefinition.slotData = slot;
int overlayID = 0;
for (int j = 1; j < slot.OverlayCount; j++)
{
OverlayData overlay = slot.GetOverlay(j);
if (overlay == null)
continue;
if (IsUVCoordinates(overlay.rect))
{
tempMaterialDefinition.rects[overlayID] = ScaleToBase(overlay.rect, overlay0.textureArray[0]);
}
else
{
tempMaterialDefinition.rects[overlayID] = overlay.rect; // JRRM: Convert here into base overlay coordinates?
}
tempMaterialDefinition.overlays[overlayID] = new UMAData.textureData();
tempMaterialDefinition.overlays[overlayID].textureList = overlay.textureArray;
tempMaterialDefinition.overlays[overlayID].alphaTexture = overlay.alphaMask;
tempMaterialDefinition.overlays[overlayID].overlayType = overlay.overlayType;
tempMaterialDefinition.overlayColors[overlayID] = overlay.colorData.color;
overlayID++;
tempMaterialDefinition.overlayData[overlayID] = overlay;
tempMaterialDefinition.channelMask[overlayID] = overlay.colorData.channelMask;
tempMaterialDefinition.channelAdditiveMask[overlayID] = overlay.colorData.channelAdditiveMask;
}
tempMaterialDefinition.overlayList = lookupKey.overlayList;
tempMaterialDefinition.isRectShared = false;
for (int j = 0; j < generatedMaterial.materialFragments.Count; j++)
{
if (tempMaterialDefinition.overlayList == generatedMaterial.materialFragments[j].overlayList)
{
tempMaterialDefinition.isRectShared = true;
tempMaterialDefinition.rectFragment = generatedMaterial.materialFragments[j];
break;
}
}
generatedMaterial.materialFragments.Add(tempMaterialDefinition);
}
}
//****************************************************
//* Set parameters based on shader parameter mapping
//****************************************************
for (int i=0;i<generatedMaterials.Count;i++)
{
UMAData.GeneratedMaterial ugm = generatedMaterials[i];
if (ugm.umaMaterial.shaderParms != null)
{
for(int j=0;j<ugm.umaMaterial.shaderParms.Length;j++)
{
UMAMaterial.ShaderParms parm = ugm.umaMaterial.shaderParms[j];
if (ugm.material.HasProperty(parm.ParameterName))
{
foreach (OverlayColorData ocd in umaData.umaRecipe.sharedColors)
{
if (ocd.name == parm.ColorName)
{
ugm.material.SetColor(parm.ParameterName, ocd.color);
break;
}
}
}
}
}
}
packTexture = new MaxRectsBinPack(umaGenerator.atlasResolution, umaGenerator.atlasResolution, false);
}
public class MaterialDefinitionComparer : IComparer<UMAData.MaterialFragment>
{
public int Compare(UMAData.MaterialFragment x, UMAData.MaterialFragment y)
{
return y.size - x.size;
}
}
protected override IEnumerator workerMethod()
{
umaData.generatedMaterials.rendererAssets = uniqueRenderers;
umaData.generatedMaterials.materials = generatedMaterials;
GenerateAtlasData();
OptimizeAtlas();
textureProcessCoroutine.Prepare(umaData, umaGenerator);
yield return textureProcessCoroutine;
CleanBackUpTextures();
UpdateUV();
// Procedural textures were done here
if (updateMaterialList)
{
for (int j = 0; j < umaData.rendererCount; j++)
{
var renderer = umaData.GetRenderer(j);
var mats = renderer.sharedMaterials;
var newMats = new Material[mats.Length];
var atlasses = umaData.generatedMaterials.materials;
int materialIndex = 0;
for (int i = 0; i < atlasses.Count; i++)
{
if (atlasses[i].rendererAsset == umaData.GetRendererAsset(j))
{
UMAUtils.DestroySceneObject(mats[materialIndex]);
newMats[materialIndex] = atlasses[i].material;
atlasses[i].skinnedMeshRenderer = renderer;
atlasses[i].materialIndex = materialIndex;
materialIndex++;
}
}
renderer.sharedMaterials = newMats;
}
}
}
protected override void Stop()
{
}
private void CleanBackUpTextures()
{
for (int textureIndex = 0; textureIndex < backUpTexture.Length; textureIndex++)
{
if (backUpTexture[textureIndex] != null)
{
Texture tempTexture = backUpTexture[textureIndex];
if (tempTexture is RenderTexture)
{
RenderTexture tempRenderTexture = tempTexture as RenderTexture;
tempRenderTexture.Release();
UMAUtils.DestroySceneObject(tempRenderTexture);
tempRenderTexture = null;
}
else
{
UMAUtils.DestroySceneObject(tempTexture);
}
backUpTexture[textureIndex] = null;
}
}
}
/// <summary>
/// JRRM - this is where we calculate the atlas rectangles.
/// </summary>
private void GenerateAtlasData()
{
PackSize area = new PackSize();
float atlasRes = umaGenerator.atlasResolution;
Vector2 StartScale = Vector2.one / (float)scaleFactor;
Vector2 Scale = Vector2.one;
bool scaled = false;
for (int i = 0; i < atlassedMaterials.Count; i++)
{
area.Width = umaGenerator.atlasResolution;
area.Height = umaGenerator.atlasResolution;
var generatedMaterial = atlassedMaterials[i];
generatedMaterial.materialFragments.Sort(comparer);
generatedMaterial.resolutionScale = StartScale;
generatedMaterial.cropResolution = new Vector2(atlasRes, atlasRes);
// We need a better method than this.
// if "BestFitSquare"
/*switch (umaGenerator.AtlasOverflowFitMethod)
{
case UMAGeneratorBase.FitMethod.BestFitSquare:
while (true)
{
PackSize lastRect = CalculateRects(generatedMaterial, area);
if (lastRect.success)
{
if (area.Width != umaGenerator.atlasResolution || area.Height != umaGenerator.atlasResolution)
{
float neww = area.Width;
float newh = area.Height;
Scale.x = atlasRes / neww;
Scale.y = atlasRes / newh;
scaled = true;
}
break; // Everything fit, let's leave.
}
// do the smallest increase possible and try again.
if ((area.Width+lastRect.Width) < (area.Height+lastRect.Height))
{
area.Width += lastRect.Width;
}
else
{
area.Height += lastRect.Height;
}
}
break;
default: // Shrink Textures */
while (!CalculateRects(generatedMaterial, area).success)
{
generatedMaterial.resolutionScale = generatedMaterial.resolutionScale * umaGenerator.FitPercentageDecrease;
}/*
break;
}*/
UpdateSharedRect(generatedMaterial);
if (scaled)
{
UpdateAtlasRects(generatedMaterial, Scale);
}
}
}
private void UpdateAtlasRects(UMAData.GeneratedMaterial generatedMaterial, Vector2 Scale)
{
for (int i = 0; i < generatedMaterial.materialFragments.Count; i++)
{
var fragment = generatedMaterial.materialFragments[i];
Vector2 pos = fragment.atlasRegion.position * Scale; //ceil ?
Vector2 size = fragment.atlasRegion.size *= Scale; // floor ?
pos.x = Mathf.Ceil(pos.x);
pos.y = Mathf.Ceil(pos.y);
size.x = Mathf.Floor(size.x);
size.y = Mathf.Floor(size.y);
fragment.atlasRegion.Set(pos.x, pos.y, size.x, size.y);
}
}
private void UpdateSharedRect(UMAData.GeneratedMaterial generatedMaterial)
{
for (int i = 0; i < generatedMaterial.materialFragments.Count; i++)
{
var fragment = generatedMaterial.materialFragments[i];
if (fragment.isRectShared)
{
fragment.atlasRegion = fragment.rectFragment.atlasRegion;
}
}
}
private PackSize CalculateRects(UMAData.GeneratedMaterial material, PackSize area)
{
Rect nullRect = new Rect(0, 0, 0, 0);
PackSize lastPackSize = new PackSize();
packTexture.Init(area.Width, area.Height, false);
for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++)
{
var tempMaterialDef = material.materialFragments[atlasElementIndex];
if (tempMaterialDef.isRectShared)
continue;
int width = Mathf.FloorToInt(tempMaterialDef.baseOverlay.textureList[0].width * material.resolutionScale.x * tempMaterialDef.slotData.overlayScale);
int height = Mathf.FloorToInt(tempMaterialDef.baseOverlay.textureList[0].height * material.resolutionScale.y * tempMaterialDef.slotData.overlayScale);
// If either width or height are 0 we will end up with nullRect and potentially loop forever
if (width == 0 || height == 0)
{
tempMaterialDef.atlasRegion = nullRect;
continue;
}
tempMaterialDef.atlasRegion = packTexture.Insert(width, height, MaxRectsBinPack.FreeRectChoiceHeuristic.RectBestLongSideFit);
lastPackSize.Width = width;
lastPackSize.Height = height;
if (tempMaterialDef.atlasRegion == nullRect)
{
if (umaGenerator.fitAtlas)
{
//if (Debug.isDebugBuild) // JRRM : re-enable this
// Debug.LogWarning("Atlas resolution is too small, Textures will be reduced.", umaData.gameObject);
lastPackSize.success = false;
return lastPackSize;
}
else
{
if (Debug.isDebugBuild)
Debug.LogError("Atlas resolution is too small, not all textures will fit.", umaData.gameObject);
}
}
}
lastPackSize.success = true;
return lastPackSize;
}
private void OptimizeAtlas()
{
for (int atlasIndex = 0; atlasIndex < atlassedMaterials.Count; atlasIndex++)
{
var material = atlassedMaterials[atlasIndex];
Vector2 usedArea = new Vector2(0, 0);
for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++)
{
if (material.materialFragments[atlasElementIndex].atlasRegion.xMax > usedArea.x)
{
usedArea.x = material.materialFragments[atlasElementIndex].atlasRegion.xMax;
}
if (material.materialFragments[atlasElementIndex].atlasRegion.yMax > usedArea.y)
{
usedArea.y = material.materialFragments[atlasElementIndex].atlasRegion.yMax;
}
}
//Headless mode ends up with zero usedArea
if(Mathf.Approximately( usedArea.x, 0f ) || Mathf.Approximately( usedArea.y, 0f ))
{
material.cropResolution = Vector2.zero;
return;
}
Vector2 tempResolution = new Vector2(umaGenerator.atlasResolution, umaGenerator.atlasResolution);
bool done = false;
while (!done && Mathf.Abs(usedArea.x) > 0.0001)
{
if (tempResolution.x * 0.5f >= usedArea.x)
{
tempResolution = new Vector2(tempResolution.x * 0.5f, tempResolution.y);
}
else
{
done = true;
}
}
done = false;
while (!done && Mathf.Abs(usedArea.y) > 0.0001)
{
if (tempResolution.y * 0.5f >= usedArea.y)
{
tempResolution = new Vector2(tempResolution.x, tempResolution.y * 0.5f);
}
else
{
done = true;
}
}
material.cropResolution = tempResolution;
}
}
private void UpdateUV()
{
UMAData.GeneratedMaterials umaAtlasList = umaData.generatedMaterials;
for (int atlasIndex = 0; atlasIndex < umaAtlasList.materials.Count; atlasIndex++)
{
var material = umaAtlasList.materials[atlasIndex];
if (material.umaMaterial.materialType != UMAMaterial.MaterialType.Atlas)
continue;
Vector2 finalAtlasAspect = new Vector2(umaGenerator.atlasResolution / material.cropResolution.x, umaGenerator.atlasResolution / material.cropResolution.y);
for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++)
{
Rect tempRect = material.materialFragments[atlasElementIndex].atlasRegion;
tempRect.xMin = tempRect.xMin * finalAtlasAspect.x;
tempRect.xMax = tempRect.xMax * finalAtlasAspect.x;
tempRect.yMin = tempRect.yMin * finalAtlasAspect.y;
tempRect.yMax = tempRect.yMax * finalAtlasAspect.y;
material.materialFragments[atlasElementIndex].atlasRegion = tempRect;
}
}
}
}
}
| |
// Copyright (c) AlphaSierraPapa for the SharpDevelop 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 System.Diagnostics;
using System.Linq;
using System.Threading;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver
{
public delegate void FoundReferenceCallback(AstNode astNode, ResolveResult result);
/// <summary>
/// 'Find references' implementation.
/// </summary>
/// <remarks>
/// This class is thread-safe.
/// The intended multi-threaded usage is to call GetSearchScopes() once, and then
/// call FindReferencesInFile() concurrently on multiple threads (parallel foreach over all interesting files).
/// </remarks>
public sealed class FindReferences
{
#region Properties
/// <summary>
/// Specifies whether to find type references even if an alias is being used.
/// Aliases may be <c>var</c> or <c>using Alias = ...;</c>.
/// </summary>
public bool FindTypeReferencesEvenIfAliased { get; set; }
/// <summary>
/// Specifies whether find references should only look for specialized matches
/// with equal type parameter substitution to the member we are searching for.
/// </summary>
public bool FindOnlySpecializedReferences { get; set; }
/// <summary>
/// If this option is enabled, find references on a overridden member
/// will find calls to the base member.
/// </summary>
public bool FindCallsThroughVirtualBaseMethod { get; set; }
/// <summary>
/// If this option is enabled, find references on a member implementing
/// an interface will also find calls to the interface.
/// </summary>
public bool FindCallsThroughInterface { get; set; }
/// <summary>
/// If this option is enabled, find references will look for all references
/// to the virtual method slot.
/// </summary>
public bool WholeVirtualSlot { get; set; }
/// <summary>
/// Specifies whether to look for references in documentation comments.
/// This will find entity references in <c>cref</c> attributes and
/// parameter references in <c><param></c> and <c><paramref></c> tags.
/// TODO: implement this feature.
/// </summary>
public bool SearchInDocumentationComments { get; set; }
#endregion
#region GetEffectiveAccessibility
/// <summary>
/// Gets the effective accessibility of the specified entity -
/// that is, the accessibility viewed from the top level.
/// </summary>
/// <remarks>
/// internal member in public class -> internal
/// public member in internal class -> internal
/// protected member in public class -> protected
/// protected member in internal class -> protected and internal
/// </remarks>
public static Accessibility GetEffectiveAccessibility(IEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
Accessibility a = entity.Accessibility;
for (ITypeDefinition declType = entity.DeclaringTypeDefinition; declType != null; declType = declType.DeclaringTypeDefinition) {
a = MergeAccessibility(declType.Accessibility, a);
}
return a;
}
static Accessibility MergeAccessibility(Accessibility outer, Accessibility inner)
{
if (outer == inner)
return inner;
if (outer == Accessibility.None || inner == Accessibility.None)
return Accessibility.None;
if (outer == Accessibility.Private || inner == Accessibility.Private)
return Accessibility.Private;
if (outer == Accessibility.Public)
return inner;
if (inner == Accessibility.Public)
return outer;
// Inner and outer are both in { protected, internal, protected and internal, protected or internal }
// (but they aren't both the same)
if (outer == Accessibility.ProtectedOrInternal)
return inner;
if (inner == Accessibility.ProtectedOrInternal)
return outer;
// Inner and outer are both in { protected, internal, protected and internal },
// but aren't both the same, so the result is protected and internal.
return Accessibility.ProtectedAndInternal;
}
#endregion
#region class SearchScope
sealed class SearchScope : IFindReferenceSearchScope
{
readonly Func<ICompilation, FindReferenceNavigator> factory;
public SearchScope(Func<ICompilation, FindReferenceNavigator> factory)
{
this.factory = factory;
}
public SearchScope(string searchTerm, Func<ICompilation, FindReferenceNavigator> factory)
{
this.searchTerm = searchTerm;
this.factory = factory;
}
internal string searchTerm;
internal FindReferences findReferences;
internal ICompilation declarationCompilation;
internal Accessibility accessibility;
internal ITypeDefinition topLevelTypeDefinition;
IResolveVisitorNavigator IFindReferenceSearchScope.GetNavigator(ICompilation compilation, FoundReferenceCallback callback)
{
FindReferenceNavigator n = factory(compilation);
if (n != null) {
n.callback = callback;
n.findReferences = findReferences;
return n;
} else {
return new ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Skip, null);
}
}
ICompilation IFindReferenceSearchScope.Compilation {
get { return declarationCompilation; }
}
string IFindReferenceSearchScope.SearchTerm {
get { return searchTerm; }
}
Accessibility IFindReferenceSearchScope.Accessibility {
get { return accessibility; }
}
ITypeDefinition IFindReferenceSearchScope.TopLevelTypeDefinition {
get { return topLevelTypeDefinition; }
}
}
abstract class FindReferenceNavigator : IResolveVisitorNavigator
{
internal FoundReferenceCallback callback;
internal FindReferences findReferences;
internal abstract bool CanMatch(AstNode node);
internal abstract bool IsMatch(ResolveResult rr);
ResolveVisitorNavigationMode IResolveVisitorNavigator.Scan(AstNode node)
{
if (CanMatch(node))
return ResolveVisitorNavigationMode.Resolve;
else
return ResolveVisitorNavigationMode.Scan;
}
void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result)
{
if (CanMatch(node) && IsMatch(result)) {
ReportMatch(node, result);
}
}
public virtual void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
{
}
protected void ReportMatch(AstNode node, ResolveResult result)
{
if (callback != null)
callback(node, result);
}
internal virtual void NavigatorDone(CSharpAstResolver resolver, CancellationToken cancellationToken)
{
}
}
#endregion
#region GetSearchScopes
public IList<IFindReferenceSearchScope> GetSearchScopes(IEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
if (entity is IMember)
entity = NormalizeMember((IMember)entity);
Accessibility effectiveAccessibility = GetEffectiveAccessibility(entity);
ITypeDefinition topLevelTypeDefinition = entity.DeclaringTypeDefinition;
while (topLevelTypeDefinition != null && topLevelTypeDefinition.DeclaringTypeDefinition != null)
topLevelTypeDefinition = topLevelTypeDefinition.DeclaringTypeDefinition;
SearchScope scope;
SearchScope additionalScope = null;
switch (entity.EntityType) {
case EntityType.TypeDefinition:
scope = FindTypeDefinitionReferences((ITypeDefinition)entity, this.FindTypeReferencesEvenIfAliased, out additionalScope);
break;
case EntityType.Field:
if (entity.DeclaringTypeDefinition != null && entity.DeclaringTypeDefinition.Kind == TypeKind.Enum)
scope = FindMemberReferences(entity, m => new FindEnumMemberReferences((IField)m));
else
scope = FindMemberReferences(entity, m => new FindFieldReferences((IField)m));
break;
case EntityType.Property:
scope = FindMemberReferences(entity, m => new FindPropertyReferences((IProperty)m));
if (entity.Name == "Current")
additionalScope = FindEnumeratorCurrentReferences((IProperty)entity);
break;
case EntityType.Event:
scope = FindMemberReferences(entity, m => new FindEventReferences((IEvent)m));
break;
case EntityType.Method:
scope = GetSearchScopeForMethod((IMethod)entity);
break;
case EntityType.Indexer:
scope = FindIndexerReferences((IProperty)entity);
break;
case EntityType.Operator:
scope = GetSearchScopeForOperator((IMethod)entity);
break;
case EntityType.Constructor:
IMethod ctor = (IMethod)entity;
scope = FindObjectCreateReferences(ctor);
additionalScope = FindChainedConstructorReferences(ctor);
break;
case EntityType.Destructor:
scope = GetSearchScopeForDestructor((IMethod)entity);
break;
default:
throw new ArgumentException("Unknown entity type " + entity.EntityType);
}
if (scope.accessibility == Accessibility.None)
scope.accessibility = effectiveAccessibility;
scope.declarationCompilation = entity.Compilation;
scope.topLevelTypeDefinition = topLevelTypeDefinition;
scope.findReferences = this;
if (additionalScope != null) {
if (additionalScope.accessibility == Accessibility.None)
additionalScope.accessibility = effectiveAccessibility;
additionalScope.declarationCompilation = entity.Compilation;
additionalScope.topLevelTypeDefinition = topLevelTypeDefinition;
additionalScope.findReferences = this;
return new[] { scope, additionalScope };
} else {
return new[] { scope };
}
}
#endregion
#region GetInterestingFileNames
/// <summary>
/// Gets the file names that possibly contain references to the element being searched for.
/// </summary>
public IEnumerable<CSharpUnresolvedFile> GetInterestingFiles(IFindReferenceSearchScope searchScope, ICompilation compilation)
{
if (searchScope == null)
throw new ArgumentNullException("searchScope");
if (compilation == null)
throw new ArgumentNullException("compilation");
var pc = compilation.MainAssembly.UnresolvedAssembly as IProjectContent;
if (pc == null)
throw new ArgumentException("Main assembly is not a project content");
if (searchScope.TopLevelTypeDefinition != null) {
ITypeDefinition topLevelTypeDef = compilation.Import(searchScope.TopLevelTypeDefinition);
if (topLevelTypeDef == null) {
// This compilation cannot have references to the target entity.
return EmptyList<CSharpUnresolvedFile>.Instance;
}
switch (searchScope.Accessibility) {
case Accessibility.None:
case Accessibility.Private:
if (topLevelTypeDef.ParentAssembly == compilation.MainAssembly)
return topLevelTypeDef.Parts.Select(p => p.UnresolvedFile).OfType<CSharpUnresolvedFile>().Distinct();
else
return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.Protected:
return GetInterestingFilesProtected(topLevelTypeDef);
case Accessibility.Internal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return pc.Files.OfType<CSharpUnresolvedFile>();
else
return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.ProtectedAndInternal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return GetInterestingFilesProtected(topLevelTypeDef);
else
return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.ProtectedOrInternal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return pc.Files.OfType<CSharpUnresolvedFile>();
else
return GetInterestingFilesProtected(topLevelTypeDef);
default:
return pc.Files.OfType<CSharpUnresolvedFile>();
}
} else {
return pc.Files.OfType<CSharpUnresolvedFile>();
}
}
IEnumerable<CSharpUnresolvedFile> GetInterestingFilesProtected(ITypeDefinition referencedTypeDefinition)
{
return (from typeDef in referencedTypeDefinition.Compilation.MainAssembly.GetAllTypeDefinitions()
where typeDef.IsDerivedFrom(referencedTypeDefinition)
from part in typeDef.Parts
select part.UnresolvedFile
).OfType<CSharpUnresolvedFile>().Distinct();
}
#endregion
#region FindReferencesInFile
/// <summary>
/// Finds all references in the given file.
/// </summary>
/// <param name="searchScope">The search scope for which to look.</param>
/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation for the project that contains the file.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (searchScope == null)
throw new ArgumentNullException("searchScope");
FindReferencesInFile(new[] { searchScope }, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
}
/// <summary>
/// Finds all references in the given file.
/// </summary>
/// <param name="searchScopes">The search scopes for which to look.</param>
/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation for the project that contains the file.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (searchScopes == null)
throw new ArgumentNullException("searchScopes");
if (unresolvedFile == null)
throw new ArgumentNullException("unresolvedFile");
if (syntaxTree == null)
throw new ArgumentNullException("syntaxTree");
if (compilation == null)
throw new ArgumentNullException("compilation");
if (callback == null)
throw new ArgumentNullException("callback");
if (searchScopes.Count == 0)
return;
var navigators = new IResolveVisitorNavigator[searchScopes.Count];
for (int i = 0; i < navigators.Length; i++) {
navigators[i] = searchScopes[i].GetNavigator(compilation, callback);
}
IResolveVisitorNavigator combinedNavigator;
if (searchScopes.Count == 1) {
combinedNavigator = navigators[0];
} else {
combinedNavigator = new CompositeResolveVisitorNavigator(navigators);
}
cancellationToken.ThrowIfCancellationRequested();
combinedNavigator = new DetectSkippableNodesNavigator(combinedNavigator, syntaxTree);
cancellationToken.ThrowIfCancellationRequested();
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
resolver.ApplyNavigator(combinedNavigator, cancellationToken);
foreach (var n in navigators) {
var frn = n as FindReferenceNavigator;
if (frn != null)
frn.NavigatorDone(resolver, cancellationToken);
}
}
#endregion
#region Find TypeDefinition References
SearchScope FindTypeDefinitionReferences(ITypeDefinition typeDefinition, bool findTypeReferencesEvenIfAliased, out SearchScope additionalScope)
{
string searchTerm = null;
additionalScope = null;
if (!findTypeReferencesEvenIfAliased && KnownTypeReference.GetCSharpNameByTypeCode(typeDefinition.KnownTypeCode) == null) {
// We can optimize the search by looking only for the type references with the right identifier,
// but only if it's not a primitive type and we're not looking for indirect references (through an alias)
searchTerm = typeDefinition.Name;
if (searchTerm.Length > 9 && searchTerm.EndsWith("Attribute", StringComparison.Ordinal)) {
// The type might be an attribute, so we also need to look for the short form:
string shortForm = searchTerm.Substring(0, searchTerm.Length - 9);
additionalScope = FindTypeDefinitionReferences(typeDefinition, shortForm);
}
}
return FindTypeDefinitionReferences(typeDefinition, searchTerm);
}
SearchScope FindTypeDefinitionReferences(ITypeDefinition typeDefinition, string searchTerm)
{
return new SearchScope(
searchTerm,
delegate (ICompilation compilation) {
ITypeDefinition imported = compilation.Import(typeDefinition);
if (imported != null)
return new FindTypeDefinitionReferencesNavigator(imported, searchTerm);
else
return null;
});
}
sealed class FindTypeDefinitionReferencesNavigator : FindReferenceNavigator
{
readonly ITypeDefinition typeDefinition;
readonly string searchTerm;
public FindTypeDefinitionReferencesNavigator(ITypeDefinition typeDefinition, string searchTerm)
{
this.typeDefinition = typeDefinition;
this.searchTerm = searchTerm;
}
internal override bool CanMatch(AstNode node)
{
IdentifierExpression ident = node as IdentifierExpression;
if (ident != null)
return searchTerm == null || ident.Identifier == searchTerm;
MemberReferenceExpression mre = node as MemberReferenceExpression;
if (mre != null)
return searchTerm == null || mre.MemberName == searchTerm;
SimpleType st = node as SimpleType;
if (st != null)
return searchTerm == null || st.Identifier == searchTerm;
MemberType mt = node as MemberType;
if (mt != null)
return searchTerm == null || mt.MemberName == searchTerm;
if (searchTerm == null && node is PrimitiveType)
return true;
TypeDeclaration typeDecl = node as TypeDeclaration;
if (typeDecl != null)
return searchTerm == null || typeDecl.Name == searchTerm;
DelegateDeclaration delegateDecl = node as DelegateDeclaration;
if (delegateDecl != null)
return searchTerm == null || delegateDecl.Name == searchTerm;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
TypeResolveResult trr = rr as TypeResolveResult;
return trr != null && typeDefinition.Equals(trr.Type.GetDefinition());
}
}
#endregion
#region Find Member References
SearchScope FindMemberReferences(IEntity member, Func<IMember, FindMemberReferencesNavigator> factory)
{
string searchTerm = member.Name;
return new SearchScope(
searchTerm,
delegate(ICompilation compilation) {
IMember imported = compilation.Import((IMember)member);
return imported != null ? factory(imported) : null;
});
}
class FindMemberReferencesNavigator : FindReferenceNavigator
{
readonly IMember member;
readonly string searchTerm;
public FindMemberReferencesNavigator(IMember member)
{
this.member = member;
this.searchTerm = member.Name;
}
internal override bool CanMatch(AstNode node)
{
IdentifierExpression ident = node as IdentifierExpression;
if (ident != null)
return ident.Identifier == searchTerm;
MemberReferenceExpression mre = node as MemberReferenceExpression;
if (mre != null)
return mre.MemberName == searchTerm;
PointerReferenceExpression pre = node as PointerReferenceExpression;
if (pre != null)
return pre.MemberName == searchTerm;
NamedExpression ne = node as NamedExpression;
if (ne != null)
return ne.Name == searchTerm;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(member, mrr.Member, mrr.IsVirtualCall);
}
}
IMember NormalizeMember(IMember member)
{
if (WholeVirtualSlot && member.IsOverride)
member = InheritanceHelper.GetBaseMembers(member, false).FirstOrDefault(m => !m.IsOverride) ?? member;
if (!FindOnlySpecializedReferences)
member = member.MemberDefinition;
return member;
}
bool IsMemberMatch(IMember member, IMember referencedMember, bool isVirtualCall)
{
referencedMember = NormalizeMember(referencedMember);
if (member.Equals(referencedMember))
return true;
if (!isVirtualCall)
return false;
bool isInterfaceCall = referencedMember.DeclaringTypeDefinition != null && referencedMember.DeclaringTypeDefinition.Kind == TypeKind.Interface;
if (FindCallsThroughVirtualBaseMethod && member.IsOverride && !WholeVirtualSlot && !isInterfaceCall) {
// Test if 'member' overrides 'referencedMember':
foreach (var baseMember in InheritanceHelper.GetBaseMembers(member, false)) {
if (FindOnlySpecializedReferences) {
if (baseMember.Equals(referencedMember))
return true;
} else {
if (baseMember.MemberDefinition.Equals(referencedMember))
return true;
}
if (!baseMember.IsOverride)
break;
}
return false;
} else if (FindCallsThroughInterface && isInterfaceCall) {
// Test if 'member' implements 'referencedMember':
if (FindOnlySpecializedReferences) {
return member.ImplementedInterfaceMembers.Contains(referencedMember);
} else {
return member.ImplementedInterfaceMembers.Any(m => m.MemberDefinition.Equals(referencedMember));
}
}
return false;
}
bool PerformVirtualLookup(IMember member, IMember referencedMember)
{
if (FindCallsThroughVirtualBaseMethod && member.IsOverride && !WholeVirtualSlot)
return true;
var typeDef = referencedMember.DeclaringTypeDefinition;
return FindCallsThroughInterface && typeDef != null && typeDef.Kind == TypeKind.Interface;
}
sealed class FindFieldReferences : FindMemberReferencesNavigator
{
public FindFieldReferences(IField field) : base(field)
{
}
internal override bool CanMatch(AstNode node)
{
if (node is VariableInitializer) {
return node.Parent is FieldDeclaration;
}
return base.CanMatch(node);
}
}
sealed class FindEnumMemberReferences : FindMemberReferencesNavigator
{
public FindEnumMemberReferences(IField field) : base(field)
{
}
internal override bool CanMatch(AstNode node)
{
return node is EnumMemberDeclaration || base.CanMatch(node);
}
}
sealed class FindPropertyReferences : FindMemberReferencesNavigator
{
public FindPropertyReferences(IProperty property) : base(property)
{
}
internal override bool CanMatch(AstNode node)
{
return node is PropertyDeclaration || base.CanMatch(node);
}
}
sealed class FindEventReferences : FindMemberReferencesNavigator
{
public FindEventReferences(IEvent ev) : base(ev)
{
}
internal override bool CanMatch(AstNode node)
{
if (node is VariableInitializer) {
return node.Parent is EventDeclaration;
}
return node is CustomEventDeclaration || base.CanMatch(node);
}
}
#endregion
#region Find References to IEnumerator.Current
SearchScope FindEnumeratorCurrentReferences(IProperty property)
{
return new SearchScope(
delegate(ICompilation compilation) {
IProperty imported = compilation.Import(property);
return imported != null ? new FindEnumeratorCurrentReferencesNavigator(imported) : null;
});
}
sealed class FindEnumeratorCurrentReferencesNavigator : FindReferenceNavigator
{
IProperty property;
public FindEnumeratorCurrentReferencesNavigator(IProperty property)
{
this.property = property;
}
internal override bool CanMatch(AstNode node)
{
return node is ForeachStatement;
}
internal override bool IsMatch(ResolveResult rr)
{
ForEachResolveResult ferr = rr as ForEachResolveResult;
return ferr != null && ferr.CurrentProperty != null && findReferences.IsMemberMatch(property, ferr.CurrentProperty, true);
}
}
#endregion
#region Find Method References
SearchScope GetSearchScopeForMethod(IMethod method)
{
Type specialNodeType;
switch (method.Name) {
case "Add":
specialNodeType = typeof(ArrayInitializerExpression);
break;
case "Where":
specialNodeType = typeof(QueryWhereClause);
break;
case "Select":
specialNodeType = typeof(QuerySelectClause);
break;
case "SelectMany":
specialNodeType = typeof(QueryFromClause);
break;
case "Join":
case "GroupJoin":
specialNodeType = typeof(QueryJoinClause);
break;
case "OrderBy":
case "OrderByDescending":
case "ThenBy":
case "ThenByDescending":
specialNodeType = typeof(QueryOrdering);
break;
case "GroupBy":
specialNodeType = typeof(QueryGroupClause);
break;
case "Invoke":
if (method.DeclaringTypeDefinition != null && method.DeclaringTypeDefinition.Kind == TypeKind.Delegate)
specialNodeType = typeof(InvocationExpression);
else
specialNodeType = null;
break;
case "GetEnumerator":
case "MoveNext":
specialNodeType = typeof(ForeachStatement);
break;
default:
specialNodeType = null;
break;
}
// Use searchTerm only if specialNodeType==null
string searchTerm = (specialNodeType == null) ? method.Name : null;
return new SearchScope(
searchTerm,
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(method);
if (imported != null)
return new FindMethodReferences(imported, specialNodeType);
else
return null;
});
}
sealed class FindMethodReferences : FindReferenceNavigator
{
readonly IMethod method;
readonly Type specialNodeType;
HashSet<Expression> potentialMethodGroupConversions = new HashSet<Expression>();
public FindMethodReferences(IMethod method, Type specialNodeType)
{
this.method = method;
this.specialNodeType = specialNodeType;
}
internal override bool CanMatch(AstNode node)
{
if (specialNodeType != null && node.GetType() == specialNodeType)
return true;
Expression expr = node as Expression;
if (expr == null)
return node is MethodDeclaration;
InvocationExpression ie = node as InvocationExpression;
if (ie != null) {
Expression target = ParenthesizedExpression.UnpackParenthesizedExpression(ie.Target);
IdentifierExpression ident = target as IdentifierExpression;
if (ident != null)
return ident.Identifier == method.Name;
MemberReferenceExpression mre = target as MemberReferenceExpression;
if (mre != null)
return mre.MemberName == method.Name;
PointerReferenceExpression pre = target as PointerReferenceExpression;
if (pre != null)
return pre.MemberName == method.Name;
} else if (expr.Role != Roles.TargetExpression) {
// MemberReferences & Identifiers that aren't used in an invocation can still match the method
// as delegate name.
if (expr.GetChildByRole(Roles.Identifier).Name == method.Name)
potentialMethodGroupConversions.Add(expr);
}
return node is MethodDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
if (specialNodeType != null) {
var ferr = rr as ForEachResolveResult;
if (ferr != null) {
return IsMatch(ferr.GetEnumeratorCall)
|| (ferr.MoveNextMethod != null && findReferences.IsMemberMatch(method, ferr.MoveNextMethod, true));
}
}
var mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(method, mrr.Member, mrr.IsVirtualCall);
}
internal override void NavigatorDone(CSharpAstResolver resolver, CancellationToken cancellationToken)
{
foreach (var expr in potentialMethodGroupConversions) {
var conversion = resolver.GetConversion(expr, cancellationToken);
if (conversion.IsMethodGroupConversion && findReferences.IsMemberMatch(method, conversion.Method, conversion.IsVirtualMethodLookup)) {
IType targetType = resolver.GetExpectedType(expr, cancellationToken);
ResolveResult result = resolver.Resolve(expr, cancellationToken);
ReportMatch(expr, new ConversionResolveResult(targetType, result, conversion));
}
}
base.NavigatorDone(resolver, cancellationToken);
}
}
#endregion
#region Find Indexer References
SearchScope FindIndexerReferences(IProperty indexer)
{
return new SearchScope(
delegate (ICompilation compilation) {
IProperty imported = compilation.Import(indexer);
if (imported != null)
return new FindIndexerReferencesNavigator(imported);
else
return null;
});
}
sealed class FindIndexerReferencesNavigator : FindReferenceNavigator
{
readonly IProperty indexer;
public FindIndexerReferencesNavigator(IProperty indexer)
{
this.indexer = indexer;
}
internal override bool CanMatch(AstNode node)
{
return node is IndexerExpression || node is IndexerDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(indexer, mrr.Member, mrr.IsVirtualCall);
}
}
#endregion
#region Find Operator References
SearchScope GetSearchScopeForOperator(IMethod op)
{
OperatorType? opType = OperatorDeclaration.GetOperatorType(op.Name);
if (opType == null)
return GetSearchScopeForMethod(op);
switch (opType.Value) {
case OperatorType.LogicalNot:
return FindUnaryOperator(op, UnaryOperatorType.Not);
case OperatorType.OnesComplement:
return FindUnaryOperator(op, UnaryOperatorType.BitNot);
case OperatorType.UnaryPlus:
return FindUnaryOperator(op, UnaryOperatorType.Plus);
case OperatorType.UnaryNegation:
return FindUnaryOperator(op, UnaryOperatorType.Minus);
case OperatorType.Increment:
return FindUnaryOperator(op, UnaryOperatorType.Increment);
case OperatorType.Decrement:
return FindUnaryOperator(op, UnaryOperatorType.Decrement);
case OperatorType.True:
case OperatorType.False:
// TODO: implement search for op_True/op_False correctly
return GetSearchScopeForMethod(op);
case OperatorType.Addition:
return FindBinaryOperator(op, BinaryOperatorType.Add);
case OperatorType.Subtraction:
return FindBinaryOperator(op, BinaryOperatorType.Subtract);
case OperatorType.Multiply:
return FindBinaryOperator(op, BinaryOperatorType.Multiply);
case OperatorType.Division:
return FindBinaryOperator(op, BinaryOperatorType.Divide);
case OperatorType.Modulus:
return FindBinaryOperator(op, BinaryOperatorType.Modulus);
case OperatorType.BitwiseAnd:
// TODO: an overloaded bitwise operator can also be called using the corresponding logical operator
// (if op_True/op_False is defined)
return FindBinaryOperator(op, BinaryOperatorType.BitwiseAnd);
case OperatorType.BitwiseOr:
return FindBinaryOperator(op, BinaryOperatorType.BitwiseOr);
case OperatorType.ExclusiveOr:
return FindBinaryOperator(op, BinaryOperatorType.ExclusiveOr);
case OperatorType.LeftShift:
return FindBinaryOperator(op, BinaryOperatorType.ShiftLeft);
case OperatorType.RightShift:
return FindBinaryOperator(op, BinaryOperatorType.ShiftRight);
case OperatorType.Equality:
return FindBinaryOperator(op, BinaryOperatorType.Equality);
case OperatorType.Inequality:
return FindBinaryOperator(op, BinaryOperatorType.InEquality);
case OperatorType.GreaterThan:
return FindBinaryOperator(op, BinaryOperatorType.GreaterThan);
case OperatorType.LessThan:
return FindBinaryOperator(op, BinaryOperatorType.LessThan);
case OperatorType.GreaterThanOrEqual:
return FindBinaryOperator(op, BinaryOperatorType.GreaterThanOrEqual);
case OperatorType.LessThanOrEqual:
return FindBinaryOperator(op, BinaryOperatorType.LessThanOrEqual);
case OperatorType.Implicit:
return FindOperator(op, m => new FindImplicitOperatorNavigator(m));
case OperatorType.Explicit:
return FindOperator(op, m => new FindExplicitOperatorNavigator(m));
default:
throw new InvalidOperationException("Invalid value for OperatorType");
}
}
SearchScope FindOperator(IMethod op, Func<IMethod, FindReferenceNavigator> factory)
{
return new SearchScope(
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(op);
return imported != null ? factory(imported) : null;
});
}
SearchScope FindUnaryOperator(IMethod op, UnaryOperatorType operatorType)
{
return FindOperator(op, m => new FindUnaryOperatorNavigator(m, operatorType));
}
sealed class FindUnaryOperatorNavigator : FindReferenceNavigator
{
readonly IMethod op;
readonly UnaryOperatorType operatorType;
public FindUnaryOperatorNavigator(IMethod op, UnaryOperatorType operatorType)
{
this.op = op;
this.operatorType = operatorType;
}
internal override bool CanMatch(AstNode node)
{
UnaryOperatorExpression uoe = node as UnaryOperatorExpression;
if (uoe != null) {
if (operatorType == UnaryOperatorType.Increment)
return uoe.Operator == UnaryOperatorType.Increment || uoe.Operator == UnaryOperatorType.PostIncrement;
else if (operatorType == UnaryOperatorType.Decrement)
return uoe.Operator == UnaryOperatorType.Decrement || uoe.Operator == UnaryOperatorType.PostDecrement;
else
return uoe.Operator == operatorType;
}
return node is OperatorDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
}
}
SearchScope FindBinaryOperator(IMethod op, BinaryOperatorType operatorType)
{
return FindOperator(op, m => new FindBinaryOperatorNavigator(m, operatorType));
}
sealed class FindBinaryOperatorNavigator : FindReferenceNavigator
{
readonly IMethod op;
readonly BinaryOperatorType operatorType;
public FindBinaryOperatorNavigator(IMethod op, BinaryOperatorType operatorType)
{
this.op = op;
this.operatorType = operatorType;
}
internal override bool CanMatch(AstNode node)
{
BinaryOperatorExpression boe = node as BinaryOperatorExpression;
if (boe != null) {
return boe.Operator == operatorType;
}
return node is OperatorDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
}
}
sealed class FindImplicitOperatorNavigator : FindReferenceNavigator
{
readonly IMethod op;
public FindImplicitOperatorNavigator(IMethod op)
{
this.op = op;
}
internal override bool CanMatch(AstNode node)
{
return true;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
}
public override void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
{
if (conversion.IsUserDefined && findReferences.IsMemberMatch(op, conversion.Method, conversion.IsVirtualMethodLookup)) {
ReportMatch(expression, result);
}
}
}
sealed class FindExplicitOperatorNavigator : FindReferenceNavigator
{
readonly IMethod op;
public FindExplicitOperatorNavigator(IMethod op)
{
this.op = op;
}
internal override bool CanMatch(AstNode node)
{
return node is CastExpression;
}
internal override bool IsMatch(ResolveResult rr)
{
ConversionResolveResult crr = rr as ConversionResolveResult;
return crr != null && crr.Conversion.IsUserDefined
&& findReferences.IsMemberMatch(op, crr.Conversion.Method, crr.Conversion.IsVirtualMethodLookup);
}
}
#endregion
#region Find Constructor References
SearchScope FindObjectCreateReferences(IMethod ctor)
{
string searchTerm = null;
if (KnownTypeReference.GetCSharpNameByTypeCode(ctor.DeclaringTypeDefinition.KnownTypeCode) == null) {
// not a built-in type
searchTerm = ctor.DeclaringTypeDefinition.Name;
if (searchTerm.Length > 9 && searchTerm.EndsWith("Attribute", StringComparison.Ordinal)) {
// we also need to look for the short form
searchTerm = null;
}
}
return new SearchScope(
searchTerm,
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(ctor);
if (imported != null)
return new FindObjectCreateReferencesNavigator(imported);
else
return null;
});
}
sealed class FindObjectCreateReferencesNavigator : FindReferenceNavigator
{
readonly IMethod ctor;
public FindObjectCreateReferencesNavigator(IMethod ctor)
{
this.ctor = ctor;
}
internal override bool CanMatch(AstNode node)
{
return node is ObjectCreateExpression || node is ConstructorDeclaration || node is Attribute;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(ctor, mrr.Member, mrr.IsVirtualCall);
}
}
SearchScope FindChainedConstructorReferences(IMethod ctor)
{
SearchScope searchScope = new SearchScope(
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(ctor);
if (imported != null)
return new FindChainedConstructorReferencesNavigator(imported);
else
return null;
});
if (ctor.DeclaringTypeDefinition.IsSealed)
searchScope.accessibility = Accessibility.Private;
else
searchScope.accessibility = Accessibility.Protected;
searchScope.accessibility = MergeAccessibility(GetEffectiveAccessibility(ctor), searchScope.accessibility);
return searchScope;
}
sealed class FindChainedConstructorReferencesNavigator : FindReferenceNavigator
{
readonly IMethod ctor;
public FindChainedConstructorReferencesNavigator(IMethod ctor)
{
this.ctor = ctor;
}
internal override bool CanMatch(AstNode node)
{
return node is ConstructorInitializer;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(ctor, mrr.Member, mrr.IsVirtualCall);
}
}
#endregion
#region Find Destructor References
SearchScope GetSearchScopeForDestructor(IMethod dtor)
{
var scope = new SearchScope (
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(dtor);
if (imported != null) {
return new FindDestructorReferencesNavigator (imported);
} else {
return null;
}
});
scope.accessibility = Accessibility.Private;
return scope;
}
sealed class FindDestructorReferencesNavigator : FindReferenceNavigator
{
readonly IMethod dtor;
public FindDestructorReferencesNavigator (IMethod dtor)
{
this.dtor = dtor;
}
internal override bool CanMatch(AstNode node)
{
return node is DestructorDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(dtor, mrr.Member, mrr.IsVirtualCall);
}
}
#endregion
#region Find Local Variable References
/// <summary>
/// Finds all references of a given variable.
/// </summary>
/// <param name="variable">The variable for which to look.</param>
/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
public void FindLocalReferences(IVariable variable, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (variable == null)
throw new ArgumentNullException("variable");
var searchScope = new SearchScope(c => new FindLocalReferencesNavigator(variable));
searchScope.declarationCompilation = compilation;
FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
}
class FindLocalReferencesNavigator : FindReferenceNavigator
{
readonly IVariable variable;
public FindLocalReferencesNavigator(IVariable variable)
{
this.variable = variable;
}
internal override bool CanMatch(AstNode node)
{
var expr = node as IdentifierExpression;
if (expr != null)
return expr.TypeArguments.Count == 0 && variable.Name == expr.Identifier;
var vi = node as VariableInitializer;
if (vi != null)
return vi.Name == variable.Name;
var pd = node as ParameterDeclaration;
if (pd != null)
return pd.Name == variable.Name;
var id = node as Identifier;
if (id != null)
return id.Name == variable.Name;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
var lrr = rr as LocalResolveResult;
return lrr != null && lrr.Variable.Name == variable.Name && lrr.Variable.Region == variable.Region;
}
}
#endregion
#region Find Type Parameter References
/// <summary>
/// Finds all references of a given type parameter.
/// </summary>
/// <param name="typeParameter">The type parameter for which to look.</param>
/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
public void FindTypeParameterReferences(IType typeParameter, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (typeParameter == null)
throw new ArgumentNullException("typeParameter");
if (typeParameter.Kind != TypeKind.TypeParameter)
throw new ArgumentOutOfRangeException("typeParameter", "Only type parameters are allowed");
var searchScope = new SearchScope(c => new FindTypeParameterReferencesNavigator((ITypeParameter)typeParameter));
searchScope.declarationCompilation = compilation;
searchScope.accessibility = Accessibility.Private;
FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
}
class FindTypeParameterReferencesNavigator : FindReferenceNavigator
{
readonly ITypeParameter typeParameter;
public FindTypeParameterReferencesNavigator(ITypeParameter typeParameter)
{
this.typeParameter = typeParameter;
}
internal override bool CanMatch(AstNode node)
{
var type = node as SimpleType;
if (type != null)
return type.Identifier == typeParameter.Name;
var declaration = node as TypeParameterDeclaration;
if (declaration != null)
return declaration.Name == typeParameter.Name;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
var lrr = rr as TypeResolveResult;
return lrr != null && lrr.Type.Kind == TypeKind.TypeParameter && ((ITypeParameter)lrr.Type).Region == typeParameter.Region;
}
}
#endregion
}
}
| |
// 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.EntityState.Type
{
/// <summary>
/// Enumeration values for AirPlatform (es.type.kind.1.domain.2.cat, Platform-Air Category,
/// section 4.2.1.1.3.2)
/// 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 enum AirPlatform : byte
{
/// <summary>
/// Other.
/// </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("Other.")]
Other = 0,
/// <summary>
/// Fighter/Air Defense.
/// </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("Fighter/Air Defense.")]
FighterAirDefense = 1,
/// <summary>
/// Attack/Strike.
/// </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("Attack/Strike.")]
AttackStrike = 2,
/// <summary>
/// Bomber.
/// </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("Bomber.")]
Bomber = 3,
/// <summary>
/// Cargo/Tanker.
/// </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("Cargo/Tanker.")]
CargoTanker = 4,
/// <summary>
/// ASW/Patrol/Observation.
/// </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("ASW/Patrol/Observation.")]
ASWPatrolObservation = 5,
/// <summary>
/// Electronic Warfare (EW).
/// </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("Electronic Warfare (EW).")]
ElectronicWarfare = 6,
/// <summary>
/// Reconnaissance.
/// </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("Reconnaissance.")]
Reconnaissance = 7,
/// <summary>
/// Surveillance/C2 (Airborne Early Warning).
/// </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("Surveillance/C2 (Airborne Early Warning).")]
SurveillanceC2AirborneEarlyWarning = 8,
/// <summary>
/// Attack Helicopter.
/// </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("Attack Helicopter.")]
AttackHelicopter = 20,
/// <summary>
/// Utility Helicopter.
/// </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("Utility Helicopter.")]
UtilityHelicopter = 21,
/// <summary>
/// Antisubmarine Warfare/Patrol Helicopter.
/// </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("Antisubmarine Warfare/Patrol Helicopter.")]
AntisubmarineWarfarePatrolHelicopter = 22,
/// <summary>
/// Cargo Helicopter.
/// </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("Cargo Helicopter.")]
CargoHelicopter = 23,
/// <summary>
/// Observation Helicopter.
/// </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("Observation Helicopter.")]
ObservationHelicopter = 24,
/// <summary>
/// Special Operations Helicopter.
/// </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("Special Operations Helicopter.")]
SpecialOperationsHelicopter = 25,
/// <summary>
/// Trainer.
/// </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("Trainer.")]
Trainer = 40,
/// <summary>
/// Unmanned.
/// </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("Unmanned.")]
Unmanned = 50,
/// <summary>
/// Non-Combatant Commercial Aircraft.
/// </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("Non-Combatant Commercial Aircraft.")]
NonCombatantCommercialAircraft = 57
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MyExamination.Web.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebApi.Server.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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 System.Xml;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Globalization;
using System.Runtime.Serialization;
namespace System.Xml
{
internal class XmlBinaryReader : XmlBaseReader
{
private bool _isTextWithEndElement;
private bool _buffered;
private ArrayState _arrayState;
private int _arrayCount;
private int _maxBytesPerRead;
private XmlBinaryNodeType _arrayNodeType;
public XmlBinaryReader()
{
}
public void SetInput(byte[] buffer, int offset, int count,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.ValueMustBeNonNegative)));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.ValueMustBeNonNegative)));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
MoveToInitial(quotas, session, null);
BufferReader.SetBuffer(buffer, offset, count, dictionary, session);
_buffered = true;
}
public void SetInput(Stream stream,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session)
{
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
MoveToInitial(quotas, session, null);
BufferReader.SetBuffer(stream, dictionary, session);
_buffered = false;
}
private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose)
{
MoveToInitial(quotas);
_maxBytesPerRead = quotas.MaxBytesPerRead;
_arrayState = ArrayState.None;
_isTextWithEndElement = false;
}
public override void Close()
{
base.Close();
}
public override string ReadElementContentAsString()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsString();
string value;
switch (GetNodeType())
{
case XmlBinaryNodeType.Chars8TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadUTF8String(ReadUInt8());
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.DictionaryTextWithEndElement:
SkipNodeType();
value = BufferReader.GetDictionaryString(ReadDictionaryKey()).Value;
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsString();
break;
}
DiagnosticUtility.DebugAssert(value.Length < Quotas.MaxStringContentLength, "");
return value;
}
public override bool ReadElementContentAsBoolean()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsBoolean();
bool value;
switch (GetNodeType())
{
case XmlBinaryNodeType.TrueTextWithEndElement:
SkipNodeType();
value = true;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.FalseTextWithEndElement:
SkipNodeType();
value = false;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.BoolTextWithEndElement:
SkipNodeType();
value = (BufferReader.ReadUInt8() != 0);
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsBoolean();
break;
}
return value;
}
public override int ReadElementContentAsInt()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsInt();
int value;
switch (GetNodeType())
{
case XmlBinaryNodeType.ZeroTextWithEndElement:
SkipNodeType();
value = 0;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.OneTextWithEndElement:
SkipNodeType();
value = 1;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int8TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt8();
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int16TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt16();
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int32TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt32();
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsInt();
break;
}
return value;
}
private bool CanOptimizeReadElementContent()
{
return (_arrayState == ArrayState.None);
}
public override float ReadElementContentAsFloat()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.FloatTextWithEndElement)
{
SkipNodeType();
float value = BufferReader.ReadSingle();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsFloat();
}
public override double ReadElementContentAsDouble()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DoubleTextWithEndElement)
{
SkipNodeType();
double value = BufferReader.ReadDouble();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDouble();
}
public override decimal ReadElementContentAsDecimal()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DecimalTextWithEndElement)
{
SkipNodeType();
decimal value = BufferReader.ReadDecimal();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDecimal();
}
public override DateTime ReadElementContentAsDateTime()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DateTimeTextWithEndElement)
{
SkipNodeType();
DateTime value = BufferReader.ReadDateTime();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDateTime();
}
public override TimeSpan ReadElementContentAsTimeSpan()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.TimeSpanTextWithEndElement)
{
SkipNodeType();
TimeSpan value = BufferReader.ReadTimeSpan();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsTimeSpan();
}
public override Guid ReadElementContentAsGuid()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.GuidTextWithEndElement)
{
SkipNodeType();
Guid value = BufferReader.ReadGuid();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsGuid();
}
public override UniqueId ReadElementContentAsUniqueId()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.UniqueIdTextWithEndElement)
{
SkipNodeType();
UniqueId value = BufferReader.ReadUniqueId();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsUniqueId();
}
public override bool TryGetBase64ContentLength(out int length)
{
length = 0;
if (!_buffered)
return false;
if (_arrayState != ArrayState.None)
return false;
int totalLength;
if (!this.Node.Value.TryGetByteArrayLength(out totalLength))
return false;
int offset = BufferReader.Offset;
try
{
bool done = false;
while (!done && !BufferReader.EndOfFile)
{
XmlBinaryNodeType nodeType = GetNodeType();
SkipNodeType();
int actual;
switch (nodeType)
{
case XmlBinaryNodeType.Bytes8TextWithEndElement:
actual = BufferReader.ReadUInt8();
done = true;
break;
case XmlBinaryNodeType.Bytes16TextWithEndElement:
actual = BufferReader.ReadUInt16();
done = true;
break;
case XmlBinaryNodeType.Bytes32TextWithEndElement:
actual = BufferReader.ReadUInt31();
done = true;
break;
case XmlBinaryNodeType.EndElement:
actual = 0;
done = true;
break;
case XmlBinaryNodeType.Bytes8Text:
actual = BufferReader.ReadUInt8();
break;
case XmlBinaryNodeType.Bytes16Text:
actual = BufferReader.ReadUInt16();
break;
case XmlBinaryNodeType.Bytes32Text:
actual = BufferReader.ReadUInt31();
break;
default:
// Non-optimal or unexpected node - fallback
return false;
}
BufferReader.Advance(actual);
if (totalLength > int.MaxValue - actual)
return false;
totalLength += actual;
}
length = totalLength;
return true;
}
finally
{
BufferReader.Offset = offset;
}
}
private void ReadTextWithEndElement()
{
ExitScope();
ReadNode();
}
private XmlAtomicTextNode MoveToAtomicTextWithEndElement()
{
_isTextWithEndElement = true;
return MoveToAtomicText();
}
public override bool Read()
{
if (this.Node.ReadState == ReadState.Closed)
return false;
if (_isTextWithEndElement)
{
_isTextWithEndElement = false;
MoveToEndElement();
return true;
}
if (_arrayState == ArrayState.Content)
{
if (_arrayCount != 0)
{
MoveToArrayElement();
return true;
}
_arrayState = ArrayState.None;
}
if (this.Node.ExitScope)
{
ExitScope();
}
return ReadNode();
}
private bool ReadNode()
{
if (BufferReader.EndOfFile)
{
MoveToEndOfFile();
return false;
}
if (!_buffered)
BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead);
XmlBinaryNodeType nodeType;
if (_arrayState == ArrayState.None)
{
nodeType = GetNodeType();
SkipNodeType();
}
else
{
DiagnosticUtility.DebugAssert(_arrayState == ArrayState.Element, "");
nodeType = _arrayNodeType;
_arrayCount--;
_arrayState = ArrayState.Content;
}
XmlElementNode elementNode;
PrefixHandleType prefix;
switch (nodeType)
{
case XmlBinaryNodeType.ShortElement:
elementNode = EnterScope();
elementNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.Element:
elementNode = EnterScope();
ReadName(elementNode.Prefix);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.ShortDictionaryElement:
elementNode = EnterScope();
elementNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.DictionaryElement:
elementNode = EnterScope();
ReadName(elementNode.Prefix);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.PrefixElementA:
case XmlBinaryNodeType.PrefixElementB:
case XmlBinaryNodeType.PrefixElementC:
case XmlBinaryNodeType.PrefixElementD:
case XmlBinaryNodeType.PrefixElementE:
case XmlBinaryNodeType.PrefixElementF:
case XmlBinaryNodeType.PrefixElementG:
case XmlBinaryNodeType.PrefixElementH:
case XmlBinaryNodeType.PrefixElementI:
case XmlBinaryNodeType.PrefixElementJ:
case XmlBinaryNodeType.PrefixElementK:
case XmlBinaryNodeType.PrefixElementL:
case XmlBinaryNodeType.PrefixElementM:
case XmlBinaryNodeType.PrefixElementN:
case XmlBinaryNodeType.PrefixElementO:
case XmlBinaryNodeType.PrefixElementP:
case XmlBinaryNodeType.PrefixElementQ:
case XmlBinaryNodeType.PrefixElementR:
case XmlBinaryNodeType.PrefixElementS:
case XmlBinaryNodeType.PrefixElementT:
case XmlBinaryNodeType.PrefixElementU:
case XmlBinaryNodeType.PrefixElementV:
case XmlBinaryNodeType.PrefixElementW:
case XmlBinaryNodeType.PrefixElementX:
case XmlBinaryNodeType.PrefixElementY:
case XmlBinaryNodeType.PrefixElementZ:
elementNode = EnterScope();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixElementA);
elementNode.Prefix.SetValue(prefix);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.PrefixDictionaryElementA:
case XmlBinaryNodeType.PrefixDictionaryElementB:
case XmlBinaryNodeType.PrefixDictionaryElementC:
case XmlBinaryNodeType.PrefixDictionaryElementD:
case XmlBinaryNodeType.PrefixDictionaryElementE:
case XmlBinaryNodeType.PrefixDictionaryElementF:
case XmlBinaryNodeType.PrefixDictionaryElementG:
case XmlBinaryNodeType.PrefixDictionaryElementH:
case XmlBinaryNodeType.PrefixDictionaryElementI:
case XmlBinaryNodeType.PrefixDictionaryElementJ:
case XmlBinaryNodeType.PrefixDictionaryElementK:
case XmlBinaryNodeType.PrefixDictionaryElementL:
case XmlBinaryNodeType.PrefixDictionaryElementM:
case XmlBinaryNodeType.PrefixDictionaryElementN:
case XmlBinaryNodeType.PrefixDictionaryElementO:
case XmlBinaryNodeType.PrefixDictionaryElementP:
case XmlBinaryNodeType.PrefixDictionaryElementQ:
case XmlBinaryNodeType.PrefixDictionaryElementR:
case XmlBinaryNodeType.PrefixDictionaryElementS:
case XmlBinaryNodeType.PrefixDictionaryElementT:
case XmlBinaryNodeType.PrefixDictionaryElementU:
case XmlBinaryNodeType.PrefixDictionaryElementV:
case XmlBinaryNodeType.PrefixDictionaryElementW:
case XmlBinaryNodeType.PrefixDictionaryElementX:
case XmlBinaryNodeType.PrefixDictionaryElementY:
case XmlBinaryNodeType.PrefixDictionaryElementZ:
elementNode = EnterScope();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryElementA);
elementNode.Prefix.SetValue(prefix);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.EndElement:
MoveToEndElement();
return true;
case XmlBinaryNodeType.Comment:
ReadName(MoveToComment().Value);
return true;
case XmlBinaryNodeType.EmptyTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Empty);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.ZeroTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Zero);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.OneTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.One);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.TrueTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.True);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.FalseTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.False);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.BoolTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ReadUInt8() != 0 ? ValueHandleType.True : ValueHandleType.False);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.Chars8TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt8());
else
ReadPartialUTF8Text(true, ReadUInt8());
return true;
case XmlBinaryNodeType.Chars8Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt8());
else
ReadPartialUTF8Text(false, ReadUInt8());
return true;
case XmlBinaryNodeType.Chars16TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt16());
else
ReadPartialUTF8Text(true, ReadUInt16());
return true;
case XmlBinaryNodeType.Chars16Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt16());
else
ReadPartialUTF8Text(false, ReadUInt16());
return true;
case XmlBinaryNodeType.Chars32TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt31());
else
ReadPartialUTF8Text(true, ReadUInt31());
return true;
case XmlBinaryNodeType.Chars32Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt31());
else
ReadPartialUTF8Text(false, ReadUInt31());
return true;
case XmlBinaryNodeType.UnicodeChars8TextWithEndElement:
ReadUnicodeText(true, ReadUInt8());
return true;
case XmlBinaryNodeType.UnicodeChars8Text:
ReadUnicodeText(false, ReadUInt8());
return true;
case XmlBinaryNodeType.UnicodeChars16TextWithEndElement:
ReadUnicodeText(true, ReadUInt16());
return true;
case XmlBinaryNodeType.UnicodeChars16Text:
ReadUnicodeText(false, ReadUInt16());
return true;
case XmlBinaryNodeType.UnicodeChars32TextWithEndElement:
ReadUnicodeText(true, ReadUInt31());
return true;
case XmlBinaryNodeType.UnicodeChars32Text:
ReadUnicodeText(false, ReadUInt31());
return true;
case XmlBinaryNodeType.Bytes8TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt8());
else
ReadPartialBinaryText(true, ReadUInt8());
return true;
case XmlBinaryNodeType.Bytes8Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt8());
else
ReadPartialBinaryText(false, ReadUInt8());
return true;
case XmlBinaryNodeType.Bytes16TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt16());
else
ReadPartialBinaryText(true, ReadUInt16());
return true;
case XmlBinaryNodeType.Bytes16Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt16());
else
ReadPartialBinaryText(false, ReadUInt16());
return true;
case XmlBinaryNodeType.Bytes32TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt31());
else
ReadPartialBinaryText(true, ReadUInt31());
return true;
case XmlBinaryNodeType.Bytes32Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt31());
else
ReadPartialBinaryText(false, ReadUInt31());
return true;
case XmlBinaryNodeType.DictionaryTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetDictionaryValue(ReadDictionaryKey());
return true;
case XmlBinaryNodeType.UniqueIdTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UniqueId, ValueHandleLength.UniqueId);
return true;
case XmlBinaryNodeType.GuidTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Guid, ValueHandleLength.Guid);
return true;
case XmlBinaryNodeType.DecimalTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Decimal, ValueHandleLength.Decimal);
return true;
case XmlBinaryNodeType.Int8TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int8, ValueHandleLength.Int8);
return true;
case XmlBinaryNodeType.Int16TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int16, ValueHandleLength.Int16);
return true;
case XmlBinaryNodeType.Int32TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int32, ValueHandleLength.Int32);
return true;
case XmlBinaryNodeType.Int64TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int64, ValueHandleLength.Int64);
return true;
case XmlBinaryNodeType.UInt64TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UInt64, ValueHandleLength.UInt64);
return true;
case XmlBinaryNodeType.FloatTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Single, ValueHandleLength.Single);
return true;
case XmlBinaryNodeType.DoubleTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Double, ValueHandleLength.Double);
return true;
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.TimeSpan, ValueHandleLength.TimeSpan);
return true;
case XmlBinaryNodeType.DateTimeTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.DateTime, ValueHandleLength.DateTime);
return true;
case XmlBinaryNodeType.QNameDictionaryTextWithEndElement:
BufferReader.ReadQName(MoveToAtomicTextWithEndElement().Value);
return true;
case XmlBinaryNodeType.Array:
ReadArray();
return true;
default:
BufferReader.ReadValue(nodeType, MoveToComplexText().Value);
return true;
}
}
private void VerifyWhitespace()
{
if (!this.Node.Value.IsWhitespace())
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
}
private void ReadAttributes()
{
XmlBinaryNodeType nodeType = GetNodeType();
if (nodeType < XmlBinaryNodeType.MinAttribute || nodeType > XmlBinaryNodeType.MaxAttribute)
return;
ReadAttributes2();
}
private void ReadAttributes2()
{
int startOffset = 0;
if (_buffered)
startOffset = BufferReader.Offset;
while (true)
{
XmlAttributeNode attributeNode;
Namespace nameSpace;
PrefixHandleType prefix;
XmlBinaryNodeType nodeType = GetNodeType();
switch (nodeType)
{
case XmlBinaryNodeType.ShortAttribute:
SkipNodeType();
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.Attribute:
SkipNodeType();
attributeNode = AddAttribute();
ReadName(attributeNode.Prefix);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
FixXmlAttribute(attributeNode);
break;
case XmlBinaryNodeType.ShortDictionaryAttribute:
SkipNodeType();
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.DictionaryAttribute:
SkipNodeType();
attributeNode = AddAttribute();
ReadName(attributeNode.Prefix);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.XmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
ReadName(nameSpace.Prefix);
ReadName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.ShortXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
nameSpace.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.ShortDictionaryXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
nameSpace.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.DictionaryXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
ReadName(nameSpace.Prefix);
ReadDictionaryName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.PrefixDictionaryAttributeA:
case XmlBinaryNodeType.PrefixDictionaryAttributeB:
case XmlBinaryNodeType.PrefixDictionaryAttributeC:
case XmlBinaryNodeType.PrefixDictionaryAttributeD:
case XmlBinaryNodeType.PrefixDictionaryAttributeE:
case XmlBinaryNodeType.PrefixDictionaryAttributeF:
case XmlBinaryNodeType.PrefixDictionaryAttributeG:
case XmlBinaryNodeType.PrefixDictionaryAttributeH:
case XmlBinaryNodeType.PrefixDictionaryAttributeI:
case XmlBinaryNodeType.PrefixDictionaryAttributeJ:
case XmlBinaryNodeType.PrefixDictionaryAttributeK:
case XmlBinaryNodeType.PrefixDictionaryAttributeL:
case XmlBinaryNodeType.PrefixDictionaryAttributeM:
case XmlBinaryNodeType.PrefixDictionaryAttributeN:
case XmlBinaryNodeType.PrefixDictionaryAttributeO:
case XmlBinaryNodeType.PrefixDictionaryAttributeP:
case XmlBinaryNodeType.PrefixDictionaryAttributeQ:
case XmlBinaryNodeType.PrefixDictionaryAttributeR:
case XmlBinaryNodeType.PrefixDictionaryAttributeS:
case XmlBinaryNodeType.PrefixDictionaryAttributeT:
case XmlBinaryNodeType.PrefixDictionaryAttributeU:
case XmlBinaryNodeType.PrefixDictionaryAttributeV:
case XmlBinaryNodeType.PrefixDictionaryAttributeW:
case XmlBinaryNodeType.PrefixDictionaryAttributeX:
case XmlBinaryNodeType.PrefixDictionaryAttributeY:
case XmlBinaryNodeType.PrefixDictionaryAttributeZ:
SkipNodeType();
attributeNode = AddAttribute();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryAttributeA);
attributeNode.Prefix.SetValue(prefix);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.PrefixAttributeA:
case XmlBinaryNodeType.PrefixAttributeB:
case XmlBinaryNodeType.PrefixAttributeC:
case XmlBinaryNodeType.PrefixAttributeD:
case XmlBinaryNodeType.PrefixAttributeE:
case XmlBinaryNodeType.PrefixAttributeF:
case XmlBinaryNodeType.PrefixAttributeG:
case XmlBinaryNodeType.PrefixAttributeH:
case XmlBinaryNodeType.PrefixAttributeI:
case XmlBinaryNodeType.PrefixAttributeJ:
case XmlBinaryNodeType.PrefixAttributeK:
case XmlBinaryNodeType.PrefixAttributeL:
case XmlBinaryNodeType.PrefixAttributeM:
case XmlBinaryNodeType.PrefixAttributeN:
case XmlBinaryNodeType.PrefixAttributeO:
case XmlBinaryNodeType.PrefixAttributeP:
case XmlBinaryNodeType.PrefixAttributeQ:
case XmlBinaryNodeType.PrefixAttributeR:
case XmlBinaryNodeType.PrefixAttributeS:
case XmlBinaryNodeType.PrefixAttributeT:
case XmlBinaryNodeType.PrefixAttributeU:
case XmlBinaryNodeType.PrefixAttributeV:
case XmlBinaryNodeType.PrefixAttributeW:
case XmlBinaryNodeType.PrefixAttributeX:
case XmlBinaryNodeType.PrefixAttributeY:
case XmlBinaryNodeType.PrefixAttributeZ:
SkipNodeType();
attributeNode = AddAttribute();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixAttributeA);
attributeNode.Prefix.SetValue(prefix);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
default:
ProcessAttributes();
return;
}
}
}
private void ReadText(XmlTextNode textNode, ValueHandleType type, int length)
{
int offset = BufferReader.ReadBytes(length);
textNode.Value.SetValue(type, offset, length);
if (this.OutsideRootElement)
VerifyWhitespace();
}
private void ReadBinaryText(XmlTextNode textNode, int length)
{
ReadText(textNode, ValueHandleType.Base64, length);
}
private void ReadPartialUTF8Text(bool withEndElement, int length)
{
// The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need
// to account for that.
const int maxTextNodeLength = 5;
int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0);
if (length <= maxLength)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, length);
else
ReadText(MoveToComplexText(), ValueHandleType.UTF8, length);
}
else
{
// We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode
// for the split data.
int actual = Math.Max(maxLength - maxTextNodeLength, 0);
int offset = BufferReader.ReadBytes(actual);
// We need to make sure we don't split a utf8 character, so scan backwards for a
// character boundary. We'll actually always push off at least one character since
// although we find the character boundary, we don't bother to figure out if we have
// all the bytes that comprise the character.
int i;
for (i = offset + actual - 1; i >= offset; i--)
{
byte b = BufferReader.GetByte(i);
// The first byte of UTF8 character sequence has either the high bit off, or the
// two high bits set.
if ((b & 0x80) == 0 || (b & 0xC0) == 0xC0)
break;
}
// Move any split characters so we can insert the node
int byteCount = (offset + actual - i);
// Include the split characters in the count
BufferReader.Offset = BufferReader.Offset - byteCount;
actual -= byteCount;
MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, actual);
if (this.OutsideRootElement)
VerifyWhitespace();
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Chars32TextWithEndElement : XmlBinaryNodeType.Chars32Text);
InsertNode(nodeType, length - actual);
}
}
private void ReadUnicodeText(bool withEndElement, int length)
{
if ((length & 1) != 0)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
if (_buffered)
{
if (withEndElement)
{
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length);
}
else
{
ReadText(MoveToComplexText(), ValueHandleType.Unicode, length);
}
}
else
{
ReadPartialUnicodeText(withEndElement, length);
}
}
private void ReadPartialUnicodeText(bool withEndElement, int length)
{
// The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need
// to account for that.
const int maxTextNodeLength = 5;
int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0);
if (length <= maxLength)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length);
else
ReadText(MoveToComplexText(), ValueHandleType.Unicode, length);
}
else
{
// We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode
// for the split data.
int actual = Math.Max(maxLength - maxTextNodeLength, 0);
// Make sure we break on a char boundary
if ((actual & 1) != 0)
actual--;
int offset = BufferReader.ReadBytes(actual);
// We need to make sure we don't split a unicode surrogate character
int byteCount = 0;
char ch = (char)BufferReader.GetInt16(offset + actual - sizeof(char));
// If the last char is a high surrogate char, then move back
if (ch >= 0xD800 && ch < 0xDC00)
byteCount = sizeof(char);
// Include the split characters in the count
BufferReader.Offset = BufferReader.Offset - byteCount;
actual -= byteCount;
MoveToComplexText().Value.SetValue(ValueHandleType.Unicode, offset, actual);
if (this.OutsideRootElement)
VerifyWhitespace();
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.UnicodeChars32TextWithEndElement : XmlBinaryNodeType.UnicodeChars32Text);
InsertNode(nodeType, length - actual);
}
}
private void ReadPartialBinaryText(bool withEndElement, int length)
{
const int nodeLength = 5;
int maxBytesPerRead = Math.Max(_maxBytesPerRead - nodeLength, 0);
if (length <= maxBytesPerRead)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Base64, length);
else
ReadText(MoveToComplexText(), ValueHandleType.Base64, length);
}
else
{
int actual = maxBytesPerRead;
if (actual > 3)
actual -= (actual % 3);
ReadText(MoveToComplexText(), ValueHandleType.Base64, actual);
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Bytes32TextWithEndElement : XmlBinaryNodeType.Bytes32Text);
InsertNode(nodeType, length - actual);
}
}
private void InsertNode(XmlBinaryNodeType nodeType, int length)
{
byte[] buffer = new byte[5];
buffer[0] = (byte)nodeType;
buffer[1] = (byte)length;
length >>= 8;
buffer[2] = (byte)length;
length >>= 8;
buffer[3] = (byte)length;
length >>= 8;
buffer[4] = (byte)length;
BufferReader.InsertBytes(buffer, 0, buffer.Length);
}
private void ReadAttributeText(XmlAttributeTextNode textNode)
{
XmlBinaryNodeType nodeType = GetNodeType();
SkipNodeType();
BufferReader.ReadValue(nodeType, textNode.Value);
}
private void ReadName(ValueHandle value)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
value.SetValue(ValueHandleType.UTF8, offset, length);
}
private void ReadName(StringHandle handle)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
handle.SetValue(offset, length);
}
private void ReadName(PrefixHandle prefix)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
prefix.SetValue(offset, length);
}
private void ReadDictionaryName(StringHandle s)
{
int key = ReadDictionaryKey();
s.SetValue(key);
}
private XmlBinaryNodeType GetNodeType()
{
return BufferReader.GetNodeType();
}
private void SkipNodeType()
{
BufferReader.SkipNodeType();
}
private int ReadDictionaryKey()
{
return BufferReader.ReadDictionaryKey();
}
private int ReadMultiByteUInt31()
{
return BufferReader.ReadMultiByteUInt31();
}
private int ReadUInt8()
{
return BufferReader.ReadUInt8();
}
private int ReadUInt16()
{
return BufferReader.ReadUInt16();
}
private int ReadUInt31()
{
return BufferReader.ReadUInt31();
}
private bool IsValidArrayType(XmlBinaryNodeType nodeType)
{
switch (nodeType)
{
case XmlBinaryNodeType.BoolTextWithEndElement:
case XmlBinaryNodeType.Int16TextWithEndElement:
case XmlBinaryNodeType.Int32TextWithEndElement:
case XmlBinaryNodeType.Int64TextWithEndElement:
case XmlBinaryNodeType.FloatTextWithEndElement:
case XmlBinaryNodeType.DoubleTextWithEndElement:
case XmlBinaryNodeType.DecimalTextWithEndElement:
case XmlBinaryNodeType.DateTimeTextWithEndElement:
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
case XmlBinaryNodeType.GuidTextWithEndElement:
return true;
default:
return false;
}
}
private void ReadArray()
{
if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
ReadNode(); // ReadStartElement
if (this.Node.NodeType != XmlNodeType.Element)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
ReadNode(); // ReadEndElement
if (this.Node.NodeType != XmlNodeType.EndElement)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
_arrayState = ArrayState.Element;
_arrayNodeType = GetNodeType();
if (!IsValidArrayType(_arrayNodeType))
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
SkipNodeType();
_arrayCount = ReadMultiByteUInt31();
if (_arrayCount == 0)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
MoveToArrayElement();
}
private void MoveToArrayElement()
{
_arrayState = ArrayState.Element;
MoveToNode(ElementNode);
}
private void SkipArrayElements(int count)
{
_arrayCount -= count;
if (_arrayCount == 0)
{
_arrayState = ArrayState.None;
ExitScope();
ReadNode();
}
}
public override bool IsStartArray(out Type type)
{
type = null;
if (_arrayState != ArrayState.Element)
return false;
switch (_arrayNodeType)
{
case XmlBinaryNodeType.BoolTextWithEndElement:
type = typeof(bool);
break;
case XmlBinaryNodeType.Int16TextWithEndElement:
type = typeof(Int16);
break;
case XmlBinaryNodeType.Int32TextWithEndElement:
type = typeof(Int32);
break;
case XmlBinaryNodeType.Int64TextWithEndElement:
type = typeof(Int64);
break;
case XmlBinaryNodeType.FloatTextWithEndElement:
type = typeof(float);
break;
case XmlBinaryNodeType.DoubleTextWithEndElement:
type = typeof(double);
break;
case XmlBinaryNodeType.DecimalTextWithEndElement:
type = typeof(decimal);
break;
case XmlBinaryNodeType.DateTimeTextWithEndElement:
type = typeof(DateTime);
break;
case XmlBinaryNodeType.GuidTextWithEndElement:
type = typeof(Guid);
break;
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
type = typeof(TimeSpan);
break;
case XmlBinaryNodeType.UniqueIdTextWithEndElement:
type = typeof(UniqueId);
break;
default:
return false;
}
return true;
}
public override bool TryGetArrayLength(out int count)
{
count = 0;
if (!_buffered)
return false;
if (_arrayState != ArrayState.Element)
return false;
count = _arrayCount;
return true;
}
private bool IsStartArray(string localName, string namespaceUri, XmlBinaryNodeType nodeType)
{
return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType;
}
private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType)
{
return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType;
}
private void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.ValueMustBeNonNegative)));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.ValueMustBeNonNegative)));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
// bool
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (bool* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Int16
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(Int16[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (Int16* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Int16[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Int32
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(Int32[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (Int32* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Int32[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Int64
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(Int64[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (Int64* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Int64[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// float
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(float[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (float* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// double
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(double[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (double* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// decimal
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe int ReadArray(decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (decimal* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// DateTime
private int ReadArray(DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadDateTime();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Guid
private int ReadArray(Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadGuid();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// TimeSpan
private int ReadArray(TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadTimeSpan();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private enum ArrayState
{
None,
Element,
Content
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2016 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if !PORTABLE && !NETSTANDARD1_6
using System;
using System.Linq;
namespace NUnit.Framework.Internal
{
/// <summary>
/// PlatformHelper class is used by the PlatformAttribute class to
/// determine whether a platform is supported.
/// </summary>
public class PlatformHelper
{
private readonly OSPlatform _os;
private readonly RuntimeFramework _rt;
// Set whenever we fail to support a list of platforms
private string _reason = string.Empty;
const string CommonOSPlatforms =
"Win,Win32,Win32S,Win32NT,Win32Windows,Win95,Win98,WinMe,NT3,NT4,NT5,NT6," +
"Win2008Server,Win2008ServerR2,Win2012Server,Win2012ServerR2," +
"Win2K,WinXP,Win2003Server,Vista,Win7,Windows7,Win8,Windows8,"+
"Win8.1,Windows8.1,Win10,Windows10,WindowsServer10,Unix,Linux";
/// <summary>
/// Comma-delimited list of all supported OS platform constants
/// </summary>
public const string OSPlatforms = CommonOSPlatforms + ",Xbox,MacOSX";
/// <summary>
/// Comma-delimited list of all supported Runtime platform constants
/// </summary>
public static readonly string RuntimePlatforms =
"Net,SSCLI,Rotor,Mono,MonoTouch";
/// <summary>
/// Default constructor uses the operating system and
/// common language runtime of the system.
/// </summary>
public PlatformHelper()
{
_os = OSPlatform.CurrentPlatform;
_rt = RuntimeFramework.CurrentFramework;
}
/// <summary>
/// Construct a PlatformHelper for a particular operating
/// system and common language runtime. Used in testing.
/// </summary>
/// <param name="rt">RuntimeFramework to be used</param>
/// <param name="os">OperatingSystem to be used</param>
public PlatformHelper( OSPlatform os, RuntimeFramework rt )
{
_os = os;
_rt = rt;
}
/// <summary>
/// Test to determine if one of a collection of platforms
/// is being used currently.
/// </summary>
/// <param name="platforms"></param>
/// <returns></returns>
public bool IsPlatformSupported( string[] platforms )
{
return platforms.Any( IsPlatformSupported );
}
/// <summary>
/// Tests to determine if the current platform is supported
/// based on a platform attribute.
/// </summary>
/// <param name="platformAttribute">The attribute to examine</param>
/// <returns></returns>
public bool IsPlatformSupported( PlatformAttribute platformAttribute )
{
string include = platformAttribute.Include;
string exclude = platformAttribute.Exclude;
return IsPlatformSupported( include, exclude );
}
/// <summary>
/// Tests to determine if the current platform is supported
/// based on a platform attribute.
/// </summary>
/// <param name="testCaseAttribute">The attribute to examine</param>
/// <returns></returns>
public bool IsPlatformSupported(TestCaseAttribute testCaseAttribute)
{
string include = testCaseAttribute.IncludePlatform;
string exclude = testCaseAttribute.ExcludePlatform;
return IsPlatformSupported(include, exclude);
}
private bool IsPlatformSupported(string include, string exclude)
{
try
{
if (include != null && !IsPlatformSupported(include))
{
_reason = string.Format("Only supported on {0}", include);
return false;
}
if (exclude != null && IsPlatformSupported(exclude))
{
_reason = string.Format("Not supported on {0}", exclude);
return false;
}
}
catch (Exception ex)
{
_reason = ex.Message;
return false;
}
return true;
}
/// <summary>
/// Test to determine if the a particular platform or comma-
/// delimited set of platforms is in use.
/// </summary>
/// <param name="platform">Name of the platform or comma-separated list of platform ids</param>
/// <returns>True if the platform is in use on the system</returns>
public bool IsPlatformSupported( string platform )
{
if ( platform.IndexOf( ',' ) >= 0 )
return IsPlatformSupported( platform.Split(',') );
string platformName = platform.Trim();
bool isSupported;
// string versionSpecification = null;
//
// string[] parts = platformName.Split( new char[] { '-' } );
// if ( parts.Length == 2 )
// {
// platformName = parts[0];
// versionSpecification = parts[1];
// }
switch( platformName.ToUpper() )
{
case "WIN":
case "WIN32":
isSupported = _os.IsWindows;
break;
case "WIN32S":
isSupported = _os.IsWin32S;
break;
case "WIN32WINDOWS":
isSupported = _os.IsWin32Windows;
break;
case "WIN32NT":
isSupported = _os.IsWin32NT;
break;
case "WIN95":
isSupported = _os.IsWin95;
break;
case "WIN98":
isSupported = _os.IsWin98;
break;
case "WINME":
isSupported = _os.IsWinME;
break;
case "NT3":
isSupported = _os.IsNT3;
break;
case "NT4":
isSupported = _os.IsNT4;
break;
case "NT5":
isSupported = _os.IsNT5;
break;
case "WIN2K":
isSupported = _os.IsWin2K;
break;
case "WINXP":
isSupported = _os.IsWinXP;
break;
case "WIN2003SERVER":
isSupported = _os.IsWin2003Server;
break;
case "NT6":
isSupported = _os.IsNT6;
break;
case "VISTA":
isSupported = _os.IsVista;
break;
case "WIN2008SERVER":
isSupported = _os.IsWin2008Server;
break;
case "WIN2008SERVERR2":
isSupported = _os.IsWin2008ServerR2;
break;
case "WIN2012SERVER":
isSupported = _os.IsWin2012ServerR1 || _os.IsWin2012ServerR2;
break;
case "WIN2012SERVERR2":
isSupported = _os.IsWin2012ServerR2;
break;
case "WIN7":
case "WINDOWS7":
isSupported = _os.IsWindows7;
break;
case "WINDOWS8":
case "WIN8":
isSupported = _os.IsWindows8;
break;
case "WINDOWS8.1":
case "WIN8.1":
isSupported = _os.IsWindows81;
break;
case "WINDOWS10":
case "WIN10":
isSupported = _os.IsWindows10;
break;
case "WINDOWSSERVER10":
isSupported = _os.IsWindowsServer10;
break;
case "UNIX":
case "LINUX":
isSupported = _os.IsUnix;
break;
case "XBOX":
isSupported = _os.IsXbox;
break;
case "MACOSX":
isSupported = _os.IsMacOSX;
break;
// These bitness tests relate to the process, not the OS.
// We can't use Environment.Is64BitProcess because it's
// only supported in NET 4.0 and higher.
case "64-BIT":
case "64-BIT-PROCESS":
isSupported = IntPtr.Size == 8;
break;
case "32-BIT":
case "32-BIT-PROCESS":
isSupported = IntPtr.Size == 4;
break;
#if NET_4_0 || NET_4_5
// We only support bitness tests of the OS in .NET 4.0 and up
case "64-BIT-OS":
isSupported = Environment.Is64BitOperatingSystem;
break;
case "32-BIT-OS":
isSupported = !Environment.Is64BitOperatingSystem;
break;
#endif
default:
isSupported = IsRuntimeSupported(platformName);
break;
}
if (!isSupported)
_reason = "Only supported on " + platform;
return isSupported;
}
/// <summary>
/// Return the last failure reason. Results are not
/// defined if called before IsSupported( Attribute )
/// is called.
/// </summary>
public string Reason
{
get { return _reason; }
}
private bool IsRuntimeSupported(string platformName)
{
string versionSpecification = null;
string[] parts = platformName.Split('-');
if (parts.Length == 2)
{
platformName = parts[0];
versionSpecification = parts[1];
}
switch (platformName.ToUpper())
{
case "NET":
return IsRuntimeSupported(RuntimeType.Net, versionSpecification);
case "SSCLI":
case "ROTOR":
return IsRuntimeSupported(RuntimeType.SSCLI, versionSpecification);
case "MONO":
return IsRuntimeSupported(RuntimeType.Mono, versionSpecification);
case "MONOTOUCH":
return IsRuntimeSupported(RuntimeType.MonoTouch, versionSpecification);
default:
throw new ArgumentException("Invalid platform name", platformName);
}
}
private bool IsRuntimeSupported(RuntimeType runtime, string versionSpecification)
{
Version version = versionSpecification == null
? RuntimeFramework.DefaultVersion
: new Version(versionSpecification);
RuntimeFramework target = new RuntimeFramework(runtime, version);
return _rt.Supports(target);
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Management.Automation;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Gets formatting information from the loading format information database.
/// </summary>
/// <remarks>Currently supports only table controls
/// </remarks>
[Cmdlet(VerbsCommon.Get, "FormatData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=144303")]
[OutputType(typeof(System.Management.Automation.ExtendedTypeDefinition))]
public class GetFormatDataCommand : PSCmdlet
{
private string[] _typename;
private WildcardPattern[] _filter = new WildcardPattern[1];
/// <summary>
/// Get Formatting information only for the specified typename.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[ValidateNotNullOrEmpty]
[Parameter(Position = 0)]
public string[] TypeName
{
get
{
return _typename;
}
set
{
_typename = value;
if (_typename == null)
{
_filter = Utils.EmptyArray<WildcardPattern>();
}
else
{
_filter = new WildcardPattern[_typename.Length];
for (int i = 0; i < _filter.Length; i++)
{
_filter[i] = WildcardPattern.Get(_typename[i],
WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
}
}
}
}
/// <summary>
/// When specified, helps control whether or not to send richer formatting data
/// that was not supported by earlier versions of PowerShell.
/// </summary>
[Parameter]
public Version PowerShellVersion { get; set; }
/// <summary>
/// Set the default filter.
/// </summary>
protected override void BeginProcessing()
{
if (_filter[0] == null)
{
_filter[0] = WildcardPattern.Get("*", WildcardOptions.None);
}
}
private static Dictionary<string, List<string>> GetTypeGroupMap(IEnumerable<TypeGroupDefinition> groupDefinitions)
{
var typeGroupMap = new Dictionary<string, List<string>>();
foreach (TypeGroupDefinition typeGroup in groupDefinitions)
{
// The format system actually allows you to define multiple SelectionSets with the same name, but only the
// first type group will take effect. So we skip the rest groups that have the same name.
if (!typeGroupMap.ContainsKey(typeGroup.name))
{
var typesInGroup = typeGroup.typeReferenceList.Select(typeReference => typeReference.name).ToList();
typeGroupMap.Add(typeGroup.name, typesInGroup);
}
}
return typeGroupMap;
}
/// <summary>
/// Takes out the content from the database and writes them out.
/// </summary>
protected override void ProcessRecord()
{
bool writeOldWay = PowerShellVersion == null ||
PowerShellVersion.Major < 5 ||
(PowerShellVersion.Major == 5 && PowerShellVersion.Minor < 1);
TypeInfoDataBase db = this.Context.FormatDBManager.Database;
List<ViewDefinition> viewdefinitions = db.viewDefinitionsSection.viewDefinitionList;
Dictionary<string, List<string>> typeGroupMap = GetTypeGroupMap(db.typeGroupSection.typeGroupDefinitionList);
var typedefs = new Dictionary<ConsolidatedString, List<FormatViewDefinition>>(ConsolidatedString.EqualityComparer);
foreach (ViewDefinition definition in viewdefinitions)
{
if (definition.isHelpFormatter)
continue;
var consolidatedTypeName = CreateConsolidatedTypeName(definition, typeGroupMap);
if (!ShouldGenerateView(consolidatedTypeName))
continue;
PSControl control;
var tableControlBody = definition.mainControl as TableControlBody;
if (tableControlBody != null)
{
control = new TableControl(tableControlBody, definition);
}
else
{
var listControlBody = definition.mainControl as ListControlBody;
if (listControlBody != null)
{
control = new ListControl(listControlBody, definition);
}
else
{
var wideControlBody = definition.mainControl as WideControlBody;
if (wideControlBody != null)
{
control = new WideControl(wideControlBody, definition);
if (writeOldWay)
{
// Alignment was added to WideControl in V2, but wasn't
// used. It was removed in V5, but old PowerShell clients
// expect this property or fail to rehydrate the remote object.
var psobj = new PSObject(control);
psobj.Properties.Add(new PSNoteProperty("Alignment", 0));
}
}
else
{
var complexControlBody = (ComplexControlBody)definition.mainControl;
control = new CustomControl(complexControlBody, definition);
}
}
}
// Older version of PowerShell do not know about something in the control, so
// don't return it.
if (writeOldWay && !control.CompatibleWithOldPowerShell())
continue;
var formatdef = new FormatViewDefinition(definition.name, control, definition.InstanceId);
List<FormatViewDefinition> viewList;
if (!typedefs.TryGetValue(consolidatedTypeName, out viewList))
{
viewList = new List<FormatViewDefinition>();
typedefs.Add(consolidatedTypeName, viewList);
}
viewList.Add(formatdef);
}
// write out all the available type definitions
foreach (var pair in typedefs)
{
var typeNames = pair.Key;
if (writeOldWay)
{
foreach (var typeName in typeNames)
{
var etd = new ExtendedTypeDefinition(typeName, pair.Value);
WriteObject(etd);
}
}
else
{
var etd = new ExtendedTypeDefinition(typeNames[0], pair.Value);
for (int i = 1; i < typeNames.Count; i++)
{
etd.TypeNames.Add(typeNames[i]);
}
WriteObject(etd);
}
}
}
private static ConsolidatedString CreateConsolidatedTypeName(ViewDefinition definition, Dictionary<string, List<string>> typeGroupMap)
{
// Create our "consolidated string" typename which is used as a dictionary key
var reflist = definition.appliesTo.referenceList;
var consolidatedTypeName = new ConsolidatedString(ConsolidatedString.Empty);
foreach (TypeOrGroupReference item in reflist)
{
// If it's a TypeGroup, we need to look that up and add it's members
if (item is TypeGroupReference)
{
List<string> typesInGroup;
if (typeGroupMap.TryGetValue(item.name, out typesInGroup))
{
foreach (string typeName in typesInGroup)
{
consolidatedTypeName.Add(typeName);
}
}
}
else
{
consolidatedTypeName.Add(item.name);
}
}
return consolidatedTypeName;
}
private bool ShouldGenerateView(ConsolidatedString consolidatedTypeName)
{
foreach (WildcardPattern pattern in _filter)
{
foreach (var typeName in consolidatedTypeName)
{
if (pattern.IsMatch(typeName))
{
return true;
}
}
}
return false;
}
}
}
| |
// ===============================================================================
// Microsoft Data Access Application Block for .NET 3.0
//
// Odbc.cs
//
// This file contains the implementations of the AdoHelper supporting Odbc.
//
// For more information see the Documentation.
// ===============================================================================
// Release history
// VERSION DESCRIPTION
// 2.0 Added support for FillDataset, UpdateDataset and "Param" helper methods
// 3.0 New abstract class supporting the same methods using ADO.NET interfaces
//
// ===============================================================================
// Copyright (C) 2000-2001 Microsoft Corporation
// All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
// FITNESS FOR A PARTICULAR PURPOSE.
// ==============================================================================
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Data.Odbc;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;
namespace org.swyn.foundation.db
{
/// <summary>
/// The Odbc class is intended to encapsulate high performance, scalable best practices for
/// common uses of the Odbc ADO.NET provider. It is created using the abstract factory in AdoHelper
/// </summary>
public class Odbc : AdoHelper
{
// used for correcting Call syntax for stored procedures in ODBC
static Regex _regExpr = new Regex( @"\{.*call|CALL\s\w+.*}", RegexOptions.Compiled );
/// <summary>
/// Create an Odbc Helper. Needs to be a default constructor so that the Factory can create it
/// </summary>
public Odbc()
{
}
#region Overrides
/// <summary>
/// Returns an array of OdbcParameters of the specified size
/// </summary>
/// <param name="size">size of the array</param>
/// <returns>The array of OdbcParameters</returns>
protected override IDataParameter[] GetDataParameters(int size)
{
return new OdbcParameter[size];
}
/// <summary>
/// Returns an OdbcConnection object for the given connection string
/// </summary>
/// <param name="connectionString">The connection string to be used to create the connection</param>
/// <returns>An OdbcConnection object</returns>
public override IDbConnection GetConnection( string connectionString )
{
return new OdbcConnection( connectionString );
}
/// <summary>
/// Returns an OdbcDataAdapter object
/// </summary>
/// <returns>The OdbcDataAdapter</returns>
public override IDbDataAdapter GetDataAdapter()
{
return new OdbcDataAdapter();
}
/// <summary>
/// Calls the CommandBuilder.DeriveParameters method for the specified provider, doing any setup and cleanup necessary
/// </summary>
/// <param name="cmd">The IDbCommand referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the Parameters collection of the IDbCommand. </param>
public override void DeriveParameters( IDbCommand cmd )
{
bool mustCloseConnection = false;
if( !( cmd is OdbcCommand ) )
throw new ArgumentException( "The command provided is not a OdbcCommand instance.", "cmd" );
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
mustCloseConnection = true;
}
OdbcCommandBuilder.DeriveParameters( (OdbcCommand)cmd );
if (mustCloseConnection)
{
cmd.Connection.Close();
}
}
/// <summary>
/// Returns an OdbcParameter object
/// </summary>
/// <returns>The OdbcParameter object</returns>
public override IDataParameter GetParameter()
{
return new OdbcParameter();
}
/// <summary>
/// This cleans up the parameter syntax for an ODBC call. This was split out from PrepareCommand so that it could be called independently.
/// </summary>
/// <param name="command">An IDbCommand object containing the CommandText to clean.</param>
public override void CleanParameterSyntax(IDbCommand command)
{
string call = " call ";
if( command.CommandType == CommandType.StoredProcedure )
{
if( !_regExpr.Match( command.CommandText ).Success && // It does not like like { call sp_name() }
command.CommandText.Trim().IndexOf( " " ) == -1 ) // If there's only a stored procedure name
{
// If there's only a stored procedure name
StringBuilder par = new StringBuilder();
if( command.Parameters.Count != 0 )
{
bool isFirst = true;
bool hasParameters = false;
for( int i = 0; i < command.Parameters.Count; i++ )
{
OdbcParameter p = command.Parameters[i] as OdbcParameter;
if( p.Direction != ParameterDirection.ReturnValue )
{
if( isFirst )
{
isFirst = false;
par.Append( "(?" );
}
else
{
par.Append( ",?" );
}
hasParameters = true;
}
else
{
call = " ? = call ";
}
}
if (hasParameters)
{
par.Append( ")" );
}
}
command.CommandText = "{" + call + command.CommandText + par.ToString() + " }";
}
}
}
/// <summary>
/// Execute an IDbCommand (that returns a resultset) against the provided IDbConnection.
/// </summary>
/// <example>
/// <code>
/// XmlReader r = helper.ExecuteXmlReader(command);
/// </code></example>
/// <param name="command">The IDbCommand to execute</param>
/// <returns>An XmlReader containing the resultset generated by the command</returns>
public override XmlReader ExecuteXmlReader(IDbCommand command)
{
bool mustCloseConnection = false;
if (command.Connection.State != ConnectionState.Open)
{
command.Connection.Open();
mustCloseConnection = true;
}
CleanParameterSyntax(command);
OdbcDataAdapter da = new OdbcDataAdapter((OdbcCommand)command);
DataSet ds = new DataSet();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
StringReader stream = new StringReader(ds.GetXml());
if (mustCloseConnection)
{
command.Connection.Close();
}
return new XmlTextReader(stream);
}
/// <summary>
/// Provider specific code to set up the updating/ed event handlers used by UpdateDataset
/// </summary>
/// <param name="dataAdapter">DataAdapter to attach the event handlers to</param>
/// <param name="rowUpdatingHandler">The handler to be called when a row is updating</param>
/// <param name="rowUpdatedHandler">The handler to be called when a row is updated</param>
protected override void AddUpdateEventHandlers(IDbDataAdapter dataAdapter, RowUpdatingHandler rowUpdatingHandler, RowUpdatedHandler rowUpdatedHandler)
{
if (rowUpdatingHandler != null)
{
this.m_rowUpdating = rowUpdatingHandler;
((OdbcDataAdapter)dataAdapter).RowUpdating += new OdbcRowUpdatingEventHandler(RowUpdating);
}
if (rowUpdatedHandler != null)
{
this.m_rowUpdated = rowUpdatedHandler;
((OdbcDataAdapter)dataAdapter).RowUpdated += new OdbcRowUpdatedEventHandler(RowUpdated);
}
}
/// <summary>
/// Handles the RowUpdating event
/// </summary>
/// <param name="obj">The object that published the event</param>
/// <param name="e">The OdbcRowUpdatingEventArgs</param>
protected void RowUpdating(object obj, OdbcRowUpdatingEventArgs e)
{
base.RowUpdating(obj, e);
}
/// <summary>
/// Handles the RowUpdated event
/// </summary>
/// <param name="obj">The object that published the event</param>
/// <param name="e">The OdbcRowUpdatedEventArgs</param>
protected void RowUpdated(object obj, OdbcRowUpdatedEventArgs e)
{
base.RowUpdated(obj, e);
}
/// <summary>
/// Handle any provider-specific issues with BLOBs here by "washing" the IDataParameter and returning a new one that is set up appropriately for the provider.
/// </summary>
/// <param name="connection">The IDbConnection to use in cleansing the parameter</param>
/// <param name="p">The parameter before cleansing</param>
/// <returns>The parameter after it's been cleansed.</returns>
protected override IDataParameter GetBlobParameter(IDbConnection connection, IDataParameter p)
{
// nothing special needed for ODBC...so far as we know now.
return p;
}
#endregion
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// An implementation of IMessage that can represent arbitrary types, given a MessageaDescriptor.
/// </summary>
public sealed partial class DynamicMessage : AbstractMessage<DynamicMessage, DynamicMessage.Builder>
{
private readonly MessageDescriptor type;
private readonly FieldSet fields;
private readonly UnknownFieldSet unknownFields;
private int memoizedSize = -1;
/// <summary>
/// Creates a DynamicMessage with the given FieldSet.
/// </summary>
/// <param name="type"></param>
/// <param name="fields"></param>
/// <param name="unknownFields"></param>
private DynamicMessage(MessageDescriptor type, FieldSet fields, UnknownFieldSet unknownFields)
{
this.type = type;
this.fields = fields;
this.unknownFields = unknownFields;
}
/// <summary>
/// Returns a DynamicMessage representing the default instance of the given type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static DynamicMessage GetDefaultInstance(MessageDescriptor type)
{
return new DynamicMessage(type, FieldSet.DefaultInstance, UnknownFieldSet.DefaultInstance);
}
/// <summary>
/// Parses a message of the given type from the given stream.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, ICodedInputStream input)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(input);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse a message of the given type from the given stream and extension registry.
/// </summary>
/// <param name="type"></param>
/// <param name="input"></param>
/// <param name="extensionRegistry"></param>
/// <returns></returns>
public static DynamicMessage ParseFrom(MessageDescriptor type, ICodedInputStream input,
ExtensionRegistry extensionRegistry)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(input, extensionRegistry);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parses a message of the given type from the given stream.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, Stream input)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(input);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse a message of the given type from the given stream and extension registry.
/// </summary>
/// <param name="type"></param>
/// <param name="input"></param>
/// <param name="extensionRegistry"></param>
/// <returns></returns>
public static DynamicMessage ParseFrom(MessageDescriptor type, Stream input, ExtensionRegistry extensionRegistry)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(input, extensionRegistry);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse <paramref name="data"/> as a message of the given type and return it.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, ByteString data)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(data);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse <paramref name="data"/> as a message of the given type and return it.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, ByteString data,
ExtensionRegistry extensionRegistry)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(data, extensionRegistry);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse <paramref name="data"/> as a message of the given type and return it.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, byte[] data)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(data);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse <paramref name="data"/> as a message of the given type and return it.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, byte[] data, ExtensionRegistry extensionRegistry)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(data, extensionRegistry);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Constructs a builder for the given type.
/// </summary>
public static Builder CreateBuilder(MessageDescriptor type)
{
return new Builder(type);
}
/// <summary>
/// Constructs a builder for a message of the same type as <paramref name="prototype"/>,
/// and initializes it with the same contents.
/// </summary>
/// <param name="prototype"></param>
/// <returns></returns>
public static Builder CreateBuilder(IMessage prototype)
{
return new Builder(prototype.DescriptorForType).MergeFrom(prototype);
}
// -----------------------------------------------------------------
// Implementation of IMessage interface.
public override MessageDescriptor DescriptorForType
{
get { return type; }
}
public override DynamicMessage DefaultInstanceForType
{
get { return GetDefaultInstance(type); }
}
public override IDictionary<FieldDescriptor, object> AllFields
{
get { return fields.AllFieldDescriptors; }
}
public override bool HasField(FieldDescriptor field)
{
VerifyContainingType(field);
return fields.HasField(field);
}
public override object this[FieldDescriptor field]
{
get
{
VerifyContainingType(field);
object result = fields[field];
if (result == null)
{
result = GetDefaultInstance(field.MessageType);
}
return result;
}
}
public override int GetRepeatedFieldCount(FieldDescriptor field)
{
VerifyContainingType(field);
return fields.GetRepeatedFieldCount(field);
}
public override object this[FieldDescriptor field, int index]
{
get
{
VerifyContainingType(field);
return fields[field, index];
}
}
public override UnknownFieldSet UnknownFields
{
get { return unknownFields; }
}
public bool Initialized
{
get { return fields.IsInitializedWithRespectTo(type.Fields); }
}
public override void WriteTo(ICodedOutputStream output)
{
fields.WriteTo(output);
if (type.Options.MessageSetWireFormat)
{
unknownFields.WriteAsMessageSetTo(output);
}
else
{
unknownFields.WriteTo(output);
}
}
public override int SerializedSize
{
get
{
int size = memoizedSize;
if (size != -1)
{
return size;
}
size = fields.SerializedSize;
if (type.Options.MessageSetWireFormat)
{
size += unknownFields.SerializedSizeAsMessageSet;
}
else
{
size += unknownFields.SerializedSize;
}
memoizedSize = size;
return size;
}
}
public override Builder CreateBuilderForType()
{
return new Builder(type);
}
public override Builder ToBuilder()
{
return CreateBuilderForType().MergeFrom(this);
}
/// <summary>
/// Verifies that the field is a field of this message.
/// </summary>
private void VerifyContainingType(FieldDescriptor field)
{
if (field.ContainingType != type)
{
throw new ArgumentException("FieldDescriptor does not match message type.");
}
}
/// <summary>
/// Builder for dynamic messages. Instances are created with DynamicMessage.CreateBuilder.
/// </summary>
public sealed partial class Builder : AbstractBuilder<DynamicMessage, Builder>
{
private readonly MessageDescriptor type;
private FieldSet fields;
private UnknownFieldSet unknownFields;
internal Builder(MessageDescriptor type)
{
this.type = type;
this.fields = FieldSet.CreateInstance();
this.unknownFields = UnknownFieldSet.DefaultInstance;
}
protected override Builder ThisBuilder
{
get { return this; }
}
public override Builder Clear()
{
fields.Clear();
return this;
}
public override Builder MergeFrom(IMessage other)
{
if (other.DescriptorForType != type)
{
throw new ArgumentException("MergeFrom(IMessage) can only merge messages of the same type.");
}
fields.MergeFrom(other);
MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(DynamicMessage other)
{
IMessage downcast = other;
return MergeFrom(downcast);
}
public override DynamicMessage Build()
{
if (fields != null && !IsInitialized)
{
throw new UninitializedMessageException(new DynamicMessage(type, fields, unknownFields));
}
return BuildPartial();
}
/// <summary>
/// Helper for DynamicMessage.ParseFrom() methods to call. Throws
/// InvalidProtocolBufferException
/// </summary>
/// <returns></returns>
internal DynamicMessage BuildParsed()
{
if (!IsInitialized)
{
throw new UninitializedMessageException(new DynamicMessage(type, fields, unknownFields)).
AsInvalidProtocolBufferException();
}
return BuildPartial();
}
public override DynamicMessage BuildPartial()
{
if (fields == null)
{
throw new InvalidOperationException("Build() has already been called on this Builder.");
}
fields.MakeImmutable();
DynamicMessage result = new DynamicMessage(type, fields, unknownFields);
fields = null;
unknownFields = null;
return result;
}
public override Builder Clone()
{
Builder result = new Builder(type);
result.fields.MergeFrom(fields);
return result;
}
public override bool IsInitialized
{
get { return fields.IsInitializedWithRespectTo(type.Fields); }
}
public override Builder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry)
{
UnknownFieldSet.Builder unknownFieldsBuilder = UnknownFieldSet.CreateBuilder(unknownFields);
unknownFieldsBuilder.MergeFrom(input, extensionRegistry, this);
unknownFields = unknownFieldsBuilder.Build();
return this;
}
public override MessageDescriptor DescriptorForType
{
get { return type; }
}
public override DynamicMessage DefaultInstanceForType
{
get { return GetDefaultInstance(type); }
}
public override IDictionary<FieldDescriptor, object> AllFields
{
get { return fields.AllFieldDescriptors; }
}
public override IBuilder CreateBuilderForField(FieldDescriptor field)
{
VerifyContainingType(field);
if (field.MappedType != MappedType.Message)
{
throw new ArgumentException("CreateBuilderForField is only valid for fields with message type.");
}
return new Builder(field.MessageType);
}
public override bool HasField(FieldDescriptor field)
{
VerifyContainingType(field);
return fields.HasField(field);
}
public override object this[FieldDescriptor field, int index]
{
get
{
VerifyContainingType(field);
return fields[field, index];
}
set
{
VerifyContainingType(field);
fields[field, index] = value;
}
}
public override object this[FieldDescriptor field]
{
get
{
VerifyContainingType(field);
object result = fields[field];
if (result == null)
{
result = GetDefaultInstance(field.MessageType);
}
return result;
}
set
{
VerifyContainingType(field);
fields[field] = value;
}
}
public override Builder ClearField(FieldDescriptor field)
{
VerifyContainingType(field);
fields.ClearField(field);
return this;
}
public override int GetRepeatedFieldCount(FieldDescriptor field)
{
VerifyContainingType(field);
return fields.GetRepeatedFieldCount(field);
}
public override Builder AddRepeatedField(FieldDescriptor field, object value)
{
VerifyContainingType(field);
fields.AddRepeatedField(field, value);
return this;
}
public override UnknownFieldSet UnknownFields
{
get { return unknownFields; }
set { unknownFields = value; }
}
/// <summary>
/// Verifies that the field is a field of this message.
/// </summary>
/// <param name="field"></param>
private void VerifyContainingType(FieldDescriptor field)
{
if (field.ContainingType != type)
{
throw new ArgumentException("FieldDescriptor does not match message type.");
}
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class BoxingTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
Log.Comment("The Boxing tests determine if a type's data can survive being stored in");
Log.Comment("an object and then re-cast as their original type.");
Log.Comment("The tests are named for the type they test.");
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//Boxing Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Boxing
//byte,char,double,float,int,long,sbyte,short,uint,ulong,ushort,struct_to_ValType,ValType_to_struct
//Test Case Calls
[TestMethod]
public MFTestResults Boxingbyte_Test()
{
if (BoxingTestClassbyte.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingchar_Test()
{
if (BoxingTestClasschar.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingdouble_Test()
{
if (BoxingTestClassdouble.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingfloat_Test()
{
if (BoxingTestClassfloat.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingint_Test()
{
if (BoxingTestClassint.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxinglong_Test()
{
if (BoxingTestClasslong.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingsbyte_Test()
{
if (BoxingTestClasssbyte.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingshort_Test()
{
if (BoxingTestClassshort.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxinguint_Test()
{
if (BoxingTestClassuint.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingulong_Test()
{
if (BoxingTestClassulong.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingushort_Test()
{
if (BoxingTestClassushort.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Boxingstruct_to_ValType_Test()
{
if (BoxingTestClassStruct_to_ValType.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults BoxingValType_to_struct_Test()
{
if (BoxingTestClassValType_to_struct.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
//Compiled Test Cases
public class BoxingTestClassbyte
{
public static bool testMethod()
{
byte value = 1;
object obj;
obj = value; // box
byte value2;
value2 = (byte) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClasschar
{
public static bool testMethod()
{
char value = '\x1';
object obj;
obj = value; // box
char value2;
value2 = (char) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassdouble
{
public static bool testMethod()
{
double value = 1.0;
object obj;
obj = value; // box
double value2;
value2 = (double) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassfloat
{
public static bool testMethod()
{
float value = 1F;
object obj;
obj = value; // box
float value2;
value2 = (float) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassint
{
public static bool testMethod()
{
int value = 1;
object obj;
obj = value; // box
int value2;
value2 = (int) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClasslong
{
public static bool testMethod()
{
long value = 1;
object obj;
obj = value; // box
long value2;
value2 = (long) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClasssbyte
{
public static bool testMethod()
{
sbyte value = 1;
object obj;
obj = value; // box
sbyte value2;
value2 = (sbyte) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassshort
{
public static bool testMethod()
{
short value = 1;
object obj;
obj = value; // box
short value2;
value2 = (short) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassuint
{
public static bool testMethod()
{
uint value = 1;
object obj;
obj = value; // box
uint value2;
value2 = (uint) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassulong
{
public static bool testMethod()
{
ulong value = 1;
object obj;
obj = value; // box
ulong value2;
value2 = (ulong) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassushort
{
public static bool testMethod()
{
ushort value = 1;
object obj;
obj = value; // box
ushort value2;
value2 = (ushort) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
struct BoxingTestClassStruct_to_ValTypeTest_struct { }
class BoxingTestClassStruct_to_ValType
{
public static bool testMethod()
{
BoxingTestClassStruct_to_ValTypeTest_struct src = new BoxingTestClassStruct_to_ValTypeTest_struct();
System.ValueType dst = src;
return true;
}
}
struct BoxingTestClassValType_to_struct_struct { }
class BoxingTestClassValType_to_struct
{
public static bool testMethod()
{
System.ValueType src = new BoxingTestClassValType_to_struct_struct();
BoxingTestClassValType_to_struct_struct dst = (BoxingTestClassValType_to_struct_struct) src;
return true;
}
}
}
}
| |
using System;
namespace XSharpx {
/// <summary>
/// The conjunction of 2 values.
/// </summary>
/// <typeparam name="A">The element type of one of the two values.</typeparam>
/// <typeparam name="B">The element type of one of the two values.</typeparam>
/// <remarks>Also known as a pair.</remarks>
public struct Pair<A, B> {
private readonly A a;
private readonly B b;
private Pair(A a, B b) {
this.a = a;
this.b = b;
}
public Store<A, Pair<A, B>> _1 {
get {
var t = this;
return a.StoreSet(aa => aa.And(t.b));
}
}
public Store<B, Pair<A, B>> _2 {
get {
var t = this;
return b.StoreSet(bb => t.a.And(bb));
}
}
public Pair<A, X> Select<X>(Func<B, X> f) {
return a.And(f(b));
}
public Pair<A, Pair<A, B>> Duplicate {
get {
return a.And(a.And(b));
}
}
public Pair<A, X> Extend<X>(Func<Pair<A, B>, X> f) {
return a.And(f(this));
}
public Pair<X, B> First<X>(Func<A, X> f) {
return f(a).And(b);
}
public Pair<A, X> Second<X>(Func<B, X> f) {
return a.And(f(b));
}
public Pair<X, Y> BinarySelect<X, Y>(Func<A, X> f, Func<B, Y> g) {
return f(a).And(g(b));
}
public Pair<B, A> Swap {
get {
return b.And(a);
}
}
public PairAndSemigroup<A, B> Constrain(Semigroup<A> s) {
return new PairAndSemigroup<A, B>(this, s);
}
public PairAndMonoid<A, B> Constrain(Monoid<A> m) {
return new PairAndMonoid<A, B>(this, m);
}
public Pair<X, Y> Swapped<X, Y>(Func<Pair<B, A>, Pair<Y, X>> f) {
return f(Swap).Swap;
}
public X Fold<X>(Func<A, B, X> f) {
return f(a, b);
}
public static Pair<A, B> pair(A a, B b) {
return new Pair<A, B>(a, b);
}
public static Func<A, Func<B, Pair<A, B>>> pairF() {
return a => b => new Pair<A, B>(a, b);
}
}
public static class PairExtension {
public static Pair<X, B> Select<X, A, B>(this Pair<X, A> ps, Func<A, B> f) {
return ps._1.Get.And(f(ps._2.Get));
}
public static Pair<A, B> And<A, B>(this A a, B b) {
return Pair<A, B>.pair(a, b);
}
}
public struct PairAndSemigroup<A, B> {
private readonly Pair<A, B> pair;
private readonly Semigroup<A> s;
internal PairAndSemigroup(Pair<A, B> pair, Semigroup<A> s) {
this.pair = pair;
this.s = s;
}
public A a {
get {
return pair._1.Get;
}
}
public B b {
get {
return pair._2.Get;
}
}
internal Semigroup<A> S {
get {
return s;
}
}
public Pair<A, B> Pair {
get {
return pair;
}
}
public PairAndSemigroup<A, D> ZipWith<C, D>(PairAndSemigroup<A, C> o, Func<B, Func<C, D>> f) {
return this.SelectMany(a => o.Select(b => f(a)(b)));
}
public PairAndSemigroup<A, Pair<B, C>> Zip<C>(PairAndSemigroup<A, C> o) {
return ZipWith<C, Pair<B, C>>(o, Pair<B, C>.pairF());
}
public Pair<X, B> First<X>(Func<A, X> f) {
return pair.First(f);
}
public PairAndSemigroup<A, X> Second<X>(Func<B, X> f) {
return new PairAndSemigroup<A, X>(pair.Second(f), s);
}
public Pair<X, Y> BinarySelect<X, Y>(Func<A, X> f, Func<B, Y> g) {
return pair.BinarySelect(f, g);
}
public Pair<B, A> Swap {
get {
return pair.Swap;
}
}
public Pair<X, Y> Swapped<X, Y>(Func<Pair<B, A>, Pair<Y, X>> f) {
return pair.Swapped(f);
}
public X Fold<X>(Func<A, B, X> f) {
return pair.Fold(f);
}
}
public static class PairAndSemigroupExtension {
public static PairAndSemigroup<X, B> Select<X, A, B>(this PairAndSemigroup<X, A> ps, Func<A, B> f) {
return new PairAndSemigroup<X, B>(ps.Pair.Select(f), ps.S);
}
public static PairAndSemigroup<X, B> SelectMany<X, A, B>(this PairAndSemigroup<X, A> ps, Func<A, PairAndSemigroup<X, B>> f) {
var r = f(ps.b);
return new PairAndSemigroup<X, B>(ps.S.Op(ps.a, r.a).And(r.b), ps.S);
}
public static PairAndSemigroup<X, C> SelectMany<X, A, B, C>(this PairAndSemigroup<X, A> ps, Func<A, PairAndSemigroup<X, B>> p, Func<A, B, C> f) {
return SelectMany(ps, a => Select(p(a), b => f(a, b)));
}
}
public struct PairAndMonoid<A, B> {
private readonly Pair<A, B> pair;
private readonly Monoid<A> m;
internal PairAndMonoid(Pair<A, B> pair, Monoid<A> m) {
this.pair = pair;
this.m = m;
}
public A a {
get {
return pair._1.Get;
}
}
public B b {
get {
return pair._2.Get;
}
}
internal Monoid<A> M {
get {
return m;
}
}
public Pair<A, B> Pair {
get {
return pair;
}
}
public PairAndMonoid<A, D> ZipWith<C, D>(PairAndMonoid<A, C> o, Func<B, Func<C, D>> f) {
return this.SelectMany(a => o.Select(b => f(a)(b)));
}
public PairAndMonoid<A, Pair<B, C>> Zip<C>(PairAndMonoid<A, C> o) {
return ZipWith<C, Pair<B, C>>(o, Pair<B, C>.pairF());
}
public Pair<X, B> First<X>(Func<A, X> f) {
return pair.First(f);
}
public PairAndMonoid<A, X> Second<X>(Func<B, X> f) {
return new PairAndMonoid<A, X>(pair.Second(f), m);
}
public Pair<X, Y> BinarySelect<X, Y>(Func<A, X> f, Func<B, Y> g) {
return pair.BinarySelect(f, g);
}
public Pair<B, A> Swap {
get {
return pair.Swap;
}
}
public Pair<X, Y> Swapped<X, Y>(Func<Pair<B, A>, Pair<Y, X>> f) {
return pair.Swapped(f);
}
public X Fold<X>(Func<A, B, X> f) {
return pair.Fold(f);
}
}
public static class PairAndMonoidExtension {
public static PairAndMonoid<X, B> Select<X, A, B>(this PairAndMonoid<X, A> ps, Func<A, B> f) {
return new PairAndMonoid<X, B>(ps.Pair.Select(f), ps.M);
}
public static PairAndMonoid<X, B> SelectMany<X, A, B>(this PairAndMonoid<X, A> ps, Func<A, PairAndMonoid<X, B>> f) {
var r = f(ps.b);
return new PairAndMonoid<X, B>(Pair<X, B>.pair(ps.M.Op(ps.a, r.a), r.b), ps.M);
}
public static PairAndMonoid<X, C> SelectMany<X, A, B, C>(this PairAndMonoid<X, A> ps, Func<A, PairAndMonoid<X, B>> p, Func<A, B, C> f) {
return SelectMany(ps, a => Select(p(a), b => f(a, b)));
}
}
}
| |
/*
* 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.Specialized;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using HttpServer;
using HttpServer.FormDecoders;
using NUnit.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Tests.Common;
namespace OpenSim.Framework.Servers.Tests
{
[TestFixture]
public class OSHttpTests : OpenSimTestCase
{
// we need an IHttpClientContext for our tests
public class TestHttpClientContext: IHttpClientContext
{
private bool _secured;
public bool IsSecured
{
get { return _secured; }
}
public bool Secured
{
get { return _secured; }
}
public TestHttpClientContext(bool secured)
{
_secured = secured;
}
public void Disconnect(SocketError error) {}
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body) {}
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) {}
public void Respond(string body) {}
public void Send(byte[] buffer) {}
public void Send(byte[] buffer, int offset, int size) {}
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType) {}
public void Close() { }
public bool EndWhenDone { get { return false;} set { return;}}
public HTTPNetworkContext GiveMeTheNetworkStreamIKnowWhatImDoing()
{
return new HTTPNetworkContext();
}
public event EventHandler<DisconnectedEventArgs> Disconnected = delegate { };
/// <summary>
/// A request have been received in the context.
/// </summary>
public event EventHandler<RequestEventArgs> RequestReceived = delegate { };
public bool CanSend { get { return true; } }
public string RemoteEndPoint { get { return ""; } }
public string RemoteEndPointAddress { get { return ""; } }
public string RemoteEndPointPort { get { return ""; } }
}
public class TestHttpRequest: IHttpRequest
{
private string _uriPath;
public bool BodyIsComplete
{
get { return true; }
}
public string[] AcceptTypes
{
get {return _acceptTypes; }
}
private string[] _acceptTypes;
public Stream Body
{
get { return _body; }
set { _body = value;}
}
private Stream _body;
public ConnectionType Connection
{
get { return _connection; }
set { _connection = value; }
}
private ConnectionType _connection;
public int ContentLength
{
get { return _contentLength; }
set { _contentLength = value; }
}
private int _contentLength;
public NameValueCollection Headers
{
get { return _headers; }
}
private NameValueCollection _headers = new NameValueCollection();
public string HttpVersion
{
get { return _httpVersion; }
set { _httpVersion = value; }
}
private string _httpVersion = null;
public string Method
{
get { return _method; }
set { _method = value; }
}
private string _method = null;
public HttpInput QueryString
{
get { return _queryString; }
}
private HttpInput _queryString = null;
public Uri Uri
{
get { return _uri; }
set { _uri = value; }
}
private Uri _uri = null;
public string[] UriParts
{
get { return _uri.Segments; }
}
public HttpParam Param
{
get { return null; }
}
public HttpForm Form
{
get { return null; }
}
public bool IsAjax
{
get { return false; }
}
public RequestCookies Cookies
{
get { return null; }
}
public TestHttpRequest() {}
public TestHttpRequest(string contentEncoding, string contentType, string userAgent,
string remoteAddr, string remotePort, string[] acceptTypes,
ConnectionType connectionType, int contentLength, Uri uri)
{
_headers["content-encoding"] = contentEncoding;
_headers["content-type"] = contentType;
_headers["user-agent"] = userAgent;
_headers["remote_addr"] = remoteAddr;
_headers["remote_port"] = remotePort;
_acceptTypes = acceptTypes;
_connection = connectionType;
_contentLength = contentLength;
_uri = uri;
}
public void DecodeBody(FormDecoderProvider providers) {}
public void SetCookies(RequestCookies cookies) {}
public void AddHeader(string name, string value)
{
_headers.Add(name, value);
}
public int AddToBody(byte[] bytes, int offset, int length)
{
return 0;
}
public void Clear() {}
public object Clone()
{
TestHttpRequest clone = new TestHttpRequest();
clone._acceptTypes = _acceptTypes;
clone._connection = _connection;
clone._contentLength = _contentLength;
clone._uri = _uri;
clone._headers = new NameValueCollection(_headers);
return clone;
}
public IHttpResponse CreateResponse(IHttpClientContext context)
{
return new HttpResponse(context, this);
}
/// <summary>
/// Path and query (will be merged with the host header) and put in Uri
/// </summary>
/// <see cref="Uri"/>
public string UriPath
{
get { return _uriPath; }
set
{
_uriPath = value;
}
}
}
public class TestHttpResponse: IHttpResponse
{
public Stream Body
{
get { return _body; }
set { _body = value; }
}
private Stream _body;
public string ProtocolVersion
{
get { return _protocolVersion; }
set { _protocolVersion = value; }
}
private string _protocolVersion;
public bool Chunked
{
get { return _chunked; }
set { _chunked = value; }
}
private bool _chunked;
public ConnectionType Connection
{
get { return _connection; }
set { _connection = value; }
}
private ConnectionType _connection;
public Encoding Encoding
{
get { return _encoding; }
set { _encoding = value; }
}
private Encoding _encoding;
public int KeepAlive
{
get { return _keepAlive; }
set { _keepAlive = value; }
}
private int _keepAlive;
public HttpStatusCode Status
{
get { return _status; }
set { _status = value; }
}
private HttpStatusCode _status;
public string Reason
{
get { return _reason; }
set { _reason = value; }
}
private string _reason;
public long ContentLength
{
get { return _contentLength; }
set { _contentLength = value; }
}
private long _contentLength;
public string ContentType
{
get { return _contentType; }
set { _contentType = value; }
}
private string _contentType;
public bool HeadersSent
{
get { return _headersSent; }
}
private bool _headersSent;
public bool Sent
{
get { return _sent; }
}
private bool _sent;
public ResponseCookies Cookies
{
get { return _cookies; }
}
private ResponseCookies _cookies = null;
public TestHttpResponse()
{
_headersSent = false;
_sent = false;
}
public void AddHeader(string name, string value) {}
public void Send()
{
if (!_headersSent) SendHeaders();
if (_sent) throw new InvalidOperationException("stuff already sent");
_sent = true;
}
public void SendBody(byte[] buffer, int offset, int count)
{
if (!_headersSent) SendHeaders();
_sent = true;
}
public void SendBody(byte[] buffer)
{
if (!_headersSent) SendHeaders();
_sent = true;
}
public void SendHeaders()
{
if (_headersSent) throw new InvalidOperationException("headers already sent");
_headersSent = true;
}
public void Redirect(Uri uri) {}
public void Redirect(string url) {}
}
public OSHttpRequest req0;
public OSHttpRequest req1;
public OSHttpResponse rsp0;
public IPEndPoint ipEP0;
[TestFixtureSetUp]
public void Init()
{
TestHttpRequest threq0 = new TestHttpRequest("utf-8", "text/xml", "OpenSim Test Agent", "192.168.0.1", "4711",
new string[] {"text/xml"},
ConnectionType.KeepAlive, 4711,
new Uri("http://127.0.0.1/admin/inventory/Dr+Who/Tardis"));
threq0.Method = "GET";
threq0.HttpVersion = HttpHelper.HTTP10;
TestHttpRequest threq1 = new TestHttpRequest("utf-8", "text/xml", "OpenSim Test Agent", "192.168.0.1", "4711",
new string[] {"text/xml"},
ConnectionType.KeepAlive, 4711,
new Uri("http://127.0.0.1/admin/inventory/Dr+Who/Tardis?a=0&b=1&c=2"));
threq1.Method = "POST";
threq1.HttpVersion = HttpHelper.HTTP11;
threq1.Headers["x-wuff"] = "wuffwuff";
threq1.Headers["www-authenticate"] = "go away";
req0 = new OSHttpRequest(new TestHttpClientContext(false), threq0);
req1 = new OSHttpRequest(new TestHttpClientContext(false), threq1);
rsp0 = new OSHttpResponse(new TestHttpResponse());
ipEP0 = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 4711);
}
[Test]
public void T000_OSHttpRequest()
{
Assert.That(req0.HttpMethod, Is.EqualTo("GET"));
Assert.That(req0.ContentType, Is.EqualTo("text/xml"));
Assert.That(req0.ContentLength, Is.EqualTo(4711));
Assert.That(req1.HttpMethod, Is.EqualTo("POST"));
}
[Test]
public void T001_OSHttpRequestHeaderAccess()
{
Assert.That(req1.Headers["x-wuff"], Is.EqualTo("wuffwuff"));
Assert.That(req1.Headers.Get("x-wuff"), Is.EqualTo("wuffwuff"));
Assert.That(req1.Headers["www-authenticate"], Is.EqualTo("go away"));
Assert.That(req1.Headers.Get("www-authenticate"), Is.EqualTo("go away"));
Assert.That(req0.RemoteIPEndPoint, Is.EqualTo(ipEP0));
}
[Test]
public void T002_OSHttpRequestUriParsing()
{
Assert.That(req0.RawUrl, Is.EqualTo("/admin/inventory/Dr+Who/Tardis"));
Assert.That(req1.Url.ToString(), Is.EqualTo("http://127.0.0.1/admin/inventory/Dr+Who/Tardis?a=0&b=1&c=2"));
}
[Test]
public void T100_OSHttpResponse()
{
rsp0.ContentType = "text/xml";
Assert.That(rsp0.ContentType, Is.EqualTo("text/xml"));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenSim.Region.ScriptEngine.Shared;
using log4net;
namespace OpenSim.Region.ScriptEngine.DotNetEngine
{
/// <summary>
/// EventQueueManager handles event queues
/// Events are queued and executed in separate thread
/// </summary>
[Serializable]
public class EventQueueManager
{
//
// Class is instanced in "ScriptEngine" and used by "EventManager" which is also instanced in "ScriptEngine".
//
// Class purpose is to queue and execute functions that are received by "EventManager":
// - allowing "EventManager" to release its event thread immediately, thus not interrupting server execution.
// - allowing us to prioritize and control execution of script functions.
// Class can use multiple threads for simultaneous execution. Mutexes are used for thread safety.
//
// 1. Hold an execution queue for scripts
// 2. Use threads to process queue, each thread executes one script function on each pass.
// 3. Catch any script error and process it
//
//
// Notes:
// * Current execution load balancing is optimized for 1 thread, and can cause unfair execute balancing between scripts.
// Not noticeable unless server is under high load.
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public ScriptEngine m_ScriptEngine;
/// <summary>
/// List of threads (classes) processing event queue
/// Note that this may or may not be a reference to a static object depending on PrivateRegionThreads config setting.
/// </summary>
internal static List<EventQueueThreadClass> eventQueueThreads = new List<EventQueueThreadClass>(); // Thread pool that we work on
/// <summary>
/// Locking access to eventQueueThreads AND staticGlobalEventQueueThreads.
/// </summary>
// private object eventQueueThreadsLock = new object();
// Static objects for referencing the objects above if we don't have private threads:
//internal static List<EventQueueThreadClass> staticEventQueueThreads; // A static reference used if we don't use private threads
// internal static object staticEventQueueThreadsLock; // Statick lock object reference for same reason
/// <summary>
/// Global static list of all threads (classes) processing event queue -- used by max enforcment thread
/// </summary>
//private List<EventQueueThreadClass> staticGlobalEventQueueThreads = new List<EventQueueThreadClass>();
/// <summary>
/// Used internally to specify how many threads should exit gracefully
/// </summary>
public static int ThreadsToExit;
public static object ThreadsToExitLock = new object();
//public object queueLock = new object(); // Mutex lock object
/// <summary>
/// How many threads to process queue with
/// </summary>
internal static int numberOfThreads;
internal static int EventExecutionMaxQueueSize;
/// <summary>
/// Maximum time one function can use for execution before we perform a thread kill.
/// </summary>
private static int maxFunctionExecutionTimems
{
get { return (int)(maxFunctionExecutionTimens / 10000); }
set { maxFunctionExecutionTimens = value * 10000; }
}
/// <summary>
/// Contains nanoseconds version of maxFunctionExecutionTimems so that it matches time calculations better (performance reasons).
/// WARNING! ONLY UPDATE maxFunctionExecutionTimems, NEVER THIS DIRECTLY.
/// </summary>
public static long maxFunctionExecutionTimens;
/// <summary>
/// Enforce max execution time
/// </summary>
public static bool EnforceMaxExecutionTime;
/// <summary>
/// Kill script (unload) when it exceeds execution time
/// </summary>
private static bool KillScriptOnMaxFunctionExecutionTime;
/// <summary>
/// List of localID locks for mutex processing of script events
/// </summary>
private List<uint> objectLocks = new List<uint>();
private object tryLockLock = new object(); // Mutex lock object
/// <summary>
/// Queue containing events waiting to be executed
/// </summary>
public Queue<QueueItemStruct> eventQueue = new Queue<QueueItemStruct>();
#region " Queue structures "
/// <summary>
/// Queue item structure
/// </summary>
public struct QueueItemStruct
{
public uint localID;
public UUID itemID;
public string functionName;
public DetectParams[] llDetectParams;
public object[] param;
public Dictionary<KeyValuePair<int,int>,KeyValuePair<int,int>>
LineMap;
}
#endregion
#region " Initialization / Startup "
public EventQueueManager(ScriptEngine _ScriptEngine)
{
m_ScriptEngine = _ScriptEngine;
ReadConfig();
AdjustNumberOfScriptThreads();
}
public void ReadConfig()
{
// Refresh config
numberOfThreads = m_ScriptEngine.ScriptConfigSource.GetInt("NumberOfScriptThreads", 2);
maxFunctionExecutionTimems = m_ScriptEngine.ScriptConfigSource.GetInt("MaxEventExecutionTimeMs", 5000);
EnforceMaxExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("EnforceMaxEventExecutionTime", true);
KillScriptOnMaxFunctionExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("DeactivateScriptOnTimeout", false);
EventExecutionMaxQueueSize = m_ScriptEngine.ScriptConfigSource.GetInt("EventExecutionMaxQueueSize", 300);
// Now refresh config in all threads
lock (eventQueueThreads)
{
foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
{
EventQueueThread.ReadConfig();
}
}
}
#endregion
#region " Shutdown all threads "
~EventQueueManager()
{
Stop();
}
private void Stop()
{
if (eventQueueThreads != null)
{
// Kill worker threads
lock (eventQueueThreads)
{
foreach (EventQueueThreadClass EventQueueThread in new ArrayList(eventQueueThreads))
{
AbortThreadClass(EventQueueThread);
}
//eventQueueThreads.Clear();
//staticGlobalEventQueueThreads.Clear();
}
}
// Remove all entries from our event queue
lock (eventQueue)
{
eventQueue.Clear();
}
}
#endregion
#region " Start / stop script execution threads (ThreadClasses) "
private void StartNewThreadClass()
{
EventQueueThreadClass eqtc = new EventQueueThreadClass();
eventQueueThreads.Add(eqtc);
//m_log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Started new script execution thread. Current thread count: " + eventQueueThreads.Count);
}
private void AbortThreadClass(EventQueueThreadClass threadClass)
{
if (eventQueueThreads.Contains(threadClass))
eventQueueThreads.Remove(threadClass);
try
{
threadClass.Stop();
}
catch (Exception)
{
//m_log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: If you see this, could you please report it to Tedd:");
//m_log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: Script thread execution timeout kill ended in exception: " + ex.ToString());
}
//m_log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Killed script execution thread. Remaining thread count: " + eventQueueThreads.Count);
}
#endregion
#region " Mutex locks for queue access "
/// <summary>
/// Try to get a mutex lock on localID
/// </summary>
/// <param name="localID"></param>
/// <returns></returns>
public bool TryLock(uint localID)
{
lock (tryLockLock)
{
if (objectLocks.Contains(localID) == true)
{
return false;
}
else
{
objectLocks.Add(localID);
return true;
}
}
}
/// <summary>
/// Release mutex lock on localID
/// </summary>
/// <param name="localID"></param>
public void ReleaseLock(uint localID)
{
lock (tryLockLock)
{
if (objectLocks.Contains(localID) == true)
{
objectLocks.Remove(localID);
}
}
}
#endregion
#region " Check execution queue for a specified Event"
/// <summary>
/// checks to see if a specified event type is already in the queue
/// </summary>
/// <param name="localID">Region object ID</param>
/// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
/// <returns>true if event is found , false if not found</returns>
///
public bool CheckEeventQueueForEvent(uint localID, string FunctionName)
{
if (eventQueue.Count > 0)
{
lock (eventQueue)
{
foreach (EventQueueManager.QueueItemStruct QIS in eventQueue)
{
if ((QIS.functionName == FunctionName) && (QIS.localID == localID))
return true;
}
}
}
return false;
}
#endregion
#region " Add events to execution queue "
/// <summary>
/// Add event to event execution queue
/// </summary>
/// <param name="localID">Region object ID</param>
/// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
/// <param name="param">Array of parameters to match event mask</param>
public bool AddToObjectQueue(uint localID, string FunctionName, DetectParams[] qParams, params object[] param)
{
// Determine all scripts in Object and add to their queue
//myScriptEngine.log.Info("[" + ScriptEngineName + "]: EventQueueManager Adding localID: " + localID + ", FunctionName: " + FunctionName);
// Do we have any scripts in this object at all? If not, return
if (m_ScriptEngine.m_ScriptManager.Scripts.ContainsKey(localID) == false)
{
//m_log.Debug("Event \String.Empty + FunctionName + "\" for localID: " + localID + ". No scripts found on this localID.");
return false;
}
List<UUID> scriptKeys =
m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
foreach (UUID itemID in scriptKeys)
{
// Add to each script in that object
// TODO: Some scripts may not subscribe to this event. Should we NOT add it? Does it matter?
AddToScriptQueue(localID, itemID, FunctionName, qParams, param);
}
return true;
}
/// <summary>
/// Add event to event execution queue
/// </summary>
/// <param name="localID">Region object ID</param>
/// <param name="itemID">Region script ID</param>
/// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
/// <param name="param">Array of parameters to match event mask</param>
public bool AddToScriptQueue(uint localID, UUID itemID, string FunctionName, DetectParams[] qParams, params object[] param)
{
List<UUID> keylist = m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
if (!keylist.Contains(itemID)) // We don't manage that script
{
return false;
}
lock (eventQueue)
{
if (eventQueue.Count >= EventExecutionMaxQueueSize)
{
m_log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: ERROR: Event execution queue item count is at " + eventQueue.Count + ". Config variable \"EventExecutionMaxQueueSize\" is set to " + EventExecutionMaxQueueSize + ", so ignoring new event.");
m_log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: Event ignored: localID: " + localID + ", itemID: " + itemID + ", FunctionName: " + FunctionName);
return false;
}
InstanceData id = m_ScriptEngine.m_ScriptManager.GetScript(
localID, itemID);
// Create a structure and add data
QueueItemStruct QIS = new QueueItemStruct();
QIS.localID = localID;
QIS.itemID = itemID;
QIS.functionName = FunctionName;
QIS.llDetectParams = qParams;
QIS.param = param;
if (id != null)
QIS.LineMap = id.LineMap;
// Add it to queue
eventQueue.Enqueue(QIS);
}
return true;
}
#endregion
#region " Maintenance thread "
/// <summary>
/// Adjust number of script thread classes. It can start new, but if it needs to stop it will just set number of threads in "ThreadsToExit" and threads will have to exit themselves.
/// Called from MaintenanceThread
/// </summary>
public void AdjustNumberOfScriptThreads()
{
// Is there anything here for us to do?
if (eventQueueThreads.Count == numberOfThreads)
return;
lock (eventQueueThreads)
{
int diff = numberOfThreads - eventQueueThreads.Count;
// Positive number: Start
// Negative number: too many are running
if (diff > 0)
{
// We need to add more threads
for (int ThreadCount = eventQueueThreads.Count; ThreadCount < numberOfThreads; ThreadCount++)
{
StartNewThreadClass();
}
}
if (diff < 0)
{
// We need to kill some threads
lock (ThreadsToExitLock)
{
ThreadsToExit = Math.Abs(diff);
}
}
}
}
/// <summary>
/// Check if any thread class has been executing an event too long
/// </summary>
public void CheckScriptMaxExecTime()
{
// Iterate through all ScriptThreadClasses and check how long their current function has been executing
lock (eventQueueThreads)
{
foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
{
// Is thread currently executing anything?
if (EventQueueThread.InExecution)
{
// Has execution time expired?
if (DateTime.Now.Ticks - EventQueueThread.LastExecutionStarted >
maxFunctionExecutionTimens)
{
// Yes! We need to kill this thread!
// Set flag if script should be removed or not
EventQueueThread.KillCurrentScript = KillScriptOnMaxFunctionExecutionTime;
// Abort this thread
AbortThreadClass(EventQueueThread);
// We do not need to start another, MaintenenceThread will do that for us
//StartNewThreadClass();
}
}
}
}
}
#endregion
///// <summary>
///// If set to true then threads and stuff should try to make a graceful exit
///// </summary>
//public bool PleaseShutdown
//{
// get { return _PleaseShutdown; }
// set { _PleaseShutdown = value; }
//}
//private bool _PleaseShutdown = false;
}
}
| |
/*
* Magix - A Web Application Framework for Humans
* Copyright 2010 - 2014 - thomas@magixilluminate.com
* Magix is licensed as MITx11, see enclosed License.txt File for Details.
*/
using System;
using System.IO;
using System.Web.UI;
using Magix.Core;
using Magix.UX.Widgets;
using Magix.UX.Widgets.Core;
namespace Magix.forms
{
/*
* contains the basecontrol control
*/
public abstract class BaseControlController : ActiveController
{
/*
* lists all widget types that exists in system
*/
[ActiveEvent(Name="magix.forms.list-control-types")]
private static void magix_forms_list_control_types(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.list-control-types-dox].value");
ip["magix.forms.list-control-types"].Value = null;
return;
}
Node ctrlActiveEvents = new Node();
ctrlActiveEvents["begins-with"].Value = "magix.forms.controls.";
RaiseActiveEvent(
"magix.execute.list-events",
ctrlActiveEvents);
foreach (Node idx in ctrlActiveEvents["events"])
{
Node controlNode = new Node("widget");
controlNode["type"].Value = idx.Name;
controlNode["properties"]["id"].Value = "id";
Node inspectControlNode = new Node();
inspectControlNode["inspect"].Value = null;
RaiseActiveEvent(
idx.Name,
inspectControlNode);
if (inspectControlNode["magix.forms.create-web-part"].Contains("_no-embed"))
controlNode["_no-embed"].Value = true;
foreach (Node idxPropertyNode in inspectControlNode["magix.forms.create-web-part"]["controls"][0])
{
controlNode["properties"][idxPropertyNode.Name].Value = idxPropertyNode.Value;
controlNode["properties"][idxPropertyNode.Name].AddRange(idxPropertyNode);
}
controlNode["properties"].Sort(
delegate(Node left, Node right)
{
if (left.Name == "id")
return -1;
if (right.Name == "id")
return 1;
if (left.Name.StartsWith("on"))
return 1;
if (right.Name.StartsWith("on"))
return -1;
return left.Name.CompareTo(right.Name);
});
ip["types"].Add(controlNode);
}
}
/*
* sets visibility of control
*/
[ActiveEvent(Name = "magix.forms.set-visible")]
private static void magix_forms_set_visible(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.set-visible-dox].value");
AppendCodeFromResource(
ip,
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.set-visible-sample]");
return;
}
Control ctrl = FindControl<Control>(e.Params);
ctrl.Visible = ip["value"].Get<bool>(false);
}
/*
* retrieves visibility of control
*/
[ActiveEvent(Name = "magix.forms.get-visible")]
private static void magix_forms_get_visible(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.get-visible-dox].value");
AppendCodeFromResource(
ip,
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.get-visible-sample]");
return;
}
Control ctrl = FindControl<Control>(e.Params);
ip["value"].Value = ctrl.Visible;
}
/*
* sets value
*/
[ActiveEvent(Name = "magix.forms.set-value")]
private static void magix_forms_set_value(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.set-value-dox].value");
AppendCodeFromResource(
ip,
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.set-value-sample]");
return;
}
Node dp = Dp(e.Params);
IValueControl ctrl = FindControl<IValueControl>(e.Params);
string value = Expressions.GetFormattedExpression("value", e.Params, null);
ctrl.ControlValue = value;
}
/*
* returns value
*/
[ActiveEvent(Name = "magix.forms.get-value")]
private static void magix_forms_get_value(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.get-value-dox].value");
AppendCodeFromResource(
ip,
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.get-value-sample]");
return;
}
IValueControl ctrl = FindControl<IValueControl>(e.Params);
ip["value"].Value = ctrl.ControlValue;
}
/*
* clear all children values
*/
[ActiveEvent(Name = "magix.forms.clear-children-values")]
private static void magix_forms_clear_children_values(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.clear-children-values-dox].value");
AppendCodeFromResource(
ip,
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.clear-children-values-sample]");
return;
}
Control ctrl = FindControl<Control>(e.Params);
ClearValues(ctrl, ip);
}
private static void ClearValues(Control ctrl, Node ip)
{
IValueControl valueCtrl = ctrl as IValueControl;
if (valueCtrl != null && valueCtrl.IsTrueValue)
valueCtrl.ControlValue = null;
foreach (Control idxChild in ctrl.Controls)
{
ClearValues(idxChild, ip);
}
}
/*
* returns values
*/
[ActiveEvent(Name = "magix.forms.get-children-values")]
private static void magix_forms_get_children_values(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.get-children-values-dox].value");
AppendCodeFromResource(
ip,
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.get-children-values-sample]");
return;
}
Control ctrl = FindControl<Control>(e.Params);
GetValues(ctrl, ip);
}
/*
* helper for above
*/
private static void GetValues(Control ctrl, Node ip)
{
IValueControl valueCtrl = ctrl as IValueControl;
if (valueCtrl != null && valueCtrl.IsTrueValue)
ip["values"][ctrl.ID].Value = valueCtrl.ControlValue;
foreach (Control idxChild in ctrl.Controls)
{
GetValues(idxChild, ip);
}
}
/*
* fills out the stuff from basecontrol
*/
protected virtual void FillOutParameters(Node pars, BaseControl ctrl)
{
Node ip = Ip(pars);
Node node = ip["_code"].Get<Node>();
string idPrefix = "";
if (ip.ContainsValue("id-prefix"))
idPrefix = ip["id-prefix"].Get<string>();
if (node.ContainsValue("id"))
ctrl.ID = idPrefix + node["id"].Get<string>();
else if (node.Value != null)
ctrl.ID = idPrefix + node.Get<string>();
if (node.ContainsValue("visible"))
ctrl.Visible = node["visible"].Get<bool>();
if (node.ContainsValue("info"))
ctrl.Info = node["info"].Get<string>();
if (ShouldHandleEvent("onfirstload", node) && pars["_first"].Get<bool>(false))
{
Node codeNode = node["onfirstload"].Clone();
ctrl.Load += delegate(object sender, EventArgs e)
{
FillOutEventInputParameters(codeNode, sender);
RaiseActiveEvent(
"magix.execute",
codeNode);
};
}
}
protected static T FindControl<T>(Node pars)
{
Node ip = Ip(pars);
if (!ip.Contains("id"))
throw new ArgumentException("this active event needs an [id] parameter");
Node ctrlNode = new Node("magix.forms._get-control");
ctrlNode["id"].Value = ip["id"].Value;
ctrlNode["id"].AddRange(ip["id"].Clone());
if (ip.Contains("form-id"))
{
ctrlNode["form-id"].Value = ip["form-id"].Value;
ctrlNode["form-id"].AddRange(ip["form-id"].Clone());
}
object oldIp = pars["_ip"].Value;
pars["_ip"].Value = ctrlNode;
try
{
RaiseActiveEvent(
"magix.forms._get-control",
pars);
}
finally
{
pars["_ip"].Value = oldIp;
}
if (ctrlNode.Contains("_ctrl"))
return ctrlNode["_ctrl"].Get<T>();
else
throw new ArgumentException("couldn't find that control");
}
protected bool ShouldHandleEvent(string evt, Node node)
{
if (node.Contains(evt) && node[evt].Count > 0)
return true;
return false;
}
protected void FillOutEventInputParameters(Node node, object sender)
{
BaseControl that = sender as BaseControl;
if (!string.IsNullOrEmpty(that.Info))
node["$"]["info"].Value = that.Info;
if (that is IValueControl)
node["$"]["value"].Value = (that as IValueControl).ControlValue;
Control container = that;
while (container != null && !(container is DynamicPanel))
{
container = container.Parent;
}
if (container != null)
{
node["$"]["container"].Value = container.ID;
Node getFormIdNode = new Node();
getFormIdNode["container"].Value = container.ID;
RaiseActiveEvent(
"magix.forms.get-form-id",
getFormIdNode);
if (getFormIdNode.ContainsValue("form-id"))
node["$"]["form-id"].Value = getFormIdNode["form-id"].Value;
}
node["$"]["id"].Value = that.ID;
}
protected virtual void Inspect(Node node)
{
Node tmp = node;
while (!tmp.Contains("inspect"))
tmp = tmp.Parent;
AppendInspectFromResource(
tmp["inspect"],
"Magix.forms",
"Magix.forms.hyperlisp.inspect.hl",
"[magix.forms.base-dox].value",
true);
node.Value = "control_id";
node["visible"].Value = "true";
node["info"].Value = "additional data";
node["onfirstload"].Value = "hyperlisp code";
node["events"].Value = "hyperlisp code";
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Security;
using System.Security.Policy;
using System.Security.Principal;
using NUnit.Common;
using NUnit.Engine.Internal;
namespace NUnit.Engine.Services
{
/// <summary>
/// The DomainManager class handles the creation and unloading
/// of domains as needed and keeps track of all existing domains.
/// </summary>
public class DomainManager : Service
{
static Logger log = InternalTrace.GetLogger(typeof(DomainManager));
private static readonly PropertyInfo TargetFrameworkNameProperty =
typeof(AppDomainSetup).GetProperty("TargetFrameworkName", BindingFlags.Public | BindingFlags.Instance);
private ISettings _settingsService;
#region Create and Unload Domains
/// <summary>
/// Construct an application domain for running a test package
/// </summary>
/// <param name="package">The TestPackage to be run</param>
public AppDomain CreateDomain( TestPackage package )
{
AppDomainSetup setup = CreateAppDomainSetup(package);
string domainName = "test-domain-" + package.Name;
// Setup the Evidence
Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
if (evidence.Count == 0)
{
Zone zone = new Zone(SecurityZone.MyComputer);
evidence.AddHost(zone);
Assembly assembly = Assembly.GetExecutingAssembly();
Url url = new Url(assembly.CodeBase);
evidence.AddHost(url);
Hash hash = new Hash(assembly);
evidence.AddHost(hash);
}
log.Info("Creating AppDomain " + domainName);
AppDomain runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup);
// Set PrincipalPolicy for the domain if called for in the settings
if (_settingsService != null && _settingsService.GetSetting("Options.TestLoader.SetPrincipalPolicy", false))
{
runnerDomain.SetPrincipalPolicy(_settingsService.GetSetting(
"Options.TestLoader.PrincipalPolicy",
PrincipalPolicy.UnauthenticatedPrincipal));
}
return runnerDomain;
}
// Made separate and internal for testing
AppDomainSetup CreateAppDomainSetup(TestPackage package)
{
AppDomainSetup setup = new AppDomainSetup();
if (package.SubPackages.Count == 1)
package = package.SubPackages[0];
//For parallel tests, we need to use distinct application name
setup.ApplicationName = "Tests" + "_" + Environment.TickCount;
string appBase = GetApplicationBase(package);
setup.ApplicationBase = appBase;
setup.ConfigurationFile = GetConfigFile(appBase, package);
setup.PrivateBinPath = GetPrivateBinPath(appBase, package);
if (!string.IsNullOrEmpty(package.FullName))
{
// Setting the target framework is only supported when running with
// multiple AppDomains, one per assembly.
// TODO: Remove this limitation
// .NET versions greater than v4.0 report as v4.0, so look at
// the TargetFrameworkAttribute on the assembly if it exists
// If property is null, .NET 4.5+ is not installed, so there is no need
if (TargetFrameworkNameProperty != null)
{
var frameworkName = package.GetSetting(PackageSettings.ImageTargetFrameworkName, "");
if (frameworkName != "")
TargetFrameworkNameProperty.SetValue(setup, frameworkName, null);
}
}
if (package.GetSetting("ShadowCopyFiles", false))
{
setup.ShadowCopyFiles = "true";
setup.ShadowCopyDirectories = setup.ApplicationBase;
}
else
setup.ShadowCopyFiles = "false";
return setup;
}
public void Unload(AppDomain domain)
{
new DomainUnloader(domain).Unload();
}
#endregion
#region Nested DomainUnloader Class
class DomainUnloader
{
private Thread _unloadThread;
private AppDomain _domain;
private Exception _unloadException;
public DomainUnloader(AppDomain domain)
{
_domain = domain;
}
public void Unload()
{
_unloadThread = new Thread(new ThreadStart(UnloadOnThread));
_unloadThread.Start();
if (!_unloadThread.Join(30000))
{
string msg = "Unable to unload AppDomain, Unload thread timed out";
log.Error(msg);
Kill(_unloadThread);
throw new NUnitEngineException(msg);
}
if (_unloadException != null)
throw new NUnitEngineException("Exception encountered unloading AppDomain", _unloadException);
}
private void UnloadOnThread()
{
bool shadowCopy = false;
string domainName = "UNKNOWN";
try
{
shadowCopy = _domain.ShadowCopyFiles;
domainName = _domain.FriendlyName;
// Uncomment to simulate an error in unloading
//throw new Exception("Testing: simulated unload error");
// Uncomment to simulate a timeout while unloading
//while (true) ;
AppDomain.Unload(_domain);
}
catch (Exception ex)
{
_unloadException = ex;
// We assume that the tests did something bad and just leave
// the orphaned AppDomain "out there".
// TODO: Something useful.
log.Error("Unable to unload AppDomain " + domainName, ex);
}
}
}
#endregion
#region Helper Methods
/// <summary>
/// Figure out the ApplicationBase for a package
/// </summary>
/// <param name="package">The package</param>
/// <returns>The ApplicationBase</returns>
public static string GetApplicationBase(TestPackage package)
{
Guard.ArgumentNotNull(package, "package");
var appBase = package.GetSetting(PackageSettings.BasePath, string.Empty);
if (string.IsNullOrEmpty(appBase))
appBase = string.IsNullOrEmpty(package.FullName)
? GetCommonAppBase(package.SubPackages)
: Path.GetDirectoryName(package.FullName);
if (!string.IsNullOrEmpty(appBase))
{
char lastChar = appBase[appBase.Length - 1];
if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
appBase += Path.DirectorySeparatorChar;
}
return appBase;
}
public static string GetConfigFile(string appBase, TestPackage package)
{
Guard.ArgumentNotNullOrEmpty(appBase, "appBase");
Guard.ArgumentNotNull(package, "package");
// Use provided setting if available
string configFile = package.GetSetting(PackageSettings.ConfigurationFile, string.Empty);
if (configFile != string.Empty)
return Path.Combine(appBase, configFile);
// The ProjectService adds any project config to the settings.
// So, at this point, we only want to handle assemblies or an
// anonymous package created from the comnand-line.
string fullName = package.FullName;
if (IsExecutable(fullName))
return fullName + ".config";
// Command-line package gets no config unless it's a single assembly
if (string.IsNullOrEmpty(fullName) && package.SubPackages.Count == 1)
{
fullName = package.SubPackages[0].FullName;
if (IsExecutable(fullName))
return fullName + ".config";
}
// No config file will be specified
return null;
}
private static bool IsExecutable(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return false;
string ext = Path.GetExtension(fileName).ToLower();
return ext == ".dll" || ext == ".exe";
}
public static string GetCommonAppBase(IList<TestPackage> packages)
{
var assemblies = new List<string>();
foreach (var package in packages)
assemblies.Add(package.FullName);
return GetCommonAppBase(assemblies);
}
public static string GetCommonAppBase(IList<string> assemblies)
{
string commonBase = null;
foreach (string assembly in assemblies)
{
string dir = Path.GetDirectoryName(Path.GetFullPath(assembly));
if (commonBase == null)
commonBase = dir;
else while (!PathUtils.SamePathOrUnder(commonBase, dir) && commonBase != null)
commonBase = Path.GetDirectoryName(commonBase);
}
return commonBase;
}
public static string GetPrivateBinPath(string basePath, string fileName)
{
return GetPrivateBinPath(basePath, new string[] { fileName });
}
public static string GetPrivateBinPath(string appBase, TestPackage package)
{
var binPath = package.GetSetting(PackageSettings.PrivateBinPath, string.Empty);
if (package.GetSetting(PackageSettings.AutoBinPath, binPath == string.Empty))
binPath = package.SubPackages.Count > 0
? GetPrivateBinPath(appBase, package.SubPackages)
: package.FullName != null
? GetPrivateBinPath(appBase, package.FullName)
: null;
return binPath;
}
public static string GetPrivateBinPath(string basePath, IList<TestPackage> packages)
{
var assemblies = new List<string>();
foreach (var package in packages)
assemblies.Add(package.FullName);
return GetPrivateBinPath(basePath, assemblies);
}
public static string GetPrivateBinPath(string basePath, IList<string> assemblies)
{
List<string> dirList = new List<string>();
StringBuilder sb = new StringBuilder(200);
foreach( string assembly in assemblies )
{
string dir = PathUtils.RelativePath(
Path.GetFullPath(basePath),
Path.GetDirectoryName( Path.GetFullPath(assembly) ) );
if ( dir != null && dir != string.Empty && dir != "." && !dirList.Contains( dir ) )
{
dirList.Add( dir );
if ( sb.Length > 0 )
sb.Append( Path.PathSeparator );
sb.Append( dir );
}
}
return sb.Length == 0 ? null : sb.ToString();
}
/// <summary>
/// Do our best to kill a thread, passing state info
/// </summary>
/// <param name="thread">The thread to kill</param>
private static void Kill(Thread thread)
{
try
{
thread.Abort();
}
catch (ThreadStateException)
{
// Although obsolete, this use of Resume() takes care of
// the odd case where a ThreadStateException is received.
#pragma warning disable 0618, 0612 // Thread.Resume has been deprecated
thread.Resume();
#pragma warning restore 0618, 0612 // Thread.Resume has been deprecated
}
if ((thread.ThreadState & System.Threading.ThreadState.WaitSleepJoin) != 0)
thread.Interrupt();
}
#endregion
#region Service Overrides
public override void StartService()
{
try
{
// DomainManager has a soft dependency on the SettingsService.
// If it's not available, default values are used.
_settingsService = ServiceContext.GetService<ISettings>();
Status = ServiceStatus.Started;
}
catch
{
Status = ServiceStatus.Error;
throw;
}
}
#endregion
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.OpsWorks.Model
{
/// <summary>
/// Container for the parameters to the UpdateLayer operation.
/// <para>Updates a specified layer.</para>
/// </summary>
/// <seealso cref="Amazon.OpsWorks.AmazonOpsWorks.UpdateLayer"/>
public class UpdateLayerRequest : AmazonWebServiceRequest
{
private string layerId;
private string name;
private string shortname;
private Dictionary<string,string> attributes = new Dictionary<string,string>();
private string customInstanceProfileArn;
private List<string> customSecurityGroupIds = new List<string>();
private List<string> packages = new List<string>();
private List<VolumeConfiguration> volumeConfigurations = new List<VolumeConfiguration>();
private bool? enableAutoHealing;
private bool? autoAssignElasticIps;
private Recipes customRecipes;
private bool? installUpdatesOnBoot;
/// <summary>
/// The layer ID.
///
/// </summary>
public string LayerId
{
get { return this.layerId; }
set { this.layerId = value; }
}
/// <summary>
/// Sets the LayerId property
/// </summary>
/// <param name="layerId">The value to set for the LayerId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithLayerId(string layerId)
{
this.layerId = layerId;
return this;
}
// Check to see if LayerId property is set
internal bool IsSetLayerId()
{
return this.layerId != null;
}
/// <summary>
/// The layer name, which is used by the console.
///
/// </summary>
public string Name
{
get { return this.name; }
set { this.name = value; }
}
/// <summary>
/// Sets the Name property
/// </summary>
/// <param name="name">The value to set for the Name property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithName(string name)
{
this.name = name;
return this;
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this.name != null;
}
/// <summary>
/// The layer short name, which is used internally by AWS OpsWorksand by Chef. The short name is also used as the name for the directory where
/// your app files are installed. It can have a maximum of 200 characters and must be in the following format: /\A[a-z0-9\-\_\.]+\Z/.
///
/// </summary>
public string Shortname
{
get { return this.shortname; }
set { this.shortname = value; }
}
/// <summary>
/// Sets the Shortname property
/// </summary>
/// <param name="shortname">The value to set for the Shortname property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithShortname(string shortname)
{
this.shortname = shortname;
return this;
}
// Check to see if Shortname property is set
internal bool IsSetShortname()
{
return this.shortname != null;
}
/// <summary>
/// One or more user-defined key/value pairs to be added to the stack attributes bag.
///
/// </summary>
public Dictionary<string,string> Attributes
{
get { return this.attributes; }
set { this.attributes = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Attributes dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Attributes dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithAttributes(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Attributes[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Attributes property is set
internal bool IsSetAttributes()
{
return this.attributes != null;
}
/// <summary>
/// The ARN of an IAM profile to be used for all of the layer's EC2 instances. For more information about IAM ARNs, see <a
/// href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">Using Identifiers</a>.
///
/// </summary>
public string CustomInstanceProfileArn
{
get { return this.customInstanceProfileArn; }
set { this.customInstanceProfileArn = value; }
}
/// <summary>
/// Sets the CustomInstanceProfileArn property
/// </summary>
/// <param name="customInstanceProfileArn">The value to set for the CustomInstanceProfileArn property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithCustomInstanceProfileArn(string customInstanceProfileArn)
{
this.customInstanceProfileArn = customInstanceProfileArn;
return this;
}
// Check to see if CustomInstanceProfileArn property is set
internal bool IsSetCustomInstanceProfileArn()
{
return this.customInstanceProfileArn != null;
}
/// <summary>
/// An array containing the layer's custom security group IDs.
///
/// </summary>
public List<string> CustomSecurityGroupIds
{
get { return this.customSecurityGroupIds; }
set { this.customSecurityGroupIds = value; }
}
/// <summary>
/// Adds elements to the CustomSecurityGroupIds collection
/// </summary>
/// <param name="customSecurityGroupIds">The values to add to the CustomSecurityGroupIds collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithCustomSecurityGroupIds(params string[] customSecurityGroupIds)
{
foreach (string element in customSecurityGroupIds)
{
this.customSecurityGroupIds.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the CustomSecurityGroupIds collection
/// </summary>
/// <param name="customSecurityGroupIds">The values to add to the CustomSecurityGroupIds collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithCustomSecurityGroupIds(IEnumerable<string> customSecurityGroupIds)
{
foreach (string element in customSecurityGroupIds)
{
this.customSecurityGroupIds.Add(element);
}
return this;
}
// Check to see if CustomSecurityGroupIds property is set
internal bool IsSetCustomSecurityGroupIds()
{
return this.customSecurityGroupIds.Count > 0;
}
/// <summary>
/// An array of <c>Package</c> objects that describe the layer's packages.
///
/// </summary>
public List<string> Packages
{
get { return this.packages; }
set { this.packages = value; }
}
/// <summary>
/// Adds elements to the Packages collection
/// </summary>
/// <param name="packages">The values to add to the Packages collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithPackages(params string[] packages)
{
foreach (string element in packages)
{
this.packages.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Packages collection
/// </summary>
/// <param name="packages">The values to add to the Packages collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithPackages(IEnumerable<string> packages)
{
foreach (string element in packages)
{
this.packages.Add(element);
}
return this;
}
// Check to see if Packages property is set
internal bool IsSetPackages()
{
return this.packages.Count > 0;
}
/// <summary>
/// A <c>VolumeConfigurations</c> object that describes the layer's Amazon EBS volumes.
///
/// </summary>
public List<VolumeConfiguration> VolumeConfigurations
{
get { return this.volumeConfigurations; }
set { this.volumeConfigurations = value; }
}
/// <summary>
/// Adds elements to the VolumeConfigurations collection
/// </summary>
/// <param name="volumeConfigurations">The values to add to the VolumeConfigurations collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithVolumeConfigurations(params VolumeConfiguration[] volumeConfigurations)
{
foreach (VolumeConfiguration element in volumeConfigurations)
{
this.volumeConfigurations.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the VolumeConfigurations collection
/// </summary>
/// <param name="volumeConfigurations">The values to add to the VolumeConfigurations collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithVolumeConfigurations(IEnumerable<VolumeConfiguration> volumeConfigurations)
{
foreach (VolumeConfiguration element in volumeConfigurations)
{
this.volumeConfigurations.Add(element);
}
return this;
}
// Check to see if VolumeConfigurations property is set
internal bool IsSetVolumeConfigurations()
{
return this.volumeConfigurations.Count > 0;
}
/// <summary>
/// Whether to disable auto healing for the layer.
///
/// </summary>
public bool EnableAutoHealing
{
get { return this.enableAutoHealing ?? default(bool); }
set { this.enableAutoHealing = value; }
}
/// <summary>
/// Sets the EnableAutoHealing property
/// </summary>
/// <param name="enableAutoHealing">The value to set for the EnableAutoHealing property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithEnableAutoHealing(bool enableAutoHealing)
{
this.enableAutoHealing = enableAutoHealing;
return this;
}
// Check to see if EnableAutoHealing property is set
internal bool IsSetEnableAutoHealing()
{
return this.enableAutoHealing.HasValue;
}
/// <summary>
/// Whether to automatically assign an <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html">Elastic IP
/// address</a> to the layer.
///
/// </summary>
public bool AutoAssignElasticIps
{
get { return this.autoAssignElasticIps ?? default(bool); }
set { this.autoAssignElasticIps = value; }
}
/// <summary>
/// Sets the AutoAssignElasticIps property
/// </summary>
/// <param name="autoAssignElasticIps">The value to set for the AutoAssignElasticIps property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithAutoAssignElasticIps(bool autoAssignElasticIps)
{
this.autoAssignElasticIps = autoAssignElasticIps;
return this;
}
// Check to see if AutoAssignElasticIps property is set
internal bool IsSetAutoAssignElasticIps()
{
return this.autoAssignElasticIps.HasValue;
}
/// <summary>
/// A <c>LayerCustomRecipes</c> object that specifies the layer's custom recipes.
///
/// </summary>
public Recipes CustomRecipes
{
get { return this.customRecipes; }
set { this.customRecipes = value; }
}
/// <summary>
/// Sets the CustomRecipes property
/// </summary>
/// <param name="customRecipes">The value to set for the CustomRecipes property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithCustomRecipes(Recipes customRecipes)
{
this.customRecipes = customRecipes;
return this;
}
// Check to see if CustomRecipes property is set
internal bool IsSetCustomRecipes()
{
return this.customRecipes != null;
}
/// <summary>
/// Whether to install operating system and package updates when the instance boots. The default value is <c>true</c>. To control when updates
/// are installed, set this value to <c>false</c>. You must then update your instances manually by using <a>CreateDeployment</a> to run the
/// <c>update_dependencies</c> stack command or manually running <c>yum</c> (Amazon Linux) or <c>apt-get</c> (Ubuntu) on the instances. <note>We
/// strongly recommend using the default value of <c>true</c>, to ensure that your instances have the latest security updates.</note>
///
/// </summary>
public bool InstallUpdatesOnBoot
{
get { return this.installUpdatesOnBoot ?? default(bool); }
set { this.installUpdatesOnBoot = value; }
}
/// <summary>
/// Sets the InstallUpdatesOnBoot property
/// </summary>
/// <param name="installUpdatesOnBoot">The value to set for the InstallUpdatesOnBoot property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateLayerRequest WithInstallUpdatesOnBoot(bool installUpdatesOnBoot)
{
this.installUpdatesOnBoot = installUpdatesOnBoot;
return this;
}
// Check to see if InstallUpdatesOnBoot property is set
internal bool IsSetInstallUpdatesOnBoot()
{
return this.installUpdatesOnBoot.HasValue;
}
}
}
| |
// 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.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Xml;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.IO;
// General Notes:
// we use the same modem for our config here as we use for icorhost.exe. There are 2 config files. The 1st specifies the tests
// that are available to the runtime. The 2nd specifies our current setup based upon the settings in the 1st configuration file.
public enum TestStartModeEnum
{
AppDomainLoader,
ProcessLoader
}
public enum AppDomainLoaderMode
{
FullIsolation,
Normal,
RoundRobin,
Lazy
}
[Flags]
public enum LoggingLevels
{
Default = 0x01,
StartupShutdown = 0x02,
AppDomain = 0x04,
Tests = 0x08,
SmartDotNet = 0x10,
Logging = 0x20,
UrtFrameworks = 0x40,
TestStarter = 0x80,
All = (0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x80)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// ReliabilityConfig is responsible for parsing the available XML configuration files (both the primary config file & the concurrent
/// test config file. We do not parse single test config files).
/// </summary>
public class ReliabilityConfig : IEnumerable, IEnumerator
{
private ArrayList _testSet = new ArrayList(); // this is the set of <Test... > tags we find. There may be multiple test runs in one
// config file.
private ReliabilityTestSet _curTestSet; // The test set we're currently filling in...
private int _index = -1; // Current test set index
// Toplevel tags for all config files
private const string configHost = "Host";
private const string configInclude = "Include";
private const string configIncludes = "Includes";
internal class RFConfigOptions
{
internal const string RFConfigOptions_Test_MinMaxTestsUseCPUCount = "minMaxTestUseCPUCount";
internal const string RFConfigOptions_Test_SuppressConsoleOutputFromTests = "suppressConsoleOutputFromTests";
internal const string RFConfigOptions_Test_DebugBreakOnHang = "debugBreakOnTestHang";
internal const string RFConfigOptions_Test_DebugBreakOnBadTest = "debugBreakOnBadTest";
internal const string RFConfigOptions_Test_DebugBreakOnOutOfMemory = "debugBreakOnOutOfMemory";
internal const string RFConfigOptions_Test_DebugBreakOnPathTooLong = "debugBreakOnPathTooLong";
internal const string RFConfigOptions_Test_DebugBreakOnMissingTest = "debugBreakOnMissingTest";
}
// Various tags for the concurrent test configuration file.
private const string concurrentConfigTest = "Test";
private const string concurrentConfigAssembly = "Assembly";
private const string configTestMinimumCPU = "minimumCPU";
private const string configTestMinimumCPUStaggered = "minimumCPUStaggered";
private const string configInstallDetours = "installDetours";
private const string configLoggingLevel = "loggingLevel";
private const string configTestMinimumMem = "minimumMem";
private const string configTestMinimumTests = "minimumTests";
private const string configTestMaximumTests = "maximumTests";
private const string configTestDisableLogging = "disableLogging";
private const string configEnablePerfCounters = "enablePerfCounters";
private const string configDefaultDebugger = "defaultDebugger";
private const string configDefaultDebuggerOptions = "defaultDebuggerOptions";
private const string configDefaultTestStartMode = "defaultTestLoader";
private const string configResultReporting = "resultReporting";
private const string configResultReportingUrl = "resultReportingUrl";
private const string configResultReportingBvtCategory = "resultBvtCategory";
private const string configULAppDomainUnloadPercent = "ulAppDomainUnloadPercent";
private const string configULGeneralUnloadPercent = "ulGeneralUnloadPercent";
private const string configULAssemblyLoadPercent = "ulAssemblyLoadPercent";
private const string configULWaitTime = "ulWaitTime";
private const string configCcFailMail = "ccFailMail";
private const string configAppDomainLoaderMode = "appDomainLoaderMode";
private const string configRoundRobinAppDomainCount = "numAppDomains";
// Attributes for the <Assembly ...> tag
private const string configAssemblyName = "id";
private const string configAssemblyFilename = "filename";
private const string configAssemblySuccessCode = "successCode";
private const string configAssemblyEntryPoint = "entryPoint";
private const string configAssemblyArguments = "arguments";
private const string configAssemblyConcurrentCopies = "concurrentCopies";
private const string configAssemblyBasePath = "basePath";
private const string configAssemblyStatus = "status";
private const string configAssemblyStatusDisabled = "disabled";
private const string configAssemblyDebugger = "debugger"; // "none", "cdb.exe", "windbg.exe", etc... only w/ Process.Start test starter
private const string configAssemblyDebuggerOptions = "debuggerOptions"; // cmd line options for debugger - only w/ Process.Start test starter
private const string configAssemblySmartNetGuid = "guid";
private const string configAssemblyDuration = "expectedDuration";
private const string configAssemblyRequiresSDK = "requiresSDK";
private const string configAssemblyTestLoader = "testLoader";
private const string configAssemblyTestAttributes = "testAttrs";
private const string configAssemblyTestOwner = "testOwner";
private const string configAssemblyTestGroup = "group";
private const string configAssemblyPreCommand = "precommand";
private const string configAssemblyPostCommand = "postcommand";
private const string configAssemblyCustomAction = "customAction";
private const string configPercentPassIsPass = "percentPassIsPass";
// Attributes for the <Include ...> tag
private const string configIncludeFilename = "filename";
// Attributes for the <Discovery ...> tag
private const string configDiscovery = "Discovery";
private const string configDiscoveryPath = "path";
// Attributes related to debug mode...
private const string debugConfigIncludeInlined = "INLINE";
// Test start modes
private const string configTestStartModeAppDomainLoader = "appDomainLoader";
private const string configTestStartModeProcessLoader = "processLoader";
private const string configTestStartModeTaskLoader = "taskLoader";
// APp domain loader modes
private const string configAppDomainLoaderModeFullIsolation = "fullIsolation";
private const string configAppDomainLoaderModeNormal = "normal";
private const string configAppDomainLoaderModeRoundRobin = "roundRobin";
private const string configAppDomainLoaderModeLazy = "lazy";
/// <summary>
/// The ReliabilityConfig constructor. Takes 2 config files: The primary config & the test config file. We then load these up
/// and create all the properties on ourself so that the reliability harness knows what to do.
/// </summary>
public ReliabilityConfig(string testConfig)
{
GetTestsToRun(testConfig);
}
private bool GetTrueFalseOptionValue(string value, string configSettingName)
{
if (value == "true" || value == "1" || value == "yes")
{
return true;
}
else if (value == "false" || value == "0" || value == "no")
{
return false;
}
throw new Exception(String.Format("Unknown option value for {0}: {1}", configSettingName, value));
}
public static int ConvertTimeValueToTestRunTime(string timeValue)
{
int returnValue;
if (timeValue.IndexOf(":") == -1)
{
// just a number of minutes
returnValue = Convert.ToInt32(timeValue);
}
else
{
// time span
try
{
returnValue = unchecked((int)(TimeSpan.Parse(timeValue).Ticks / TimeSpan.TicksPerMinute));
}
catch
{
throw new Exception(String.Format("Bad time span {0} for maximum execution time", timeValue));
}
}
return returnValue;
}
/// <summary>
/// Given a test configfile we find the tests that we actually want to run.
/// </summary>
private void GetTestsToRun(string testConfig)
{
int totalDepth = 0; // used for debugging mode so we can keep proper indentation.
ArrayList foundTests = new ArrayList(); // the array of tests we've found.
ArrayList discoveryPaths = new ArrayList(); // the array of discovery paths we've found.
Stack xmlFileStack = new Stack(); // this stack keeps track of our include files.
Stack testLevelStack = new Stack();
try
{
#if PROJECTK_BUILD
FileStream fs = new FileStream(testConfig, FileMode.Open, FileAccess.Read, FileShare.Read);
xmlFileStack.Push(XmlReader.Create(fs));
#else
xmlFileStack.Push(new XmlTextReader(testConfig));
#endif
}
catch (FileNotFoundException e)
{
Console.WriteLine("Could not open config file: {0}", testConfig);
throw e;
}
do
{
#if PROJECTK_BUILD
XmlReader currentXML = (XmlReader)xmlFileStack.Pop();
#else
XmlTextReader currentXML = (XmlTextReader)xmlFileStack.Pop();
#endif
totalDepth -= currentXML.Depth;
if (currentXML.Depth != 0)
{
IndentToDepth(totalDepth + currentXML.Depth - 1); // -1 because we haven't done a .Read on the includes tag yet.
XmlDebugOutLine("</" + configInclude + ">");
}
while (currentXML.Read())
{
switch (currentXML.NodeType)
{
case XmlNodeType.Element:
bool isEmpty = currentXML.IsEmptyElement;
IndentToDepth(totalDepth + currentXML.Depth);
XmlDebugOut("<" + currentXML.Name);
switch (currentXML.Name)
{
case configInclude: // user included a file in this file.
string filename = null;
bool skipInclude = false;
while (currentXML.MoveToNextAttribute())
{
XmlDebugOut(" " + currentXML.Name + "=\"" + currentXML.Value + "\"");
switch (currentXML.Name)
{
case configIncludeFilename:
filename = currentXML.Value;
break;
case debugConfigIncludeInlined: // so we can consume the XML we spit out in debug mode-
// we ignore this include tag if it's been inlined.
if (currentXML.Value.ToLower() == "true" || currentXML.Value == "1")
{
skipInclude = true;
}
break;
default:
throw new Exception("Unknown attribute on include tag!");
}
}
if (skipInclude)
{
XmlDebugOutLine(">");
continue;
}
XmlDebugOut(" " + debugConfigIncludeInlined + "=\"true\">\r\n");
if (filename == null)
{
throw new ArgumentException("Type or Filename not set on include file! Both attributes must be set to properly include a file.");
}
xmlFileStack.Push(currentXML); // save our current file.
totalDepth += currentXML.Depth;
filename = ConvertPotentiallyRelativeFilenameToFullPath(stripFilenameFromPath(currentXML.BaseURI), filename);
try
{
#if PROJECTK_BUILD
currentXML = XmlReader.Create(filename);
#else
currentXML = new XmlTextReader(filename);
#endif
}
catch (FileNotFoundException e)
{
Console.WriteLine("Could not open included config file: {0}", filename);
throw e;
}
continue;
case configIncludes:
if (isEmpty)
{
XmlDebugOut("/>\r\n");
}
else
{
XmlDebugOut(">\r\n");
}
continue; // note: we never push or pop includes off of our stack.
case configHost:
if (testLevelStack.Count == 0) // we'll skip this tag when it shows up in an included file.
{
testLevelStack.Push(configHost);
while (currentXML.MoveToNextAttribute())
{
switch (currentXML.Name)
{
case "xmlns:xsi":
case "xmlns:xsd":
break;
default:
throw new Exception("Unknown attribute on reliability tag: " + currentXML.Name);
}
}
}
else
{
if (isEmpty)
{
XmlDebugOutLine("/>");
}
else
{
XmlDebugOutLine(">");
}
continue;
}
break;
case concurrentConfigTest:
if (testLevelStack.Count != 0 && (string)testLevelStack.Peek() != configHost)
{
throw new ArgumentException("The test tag can only appear as a child to the reliabilityFramework tag or a top level tag.");
}
// save any info we've gathered about tests into the current test set
if (_curTestSet != null && foundTests != null && foundTests.Count > 0)
{
_curTestSet.Tests = (ReliabilityTest[])foundTests.ToArray(typeof(ReliabilityTest));
_curTestSet.DiscoveryPaths = (string[])discoveryPaths.ToArray(typeof(string));
discoveryPaths.Clear();
foundTests.Clear();
}
testLevelStack.Push(concurrentConfigTest);
_curTestSet = new ReliabilityTestSet();
while (currentXML.MoveToNextAttribute())
{
XmlDebugOut(" " + currentXML.Name + "=\"" + currentXML.Value + "\"");
switch (currentXML.Name)
{
case "maximumTestRuns":
_curTestSet.MaximumLoops = Convert.ToInt32(currentXML.Value);
break;
case "maximumExecutionTime":
string timeValue = currentXML.Value;
_curTestSet.MaximumTime = ConvertTimeValueToTestRunTime(timeValue);
break;
case "id":
_curTestSet.FriendlyName = currentXML.Value;
break;
case "xmlns:xsi":
case "xmlns:xsd":
break;
case configTestMinimumMem:
_curTestSet.MinPercentMem = Convert.ToInt32(currentXML.Value);
break;
case configLoggingLevel:
_curTestSet.LoggingLevel = (LoggingLevels)Convert.ToInt32(currentXML.Value.ToString(), 16);
break;
case configTestMinimumCPUStaggered:
_curTestSet.MinPercentCPUStaggered = currentXML.Value;
break;
case configTestMinimumCPU:
_curTestSet.MinPercentCPU = Convert.ToInt32(currentXML.Value);
break;
case configInstallDetours:
if (currentXML.Value == "true" || currentXML.Value == "1" || currentXML.Value == "yes")
{
_curTestSet.InstallDetours = true;
}
else if (currentXML.Value == "false" || currentXML.Value == "0" || currentXML.Value == "no")
{
_curTestSet.InstallDetours = false;
}
else
{
throw new Exception("Unknown value for result reporting: " + currentXML.Value);
}
break;
case configTestMinimumTests:
_curTestSet.MinTestsRunning = Convert.ToInt32(currentXML.Value);
break;
case RFConfigOptions.RFConfigOptions_Test_MinMaxTestsUseCPUCount:
if (GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_MinMaxTestsUseCPUCount))
{
int CPUCount = Convert.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS"));
if (CPUCount <= 0)
throw new Exception("Invalid Value when reading NUMBER_OF_PROCESSORS: {0}" + CPUCount);
_curTestSet.MinTestsRunning = CPUCount;
_curTestSet.MaxTestsRunning = (int)(CPUCount * 1.5);
}
break;
case RFConfigOptions.RFConfigOptions_Test_SuppressConsoleOutputFromTests:
_curTestSet.SuppressConsoleOutputFromTests = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_SuppressConsoleOutputFromTests);
break;
case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnHang:
_curTestSet.DebugBreakOnTestHang = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnHang);
break;
case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnBadTest:
_curTestSet.DebugBreakOnBadTest = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnBadTest);
break;
case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnOutOfMemory:
_curTestSet.DebugBreakOnOutOfMemory = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnOutOfMemory);
break;
case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnPathTooLong:
_curTestSet.DebugBreakOnPathTooLong = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnPathTooLong);
break;
case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnMissingTest:
_curTestSet.DebugBreakOnMissingTest = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnMissingTest);
break;
case configResultReporting:
_curTestSet.ReportResults = GetTrueFalseOptionValue(currentXML.Value, configResultReporting);
break;
case configResultReportingUrl:
_curTestSet.ReportResultsTo = currentXML.Value;
break;
case configResultReportingBvtCategory:
try
{
_curTestSet.BvtCategory = new Guid(currentXML.Value);
}
catch (FormatException)
{
throw new Exception(String.Format("BVT Category Guid {0} is not in the correct form", currentXML.Value));
}
break;
case configTestMaximumTests:
_curTestSet.MaxTestsRunning = Convert.ToInt32(currentXML.Value);
break;
case configTestDisableLogging:
_curTestSet.DisableLogging = GetTrueFalseOptionValue(currentXML.Value, configTestDisableLogging);
break;
case configEnablePerfCounters:
_curTestSet.EnablePerfCounters = GetTrueFalseOptionValue(currentXML.Value, configEnablePerfCounters);
break;
case configDefaultTestStartMode:
switch (currentXML.Value)
{
case configTestStartModeAppDomainLoader:
if (null != _curTestSet.DefaultDebugger || null != _curTestSet.DefaultDebuggerOptions)
{
throw new Exception(String.Format("{0} specified with default debugger or debugger options. If you want a debugger per test please use {1}=\"{2}\" ",
configTestStartModeAppDomainLoader,
configDefaultTestStartMode,
configTestStartModeProcessLoader));
}
_curTestSet.DefaultTestStartMode = TestStartModeEnum.AppDomainLoader;
break;
case configTestStartModeProcessLoader:
_curTestSet.DefaultTestStartMode = TestStartModeEnum.ProcessLoader;
break;
default:
throw new Exception(String.Format("Unknown test starter {0} specified!", currentXML.Value));
}
break;
case configRoundRobinAppDomainCount:
try
{
_curTestSet.NumAppDomains = Convert.ToInt32(currentXML.Value);
if (_curTestSet.NumAppDomains <= 0)
{
throw new Exception("Number of app domains must be greater than zero!");
}
}
catch
{
throw new Exception(String.Format("The value {0} is not an integer", currentXML.Value));
}
break;
case configAppDomainLoaderMode:
switch (currentXML.Value)
{
case configAppDomainLoaderModeFullIsolation:
_curTestSet.AppDomainLoaderMode = AppDomainLoaderMode.FullIsolation;
break;
case configAppDomainLoaderModeNormal:
_curTestSet.AppDomainLoaderMode = AppDomainLoaderMode.Normal;
break;
case configAppDomainLoaderModeRoundRobin:
_curTestSet.AppDomainLoaderMode = AppDomainLoaderMode.RoundRobin;
break;
case configAppDomainLoaderModeLazy:
_curTestSet.AppDomainLoaderMode = AppDomainLoaderMode.Lazy;
break;
default:
throw new Exception(String.Format("Unknown AD Loader mode {0} specified!", currentXML.Value));
}
break;
case configPercentPassIsPass:
_curTestSet.PercentPassIsPass = Convert.ToInt32(currentXML.Value);
break;
case configDefaultDebugger:
if (currentXML.Value.Length >= 7 && currentXML.Value.Substring(currentXML.Value.Length - 7).ToLower() == "cdb.exe")
{
_curTestSet.DefaultDebugger = currentXML.Value;
}
else if (currentXML.Value.Length >= 10 && currentXML.Value.Substring(currentXML.Value.Length - 7).ToLower() == "windbg.exe")
{
_curTestSet.DefaultDebugger = currentXML.Value;
}
else if (currentXML.Value.ToLower() == "none")
{
_curTestSet.DefaultDebugger = String.Empty;
}
else
{
throw new Exception("Unknown default debugger specified (" + currentXML.Value + ")");
}
break;
case configDefaultDebuggerOptions:
_curTestSet.DefaultDebuggerOptions = Environment.ExpandEnvironmentVariables(currentXML.Value);
break;
case configULAssemblyLoadPercent:
_curTestSet.ULAssemblyLoadPercent = Convert.ToInt32(currentXML.Value);
break;
case configULAppDomainUnloadPercent:
_curTestSet.ULAppDomainUnloadPercent = Convert.ToInt32(currentXML.Value);
break;
case configULGeneralUnloadPercent:
_curTestSet.ULGeneralUnloadPercent = Convert.ToInt32(currentXML.Value);
break;
case configULWaitTime:
_curTestSet.ULWaitTime = Convert.ToInt32(currentXML.Value);
break;
case configCcFailMail:
_curTestSet.CCFailMail = currentXML.Value;
break;
default:
throw new Exception("Unknown attribute (" + currentXML.Name + ") on " + concurrentConfigTest + " tag!");
}
}
// Check to see if any of the test attribute environment variables are set,
// If so, then use the environment variables.
if ((Environment.GetEnvironmentVariable("TIMELIMIT") != null) && (Environment.GetEnvironmentVariable("TIMELIMIT") != ""))
_curTestSet.MaximumTime = ConvertTimeValueToTestRunTime(Environment.GetEnvironmentVariable("TIMELIMIT"));
if ((Environment.GetEnvironmentVariable("MINCPU") != null) && (Environment.GetEnvironmentVariable("MINCPU") != ""))
_curTestSet.MinPercentCPU = Convert.ToInt32(Environment.GetEnvironmentVariable("MINCPU"));
_testSet.Add(_curTestSet);
break;
case configDiscovery:
if (testLevelStack.Count == 0 || (string)testLevelStack.Peek() != concurrentConfigTest)
{
throw new ArgumentException("The assembly tag can only appear as a child to the test tag (curent parent tag==" + (string)testLevelStack.Peek() + ").");
}
testLevelStack.Push(configDiscovery);
string path = null;
while (currentXML.MoveToNextAttribute())
{
XmlDebugOut(" " + currentXML.Name + "=\"" + currentXML.Value + "\"");
switch (currentXML.Name)
{
case configDiscoveryPath:
path = currentXML.Value;
break;
default:
throw new Exception("Unknown attribute on include tag (\"" + currentXML.Name + "\")!");
}
}
discoveryPaths.Add(Environment.ExpandEnvironmentVariables(path));
break;
case concurrentConfigAssembly:
/***********************************************************************
* Here's where we process an assembly & it's options. *
***********************************************************************/
bool disabled = false;
if (testLevelStack.Count == 0 || (string)testLevelStack.Peek() != concurrentConfigTest)
{
throw new ArgumentException("The assembly tag can only appear as a child to the test tag (curent parent tag==" + (string)testLevelStack.Peek() + ").");
}
testLevelStack.Push(concurrentConfigAssembly);
ReliabilityTest rt = new ReliabilityTest(_curTestSet.SuppressConsoleOutputFromTests);
rt.TestStartMode = _curTestSet.DefaultTestStartMode;
// first we need to setup any default options which are set globally on
// the test start mode.
if (null != _curTestSet.DefaultDebugger)
{
if (_curTestSet.DefaultTestStartMode != TestStartModeEnum.ProcessLoader)
{
throw new Exception(String.Format("{0} specified with default debugger or debugger options. If you want a debugger per test please use {1}=\"{2}\" ",
configTestStartModeAppDomainLoader,
configDefaultTestStartMode,
configTestStartModeProcessLoader));
}
rt.Debugger = _curTestSet.DefaultDebugger;
}
if (null != _curTestSet.DefaultDebuggerOptions)
{
if (_curTestSet.DefaultTestStartMode != TestStartModeEnum.ProcessLoader)
{
throw new Exception(String.Format("{0} specified with default debugger or debugger options. If you want a debugger per test please use {1}=\"{2}\" ",
configTestStartModeAppDomainLoader,
configDefaultTestStartMode,
configTestStartModeProcessLoader));
}
rt.DebuggerOptions = _curTestSet.DefaultDebuggerOptions;
}
// then we need to process the individual options & overrides.
while (currentXML.MoveToNextAttribute())
{
XmlDebugOut(" " + currentXML.Name + "=\"" + currentXML.Value + "\"");
switch (currentXML.Name)
{
case configAssemblyName:
rt.RefOrID = currentXML.Value;
break;
case configAssemblyBasePath:
rt.BasePath = Environment.ExpandEnvironmentVariables(currentXML.Value);
break;
case configAssemblyRequiresSDK:
if (String.Compare(currentXML.Value, "true", true) == 0 ||
currentXML.Value == "1" ||
String.Compare(currentXML.Value, "yes", true) == 0)
{
rt.RequiresSDK = true;
}
else if (String.Compare(currentXML.Value, "false", true) == 0 ||
currentXML.Value == "0" ||
String.Compare(currentXML.Value, "no", true) == 0)
{
rt.RequiresSDK = false;
}
else
{
throw new Exception("RequiresSDK has illegal value. Must be true, 1, yes, false, 0, or no");
}
break;
case configAssemblyFilename:
rt.Assembly = Environment.ExpandEnvironmentVariables(currentXML.Value);
Console.WriteLine("test is " + rt.Assembly);
break;
case configAssemblySuccessCode:
rt.SuccessCode = Convert.ToInt32(currentXML.Value);
break;
case configAssemblyEntryPoint:
rt.Arguments = currentXML.Value;
break;
case configAssemblyArguments:
if (!string.IsNullOrEmpty(currentXML.Value))
rt.Arguments = Environment.ExpandEnvironmentVariables(currentXML.Value);
break;
case configAssemblyConcurrentCopies:
rt.ConcurrentCopies = Convert.ToInt32(currentXML.Value);
break;
case configAssemblyStatus:
if (currentXML.Value == configAssemblyStatusDisabled)
{
disabled = true;
}
break;
case configAssemblyDebugger:
if (TestStartModeEnum.ProcessLoader != _curTestSet.DefaultTestStartMode)
{
throw new Exception(String.Format("{0} can only be set for test sets with {1}=\"{2}\" set.",
configAssemblyDebugger,
configDefaultTestStartMode,
configTestStartModeProcessLoader));
}
if (currentXML.Value.Length >= 7 && currentXML.Value.Substring(currentXML.Value.Length - 7).ToLower() == "cdb.exe")
{
rt.Debugger = currentXML.Value;
}
else if (currentXML.Value.Length >= 10 && currentXML.Value.Substring(currentXML.Value.Length - 7).ToLower() == "windbg.exe")
{
rt.Debugger = currentXML.Value;
}
else if (currentXML.Value.ToLower() == "none")
{
rt.Debugger = String.Empty;
}
else
{
throw new Exception("Unknown debugger specified (" + currentXML.Value + ")");
}
break;
case configAssemblyDebuggerOptions:
if (TestStartModeEnum.ProcessLoader != _curTestSet.DefaultTestStartMode)
{
throw new Exception(String.Format("{0} can only be set for test sets with {1}=\"{2}\" set.",
configAssemblyDebuggerOptions,
configDefaultTestStartMode,
configTestStartModeProcessLoader));
}
rt.DebuggerOptions = Environment.ExpandEnvironmentVariables(currentXML.Value);
break;
case configAssemblySmartNetGuid:
try
{
rt.Guid = new Guid(currentXML.Value);
}
catch (FormatException)
{
throw new Exception(String.Format("The format for guid {0} on test {1} is invalid", currentXML.Value, rt.RefOrID));
}
break;
case configAssemblyDuration:
if (currentXML.Value.IndexOf(":") == -1)
{
// just a number of minutes
rt.ExpectedDuration = Convert.ToInt32(currentXML.Value);
}
else
{
// time span
try
{
rt.ExpectedDuration = unchecked((int)(TimeSpan.Parse(currentXML.Value).Ticks / TimeSpan.TicksPerMinute));
}
catch
{
throw new Exception(String.Format("Bad time span {0} for expected duration.", currentXML.Value));
}
}
break;
case configAssemblyTestAttributes:
string[] attrs = currentXML.Value.Split(';');
TestAttributes testAttrs = TestAttributes.None;
for (int j = 0; j < attrs.Length; j++)
{
switch (attrs[j].ToLower())
{
case "requiressta":
testAttrs |= TestAttributes.RequiresSTAThread;
break;
case "requiresmta":
testAttrs |= TestAttributes.RequiresMTAThread;
break;
default:
throw new Exception(String.Format("Unknown test attribute: {0}", attrs[j]));
}
}
rt.TestAttrs = testAttrs;
break;
case configAssemblyTestLoader:
switch (currentXML.Value)
{
case configTestStartModeAppDomainLoader:
if (null != rt.Debugger || null != rt.DebuggerOptions)
{
throw new Exception(String.Format("{0} specified with debugger or debugger options. If you want a debugger per test please use {1}=\"{2}\" ",
configTestStartModeAppDomainLoader,
configDefaultTestStartMode,
configTestStartModeProcessLoader));
}
rt.TestStartMode = TestStartModeEnum.AppDomainLoader;
break;
case configTestStartModeProcessLoader:
rt.TestStartMode = TestStartModeEnum.ProcessLoader;
break;
default:
throw new Exception(String.Format("Unknown test starter {0} specified!", currentXML.Value));
}
break;
case configAssemblyTestOwner:
rt.TestOwner = currentXML.Value;
break;
case configAssemblyTestGroup:
string groupName = currentXML.Value;
// first, we want to see if another test has this group. We store the group name in
// our group List as the 1st entry. If we find a group we set our List
// arraylist to that same List (and add ourselves to it). We're then all in
// one group, the arraylist.
int i = 0;
for (i = 0; i < foundTests.Count; i++)
{
ReliabilityTest test = foundTests[i] as ReliabilityTest;
Debug.Assert(test != null, "Non reliability test in foundTests array!");
if (null != test.Group)
{
string curGroupName = test.Group[0].ToString();
if (String.Compare(curGroupName, groupName, false) == 0)
{
test.Group.Add(rt);
rt.Group = test.Group;
break;
}
}
}
if (rt.Group == null)
{
// this is the first test in this group
rt.Group = new List<ReliabilityTest>();
rt.Group.Add(rt);
}
break;
case configAssemblyPostCommand:
if (rt.PostCommands == null)
{
// first pre command on this test
rt.PostCommands = new List<string>();
}
rt.PostCommands.Add(Environment.ExpandEnvironmentVariables(currentXML.Value));
break;
case configAssemblyPreCommand:
if (rt.PreCommands == null)
{
// first pre command on this test
rt.PreCommands = new List<string>();
}
rt.PreCommands.Add(Environment.ExpandEnvironmentVariables(currentXML.Value));
break;
case configAssemblyCustomAction:
switch (currentXML.Value)
{
case "LegacySecurityPolicy":
rt.CustomAction = CustomActionType.LegacySecurityPolicy;
break;
default:
throw new Exception(String.Format("Unknown custom action: {0}", currentXML.Value));
}
break;
default:
throw new Exception("Unknown attribute on assembly tag (" + currentXML.Name + "=" + currentXML.Value + ")");
}
}
// if the test is disabled or it requires the SDK to be installed &
// we don't have the SDK installed then don't add it to our list
// of tests to run.
if (disabled || (rt.RequiresSDK == true && Environment.GetEnvironmentVariable("INSTALL_SDK") == null))
{
break;
}
int testCopies = 1;
if (_curTestSet.AppDomainLoaderMode == AppDomainLoaderMode.FullIsolation)
{
// in this mode each copy of the test is ran in it's own app domain,
// fully isolated from all other copies of the test. If the user
// specified a cloning level we need to duplicate the test.
testCopies = rt.ConcurrentCopies;
rt.ConcurrentCopies = 1;
}
else if (_curTestSet.AppDomainLoaderMode == AppDomainLoaderMode.RoundRobin)
{
// In this mode each test is ran in an app domain w/ other tests.
testCopies = rt.ConcurrentCopies;
rt.ConcurrentCopies = 1;
}
else
{
// Normal mode - tests are ran in app domains w/ copies of themselves
}
string refOrId = rt.RefOrID;
if (rt.RefOrID == null || rt.RefOrID == String.Empty)
{
refOrId = rt.Assembly + rt.Arguments;
}
for (int j = 0; j < testCopies; j++)
{
if (testCopies > 1)
{
rt.RefOrID = String.Format("{0} Copy {1}", refOrId, j);
}
else
{
rt.RefOrID = refOrId;
}
bool fRetry;
do
{
fRetry = false;
for (int i = 0; i < foundTests.Count; i++)
{
if (((ReliabilityTest)foundTests[i]).RefOrID == rt.RefOrID)
{
rt.RefOrID = rt.RefOrID + "_" + i.ToString();
fRetry = true;
break;
}
}
} while (fRetry);
ReliabilityTest clone = (ReliabilityTest)rt.Clone();
clone.Index = foundTests.Add(clone);
}
break;
default:
throw new ArgumentException("Unknown node (\"" + currentXML.NodeType + "\") named \"" + currentXML.Name + "\"=\"" + currentXML.Value + "\" in config file!");
} // end of switch(currentXML.Name)
if (isEmpty)
{
XmlDebugOut("/>\r\n");
testLevelStack.Pop();
}
else
{
XmlDebugOut(">\r\n");
}
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.Document:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
break;
case XmlNodeType.EndElement:
IndentToDepth(totalDepth + currentXML.Depth);
XmlDebugOutLine("</" + currentXML.Name + ">");
// note: we never pop or push the includes tag. It's a special 'hidden' tag
// we should also never have to pop a configInclude tag, but it might happen
if (currentXML.Name != configIncludes && currentXML.Name != configInclude && currentXML.Name != configHost)
{
testLevelStack.Pop();
}
break;
} // end of switch(currentXML.NodeType)
} // end of while(currentXML.Read())
} while (xmlFileStack.Count > 0);
if (_curTestSet != null && foundTests != null && foundTests.Count > 0)
{
_curTestSet.Tests = (ReliabilityTest[])foundTests.ToArray(typeof(ReliabilityTest));
_curTestSet.DiscoveryPaths = (string[])discoveryPaths.ToArray(typeof(string));
discoveryPaths.Clear();
foundTests.Clear();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Filename processing helper functions.
/// <summary>
/// given a base path & a potentially relative path we'll convert the potentially
/// </summary>
public static string ConvertPotentiallyRelativeFilenameToFullPath(string basepath, string path)
{
string trimmedPath = path.Trim(); // remove excess whitespace.
#if PROJECTK_BUILD
if (String.Compare("file://", 0, trimmedPath, 0, 7, StringComparison.OrdinalIgnoreCase) == 0) // strip file:// from the front if it exists.
#else
if (String.Compare("file://", 0, trimmedPath, 0, 7, true) == 0) // strip file:// from the front if it exists.
#endif
{
trimmedPath = trimmedPath.Substring(7);
}
if (trimmedPath.Trim()[1] == ':' || (trimmedPath.Trim()[0] == '\\' && trimmedPath.Trim()[0] == '\\')) // we have a drive & UNC
{
return (path);
}
if (basepath.LastIndexOf(Path.PathSeparator) == (basepath.Length - 1))
{
return (basepath + trimmedPath);
}
else
{
return Path.Combine(basepath, trimmedPath);
}
}
/// <summary>
/// given a path with a filename on it we remove the filename (to get just the base path).
/// </summary>
private string stripFilenameFromPath(string path)
{
string trimmedPath = path.Trim();
if (trimmedPath.LastIndexOf("\\") == -1)
{
if (trimmedPath.LastIndexOf("/") == -1)
{
return (trimmedPath); // nothing to strip.
}
#if PROJECTK_BUILD
if (String.Compare("file://", 0, trimmedPath, 0, 7, StringComparison.OrdinalIgnoreCase) == 0)
#else
if (String.Compare("file://", 0, trimmedPath, 0, 7, true) == 0)
#endif
{
return (trimmedPath.Substring(0, trimmedPath.LastIndexOf("/")));
}
return (trimmedPath);
}
return (trimmedPath.Substring(0, trimmedPath.LastIndexOf("\\")));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Enumerator related - allow enumerating over multiple test runs within the config file.
//
/// <summary>
/// Gets the test set enumerator
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return (this);
}
/// <summary>
/// Get the current test set
/// </summary>
public object Current
{
get
{
if (_index < _testSet.Count && _index >= 0)
{
return (_testSet[_index]);
}
throw new InvalidOperationException();
}
}
/// <summary>
/// Move to the next test set
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
_index++;
if (_index >= _testSet.Count)
{
return (false);
}
return (true);
}
/// <summary>
/// Reset the enumerator to the 1st position
/// </summary>
public void Reset()
{
_index = 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Debugging helper functions - these are only ever called when we compile with DEBUG_XML defined.
//
//
[Conditional("DEBUG_XML")]
private void IndentToDepth(int depth)
{
while ((depth--) > 0)
{
Console.Write(" ");
}
}
[Conditional("DEBUG_XML")]
private void XmlDebugOut(string output)
{
Console.Write(output);
}
[Conditional("DEBUG_XML")]
private void XmlDebugOutLine(string output)
{
Console.WriteLine(output);
}
}
[Flags]
public enum TestAttributes
{
None = 0x00000000,
RequiresSTAThread = 0x00000001,
RequiresMTAThread = 0x00000002,
RequiresUnknownThread = 0x00000004,
RequiresThread = (RequiresSTAThread | RequiresMTAThread | RequiresUnknownThread),
}
public enum CustomActionType
{
None,
LegacySecurityPolicy
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedNodeTemplatesClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeTemplateRequest request = new GetNodeTemplateRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
NodeTemplate = "node_template118e38ae",
};
NodeTemplate expectedResponse = new NodeTemplate
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Disks = { new LocalDisk(), },
Region = "regionedb20d96",
Status = NodeTemplate.Types.Status.Ready,
ServerBinding = new ServerBinding(),
CpuOvercommitType = NodeTemplate.Types.CpuOvercommitType.UndefinedCpuOvercommitType,
Accelerators =
{
new AcceleratorConfig(),
},
StatusMessage = "status_message2c618f86",
NodeTypeFlexibility = new NodeTemplateNodeTypeFlexibility(),
NodeAffinityLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
NodeType = "node_type98c685da",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
NodeTemplate response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeTemplateRequest request = new GetNodeTemplateRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
NodeTemplate = "node_template118e38ae",
};
NodeTemplate expectedResponse = new NodeTemplate
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Disks = { new LocalDisk(), },
Region = "regionedb20d96",
Status = NodeTemplate.Types.Status.Ready,
ServerBinding = new ServerBinding(),
CpuOvercommitType = NodeTemplate.Types.CpuOvercommitType.UndefinedCpuOvercommitType,
Accelerators =
{
new AcceleratorConfig(),
},
StatusMessage = "status_message2c618f86",
NodeTypeFlexibility = new NodeTemplateNodeTypeFlexibility(),
NodeAffinityLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
NodeType = "node_type98c685da",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NodeTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
NodeTemplate responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
NodeTemplate responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeTemplateRequest request = new GetNodeTemplateRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
NodeTemplate = "node_template118e38ae",
};
NodeTemplate expectedResponse = new NodeTemplate
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Disks = { new LocalDisk(), },
Region = "regionedb20d96",
Status = NodeTemplate.Types.Status.Ready,
ServerBinding = new ServerBinding(),
CpuOvercommitType = NodeTemplate.Types.CpuOvercommitType.UndefinedCpuOvercommitType,
Accelerators =
{
new AcceleratorConfig(),
},
StatusMessage = "status_message2c618f86",
NodeTypeFlexibility = new NodeTemplateNodeTypeFlexibility(),
NodeAffinityLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
NodeType = "node_type98c685da",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
NodeTemplate response = client.Get(request.Project, request.Region, request.NodeTemplate);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeTemplateRequest request = new GetNodeTemplateRequest
{
Region = "regionedb20d96",
Project = "projectaa6ff846",
NodeTemplate = "node_template118e38ae",
};
NodeTemplate expectedResponse = new NodeTemplate
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
Disks = { new LocalDisk(), },
Region = "regionedb20d96",
Status = NodeTemplate.Types.Status.Ready,
ServerBinding = new ServerBinding(),
CpuOvercommitType = NodeTemplate.Types.CpuOvercommitType.UndefinedCpuOvercommitType,
Accelerators =
{
new AcceleratorConfig(),
},
StatusMessage = "status_message2c618f86",
NodeTypeFlexibility = new NodeTemplateNodeTypeFlexibility(),
NodeAffinityLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
NodeType = "node_type98c685da",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NodeTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
NodeTemplate responseCallSettings = await client.GetAsync(request.Project, request.Region, request.NodeTemplate, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
NodeTemplate responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.NodeTemplate, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyNodeTemplateRequest request = new GetIamPolicyNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyNodeTemplateRequest request = new GetIamPolicyNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyNodeTemplateRequest request = new GetIamPolicyNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request.Project, request.Region, request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyNodeTemplateRequest request = new GetIamPolicyNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyNodeTemplateRequest request = new SetIamPolicyNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyNodeTemplateRequest request = new SetIamPolicyNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyNodeTemplateRequest request = new SetIamPolicyNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyNodeTemplateRequest request = new SetIamPolicyNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
RegionSetPolicyRequestResource = new RegionSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsNodeTemplateRequest request = new TestIamPermissionsNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsNodeTemplateRequest request = new TestIamPermissionsNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsNodeTemplateRequest request = new TestIamPermissionsNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<NodeTemplates.NodeTemplatesClient> mockGrpcClient = new moq::Mock<NodeTemplates.NodeTemplatesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsNodeTemplateRequest request = new TestIamPermissionsNodeTemplateRequest
{
Region = "regionedb20d96",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NodeTemplatesClient client = new NodeTemplatesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class SpecifyCultureInfoTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new SpecifyCultureInfoAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new SpecifyCultureInfoAnalyzer();
}
[Fact]
public void CA1304_PlainString_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass0
{
public string SpecifyCultureInfo01()
{
return ""foo"".ToLower();
}
}",
GetCSharpResultAt(9, 16, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass0.SpecifyCultureInfo01()", "string.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_VariableStringInsideDifferentContainingSymbols_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass1
{
public string LowercaseAString(string name)
{
return name.ToLower();
}
public string InsideALambda(string insideLambda)
{
Func<string> ddd = () =>
{
return insideLambda.ToLower();
};
return null;
}
public string PropertyWithALambda
{
get
{
Func<string> ddd = () =>
{
return ""InsideGetter"".ToLower();
};
return null;
}
}
}
",
GetCSharpResultAt(9, 16, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.LowercaseAString(string)", "string.ToLower(CultureInfo)"),
GetCSharpResultAt(16, 20, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.InsideALambda(string)", "string.ToLower(CultureInfo)"),
GetCSharpResultAt(28, 24, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.PropertyWithALambda.get", "string.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsFirstArgument_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasCultureInfoAsFirstArgument(""Foo"");
}
public static void MethodOverloadHasCultureInfoAsFirstArgument(string format)
{
MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo.CurrentCulture, format);
}
public static void MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(string)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo, string)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsLastArgument_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasCultureInfoAsLastArgument(""Foo"");
}
public static void MethodOverloadHasCultureInfoAsLastArgument(string format)
{
MethodOverloadHasCultureInfoAsLastArgument(format, CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasCultureInfoAsLastArgument(string format, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadHasCultureInfoAsLastArgument(CultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(string)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(string, CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasJustCultureInfo_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasJustCultureInfo();
}
public static void MethodOverloadHasJustCultureInfo()
{
MethodOverloadHasJustCultureInfo(CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasJustCultureInfo(CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo(CultureInfo)"));
}
[Fact]
public void CA1304_DoesNotRecommendObsoleteOverload_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasJustCultureInfo();
}
public static void MethodOverloadHasJustCultureInfo()
{
MethodOverloadHasJustCultureInfo(CultureInfo.CurrentCulture);
}
[Obsolete]
public static void MethodOverloadHasJustCultureInfo(CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
}");
}
[Fact]
public void CA1304_TargetMethodIsGenericsAndNonGenerics_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
TargetMethodIsNonGenerics();
TargetMethodIsGenerics<int>(); // No Diagnostics
}
public static void TargetMethodIsNonGenerics()
{
}
public static void TargetMethodIsNonGenerics<T>(CultureInfo provider)
{
}
public static void TargetMethodIsGenerics<V>()
{
}
public static void TargetMethodIsGenerics(CultureInfo provider)
{
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.TargetMethodIsNonGenerics()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.TargetMethodIsNonGenerics<T>(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadIncludeNonCandidates_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadCount3();
}
public static void MethodOverloadCount3()
{
MethodOverloadCount3(CultureInfo.CurrentCulture);
}
public static void MethodOverloadCount3(CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
public static void MethodOverloadCount3(string b)
{
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadCount3()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadCount3(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadWithJustCultureInfoAsExtraParameter_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadWithJustCultureInfoAsExtraParameter(2, 3);
}
public static void MethodOverloadWithJustCultureInfoAsExtraParameter(int a, int b)
{
MethodOverloadWithJustCultureInfoAsExtraParameter(a, b, CultureInfo.CurrentCulture);
}
public static void MethodOverloadWithJustCultureInfoAsExtraParameter(int a, int b, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(int, int)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(int, int, CultureInfo)"));
}
[Fact]
public void CA1304_NoDiagnostics_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
// No Diag - Inherited CultureInfo
MethodOverloadHasInheritedCultureInfo(""Foo"");
// No Diag - Since the overload has more parameters apart from CultureInfo
MethodOverloadHasMoreThanCultureInfo(""Foo"");
// No Diag - Since the CultureInfo parameter is neither as the first parameter nor as the last parameter
MethodOverloadWithJustCultureInfoAsInbetweenParameter("""", """");
}
public static void MethodOverloadHasInheritedCultureInfo(string format)
{
MethodOverloadHasInheritedCultureInfo(new DerivedCultureInfo(""""), format);
}
public static void MethodOverloadHasInheritedCultureInfo(DerivedCultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadHasMoreThanCultureInfo(string format)
{
MethodOverloadHasMoreThanCultureInfo(format, null, CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasMoreThanCultureInfo(string format, string what, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadWithJustCultureInfoAsInbetweenParameter(string a, string b)
{
MethodOverloadWithJustCultureInfoAsInbetweenParameter(a, CultureInfo.CurrentCulture, b);
}
public static void MethodOverloadWithJustCultureInfoAsInbetweenParameter(string a, CultureInfo provider, string b)
{
Console.WriteLine(string.Format(provider, """"));
}
}
public class DerivedCultureInfo : CultureInfo
{
public DerivedCultureInfo(string name):
base(name)
{
}
}");
}
[Fact]
public void CA1304_PlainString_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass0
Public Function SpecifyCultureInfo01() As String
Return ""foo"".ToLower()
End Function
End Class",
GetBasicResultAt(7, 16, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass0.SpecifyCultureInfo01()", "String.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_VariableStringInsideDifferentContainingSymbols_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass1
Public Function LowercaseAString(name As String) As String
Return name.ToLower()
End Function
Public Function InsideALambda(insideLambda As String) As String
Dim ddd As Func(Of String) = Function()
Return insideLambda.ToLower()
End Function
Return Nothing
End Function
Public ReadOnly Property PropertyWithALambda() As String
Get
Dim ddd As Func(Of String) = Function()
Return ""InsideGetter"".ToLower()
End Function
Return Nothing
End Get
End Property
End Class",
GetBasicResultAt(7, 16, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.LowercaseAString(String)", "String.ToLower(CultureInfo)"),
GetBasicResultAt(12, 48, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.InsideALambda(String)", "String.ToLower(CultureInfo)"),
GetBasicResultAt(21, 52, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.PropertyWithALambda()", "String.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsFirstArgument_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasCultureInfoAsFirstArgument(""Foo"")
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsFirstArgument(format As String)
MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo.CurrentCulture, format)
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsFirstArgument(provider As CultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(String)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo, String)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsLastArgument_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasCultureInfoAsLastArgument(""Foo"")
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(format As String)
MethodOverloadHasCultureInfoAsLastArgument(format, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(format As String, provider As CultureInfo)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(provider As CultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(String)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(String, CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasJustCultureInfo_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasJustCultureInfo()
End Sub
Public Shared Sub MethodOverloadHasJustCultureInfo()
MethodOverloadHasJustCultureInfo(CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasJustCultureInfo(provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadIncludeNonCandidates_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadCount3()
End Sub
Public Shared Sub MethodOverloadCount3()
MethodOverloadCount3(CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadCount3(provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
Public Shared Sub MethodOverloadCount3(b As String)
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadCount3()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadCount3(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadWithJustCultureInfoAsExtraParameter_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadWithJustCultureInfoAsExtraParameter(2, 3)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsExtraParameter(a As Integer, b As Integer)
MethodOverloadWithJustCultureInfoAsExtraParameter(a, b, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsExtraParameter(a As Integer, b As Integer, provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(Integer, Integer)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(Integer, Integer, CultureInfo)"));
}
[Fact]
public void CA1304_NoDiagnostics_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
' No Diag - Inherited CultureInfo
MethodOverloadHasInheritedCultureInfo(""Foo"")
' No Diag - There are more parameters apart from CultureInfo
MethodOverloadHasMoreThanCultureInfo(""Foo"")
' No Diag - The CultureInfo parameter is neither the first parameter nor the last parameter
MethodOverloadWithJustCultureInfoAsInbetweenParameter("""", """")
End Sub
Public Shared Sub MethodOverloadHasInheritedCultureInfo(format As String)
MethodOverloadHasInheritedCultureInfo(New DerivedCultureInfo(""""), format)
End Sub
Public Shared Sub MethodOverloadHasInheritedCultureInfo(provider As DerivedCultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadHasMoreThanCultureInfo(format As String)
MethodOverloadHasMoreThanCultureInfo(format, Nothing, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasMoreThanCultureInfo(format As String, what As String, provider As CultureInfo)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsInbetweenParameter(a As String, b As String)
MethodOverloadWithJustCultureInfoAsInbetweenParameter(a, CultureInfo.CurrentCulture, b)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsInbetweenParameter(a As String, provider As CultureInfo, b As String)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class
Public Class DerivedCultureInfo
Inherits CultureInfo
Public Sub New(name As String)
MyBase.New(name)
End Sub
End Class");
}
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class MemberAccessTests
{
private class UnreadableIndexableClass
{
public int this[int index]
{
set { }
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructInstanceFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
Expression.Constant(new FS() { II = 42 }),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructStaticFieldTest(bool useInterpreter)
{
FS.SI = 42;
try
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FS),
"SI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
finally
{
FS.SI = 0;
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructConstFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FS),
"CI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructStaticReadOnlyFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FS),
"RI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructInstancePropertyTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
Expression.Constant(new PS() { II = 42 }),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessStructStaticPropertyTest(bool useInterpreter)
{
PS.SI = 42;
try
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
null,
typeof(PS),
"SI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
finally
{
PS.SI = 0;
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
Expression.Constant(new FC() { II = 42 }),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassStaticFieldTest(bool useInterpreter)
{
FC.SI = 42;
try
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FC),
"SI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
finally
{
FC.SI = 0;
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassConstFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FC),
"CI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassStaticReadOnlyFieldTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
null,
typeof(FC),
"RI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstancePropertyTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
Expression.Constant(new PC() { II = 42 }),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassStaticPropertyTest(bool useInterpreter)
{
PC.SI = 42;
try
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
null,
typeof(PC),
"SI"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(42, f());
}
finally
{
PC.SI = 0;
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceFieldNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Field(
Expression.Constant(null, typeof(FC)),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceFieldAssignNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Assign(
Expression.Field(
Expression.Constant(null, typeof(FC)),
"II"),
Expression.Constant(1)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstancePropertyNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
Expression.Constant(null, typeof(PC)),
"II"),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceIndexerNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Property(
Expression.Constant(null, typeof(PC)),
"Item",
Expression.Constant(1)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckMemberAccessClassInstanceIndexerAssignNullReferenceTest(bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Assign(
Expression.Property(
Expression.Constant(null, typeof(PC)),
"Item",
Expression.Constant(1)),
Expression.Constant(1)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Throws<NullReferenceException>(() => f());
}
[Fact]
public static void AccessIndexedPropertyWithoutIndex()
{
Assert.Throws<ArgumentException>(null, () => Expression.Property(Expression.Default(typeof(List<int>)), typeof(List<int>).GetProperty("Item")));
}
[Fact]
public static void AccessIndexedPropertyWithoutIndexWriteOnly()
{
Assert.Throws<ArgumentException>(null, () => Expression.Property(Expression.Default(typeof(UnreadableIndexableClass)), typeof(UnreadableIndexableClass).GetProperty("Item")));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Capabilities;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OpenSim.Capabilities.Handlers;
namespace OpenSim.Region.ClientStack.Linden
{
/// <summary>
/// This module implements both WebFetchInventoryDescendents and FetchInventoryDescendents2 capabilities.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebFetchInvDescModule")]
public class WebFetchInvDescModule : INonSharedRegionModule
{
class aPollRequest
{
public PollServiceInventoryEventArgs thepoll;
public UUID reqID;
public Hashtable request;
public ScenePresence presence;
public List<UUID> folders;
}
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Control whether requests will be processed asynchronously.
/// </summary>
/// <remarks>
/// Defaults to true. Can currently not be changed once a region has been added to the module.
/// </remarks>
public bool ProcessQueuedRequestsAsync { get; private set; }
/// <summary>
/// Number of inventory requests processed by this module.
/// </summary>
/// <remarks>
/// It's the PollServiceRequestManager that actually sends completed requests back to the requester.
/// </remarks>
public static int ProcessedRequestsCount { get; set; }
private static Stat s_queuedRequestsStat;
private static Stat s_processedRequestsStat;
public Scene Scene { get; private set; }
private IInventoryService m_InventoryService;
private ILibraryService m_LibraryService;
private bool m_Enabled;
private string m_fetchInventoryDescendents2Url;
private string m_webFetchInventoryDescendentsUrl;
private static WebFetchInvDescHandler m_webFetchHandler;
private static Thread[] m_workerThreads = null;
private static DoubleQueue<aPollRequest> m_queue =
new DoubleQueue<aPollRequest>();
#region ISharedRegionModule Members
public WebFetchInvDescModule() : this(true) {}
public WebFetchInvDescModule(bool processQueuedResultsAsync)
{
ProcessQueuedRequestsAsync = processQueuedResultsAsync;
}
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["ClientStack.LindenCaps"];
if (config == null)
return;
m_fetchInventoryDescendents2Url = config.GetString("Cap_FetchInventoryDescendents2", string.Empty);
m_webFetchInventoryDescendentsUrl = config.GetString("Cap_WebFetchInventoryDescendents", string.Empty);
if (m_fetchInventoryDescendents2Url != string.Empty || m_webFetchInventoryDescendentsUrl != string.Empty)
{
m_Enabled = true;
}
}
public void AddRegion(Scene s)
{
if (!m_Enabled)
return;
Scene = s;
}
public void RemoveRegion(Scene s)
{
if (!m_Enabled)
return;
Scene.EventManager.OnRegisterCaps -= RegisterCaps;
StatsManager.DeregisterStat(s_processedRequestsStat);
StatsManager.DeregisterStat(s_queuedRequestsStat);
if (ProcessQueuedRequestsAsync)
{
if (m_workerThreads != null)
{
foreach (Thread t in m_workerThreads)
Watchdog.AbortThread(t.ManagedThreadId);
m_workerThreads = null;
}
}
Scene = null;
}
public void RegionLoaded(Scene s)
{
if (!m_Enabled)
return;
if (s_processedRequestsStat == null)
s_processedRequestsStat =
new Stat(
"ProcessedFetchInventoryRequests",
"Number of processed fetch inventory requests",
"These have not necessarily yet been dispatched back to the requester.",
"",
"inventory",
"httpfetch",
StatType.Pull,
MeasuresOfInterest.AverageChangeOverTime,
stat => { stat.Value = ProcessedRequestsCount; },
StatVerbosity.Debug);
if (s_queuedRequestsStat == null)
s_queuedRequestsStat =
new Stat(
"QueuedFetchInventoryRequests",
"Number of fetch inventory requests queued for processing",
"",
"",
"inventory",
"httpfetch",
StatType.Pull,
MeasuresOfInterest.AverageChangeOverTime,
stat => { stat.Value = m_queue.Count; },
StatVerbosity.Debug);
StatsManager.RegisterStat(s_processedRequestsStat);
StatsManager.RegisterStat(s_queuedRequestsStat);
m_InventoryService = Scene.InventoryService;
m_LibraryService = Scene.LibraryService;
// We'll reuse the same handler for all requests.
m_webFetchHandler = new WebFetchInvDescHandler(m_InventoryService, m_LibraryService);
Scene.EventManager.OnRegisterCaps += RegisterCaps;
if (ProcessQueuedRequestsAsync && m_workerThreads == null)
{
m_workerThreads = new Thread[2];
for (uint i = 0; i < 2; i++)
{
m_workerThreads[i] = Watchdog.StartThread(DoInventoryRequests,
String.Format("InventoryWorkerThread{0}", i),
ThreadPriority.Normal,
false,
true,
null,
int.MaxValue);
}
}
}
public void PostInitialise()
{
}
public void Close() { }
public string Name { get { return "WebFetchInvDescModule"; } }
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
private class PollServiceInventoryEventArgs : PollServiceEventArgs
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<UUID, Hashtable> responses =
new Dictionary<UUID, Hashtable>();
private WebFetchInvDescModule m_module;
public PollServiceInventoryEventArgs(WebFetchInvDescModule module, string url, UUID pId) :
base(null, url, null, null, null, pId, int.MaxValue)
{
m_module = module;
HasEvents = (x, y) => { lock (responses) return responses.ContainsKey(x); };
GetEvents = (x, y) =>
{
lock (responses)
{
try
{
return responses[x];
}
finally
{
responses.Remove(x);
}
}
};
Request = (x, y) =>
{
ScenePresence sp = m_module.Scene.GetScenePresence(Id);
if (sp == null)
{
m_log.ErrorFormat("[INVENTORY]: Unable to find ScenePresence for {0}", Id);
return;
}
aPollRequest reqinfo = new aPollRequest();
reqinfo.thepoll = this;
reqinfo.reqID = x;
reqinfo.request = y;
reqinfo.presence = sp;
reqinfo.folders = new List<UUID>();
// Decode the request here
string request = y["body"].ToString();
request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>");
request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>");
request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>");
Hashtable hash = new Hashtable();
try
{
hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
}
catch (LLSD.LLSDParseException e)
{
m_log.ErrorFormat("[INVENTORY]: Fetch error: {0}{1}" + e.Message, e.StackTrace);
m_log.Error("Request: " + request);
return;
}
catch (System.Xml.XmlException)
{
m_log.ErrorFormat("[INVENTORY]: XML Format error");
}
ArrayList foldersrequested = (ArrayList)hash["folders"];
bool highPriority = false;
for (int i = 0; i < foldersrequested.Count; i++)
{
Hashtable inventoryhash = (Hashtable)foldersrequested[i];
string folder = inventoryhash["folder_id"].ToString();
UUID folderID;
if (UUID.TryParse(folder, out folderID))
{
if (!reqinfo.folders.Contains(folderID))
{
//TODO: Port COF handling from Avination
reqinfo.folders.Add(folderID);
}
}
}
if (highPriority)
m_queue.EnqueueHigh(reqinfo);
else
m_queue.EnqueueLow(reqinfo);
};
NoEvents = (x, y) =>
{
/*
lock (requests)
{
Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
requests.Remove(request);
}
*/
Hashtable response = new Hashtable();
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
return response;
};
}
public void Process(aPollRequest requestinfo)
{
UUID requestID = requestinfo.reqID;
Hashtable response = new Hashtable();
response["int_response_code"] = 200;
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
response["str_response_string"] = m_webFetchHandler.FetchInventoryDescendentsRequest(
requestinfo.request["body"].ToString(), String.Empty, String.Empty, null, null);
lock (responses)
responses[requestID] = response;
WebFetchInvDescModule.ProcessedRequestsCount++;
}
}
private void RegisterCaps(UUID agentID, Caps caps)
{
RegisterFetchDescendentsCap(agentID, caps, "FetchInventoryDescendents2", m_fetchInventoryDescendents2Url);
}
private void RegisterFetchDescendentsCap(UUID agentID, Caps caps, string capName, string url)
{
string capUrl;
// disable the cap clause
if (url == "")
{
return;
}
// handled by the simulator
else if (url == "localhost")
{
capUrl = "/CAPS/" + UUID.Random() + "/";
// Register this as a poll service
PollServiceInventoryEventArgs args = new PollServiceInventoryEventArgs(this, capUrl, agentID);
args.Type = PollServiceEventArgs.EventType.Inventory;
caps.RegisterPollHandler(capName, args);
}
// external handler
else
{
capUrl = url;
IExternalCapsModule handler = Scene.RequestModuleInterface<IExternalCapsModule>();
if (handler != null)
handler.RegisterExternalUserCapsHandler(agentID,caps,capName,capUrl);
else
caps.RegisterHandler(capName, capUrl);
}
// m_log.DebugFormat(
// "[FETCH INVENTORY DESCENDENTS2 MODULE]: Registered capability {0} at {1} in region {2} for {3}",
// capName, capUrl, m_scene.RegionInfo.RegionName, agentID);
}
// private void DeregisterCaps(UUID agentID, Caps caps)
// {
// string capUrl;
//
// if (m_capsDict.TryGetValue(agentID, out capUrl))
// {
// MainServer.Instance.RemoveHTTPHandler("", capUrl);
// m_capsDict.Remove(agentID);
// }
// }
private void DoInventoryRequests()
{
while (true)
{
Watchdog.UpdateThread();
WaitProcessQueuedInventoryRequest();
}
}
public void WaitProcessQueuedInventoryRequest()
{
aPollRequest poolreq = m_queue.Dequeue();
if (poolreq != null && poolreq.thepoll != null)
{
try
{
poolreq.thepoll.Process(poolreq);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[INVENTORY]: Failed to process queued inventory request {0} for {1} in {2}. Exception {3}",
poolreq.reqID, poolreq.presence != null ? poolreq.presence.Name : "unknown", Scene.Name, e);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license 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()
public partial struct Vector2
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
#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 Vector2(Single value) : this(value, value) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
[JitIntrinsic]
public Vector2(Single x, Single y)
{
X = x;
Y = y;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
/// <param name="array">The destination array.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from the given 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
/// or if there are not enough elements to copy.</exception>
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.GetString("Arg_NullArgumentNullRef"));
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(SR.GetString("Arg_ArgumentOutOfRangeException", index));
}
if ((array.Length - index) < 2)
{
throw new ArgumentException(SR.GetString("Arg_ElementsInSourceIsGreaterThanDestination", index));
}
array[index] = X;
array[index + 1] = Y;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector2 is equal to this Vector2 instance.
/// </summary>
/// <param name="other">The Vector2 to compare this instance to.</param>
/// <returns>True if the other Vector2 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector2 other)
{
return this.X == other.X && this.Y == other.Y;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector2 value1, Vector2 value2)
{
return value1.X * value2.X +
value1.Y * value2.Y;
}
/// <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]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y);
}
/// <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 Vector2 Max(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y);
}
/// <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 Vector2 Abs(Vector2 value)
{
return new Vector2(Math.Abs(value.X), Math.Abs(value.Y));
}
/// <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 Vector2 SquareRoot(Vector2 value)
{
return new Vector2((Single)Math.Sqrt(value.X), (Single)Math.Sqrt(value.Y));
}
#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 Vector2 operator +(Vector2 left, Vector2 right)
{
return new Vector2(left.X + right.X, left.Y + right.Y);
}
/// <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 Vector2 operator -(Vector2 left, Vector2 right)
{
return new Vector2(left.X - right.X, left.Y - right.Y);
}
/// <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 Vector2 operator *(Vector2 left, Vector2 right)
{
return new Vector2(left.X * right.X, left.Y * right.Y);
}
/// <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 Vector2 operator *(Single left, Vector2 right)
{
return new Vector2(left, left) * right;
}
/// <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 Vector2 operator *(Vector2 left, Single right)
{
return left * new Vector2(right, 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 Vector2 operator /(Vector2 left, Vector2 right)
{
return new Vector2(left.X / right.X, left.Y / right.Y);
}
/// <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 Vector2 operator /(Vector2 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector2(
value1.X * invDiv,
value1.Y * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 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>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
}
/// <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 !=(Vector2 left, Vector2 right)
{
return !(left == right);
}
#endregion Public Static Operators
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace AspNetWebApiBlog.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class NormalPriorityProcessor : AbstractPriorityProcessor
{
private const int MaxHighPriorityQueueCache = 29;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
private readonly ConcurrentDictionary<DocumentId, IDisposable> _higherPriorityDocumentsNotProcessed;
private readonly HashSet<ProjectId> _currentSnapshotVersionTrackingSet;
private ProjectId _currentProjectProcessing;
private Solution _processingSolution;
private IDisposable _projectCache;
// whether this processor is running or not
private Task _running;
public NormalPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
IGlobalOperationNotificationService globalOperationNotificationService,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, processor, lazyAnalyzers, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken)
{
_running = SpecializedTasks.EmptyTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace);
_higherPriorityDocumentsNotProcessed = new ConcurrentDictionary<DocumentId, IDisposable>(concurrencyLevel: 2, capacity: 20);
_currentProjectProcessing = default(ProjectId);
_processingSolution = null;
_currentSnapshotVersionTrackingSet = new HashSet<ProjectId>();
Start();
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
this.UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_DocumentWorker_Enqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
CheckHigherPriorityDocument(item);
SolutionCrawlerLogger.LogWorkItemEnqueue(
this.Processor._logAggregator, item.Language, item.DocumentId, item.InvocationReasons, item.IsLowPriority, item.ActiveMember, added);
}
private void CheckHigherPriorityDocument(WorkItem item)
{
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.HighPriority))
{
return;
}
AddHigherPriorityDocument(item.DocumentId);
}
private void AddHigherPriorityDocument(DocumentId id)
{
var cache = GetHighPriorityQueueProjectCache(id);
if (!_higherPriorityDocumentsNotProcessed.TryAdd(id, cache))
{
// we already have the document in the queue.
cache?.Dispose();
}
SolutionCrawlerLogger.LogHigherPriority(this.Processor._logAggregator, id.Id);
}
private IDisposable GetHighPriorityQueueProjectCache(DocumentId id)
{
// NOTE: we have one potential issue where we can cache a lot of stuff in memory
// since we will cache all high prioirty work's projects in memory until they are processed.
//
// To mitigate that, we will turn off cache if we have too many items in high priority queue
// this shouldn't affect active file since we always enable active file cache from background compiler.
return _higherPriorityDocumentsNotProcessed.Count <= MaxHighPriorityQueueCache ? Processor.EnableCaching(id.ProjectId) : null;
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
if (!_workItemQueue.HasAnyWork)
{
DisposeProjectCache();
}
return _workItemQueue.WaitAsync(cancellationToken);
}
public Task Running
{
get
{
return _running;
}
}
public bool HasAnyWork
{
get
{
return _workItemQueue.HasAnyWork;
}
}
protected override async Task ExecuteAsync()
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object>();
try
{
// mark it as running
_running = source.Task;
await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false);
// okay, there must be at least one item in the map
await ResetStatesAsync().ConfigureAwait(false);
if (await TryProcessOneHigherPriorityDocumentAsync().ConfigureAwait(false))
{
// successfully processed a high priority document.
return;
}
// process one of documents remaining
if (!_workItemQueue.TryTakeAnyWork(
_currentProjectProcessing, this.Processor.DependencyGraph, this.Processor.DiagnosticAnalyzerService,
out var workItem, out var documentCancellation))
{
return;
}
// check whether we have been shutdown
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
// check whether we have moved to new project
SetProjectProcessing(workItem.ProjectId);
// process the new document
await ProcessDocumentAsync(this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
protected override Task HigherQueueOperationTask
{
get
{
return this.Processor._highPriorityProcessor.Running;
}
}
protected override bool HigherQueueHasWorkItem
{
get
{
return this.Processor._highPriorityProcessor.HasAnyWork;
}
}
protected override void PauseOnGlobalOperation()
{
base.PauseOnGlobalOperation();
_workItemQueue.RequestCancellationOnRunningTasks();
}
private void SetProjectProcessing(ProjectId currentProject)
{
EnableProjectCacheIfNecessary(currentProject);
_currentProjectProcessing = currentProject;
}
private void EnableProjectCacheIfNecessary(ProjectId currentProject)
{
if (_projectCache != null && currentProject == _currentProjectProcessing)
{
return;
}
DisposeProjectCache();
_projectCache = Processor.EnableCaching(currentProject);
}
private static void DisposeProjectCache(IDisposable projectCache)
{
projectCache?.Dispose();
}
private void DisposeProjectCache()
{
DisposeProjectCache(_projectCache);
_projectCache = null;
}
private IEnumerable<DocumentId> GetPrioritizedPendingDocuments()
{
if (this.Processor._documentTracker != null)
{
// First the active document
var activeDocumentId = this.Processor._documentTracker.GetActiveDocument();
if (activeDocumentId != null && _higherPriorityDocumentsNotProcessed.ContainsKey(activeDocumentId))
{
yield return activeDocumentId;
}
// Now any visible documents
foreach (var visibleDocumentId in this.Processor._documentTracker.GetVisibleDocuments())
{
if (_higherPriorityDocumentsNotProcessed.ContainsKey(visibleDocumentId))
{
yield return visibleDocumentId;
}
}
}
// Any other high priority documents
foreach (var documentId in _higherPriorityDocumentsNotProcessed.Keys)
{
yield return documentId;
}
}
private async Task<bool> TryProcessOneHigherPriorityDocumentAsync()
{
try
{
foreach (var documentId in this.GetPrioritizedPendingDocuments())
{
if (this.CancellationToken.IsCancellationRequested)
{
return true;
}
// this is a best effort algorithm with some shortcomings.
//
// the most obvious issue is if there is a new work item (without a solution change - but very unlikely)
// for a opened document we already processed, the work item will be treated as a regular one rather than higher priority one
// (opened document)
// see whether we have work item for the document
if (!_workItemQueue.TryTake(documentId, out var workItem, out var documentCancellation))
{
RemoveHigherPriorityDocument(documentId);
continue;
}
// okay now we have work to do
await ProcessDocumentAsync(this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
RemoveHigherPriorityDocument(documentId);
return true;
}
return false;
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void RemoveHigherPriorityDocument(DocumentId documentId)
{
// remove opened document processed
if (_higherPriorityDocumentsNotProcessed.TryRemove(documentId, out var projectCache))
{
DisposeProjectCache(projectCache);
}
}
private async Task ProcessDocumentAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
{
var cancellationToken = source.Token;
var document = _processingSolution.GetDocument(documentId);
if (document != null)
{
await TrackSemanticVersionsAsync(document, workItem, cancellationToken).ConfigureAwait(false);
// if we are called because a document is opened, we invalidate the document so that
// it can be re-analyzed. otherwise, since newly opened document has same version as before
// analyzer will simply return same data back
if (workItem.MustRefresh && !workItem.IsRetry)
{
var isOpen = document.IsOpen();
await ProcessOpenDocumentIfNeeded(analyzers, workItem, document, isOpen, cancellationToken).ConfigureAwait(false);
await ProcessCloseDocumentIfNeeded(analyzers, workItem, document, isOpen, cancellationToken).ConfigureAwait(false);
}
// check whether we are having special reanalyze request
await ProcessReanalyzeDocumentAsync(workItem, document, cancellationToken).ConfigureAwait(false);
await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
else
{
SolutionCrawlerLogger.LogProcessDocumentNotExist(this.Processor._logAggregator);
RemoveDocument(documentId);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessDocument(this.Processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(workItem.DocumentId);
}
}
private async Task TrackSemanticVersionsAsync(Document document, WorkItem workItem, CancellationToken cancellationToken)
{
if (workItem.IsRetry ||
workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentAdded) ||
!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
return;
}
var service = document.Project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (service == null)
{
return;
}
// we already reported about this project for same snapshot, don't need to do it again
if (_currentSnapshotVersionTrackingSet.Contains(document.Project.Id))
{
return;
}
await service.RecordSemanticVersionsAsync(document.Project, cancellationToken).ConfigureAwait(false);
// mark this project as already processed.
_currentSnapshotVersionTrackingSet.Add(document.Project.Id);
}
private async Task ProcessOpenDocumentIfNeeded(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, bool isOpen, CancellationToken cancellationToken)
{
if (!isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened))
{
return;
}
SolutionCrawlerLogger.LogProcessOpenDocument(this.Processor._logAggregator, document.Id.Id);
await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.DocumentOpenAsync(d, c), cancellationToken).ConfigureAwait(false);
}
private async Task ProcessCloseDocumentIfNeeded(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, bool isOpen, CancellationToken cancellationToken)
{
if (isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed))
{
return;
}
SolutionCrawlerLogger.LogProcessCloseDocument(this.Processor._logAggregator, document.Id.Id);
await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.DocumentCloseAsync(d, c), cancellationToken).ConfigureAwait(false);
}
private async Task ProcessReanalyzeDocumentAsync(WorkItem workItem, Document document, CancellationToken cancellationToken)
{
try
{
#if DEBUG
Contract.Requires(!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze) || workItem.Analyzers.Count > 0);
#endif
// no-reanalyze request or we already have a request to re-analyze every thing
if (workItem.MustRefresh || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze))
{
return;
}
// First reset the document state in analyzers.
var reanalyzers = workItem.Analyzers.ToImmutableArray();
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.DocumentResetAsync(d, c), cancellationToken).ConfigureAwait(false);
// no request to re-run syntax change analysis. run it here
var reasons = workItem.InvocationReasons;
if (!reasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.AnalyzeSyntaxAsync(d, reasons, c), cancellationToken).ConfigureAwait(false);
}
// no request to re-run semantic change analysis. run it here
if (!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, reasons, c), cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void RemoveDocument(DocumentId documentId)
{
RemoveDocument(this.Analyzers, documentId);
}
private static void RemoveDocument(IEnumerable<IIncrementalAnalyzer> analyzers, DocumentId documentId)
{
foreach (var analyzer in analyzers)
{
analyzer.RemoveDocument(documentId);
}
}
private void ResetLogAggregatorIfNeeded(Solution currentSolution)
{
if (currentSolution == null || _processingSolution == null ||
currentSolution.Id == _processingSolution.Id)
{
return;
}
SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(
this.Processor._registration.CorrelationId, _processingSolution, this.Processor._logAggregator, this.Analyzers);
this.Processor.ResetLogAggregator();
}
private async Task ResetStatesAsync()
{
try
{
var currentSolution = this.Processor.CurrentSolution;
if (currentSolution != _processingSolution)
{
ResetLogAggregatorIfNeeded(currentSolution);
// clear version tracking set we already reported.
_currentSnapshotVersionTrackingSet.Clear();
_processingSolution = currentSolution;
await RunAnalyzersAsync(this.Analyzers, currentSolution, (a, s, c) => a.NewSolutionSnapshotAsync(s, c), this.CancellationToken).ConfigureAwait(false);
foreach (var id in this.Processor.GetOpenDocumentIds())
{
AddHigherPriorityDocument(id);
}
SolutionCrawlerLogger.LogResetStates(this.Processor._logAggregator);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override void Shutdown()
{
base.Shutdown();
SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(this.Processor._registration.CorrelationId, _processingSolution, this.Processor._logAggregator, this.Analyzers);
_workItemQueue.Dispose();
if (_projectCache != null)
{
_projectCache.Dispose();
_projectCache = null;
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items)
{
CancellationTokenSource source = new CancellationTokenSource();
_processingSolution = this.Processor.CurrentSolution;
foreach (var item in items)
{
ProcessDocumentAsync(analyzers, item, source).Wait();
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
// this shouldn't happen. would like to get some diagnostic
while (_workItemQueue.HasAnyWork)
{
Environment.FailFast("How?");
}
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing.Drawing2D
{
public sealed class GraphicsPathIterator : MarshalByRefObject, IDisposable
{
public GraphicsPathIterator(GraphicsPath path)
{
IntPtr nativeIter = IntPtr.Zero;
int status = Gdip.GdipCreatePathIter(out nativeIter, new HandleRef(path, (path == null) ? IntPtr.Zero : path._nativePath));
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
this.nativeIter = nativeIter;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (nativeIter != IntPtr.Zero)
{
try
{
#if DEBUG
int status = !Gdip.Initialized ? Gdip.Ok :
#endif
Gdip.GdipDeletePathIter(new HandleRef(this, nativeIter));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex)
{
if (ClientUtils.IsSecurityOrCriticalException(ex))
{
throw;
}
Debug.Fail("Exception thrown during Dispose: " + ex.ToString());
}
finally
{
nativeIter = IntPtr.Zero;
}
}
}
~GraphicsPathIterator() => Dispose(false);
public int NextSubpath(out int startIndex, out int endIndex, out bool isClosed)
{
int status = Gdip.GdipPathIterNextSubpath(new HandleRef(this, nativeIter), out int resultCount,
out int tempStart, out int tempEnd, out isClosed);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
else
{
startIndex = tempStart;
endIndex = tempEnd;
}
return resultCount;
}
public int NextSubpath(GraphicsPath path, out bool isClosed)
{
int status = Gdip.GdipPathIterNextSubpathPath(new HandleRef(this, nativeIter), out int resultCount,
new HandleRef(path, (path == null) ? IntPtr.Zero : path._nativePath), out isClosed);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
return resultCount;
}
public int NextPathType(out byte pathType, out int startIndex, out int endIndex)
{
int status = Gdip.GdipPathIterNextPathType(new HandleRef(this, nativeIter), out int resultCount,
out pathType, out startIndex, out endIndex);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
return resultCount;
}
public int NextMarker(out int startIndex, out int endIndex)
{
int status = Gdip.GdipPathIterNextMarker(new HandleRef(this, nativeIter), out int resultCount,
out startIndex, out endIndex);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
return resultCount;
}
public int NextMarker(GraphicsPath path)
{
int status = Gdip.GdipPathIterNextMarkerPath(new HandleRef(this, nativeIter), out int resultCount,
new HandleRef(path, (path == null) ? IntPtr.Zero : path._nativePath));
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
return resultCount;
}
public int Count
{
get
{
int status = Gdip.GdipPathIterGetCount(new HandleRef(this, nativeIter), out int resultCount);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
return resultCount;
}
}
public int SubpathCount
{
get
{
int status = Gdip.GdipPathIterGetSubpathCount(new HandleRef(this, nativeIter), out int resultCount);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
return resultCount;
}
}
public bool HasCurve()
{
int status = Gdip.GdipPathIterHasCurve(new HandleRef(this, nativeIter), out bool hasCurve);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
return hasCurve;
}
public void Rewind()
{
int status = Gdip.GdipPathIterRewind(new HandleRef(this, nativeIter));
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public unsafe int Enumerate(ref PointF[] points, ref byte[] types)
{
if (points.Length != types.Length)
throw Gdip.StatusException(Gdip.InvalidParameter);
if (points.Length == 0)
return 0;
fixed (PointF* p = points)
fixed (byte* t = types)
{
int status = Gdip.GdipPathIterEnumerate(
new HandleRef(this, nativeIter),
out int resultCount,
p,
t,
points.Length);
if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
return resultCount;
}
}
public unsafe int CopyData(ref PointF[] points, ref byte[] types, int startIndex, int endIndex)
{
if ((points.Length != types.Length) || (endIndex - startIndex + 1 > points.Length))
throw Gdip.StatusException(Gdip.InvalidParameter);
fixed (PointF* p = points)
fixed (byte* t = types)
{
int status = Gdip.GdipPathIterCopyData(
new HandleRef(this, nativeIter),
out int resultCount,
p,
t,
startIndex,
endIndex);
if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
return resultCount;
}
}
// handle to native path iterator object
internal IntPtr nativeIter;
}
}
| |
namespace RockBands.Data.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using RockBands.Data.Contracts;
using RockBands.Models;
internal sealed class Configuration : DbMigrationsConfiguration<RockBandsDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
this.ContextKey = "RockBands.Data.RockBandsDbContext";
}
protected override void Seed(RockBandsDbContext context)
{
this.SeedBands(context);
this.SeedAlbums(context);
this.SeedSongs(context);
}
private void SeedBands(IRockBandsDbContext context)
{
if (context.Bands.Any())
{
return;
}
var acdc = new Band()
{
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/ac-dc.jpg",
Name = "AC/DC",
Nationality = "Australia",
OfficialSite = "www.acdc.com",
ReleasedAt = new DateTime(1973, 1, 1),
Src = "ac-dc",
Rating = 4
};
acdc.Artists = new List<Artist>()
{
new Artist()
{
Name = "Brian Johnson"
},
new Artist()
{
Name = "Angus Young"
},
new Artist()
{
Name = "Cliff Williams"
},
new Artist()
{
Name = "Phil Rudd"
},
};
var beatles = new Band()
{
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/the-beatles.jpg",
Name = "The Beatles",
Nationality = "England",
OfficialSite = "www.thebeatles.com",
ReleasedAt = new DateTime(1960, 1, 1),
Src = "beatles",
Rating = 10
};
beatles.Artists = new List<Artist>()
{
new Artist()
{
Name = "John Lennon"
},
new Artist()
{
Name = "Paul McCartney"
},
new Artist()
{
Name = "George Harrison"
},
new Artist()
{
Name = "Ringo Starr"
},
};
var nazareth = new Band()
{
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/nazareth.jpg",
Name = "Nazareth",
Nationality = "Scotland",
OfficialSite = "www.nazarethdirect.co.uk",
ReleasedAt = new DateTime(1968, 1, 1),
Src = "nazareth",
Rating = 15
};
nazareth.Artists = new List<Artist>()
{
new Artist()
{
Name = "Dan McCafferty"
},
new Artist()
{
Name = "Darrell Sweet"
},
new Artist()
{
Name = "Manny Charlton"
},
new Artist()
{
Name = "Zal Cleminson"
},
new Artist()
{
Name = "Billy Rankin"
},
new Artist()
{
Name = "John Locke"
},
new Artist()
{
Name = "Ronnie Leahey"
},
};
context.Bands.Add(acdc);
context.Bands.Add(beatles);
context.Bands.Add(nazareth);
context.SaveChanges();
}
private void SeedAlbums(IRockBandsDbContext context)
{
if (context.Albums.Any())
{
return;
}
var razamanaz = new Album()
{
Name = "Razamanaz",
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/razamanaz.jpg",
Rating = 10,
ReleasedAt = new DateTime(1973, 1, 1),
Src = "razamanaz",
BandId = 3
};
var pastMasters = new Album()
{
Name = "Past Masters",
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/past-masters.jpg",
Rating = 8,
ReleasedAt = new DateTime(2009, 1, 1),
Src = "past-masters",
BandId = 2
};
var redAlbum = new Album()
{
Name = "Red Album",
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/red-album.jpg",
Rating = 6,
ReleasedAt = new DateTime(1973, 1, 1),
Src = "red-album",
BandId = 2
};
context.Albums.Add(razamanaz);
context.Albums.Add(pastMasters);
context.Albums.Add(redAlbum);
context.SaveChanges();
}
private void SeedSongs(IRockBandsDbContext context)
{
if (context.Songs.Any())
{
return;
}
var razamanaz = new Song()
{
Name = "Razamanaz",
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/razamanaz.jpg",
Rating = 5,
Src = "razamanaz-song",
Link = "https://youtube.com/watch?v=INR6AB6bXeQ",
AlbumId = 1
};
var nightWoman = new Song()
{
Name = "Night Woman",
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/night-woman.jpg",
Rating = 3,
Src = "night-woman",
Link = "https://youtube.com/watch?v=QVv3m1phqkQ",
AlbumId = 1
};
var soldMySoul = new Song()
{
Name = "Sold My Soul",
ImageUrl = "http://nikolov.cloudvps.bg/rockbands/images/woke-up-this-morning.jpg",
Rating = 2,
Src = "sold-my-soul",
Link = "http://youtube.com/watch?v=fAkN72B9WkY",
AlbumId = 1
};
context.Songs.Add(razamanaz);
context.Songs.Add(nightWoman);
context.Songs.Add(soldMySoul);
context.SaveChanges();
}
}
}
| |
// 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.IO;
using osu.Game.Online.API;
using osu.Game.Overlays;
using osu.Game.Rulesets;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Edit;
using osu.Game.Screens.OnlinePlay.Multiplayer;
using osu.Game.Screens.OnlinePlay.Playlists;
using osu.Game.Screens.Select;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Menu
{
public class MainMenu : OsuScreen, IHandlePresentBeatmap
{
public const float FADE_IN_DURATION = 300;
public const float FADE_OUT_DURATION = 400;
public override bool HideOverlaysOnEnter => buttons == null || buttons.State == ButtonSystemState.Initial;
public override bool AllowBackButton => false;
public override bool AllowExternalScreenChange => true;
public override bool AllowRateAdjustments => false;
private Screen songSelect;
private MenuSideFlashes sideFlashes;
private ButtonSystem buttons;
[Resolved]
private GameHost host { get; set; }
[Resolved]
private MusicController musicController { get; set; }
[Resolved(canBeNull: true)]
private LoginOverlay login { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
[Resolved(canBeNull: true)]
private DialogOverlay dialogOverlay { get; set; }
private BackgroundScreenDefault background;
protected override BackgroundScreen CreateBackground() => background;
private Bindable<float> holdDelay;
private Bindable<bool> loginDisplayed;
private ExitConfirmOverlay exitConfirmOverlay;
private ParallaxContainer buttonsContainer;
private SongTicker songTicker;
[BackgroundDependencyLoader(true)]
private void load(BeatmapListingOverlay beatmapListing, SettingsOverlay settings, RankingsOverlay rankings, OsuConfigManager config, SessionStatics statics)
{
holdDelay = config.GetBindable<float>(OsuSetting.UIHoldActivationDelay);
loginDisplayed = statics.GetBindable<bool>(Static.LoginOverlayDisplayed);
if (host.CanExit)
{
AddInternal(exitConfirmOverlay = new ExitConfirmOverlay
{
Action = () =>
{
if (holdDelay.Value > 0)
confirmAndExit();
else
this.Exit();
}
});
}
AddRangeInternal(new[]
{
buttonsContainer = new ParallaxContainer
{
ParallaxAmount = 0.01f,
Children = new Drawable[]
{
buttons = new ButtonSystem
{
OnEdit = delegate
{
Beatmap.SetDefault();
this.Push(new Editor());
},
OnSolo = loadSoloSongSelect,
OnMultiplayer = () => this.Push(new Multiplayer()),
OnPlaylists = () => this.Push(new Playlists()),
OnExit = confirmAndExit,
}
}
},
sideFlashes = new MenuSideFlashes(),
songTicker = new SongTicker
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Margin = new MarginPadding { Right = 15, Top = 5 }
},
exitConfirmOverlay?.CreateProxy() ?? Empty()
});
buttons.StateChanged += state =>
{
switch (state)
{
case ButtonSystemState.Initial:
case ButtonSystemState.Exit:
ApplyToBackground(b => b.FadeColour(Color4.White, 500, Easing.OutSine));
break;
default:
ApplyToBackground(b => b.FadeColour(OsuColour.Gray(0.8f), 500, Easing.OutSine));
break;
}
};
buttons.OnSettings = () => settings?.ToggleVisibility();
buttons.OnBeatmapListing = () => beatmapListing?.ToggleVisibility();
LoadComponentAsync(background = new BackgroundScreenDefault());
preloadSongSelect();
}
[Resolved(canBeNull: true)]
private OsuGame game { get; set; }
private void confirmAndExit()
{
if (exitConfirmed) return;
exitConfirmed = true;
game?.PerformFromScreen(menu => menu.Exit());
}
private void preloadSongSelect()
{
if (songSelect == null)
LoadComponentAsync(songSelect = new PlaySongSelect());
}
private void loadSoloSongSelect() => this.Push(consumeSongSelect());
private Screen consumeSongSelect()
{
var s = songSelect;
songSelect = null;
return s;
}
[Resolved]
private Storage storage { get; set; }
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
buttons.FadeInFromZero(500);
if (last is IntroScreen && musicController.TrackLoaded)
{
var track = musicController.CurrentTrack;
// presume the track is the current beatmap's track. not sure how correct this assumption is but it has worked until now.
if (!track.IsRunning)
{
Beatmap.Value.PrepareTrackForPreviewLooping();
track.Restart();
}
}
if (storage is OsuStorage osuStorage && osuStorage.Error != OsuStorageError.None)
dialogOverlay?.Push(new StorageErrorDialog(osuStorage, osuStorage.Error));
}
private bool exitConfirmed;
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
buttons.SetOsuLogo(logo);
logo.FadeColour(Color4.White, 100, Easing.OutQuint);
logo.FadeIn(100, Easing.OutQuint);
if (resuming)
{
buttons.State = ButtonSystemState.TopLevel;
this.FadeIn(FADE_IN_DURATION, Easing.OutQuint);
buttonsContainer.MoveTo(new Vector2(0, 0), FADE_IN_DURATION, Easing.OutQuint);
sideFlashes.Delay(FADE_IN_DURATION).FadeIn(64, Easing.InQuint);
}
else if (!api.IsLoggedIn)
{
logo.Action += displayLogin;
}
bool displayLogin()
{
if (!loginDisplayed.Value)
{
Scheduler.AddDelayed(() => login?.Show(), 500);
loginDisplayed.Value = true;
}
return true;
}
}
protected override void LogoSuspending(OsuLogo logo)
{
var seq = logo.FadeOut(300, Easing.InSine)
.ScaleTo(0.2f, 300, Easing.InSine);
seq.OnComplete(_ => buttons.SetOsuLogo(null));
seq.OnAbort(_ => buttons.SetOsuLogo(null));
}
public override void OnSuspending(IScreen next)
{
base.OnSuspending(next);
buttons.State = ButtonSystemState.EnteringMode;
this.FadeOut(FADE_OUT_DURATION, Easing.InSine);
buttonsContainer.MoveTo(new Vector2(-800, 0), FADE_OUT_DURATION, Easing.InSine);
sideFlashes.FadeOut(64, Easing.OutQuint);
}
public override void OnResuming(IScreen last)
{
base.OnResuming(last);
ApplyToBackground(b => (b as BackgroundScreenDefault)?.Next());
// we may have consumed our preloaded instance, so let's make another.
preloadSongSelect();
musicController.EnsurePlayingSomething();
}
public override bool OnExiting(IScreen next)
{
if (!exitConfirmed && dialogOverlay != null)
{
if (dialogOverlay.CurrentDialog is ConfirmExitDialog exitDialog)
exitDialog.PerformOkAction();
else
dialogOverlay.Push(new ConfirmExitDialog(confirmAndExit, () => exitConfirmOverlay.Abort()));
return true;
}
buttons.State = ButtonSystemState.Exit;
OverlayActivationMode.Value = OverlayActivation.Disabled;
songTicker.Hide();
this.FadeOut(3000);
return base.OnExiting(next);
}
public void PresentBeatmap(WorkingBeatmap beatmap, RulesetInfo ruleset)
{
Beatmap.Value = beatmap;
Ruleset.Value = ruleset;
Schedule(loadSoloSongSelect);
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using ESRI.ArcGIS.Analyst3D;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using System.Runtime.InteropServices;
namespace sceneTools
{
[ClassInterface(ClassInterfaceType.None)]
[Guid("9A3B648E-4543-438c-84C1-41CC6AD29A81")]
public sealed class Navigate : BaseTool
{
[DllImport("user32")] public static extern int SetCapture(int hwnd);
[DllImport("user32")] public static extern int SetCursor(int hCursor);
[DllImport("user32")] public static extern int GetClientRect(int hwnd, ref Rectangle lpRect);
[DllImport("user32")] public static extern int GetCapture(int fuFlags);
[DllImport("user32")] public static extern int ReleaseCapture(int hwnd);
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Unregister(regKey);
}
#endregion
#endregion
private ISceneHookHelper m_pSceneHookHelper;
private bool m_bInUse;
private bool m_bGesture;
private bool bCancel = false;
private long m_lMouseX, m_lMouseY;
private bool m_bSpinning;
private double m_dSpinStep;
private System.Windows.Forms.Cursor m_pCursorNav;
private System.Windows.Forms.Cursor m_pCursorPan;
private System.Windows.Forms.Cursor m_pCursorZoom;
private System.Windows.Forms.Cursor m_pCursorGest;
public Navigate()
{
base.m_category = "Sample_SceneControl(C#)";
base.m_caption = "Navigate";
base.m_toolTip = "Navigate";
base.m_name = "Sample_SceneControl(C#)/Navigate";
base.m_message = "Navigates the scene";
//Load resources
string[] res = GetType().Assembly.GetManifestResourceNames();
if(res.GetLength(0) > 0)
{
base.m_bitmap = new System.Drawing.Bitmap(GetType().Assembly.GetManifestResourceStream("sceneTools.Navigation.bmp"));
}
m_pCursorNav = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream("sceneTools.navigation.cur"));
m_pCursorPan = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream("sceneTools.movehand.cur"));
m_pCursorZoom = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream("sceneTools.ZOOMINOUT.CUR"));
m_pCursorGest = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream("sceneTools.gesture.cur"));
m_pSceneHookHelper = new SceneHookHelperClass ();
}
public override void OnCreate(object hook)
{
m_pSceneHookHelper.Hook = hook;
if(m_pSceneHookHelper != null)
{
m_bGesture = m_pSceneHookHelper.ActiveViewer.GestureEnabled;
m_bSpinning = false;
}
}
public override bool Enabled
{
get
{
//Disable if orthographic (2D) view
if(m_pSceneHookHelper.Hook == null || m_pSceneHookHelper.Scene == null)
return false;
else
{
ICamera pCamera = (ICamera) m_pSceneHookHelper.Camera;
if(pCamera.ProjectionType == esri3DProjectionType.esriOrthoProjection)
return false;
else
return true;
}
}
}
public override int Cursor
{
get
{
if(m_bGesture == true)
return m_pCursorGest.Handle.ToInt32();
else
return m_pCursorNav.Handle.ToInt32();
}
}
public override bool Deactivate()
{
return true;
}
public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
if (Button == 3)
bCancel = true;
else
{
m_bInUse = true;
SetCapture(m_pSceneHookHelper.ActiveViewer.hWnd);
m_lMouseX = X;
m_lMouseY = Y;
}
}
public override void OnMouseMove(int Button, int Shift, int X, int Y)
{
if(m_bInUse == false) return;
if(X - m_lMouseX == 0 && Y - m_lMouseY == 0) return;
long dx, dy;
dx = X - m_lMouseX;
dy = Y - m_lMouseY;
//If right mouse clicked
if (Button == 2)
{
//Set the zoom cursor
SetCursor(m_pCursorZoom.Handle.ToInt32());
if (dy < 0)
m_pSceneHookHelper.Camera.Zoom(1.1);
else if (dy > 0)
m_pSceneHookHelper.Camera.Zoom(0.9);
}
//If two mouse buttons clicked
if(Button == 3)
{
//Set the pan cursor
SetCursor(m_pCursorPan.Handle.ToInt32());
//Create a point with previous mouse coordinates
IPoint pStartPoint;
pStartPoint = new PointClass();
pStartPoint.PutCoords((double) m_lMouseX, (double) m_lMouseY);
//Create point with a new mouse coordinates
IPoint pEndPoint;
pEndPoint = new PointClass();
pEndPoint.PutCoords((double) X, (double) Y);
//Pan camera
m_pSceneHookHelper.Camera.Pan(pStartPoint, pEndPoint);
}
//If left mouse clicked
if(Button == 1)
{
//If scene viewer gesturing is disabled move the camera observer
if(m_bGesture == false)
m_pSceneHookHelper.Camera.PolarUpdate(1, dx, dy, true);
else
{
//if camera already spinning
if(m_bSpinning == true)
{
//Move the camera observer
m_pSceneHookHelper.Camera.PolarUpdate(1, dx, dy, true);
}
else
{
//Windows API call to get windows client coordinates
Rectangle rect;
rect = new Rectangle();
GetClientRect(m_pSceneHookHelper.ActiveViewer.hWnd, ref rect);
//Recalculate the spin step
if(dx < 0)
m_dSpinStep = (180.0 / rect.Right - rect.Left ) * (dx - m_pSceneHookHelper.ActiveViewer.GestureSensitivity);
else
m_dSpinStep = (180.0 / rect.Right - rect.Left) * (dx + m_pSceneHookHelper.ActiveViewer.GestureSensitivity);
//Start spinning
StartSpin();
}
}
}
//Set Mouse coordinates for the next
//OnMouse Event
m_lMouseX = X;
m_lMouseY = Y;
//Redraw the scene viewer
m_pSceneHookHelper.ActiveViewer.Redraw(true);
}
public override void OnMouseUp(int Button, int Shift, int X, int Y)
{
//Set the navigation cursor
if(m_bGesture == true)
SetCursor(m_pCursorGest.Handle.ToInt32());
else
SetCursor(m_pCursorNav.Handle.ToInt32());
if(GetCapture(m_pSceneHookHelper.ActiveViewer.hWnd) != 0)
ReleaseCapture(m_pSceneHookHelper.ActiveViewer.hWnd);
}
public void StartSpin()
{
m_bSpinning = true;
//Get IMessageDispatcher interface
IMessageDispatcher pMessageDispatcher;
pMessageDispatcher = new MessageDispatcherClass();
//Set the ESC key to be seen as a cancel action
pMessageDispatcher.CancelOnClick = false;
pMessageDispatcher.CancelOnEscPress = true;
do
{
//Move the camera observer
m_pSceneHookHelper.Camera.PolarUpdate(1, m_dSpinStep, 0, true);
//Redraw the scene viewer
m_pSceneHookHelper.ActiveViewer.Redraw(true);
//Dispatch any waiting messages: OnMouseMove/ OnMouseDown/ OnKeyUp/ OnKeyDown events
object b_oCancel;
pMessageDispatcher.Dispatch(m_pSceneHookHelper.ActiveViewer.hWnd, false, out b_oCancel);
if(bCancel == true)
m_bSpinning = false;
}
while(bCancel == false);
bCancel = false;
}
public override void OnKeyDown(int keyCode, int Shift)
{
if (keyCode == 27)
{
bCancel = true;
SetCursor(m_pCursorNav.Handle.ToInt32());
}
switch(Shift)
{
case 1: //Shift key
//Set pan cursor
SetCursor(m_pCursorPan.Handle.ToInt32());
break;
case 2: //Control key
//Set ZoomIn/Out cursor
SetCursor(m_pCursorZoom.Handle.ToInt32());
break;
case 3: //shift + control keys
//Set scene viewer gesture enabled property
if(m_bSpinning == false)
{
if(m_bGesture == true)
{
m_pSceneHookHelper.ActiveViewer.GestureEnabled = false;
m_bGesture = false;
SetCursor(m_pCursorNav.Handle.ToInt32());
}
else
{
m_pSceneHookHelper.ActiveViewer.GestureEnabled = true;
m_bGesture = true;
SetCursor(m_pCursorGest.Handle.ToInt32());
}
}
break;
default:
return;
}
}
public override void OnKeyUp(int keyCode, int Shift)
{
if(Shift == 1) //Shift key
{
//Pan the camera
switch(keyCode)
{
case 38: //Up key
m_pSceneHookHelper.Camera.Move(esriCameraMovementType.esriCameraMoveDown, 0.01);
break;
case 40: //Down key
m_pSceneHookHelper.Camera.Move(esriCameraMovementType.esriCameraMoveUp, 0.01);
break;
case 37: //Left key
m_pSceneHookHelper.Camera.Move(esriCameraMovementType.esriCameraMoveRight, 0.01);
break;
case 39: // Right key
m_pSceneHookHelper.Camera.Move(esriCameraMovementType.esriCameraMoveLeft, 0.01);
break;
default:
return;
}
}
else if(Shift == 2) //Control key
{
//Move camera in/out or turn camera around the observer
switch(keyCode)
{
case 38:
m_pSceneHookHelper.Camera.Move(esriCameraMovementType.esriCameraMoveAway, 0.01);
break;
case 40:
m_pSceneHookHelper.Camera.Move(esriCameraMovementType.esriCameraMoveToward, 0.01);
break;
case 37:
m_pSceneHookHelper.Camera.HTurnAround(-1);
break;
case 39:
m_pSceneHookHelper.Camera.HTurnAround(1);
break;
default:
return;
}
}
else
{
double d = 5, dAltitude = 2, dAzimuth = 2;
//Move the camera observer by the given polar
//increments or increase/decrease the spin speed
switch(keyCode)
{
case 38:
m_pSceneHookHelper.Camera.PolarUpdate(1, 0, -dAltitude * d, true);
break;
case 40:
m_pSceneHookHelper.Camera.PolarUpdate(1, 0, dAltitude * d, true);
break;
case 37:
m_pSceneHookHelper.Camera.PolarUpdate(1, dAzimuth * d, 0, true);
break;
case 39:
m_pSceneHookHelper.Camera.PolarUpdate(1, -dAzimuth * d, 0, true);
break;
case 33: //Page Up
m_dSpinStep = m_dSpinStep * 1.1;
break;
case 34: //Page Down
m_dSpinStep = m_dSpinStep / 1.1;
break;
default:
return;
}
}
//Set the navigation cursor
if(m_bGesture == true)
SetCursor(m_pCursorGest.Handle.ToInt32());
else
SetCursor(m_pCursorNav.Handle.ToInt32());
//Redraw the scene viewer
m_pSceneHookHelper.ActiveViewer.Redraw(true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#pragma warning disable 169
// There is no defined ordering between fields in multiple declarations of partial class or struct
#pragma warning disable 282
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using Internal.NativeFormat;
namespace Internal.Metadata.NativeFormat
{
// This Enum matches CorMethodSemanticsAttr defined in CorHdr.h
[Flags]
public enum MethodSemanticsAttributes
{
Setter = 0x0001,
Getter = 0x0002,
Other = 0x0004,
AddOn = 0x0008,
RemoveOn = 0x0010,
Fire = 0x0020,
}
// This Enum matches CorPInvokeMap defined in CorHdr.h
[Flags]
public enum PInvokeAttributes
{
NoMangle = 0x0001,
CharSetMask = 0x0006,
CharSetNotSpec = 0x0000,
CharSetAnsi = 0x0002,
CharSetUnicode = 0x0004,
CharSetAuto = 0x0006,
BestFitUseAssem = 0x0000,
BestFitEnabled = 0x0010,
BestFitDisabled = 0x0020,
BestFitMask = 0x0030,
ThrowOnUnmappableCharUseAssem = 0x0000,
ThrowOnUnmappableCharEnabled = 0x1000,
ThrowOnUnmappableCharDisabled = 0x2000,
ThrowOnUnmappableCharMask = 0x3000,
SupportsLastError = 0x0040,
CallConvMask = 0x0700,
CallConvWinapi = 0x0100,
CallConvCdecl = 0x0200,
CallConvStdcall = 0x0300,
CallConvThiscall = 0x0400,
CallConvFastcall = 0x0500,
MaxValue = 0xFFFF,
}
public partial struct Handle : IHandle
{
public override bool Equals(Object obj)
{
if (obj is Handle)
return _value == ((Handle)obj)._value;
else
return false;
}
public bool Equals(Handle handle)
{
return _value == handle._value;
}
public override int GetHashCode()
{
return (int)_value;
}
internal Handle(int value)
{
_value = value;
}
internal void Validate(params HandleType[] permittedTypes)
{
var myHandleType = (HandleType)(_value >> 24);
foreach (var hType in permittedTypes)
{
if (myHandleType == hType)
{
return;
}
}
if (myHandleType == HandleType.Null)
{
return;
}
throw new ArgumentException("Invalid handle type");
}
public Handle(HandleType type, int offset)
{
_value = (int)type << 24 | (int)offset;
}
public HandleType HandleType
{
get
{
return (HandleType)(_value >> 24);
}
}
internal int Offset
{
get
{
return (this._value & 0x00FFFFFF);
}
}
public bool IsNull(MetadataReader reader)
{
return reader.IsNull(this);
}
internal int _value;
public override string ToString()
{
return String.Format("{1} : {0,8:X8}", _value, Enum.GetName(typeof(HandleType), this.HandleType));
}
}
public static class NativeFormatReaderExtensions
{
public static string GetString(this MetadataReader reader, ConstantStringValueHandle handle)
{
return reader.GetConstantStringValue(handle).Value;
}
}
/// <summary>
/// ConstantReferenceValue can only be used to encapsulate null reference values,
/// and therefore does not actually store the value.
/// </summary>
public partial struct ConstantReferenceValue
{
/// Always returns null value.
public Object Value
{ get { return null; } }
} // ConstantReferenceValue
public partial struct ConstantStringValueHandle
{
public bool StringEquals(string value, MetadataReader reader)
{
return reader.StringEquals(this, value);
}
}
public sealed partial class MetadataReader : IMetadataReader
{
private MetadataHeader _header;
internal NativeReader _streamReader;
// Creates a metadata reader on a memory-mapped file block
public unsafe MetadataReader(IntPtr pBuffer, int cbBuffer)
{
_streamReader = new NativeReader((byte*)pBuffer, (uint)cbBuffer);
_header = new MetadataHeader();
_header.Decode(_streamReader);
}
/// <summary>
/// Used as the root entrypoint for metadata, this is where all top-down
/// structural walks of metadata must start.
/// </summary>
public IEnumerable<ScopeDefinitionHandle> ScopeDefinitions
{
get
{
return _header.ScopeDefinitions;
}
}
/// <summary>
/// Returns a Handle value representing the null value. Can be used
/// to test handle values of all types for null.
/// </summary>
public Handle NullHandle
{
get
{
return new Handle() { _value = ((int)HandleType.Null) << 24 };
}
}
/// <summary>
/// Returns true if handle is null.
/// </summary>
public bool IsNull(Handle handle)
{
return handle._value == NullHandle._value;
}
/// <summary>
/// Idempotent - simply returns the provided handle value. Exists for
/// consistency so that generated code does not need to handle this
/// as a special case.
/// </summary>
public Handle ToHandle(Handle handle)
{
return handle;
}
internal bool StringEquals(ConstantStringValueHandle handle, string value)
{
return _streamReader.StringEquals((uint)handle.Offset, value);
}
}
internal partial class MetadataHeader
{
/// <todo>
/// Signature should be updated every time the metadata schema changes.
/// </todo>
public const uint Signature = 0xDEADDFFD;
/// <summary>
/// The set of ScopeDefinitions contained within this metadata resource.
/// </summary>
public ScopeDefinitionHandle[] ScopeDefinitions;
public void Decode(NativeReader reader)
{
if (reader.ReadUInt32(0) != Signature)
reader.ThrowBadImageFormatException();
reader.Read(4, out ScopeDefinitions);
}
}
}
| |
//
// 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.
//
namespace DiscUtils.Ntfs
{
using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
internal class NtfsFormatter
{
private int _clusterSize;
private int _mftRecordSize;
private int _indexBufferSize;
private long _bitmapCluster;
private long _mftMirrorCluster;
private long _mftCluster;
private NtfsContext _context;
public string Label { get; set; }
public Geometry DiskGeometry { get; set; }
public long FirstSector { get; set; }
public long SectorCount { get; set; }
public byte[] BootCode { get; set; }
public SecurityIdentifier ComputerAccount { get; set; }
public NtfsFileSystem Format(Stream stream)
{
_context = new NtfsContext();
_context.Options = new NtfsOptions();
_context.RawStream = stream;
_context.AttributeDefinitions = new AttributeDefinitions();
string localAdminString = (ComputerAccount == null)
? "LA"
: new SecurityIdentifier(WellKnownSidType.AccountAdministratorSid, ComputerAccount).ToString();
using (new NtfsTransaction())
{
_clusterSize = 4096;
_mftRecordSize = 1024;
_indexBufferSize = 4096;
long totalClusters = ((SectorCount - 1) * Sizes.Sector) / _clusterSize;
// Allocate a minimum of 8KB for the boot loader, but allow for more
int numBootClusters = Utilities.Ceil(Math.Max((int)(8 * Sizes.OneKiB), BootCode == null ? 0 : BootCode.Length), _clusterSize);
// Place MFT mirror in the middle of the volume
_mftMirrorCluster = totalClusters / 2;
uint numMftMirrorClusters = 1;
// The bitmap is also near the middle
_bitmapCluster = _mftMirrorCluster + 13;
int numBitmapClusters = (int)Utilities.Ceil(totalClusters / 8, _clusterSize);
// The MFT bitmap goes 'near' the start - approx 10% in - but ensure we avoid the bootloader
long mftBitmapCluster = Math.Max(3 + (totalClusters / 10), numBootClusters);
int numMftBitmapClusters = 1;
// The MFT follows it's bitmap
_mftCluster = mftBitmapCluster + numMftBitmapClusters;
int numMftClusters = 8;
if (_mftCluster + numMftClusters > _mftMirrorCluster
|| _bitmapCluster + numBitmapClusters >= totalClusters)
{
throw new IOException("Unable to determine initial layout of NTFS metadata - disk may be too small");
}
CreateBiosParameterBlock(stream, numBootClusters * _clusterSize);
_context.Mft = new MasterFileTable(_context);
File mftFile = _context.Mft.InitializeNew(_context, mftBitmapCluster, (ulong)numMftBitmapClusters, (long)_mftCluster, (ulong)numMftClusters);
File bitmapFile = CreateFixedSystemFile(MasterFileTable.BitmapIndex, _bitmapCluster, (ulong)numBitmapClusters, true);
_context.ClusterBitmap = new ClusterBitmap(bitmapFile);
_context.ClusterBitmap.MarkAllocated(0, numBootClusters);
_context.ClusterBitmap.MarkAllocated(_bitmapCluster, numBitmapClusters);
_context.ClusterBitmap.MarkAllocated(mftBitmapCluster, numMftBitmapClusters);
_context.ClusterBitmap.MarkAllocated(_mftCluster, numMftClusters);
_context.ClusterBitmap.SetTotalClusters(totalClusters);
bitmapFile.UpdateRecordInMft();
File mftMirrorFile = CreateFixedSystemFile(MasterFileTable.MftMirrorIndex, _mftMirrorCluster, numMftMirrorClusters, true);
File logFile = CreateSystemFile(MasterFileTable.LogFileIndex);
using (Stream s = logFile.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite))
{
s.SetLength(Math.Min(Math.Max(2 * Sizes.OneMiB, (totalClusters / 500) * (long)_clusterSize), 64 * Sizes.OneMiB));
byte[] buffer = new byte[1024 * 1024];
for (int i = 0; i < buffer.Length; ++i)
{
buffer[i] = 0xFF;
}
long totalWritten = 0;
while (totalWritten < s.Length)
{
int toWrite = (int)Math.Min(s.Length - totalWritten, buffer.Length);
s.Write(buffer, 0, toWrite);
totalWritten += toWrite;
}
}
File volumeFile = CreateSystemFile(MasterFileTable.VolumeIndex);
NtfsStream volNameStream = volumeFile.CreateStream(AttributeType.VolumeName, null);
volNameStream.SetContent(new VolumeName(Label ?? "New Volume"));
NtfsStream volInfoStream = volumeFile.CreateStream(AttributeType.VolumeInformation, null);
volInfoStream.SetContent(new VolumeInformation(3, 1, VolumeInformationFlags.None));
SetSecurityAttribute(volumeFile, "O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)");
volumeFile.UpdateRecordInMft();
_context.GetFileByIndex = delegate(long index) { return new File(_context, _context.Mft.GetRecord(index, false)); };
_context.AllocateFile = delegate(FileRecordFlags frf) { return new File(_context, _context.Mft.AllocateRecord(frf, false)); };
File attrDefFile = CreateSystemFile(MasterFileTable.AttrDefIndex);
_context.AttributeDefinitions.WriteTo(attrDefFile);
SetSecurityAttribute(attrDefFile, "O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)");
attrDefFile.UpdateRecordInMft();
File bootFile = CreateFixedSystemFile(MasterFileTable.BootIndex, 0, (uint)numBootClusters, false);
SetSecurityAttribute(bootFile, "O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)");
bootFile.UpdateRecordInMft();
File badClusFile = CreateSystemFile(MasterFileTable.BadClusIndex);
badClusFile.CreateStream(AttributeType.Data, "$Bad");
badClusFile.UpdateRecordInMft();
File secureFile = CreateSystemFile(MasterFileTable.SecureIndex, FileRecordFlags.HasViewIndex);
secureFile.RemoveStream(secureFile.GetStream(AttributeType.Data, null));
_context.SecurityDescriptors = SecurityDescriptors.Initialize(secureFile);
secureFile.UpdateRecordInMft();
File upcaseFile = CreateSystemFile(MasterFileTable.UpCaseIndex);
_context.UpperCase = UpperCase.Initialize(upcaseFile);
upcaseFile.UpdateRecordInMft();
File objIdFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None);
objIdFile.RemoveStream(objIdFile.GetStream(AttributeType.Data, null));
objIdFile.CreateIndex("$O", (AttributeType)0, AttributeCollationRule.MultipleUnsignedLongs);
objIdFile.UpdateRecordInMft();
File reparseFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None);
reparseFile.CreateIndex("$R", (AttributeType)0, AttributeCollationRule.MultipleUnsignedLongs);
reparseFile.UpdateRecordInMft();
File quotaFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None);
Quotas.Initialize(quotaFile);
Directory extendDir = CreateSystemDirectory(MasterFileTable.ExtendIndex);
extendDir.AddEntry(objIdFile, "$ObjId", FileNameNamespace.Win32AndDos);
extendDir.AddEntry(reparseFile, "$Reparse", FileNameNamespace.Win32AndDos);
extendDir.AddEntry(quotaFile, "$Quota", FileNameNamespace.Win32AndDos);
extendDir.UpdateRecordInMft();
Directory rootDir = CreateSystemDirectory(MasterFileTable.RootDirIndex);
rootDir.AddEntry(mftFile, "$MFT", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(mftMirrorFile, "$MFTMirr", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(logFile, "$LogFile", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(volumeFile, "$Volume", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(attrDefFile, "$AttrDef", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(rootDir, ".", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(bitmapFile, "$Bitmap", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(bootFile, "$Boot", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(badClusFile, "$BadClus", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(secureFile, "$Secure", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(upcaseFile, "$UpCase", FileNameNamespace.Win32AndDos);
rootDir.AddEntry(extendDir, "$Extend", FileNameNamespace.Win32AndDos);
SetSecurityAttribute(rootDir, "O:" + localAdminString + "G:BUD:(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)(A;OICIIO;GA;;;CO)(A;OICI;0x1200a9;;;BU)(A;CI;LC;;;BU)(A;CIIO;DC;;;BU)(A;;0x1200a9;;;WD)");
rootDir.UpdateRecordInMft();
// A number of records are effectively 'reserved'
for (long i = MasterFileTable.ExtendIndex + 1; i <= 15; i++)
{
File f = CreateSystemFile(i);
SetSecurityAttribute(f, "O:S-1-5-21-1708537768-746137067-1060284298-1003G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)");
f.UpdateRecordInMft();
}
}
// XP-style security permissions setup
NtfsFileSystem ntfs = new NtfsFileSystem(stream);
ntfs.SetSecurity(@"$MFT", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
ntfs.SetSecurity(@"$MFTMirr", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
ntfs.SetSecurity(@"$LogFile", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
ntfs.SetSecurity(@"$Bitmap", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
ntfs.SetSecurity(@"$BadClus", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
ntfs.SetSecurity(@"$UpCase", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
ntfs.SetSecurity(@"$Secure", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
ntfs.SetSecurity(@"$Extend", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
ntfs.SetSecurity(@"$Extend\$Quota", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
ntfs.SetSecurity(@"$Extend\$ObjId", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
ntfs.SetSecurity(@"$Extend\$Reparse", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
ntfs.CreateDirectory("System Volume Information");
ntfs.SetAttributes("System Volume Information", FileAttributes.Hidden | FileAttributes.System | FileAttributes.Directory);
ntfs.SetSecurity("System Volume Information", new RawSecurityDescriptor("O:BAG:SYD:(A;OICI;FA;;;SY)"));
using (Stream s = ntfs.OpenFile(@"System Volume Information\MountPointManagerRemoteDatabase", FileMode.Create))
{
}
ntfs.SetAttributes(@"System Volume Information\MountPointManagerRemoteDatabase", FileAttributes.Hidden | FileAttributes.System | FileAttributes.Archive);
ntfs.SetSecurity(@"System Volume Information\MountPointManagerRemoteDatabase", new RawSecurityDescriptor("O:BAG:SYD:(A;;FA;;;SY)"));
return ntfs;
}
private static void SetSecurityAttribute(File file, string secDesc)
{
NtfsStream rootSecurityStream = file.CreateStream(AttributeType.SecurityDescriptor, null);
SecurityDescriptor sd = new SecurityDescriptor();
sd.Descriptor = new RawSecurityDescriptor(secDesc);
rootSecurityStream.SetContent(sd);
}
private File CreateFixedSystemFile(long mftIndex, long firstCluster, ulong numClusters, bool wipe)
{
BiosParameterBlock bpb = _context.BiosParameterBlock;
if (wipe)
{
byte[] wipeBuffer = new byte[bpb.BytesPerCluster];
_context.RawStream.Position = firstCluster * bpb.BytesPerCluster;
for (ulong i = 0; i < numClusters; ++i)
{
_context.RawStream.Write(wipeBuffer, 0, wipeBuffer.Length);
}
}
FileRecord fileRec = _context.Mft.AllocateRecord((uint)mftIndex, FileRecordFlags.None);
fileRec.Flags = FileRecordFlags.InUse;
fileRec.SequenceNumber = (ushort)mftIndex;
File file = new File(_context, fileRec);
StandardInformation.InitializeNewFile(file, FileAttributeFlags.Hidden | FileAttributeFlags.System);
file.CreateStream(AttributeType.Data, null, firstCluster, numClusters, (uint)bpb.BytesPerCluster);
file.UpdateRecordInMft();
if (_context.ClusterBitmap != null)
{
_context.ClusterBitmap.MarkAllocated(firstCluster, (long)numClusters);
}
return file;
}
private File CreateSystemFile(long mftIndex)
{
return CreateSystemFile(mftIndex, FileRecordFlags.None);
}
private File CreateSystemFile(long mftIndex, FileRecordFlags flags)
{
FileRecord fileRec = _context.Mft.AllocateRecord((uint)mftIndex, flags);
fileRec.SequenceNumber = (ushort)mftIndex;
File file = new File(_context, fileRec);
StandardInformation.InitializeNewFile(file, FileAttributeFlags.Hidden | FileAttributeFlags.System | FileRecord.ConvertFlags(flags));
file.CreateStream(AttributeType.Data, null);
file.UpdateRecordInMft();
return file;
}
private Directory CreateSystemDirectory(long mftIndex)
{
FileRecord fileRec = _context.Mft.AllocateRecord((uint)mftIndex, FileRecordFlags.None);
fileRec.Flags = FileRecordFlags.InUse | FileRecordFlags.IsDirectory;
fileRec.SequenceNumber = (ushort)mftIndex;
Directory dir = new Directory(_context, fileRec);
StandardInformation.InitializeNewFile(dir, FileAttributeFlags.Hidden | FileAttributeFlags.System);
dir.CreateIndex("$I30", AttributeType.FileName, AttributeCollationRule.Filename);
dir.UpdateRecordInMft();
return dir;
}
private void CreateBiosParameterBlock(Stream stream, int bootFileSize)
{
byte[] bootSectors = new byte[bootFileSize];
if (BootCode != null)
{
Array.Copy(BootCode, 0, bootSectors, 0, BootCode.Length);
}
BiosParameterBlock bpb = BiosParameterBlock.Initialized(DiskGeometry, _clusterSize, (uint)FirstSector, SectorCount, _mftRecordSize, _indexBufferSize);
bpb.MftCluster = _mftCluster;
bpb.MftMirrorCluster = _mftMirrorCluster;
bpb.ToBytes(bootSectors, 0);
// Primary goes at the start of the partition
stream.Position = 0;
stream.Write(bootSectors, 0, bootSectors.Length);
// Backup goes at the end of the data in the partition
stream.Position = (SectorCount - 1) * Sizes.Sector;
stream.Write(bootSectors, 0, Sizes.Sector);
_context.BiosParameterBlock = bpb;
}
}
}
| |
#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
namespace System.Web.UI
{
public partial class HtmlBuilder
{
public HtmlBuilder BeginSmartTag(HtmlTag tag, params string[] args) { return BeginSmartTag(tag, Nattrib.Parse(args)); }
public HtmlBuilder BeginSmartTag(HtmlTag tag, Nattrib attrib)
{
string c;
switch (tag)
{
case HtmlTag._CommandTarget:
throw new NotSupportedException();
case HtmlTag.Script:
o_Script(attrib);
return this;
// Container
case HtmlTag.Div:
o_Div(attrib);
return this;
// Content
case HtmlTag.A:
if ((attrib == null) || (string.IsNullOrEmpty(c = attrib.Slice<string>("url"))))
throw new ArgumentException("Local.UndefinedAttribUrl", "attrib");
o_A(c, attrib);
return this;
case HtmlTag.H1:
o_H1(attrib);
return this;
case HtmlTag.H2:
o_H2(attrib);
return this;
case HtmlTag.H3:
o_H3(attrib);
return this;
case HtmlTag.P:
o_P(attrib);
return this;
case HtmlTag.Span:
o_Span(attrib);
return this;
// List
case HtmlTag.Li:
o_Li(attrib);
return this;
case HtmlTag.Ol:
o_Ol(attrib);
return this;
case HtmlTag.Ul:
o_Ul(attrib);
return this;
// Table
case HtmlTag.Colgroup:
o_Colgroup(attrib);
return this;
case HtmlTag.Table:
o_Table(attrib);
return this;
case HtmlTag.Tbody:
o_Tbody(attrib);
return this;
case HtmlTag.Td:
o_Td(attrib);
return this;
case HtmlTag.Tfoot:
o_Tfoot(attrib);
return this;
case HtmlTag.Th:
o_Th(attrib);
return this;
case HtmlTag.Thead:
o_Thead(attrib);
return this;
case HtmlTag.Tr:
o_Tr(attrib);
return this;
// Form
case HtmlTag.Button:
o_Button(attrib);
return this;
case HtmlTag.Fieldset:
o_Fieldset(attrib);
return this;
case HtmlTag.Form:
throw new NotSupportedException();
case HtmlTag._FormReference:
throw new NotSupportedException();
case HtmlTag.Label:
if ((attrib == null) || (string.IsNullOrEmpty(c = attrib.Slice<string>("forName"))))
throw new ArgumentException("Local.UndefinedAttribForName", "attrib");
o_Label(c, attrib);
return this;
// o_optgroup - no match
case HtmlTag.Option:
if ((attrib == null) || (string.IsNullOrEmpty(c = attrib.Slice<string>("value"))))
throw new ArgumentException("Local.UndefinedAttribValue", "attrib");
o_Option(c, attrib);
return this;
case HtmlTag.Select:
if ((attrib == null) || (string.IsNullOrEmpty(c = attrib.Slice<string>("name"))))
throw new ArgumentException("Local.UndefinedAttribName", "attrib");
o_Select(c, attrib);
return this;
case HtmlTag.Textarea:
if ((attrib == null) || (string.IsNullOrEmpty(c = attrib.Slice<string>("name"))))
throw new ArgumentException("Local.UndefinedAttribName", "attrib");
o_Textarea(c, attrib);
return this;
}
BeginHtmlTag(tag);
return this;
}
public HtmlBuilder EndSmartTag(HtmlTag tag, params string[] args) { return EndSmartTag(tag, Nattrib.Parse(args)); }
public HtmlBuilder EndSmartTag(HtmlTag tag, Nattrib attrib)
{
string c;
string c2;
switch (tag)
{
case HtmlTag._CommandTarget:
x_CommandTarget();
return this;
case HtmlTag.Script:
x_Script();
return this;
// Container
case HtmlTag.Div:
x_Div();
return this;
case HtmlTag.Iframe:
if ((attrib == null) || (string.IsNullOrEmpty(c = attrib.Slice<string>("url"))))
throw new ArgumentException("Local.UndefinedAttribUrl", "attrib");
x_Iframe(c, attrib);
return this;
// Content
case HtmlTag.A:
x_A();
return this;
case HtmlTag.Br:
x_Br();
return this;
case HtmlTag.H1:
x_H1();
return this;
case HtmlTag.H2:
x_H2();
return this;
case HtmlTag.H3:
x_H3();
return this;
case HtmlTag.Hr:
x_Hr(attrib);
return this;
case HtmlTag.Img:
if ((attrib == null) || (string.IsNullOrEmpty(c = attrib.Slice<string>("url"))))
throw new ArgumentException("Local.UndefinedAttribUrl", "attrib");
if (string.IsNullOrEmpty(c2 = attrib.Slice<string>("value")))
throw new ArgumentException("Local.UndefinedAttribValue", "attrib");
x_Img(c, c2, attrib);
return this;
case HtmlTag.P:
x_P();
return this;
case HtmlTag.Span:
x_Span();
return this;
//- x_tofu - no match
// List
case HtmlTag.Li:
x_Li();
return this;
case HtmlTag.Ol:
x_Ol();
return this;
case HtmlTag.Ul:
x_Ul();
return this;
// Table
case HtmlTag.Col:
x_Col(attrib);
return this;
case HtmlTag.Colgroup:
x_Colgroup();
return this;
case HtmlTag.Table:
x_Table();
return this;
case HtmlTag.Tbody:
x_Tbody();
return this;
case HtmlTag.Td:
x_Td();
return this;
case HtmlTag.Tfoot:
x_Tfoot();
return this;
case HtmlTag.Th:
x_Th();
return this;
case HtmlTag.Thead:
x_Thead();
return this;
case HtmlTag.Tr:
x_Tr();
return this;
// Form
case HtmlTag.Button:
x_Button();
return this;
case HtmlTag.Fieldset:
x_Fieldset();
return this;
case HtmlTag.Form:
x_Form();
return this;
case HtmlTag._FormReference:
x_FormReference();
return this;
case HtmlTag.Input:
if ((attrib == null) || (string.IsNullOrEmpty(c = attrib.Slice<string>("name"))))
throw new ArgumentException("Local.UndefinedAttribName", "attrib");
if (string.IsNullOrEmpty(c2 = attrib.Slice<string>("value")))
throw new ArgumentException("Local.UndefinedAttribValue", "attrib");
x_Input(c, c2, attrib);
return this;
case HtmlTag.Label:
x_Label();
return this;
// x_optgroup - no match
case HtmlTag.Option:
x_Option();
return this;
case HtmlTag.Select:
x_Select();
return this;
case HtmlTag.Textarea:
x_Textarea();
return this;
}
EndHtmlTag();
return this;
}
}
}
| |
namespace BrickBreakerLevelEditor
{
public partial class EditorControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditorControl));
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuNumHits = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem10 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem11 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem12 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.cancelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.deleteToolStripMenuItem,
this.mnuNumHits,
this.toolStripMenuItem1,
this.cancelToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(159, 98);
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
this.deleteToolStripMenuItem.Size = new System.Drawing.Size(158, 22);
this.deleteToolStripMenuItem.Text = "&Delete";
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click);
//
// mnuNumHits
//
this.mnuNumHits.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem4,
this.toolStripMenuItem5,
this.toolStripMenuItem6,
this.toolStripMenuItem7,
this.toolStripMenuItem8,
this.toolStripMenuItem9,
this.toolStripMenuItem10,
this.toolStripMenuItem11,
this.toolStripMenuItem12});
this.mnuNumHits.Image = ((System.Drawing.Image)(resources.GetObject("mnuNumHits.Image")));
this.mnuNumHits.Name = "mnuNumHits";
this.mnuNumHits.Size = new System.Drawing.Size(158, 22);
this.mnuNumHits.Text = "&Hits to Clear";
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Checked = true;
this.toolStripMenuItem4.CheckState = System.Windows.Forms.CheckState.Checked;
this.toolStripMenuItem4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem4.Image")));
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem4.Tag = "1";
this.toolStripMenuItem4.Text = "&1 Hit";
this.toolStripMenuItem4.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem5.Image")));
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem5.Tag = "2";
this.toolStripMenuItem5.Text = "&2 Hits";
this.toolStripMenuItem5.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem6.Image")));
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem6.Tag = "3";
this.toolStripMenuItem6.Text = "&3 Hits";
this.toolStripMenuItem6.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem7
//
this.toolStripMenuItem7.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem7.Image")));
this.toolStripMenuItem7.Name = "toolStripMenuItem7";
this.toolStripMenuItem7.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem7.Tag = "4";
this.toolStripMenuItem7.Text = "&4 Hits";
this.toolStripMenuItem7.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem8
//
this.toolStripMenuItem8.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem8.Image")));
this.toolStripMenuItem8.Name = "toolStripMenuItem8";
this.toolStripMenuItem8.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem8.Tag = "5";
this.toolStripMenuItem8.Text = "&5 Hits";
this.toolStripMenuItem8.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem9.Image")));
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
this.toolStripMenuItem9.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem9.Tag = "6";
this.toolStripMenuItem9.Text = "&6 Hits";
this.toolStripMenuItem9.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem10
//
this.toolStripMenuItem10.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem10.Image")));
this.toolStripMenuItem10.Name = "toolStripMenuItem10";
this.toolStripMenuItem10.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem10.Tag = "7";
this.toolStripMenuItem10.Text = "&7 Hits";
this.toolStripMenuItem10.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem11
//
this.toolStripMenuItem11.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem11.Image")));
this.toolStripMenuItem11.Name = "toolStripMenuItem11";
this.toolStripMenuItem11.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem11.Tag = "8";
this.toolStripMenuItem11.Text = "&8 Hits";
this.toolStripMenuItem11.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem12
//
this.toolStripMenuItem12.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem12.Image")));
this.toolStripMenuItem12.Name = "toolStripMenuItem12";
this.toolStripMenuItem12.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem12.Tag = "9";
this.toolStripMenuItem12.Text = "&9 Hits";
this.toolStripMenuItem12.Click += new System.EventHandler(this.toolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(155, 6);
//
// cancelToolStripMenuItem
//
this.cancelToolStripMenuItem.Name = "cancelToolStripMenuItem";
this.cancelToolStripMenuItem.Size = new System.Drawing.Size(158, 22);
this.cancelToolStripMenuItem.Text = "&Cancel";
//
// BrickBreakerEditorControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.DoubleBuffered = true;
this.Name = "BrickBreakerEditorControl";
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.BrickBreakerEditorControl_MouseMove);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.BrickBreakerEditorControl_Paint);
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.BrickBreakerEditorControl_MouseUp);
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem cancelToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mnuNumHits;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem7;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem8;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem9;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem10;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem11;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem12;
}
}
| |
//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER && !UNITY_WSA
#define USE_FileIO
#endif
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SimpleJSON
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| |
// 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;
#pragma warning disable 1591 // TODO: doc comments
namespace Microsoft.Cci.Pdb {
internal class PdbFunction {
static internal readonly Guid msilMetaData = new Guid(0xc6ea3fc9, 0x59b3, 0x49d6, 0xbc, 0x25,
0x09, 0x02, 0xbb, 0xab, 0xb4, 0x60);
static internal readonly IComparer byAddress = new PdbFunctionsByAddress();
static internal readonly IComparer byAddressAndToken = new PdbFunctionsByAddressAndToken();
//static internal readonly IComparer byToken = new PdbFunctionsByToken();
internal uint token;
internal uint slotToken;
internal uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod;
//internal string name;
//internal string module;
//internal ushort flags;
internal uint segment;
internal uint address;
internal uint length;
//internal byte[] metadata;
internal PdbScope[] scopes;
internal PdbSlot[] slots;
internal PdbConstant[] constants;
internal string[] usedNamespaces;
internal PdbLines[] lines;
internal ushort[]/*?*/ usingCounts;
internal IEnumerable<INamespaceScope>/*?*/ namespaceScopes;
internal string/*?*/ iteratorClass;
internal List<ILocalScope>/*?*/ iteratorScopes;
internal PdbSynchronizationInformation/*?*/ synchronizationInformation;
/// <summary>
/// Flag saying whether the method has been identified as a product of VB compilation using
/// the legacy Windows PDB symbol format, in which case scope ends need to be shifted by 1
/// due to different semantics of scope limits in VB and C# compilers.
/// </summary>
private bool visualBasicScopesAdjusted = false;
private static string StripNamespace(string module) {
int li = module.LastIndexOf('.');
if (li > 0) {
return module.Substring(li + 1);
}
return module;
}
/// <summary>
/// When the Windows PDB reader identifies a PdbFunction as having 'Basic' as its source language,
/// it calls this method which adjusts all scopes by adding 1 to their lengths to compensate
/// for different behavior of VB vs. the C# compiler w.r.t. emission of scope info.
/// </summary>
internal void AdjustVisualBasicScopes()
{
if (!visualBasicScopesAdjusted)
{
visualBasicScopesAdjusted = true;
// Don't adjust root scope as that one is correct
foreach (PdbScope scope in scopes)
{
AdjustVisualBasicScopes(scope.scopes);
}
}
}
/// <summary>
/// Recursively update the entire scope tree by adding 1 to the length of each scope.
/// </summary>
private void AdjustVisualBasicScopes(PdbScope[] scopes)
{
foreach (PdbScope scope in scopes)
{
scope.length++;
AdjustVisualBasicScopes(scope.scopes);
}
}
internal static PdbFunction[] LoadManagedFunctions(/*string module,*/
BitAccess bits, uint limit,
bool readStrings) {
//string mod = StripNamespace(module);
int begin = bits.Position;
int count = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.Position = (int)proc.end;
count++;
break;
case SYM.S_END:
bits.Position = stop;
break;
default:
//Console.WriteLine("{0,6}: {1:x2} {2}",
// bits.Position, rec, (SYM)rec);
bits.Position = stop;
break;
}
}
if (count == 0) {
return null;
}
bits.Position = begin;
PdbFunction[] funcs = new PdbFunction[count];
int func = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
//int offset = bits.Position;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.ReadUInt32(out proc.next);
bits.ReadUInt32(out proc.len);
bits.ReadUInt32(out proc.dbgStart);
bits.ReadUInt32(out proc.dbgEnd);
bits.ReadUInt32(out proc.token);
bits.ReadUInt32(out proc.off);
bits.ReadUInt16(out proc.seg);
bits.ReadUInt8(out proc.flags);
bits.ReadUInt16(out proc.retReg);
if (readStrings) {
bits.ReadCString(out proc.name);
} else {
bits.SkipCString(out proc.name);
}
//Console.WriteLine("token={0:X8} [{1}::{2}]", proc.token, module, proc.name);
bits.Position = stop;
funcs[func++] = new PdbFunction(/*module,*/ proc, bits);
break;
default: {
//throw new PdbDebugException("Unknown SYMREC {0}", (SYM)rec);
bits.Position = stop;
break;
}
}
}
return funcs;
}
internal static void CountScopesAndSlots(BitAccess bits, uint limit,
out int constants, out int scopes, out int slots, out int usedNamespaces) {
int pos = bits.Position;
BlockSym32 block;
constants = 0;
slots = 0;
scopes = 0;
usedNamespaces = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_BLOCK32: {
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
scopes++;
bits.Position = (int)block.end;
break;
}
case SYM.S_MANSLOT:
slots++;
bits.Position = stop;
break;
case SYM.S_UNAMESPACE:
usedNamespaces++;
bits.Position = stop;
break;
case SYM.S_MANCONSTANT:
constants++;
bits.Position = stop;
break;
default:
bits.Position = stop;
break;
}
}
bits.Position = pos;
}
internal PdbFunction() {
}
internal PdbFunction(/*string module, */ManProcSym proc, BitAccess bits) {
this.token = proc.token;
//this.module = module;
//this.name = proc.name;
//this.flags = proc.flags;
this.segment = proc.seg;
this.address = proc.off;
this.length = proc.len;
if (proc.seg != 1) {
throw new PdbDebugException("Segment is {0}, not 1.", proc.seg);
}
if (proc.parent != 0 || proc.next != 0) {
throw new PdbDebugException("Warning parent={0}, next={1}",
proc.parent, proc.next);
}
//if (proc.dbgStart != 0 || proc.dbgEnd != 0) {
// throw new PdbDebugException("Warning DBG start={0}, end={1}",
// proc.dbgStart, proc.dbgEnd);
//}
int constantCount;
int scopeCount;
int slotCount;
int usedNamespacesCount;
CountScopesAndSlots(bits, proc.end, out constantCount, out scopeCount, out slotCount, out usedNamespacesCount);
int scope = constantCount > 0 || slotCount > 0 || usedNamespacesCount > 0 ? 1 : 0;
int slot = 0;
int constant = 0;
int usedNs = 0;
scopes = new PdbScope[scopeCount+scope];
slots = new PdbSlot[slotCount];
constants = new PdbConstant[constantCount];
usedNamespaces = new string[usedNamespacesCount];
if (scope > 0)
scopes[0] = new PdbScope(this.address, proc.len, slots, constants, usedNamespaces);
while (bits.Position < proc.end) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_OEM: { // 0x0404
OemSymbol oem;
bits.ReadGuid(out oem.idOem);
bits.ReadUInt32(out oem.typind);
// internal byte[] rgl; // user data, force 4-byte alignment
if (oem.idOem == msilMetaData) {
string name = bits.ReadString();
if (name == "MD2") {
ReadMD2CustomMetadata(bits);
} else if (name == "asyncMethodInfo") {
this.synchronizationInformation = new PdbSynchronizationInformation(bits);
}
bits.Position = stop;
break;
} else {
throw new PdbDebugException("OEM section: guid={0} ti={1}",
oem.idOem, oem.typind);
// bits.Position = stop;
}
}
case SYM.S_BLOCK32: {
BlockSym32 block = new BlockSym32();
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
bits.ReadUInt32(out block.len);
bits.ReadUInt32(out block.off);
bits.ReadUInt16(out block.seg);
bits.SkipCString(out block.name);
bits.Position = stop;
scopes[scope++] = new PdbScope(this.address, block, bits, out slotToken);
bits.Position = (int)block.end;
break;
}
case SYM.S_MANSLOT:
slots[slot++] = new PdbSlot(bits);
bits.Position = stop;
break;
case SYM.S_MANCONSTANT:
constants[constant++] = new PdbConstant(bits);
bits.Position = stop;
break;
case SYM.S_UNAMESPACE:
bits.ReadCString(out usedNamespaces[usedNs++]);
bits.Position = stop;
break;
case SYM.S_END:
bits.Position = stop;
break;
default: {
//throw new PdbDebugException("Unknown SYM: {0}", (SYM)rec);
bits.Position = stop;
break;
}
}
}
if (bits.Position != proc.end) {
throw new PdbDebugException("Not at S_END");
}
ushort esiz;
ushort erec;
bits.ReadUInt16(out esiz);
bits.ReadUInt16(out erec);
if (erec != (ushort)SYM.S_END) {
throw new PdbDebugException("Missing S_END");
}
}
internal void ReadMD2CustomMetadata(BitAccess bits)
{
byte version;
bits.ReadUInt8(out version);
if (version == 4) {
byte count;
bits.ReadUInt8(out count);
bits.Align(4);
while (count-- > 0)
this.ReadCustomMetadata(bits);
}
}
private void ReadCustomMetadata(BitAccess bits)
{
int savedPosition = bits.Position;
byte version;
bits.ReadUInt8(out version);
byte kind;
bits.ReadUInt8(out kind);
bits.Position += 2; // 2-bytes padding
uint numberOfBytesInItem;
bits.ReadUInt32(out numberOfBytesInItem);
if (version == 4)
{
switch (kind)
{
case 0: this.ReadUsingInfo(bits); break;
case 1: this.ReadForwardInfo(bits); break;
case 2: break; // this.ReadForwardedToModuleInfo(bits); break;
case 3: this.ReadIteratorLocals(bits); break;
case 4: this.ReadForwardIterator(bits); break;
case 5: break; // dynamic locals - see http://index/#Microsoft.VisualStudio.LanguageServices/Shared/CustomDebugInfoReader.cs,a3031f7681d76e93
case 6: break; // EnC data
case 7: break; // EnC data for lambdas and closures
// ignore any other unknown record types that may be added in future, instead of throwing an exception
// see more details here: https://github.com/tmat/roslyn/blob/portable-pdb/docs/specs/PortablePdb-Metadata.md
default: break; // throw new PdbDebugException("Unknown custom metadata item kind: {0}", kind);
}
}
bits.Position = savedPosition + (int)numberOfBytesInItem;
}
private void ReadForwardIterator(BitAccess bits) {
this.iteratorClass = bits.ReadString();
}
private void ReadIteratorLocals(BitAccess bits) {
uint numberOfLocals;
bits.ReadUInt32(out numberOfLocals);
this.iteratorScopes = new List<ILocalScope>((int)numberOfLocals);
while (numberOfLocals-- > 0) {
uint ilStartOffset;
uint ilEndOffset;
bits.ReadUInt32(out ilStartOffset);
bits.ReadUInt32(out ilEndOffset);
this.iteratorScopes.Add(new PdbIteratorScope(ilStartOffset, ilEndOffset-ilStartOffset));
}
}
//private void ReadForwardedToModuleInfo(BitAccess bits) {
//}
private void ReadForwardInfo(BitAccess bits) {
bits.ReadUInt32(out this.tokenOfMethodWhoseUsingInfoAppliesToThisMethod);
}
private void ReadUsingInfo(BitAccess bits) {
ushort numberOfNamespaces;
bits.ReadUInt16(out numberOfNamespaces);
this.usingCounts = new ushort[numberOfNamespaces];
for (ushort i = 0; i < numberOfNamespaces; i++) {
bits.ReadUInt16(out this.usingCounts[i]);
}
}
internal class PdbFunctionsByAddress : IComparer {
public int Compare(Object x, Object y) {
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.segment < fy.segment) {
return -1;
} else if (fx.segment > fy.segment) {
return 1;
} else if (fx.address < fy.address) {
return -1;
} else if (fx.address > fy.address) {
return 1;
} else {
return 0;
}
}
}
internal class PdbFunctionsByAddressAndToken : IComparer {
public int Compare(Object x, Object y) {
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.segment < fy.segment) {
return -1;
} else if (fx.segment > fy.segment) {
return 1;
} else if (fx.address < fy.address) {
return -1;
} else if (fx.address > fy.address) {
return 1;
} else {
if (fx.token < fy.token)
return -1;
else if (fx.token > fy.token)
return 1;
else
return 0;
}
}
}
//internal class PdbFunctionsByToken : IComparer {
// public int Compare(Object x, Object y) {
// PdbFunction fx = (PdbFunction)x;
// PdbFunction fy = (PdbFunction)y;
// if (fx.token < fy.token) {
// return -1;
// } else if (fx.token > fy.token) {
// return 1;
// } else {
// return 0;
// }
// }
//}
}
internal class PdbSynchronizationInformation {
internal uint kickoffMethodToken;
internal uint generatedCatchHandlerIlOffset;
internal PdbSynchronizationPoint[] synchronizationPoints;
internal PdbSynchronizationInformation(BitAccess bits) {
uint asyncStepInfoCount;
bits.ReadUInt32(out this.kickoffMethodToken);
bits.ReadUInt32(out this.generatedCatchHandlerIlOffset);
bits.ReadUInt32(out asyncStepInfoCount);
this.synchronizationPoints = new PdbSynchronizationPoint[asyncStepInfoCount];
for (uint i = 0; i < asyncStepInfoCount; i += 1) {
this.synchronizationPoints[i] = new PdbSynchronizationPoint(bits);
}
}
public uint GeneratedCatchHandlerOffset {
get { return this.generatedCatchHandlerIlOffset; }
}
}
internal class PdbSynchronizationPoint {
internal uint synchronizeOffset;
internal uint continuationMethodToken;
internal uint continuationOffset;
internal PdbSynchronizationPoint(BitAccess bits) {
bits.ReadUInt32(out this.synchronizeOffset);
bits.ReadUInt32(out this.continuationMethodToken);
bits.ReadUInt32(out this.continuationOffset);
}
public uint SynchronizeOffset {
get { return this.synchronizeOffset; }
}
public uint ContinuationOffset {
get { return this.continuationOffset; }
}
}
}
| |
// 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.
#if UseSingularityPDB
///////////////////////////////////////////////////////////////////////////////
//
// Microsoft Research Singularity PDB Info Library
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: PdbFunction.cs
//
using System;
using System.Collections;
using Microsoft.Singularity.PdbInfo.CodeView;
using Microsoft.Singularity.PdbInfo.Features;
namespace Microsoft.Singularity.PdbInfo
{
public class PdbFunction
{
static public readonly Guid msilMetaData = new Guid(0xc6ea3fc9,0x59b3,0x49d6,0xbc,0x25,
0x09,0x02,0xbb,0xab,0xb4,0x60);
static public readonly IComparer byAddress = new PdbFunctionsByAddress();
static public readonly IComparer byToken = new PdbFunctionsByToken();
public uint token;
public uint slotToken;
public string name;
public string module;
public ushort flags;
public uint segment;
public uint address;
public uint length;
public byte[] metadata;
public PdbScope[] scopes;
public PdbLines[] lines;
private static string StripNamespace(string module)
{
int li = module.LastIndexOf('.');
if (li > 0) {
return module.Substring(li + 1);
}
return module;
}
internal static PdbFunction[] LoadManagedFunctions(string module,
BitAccess bits, uint limit,
bool readStrings)
{
string mod = StripNamespace(module);
int begin = bits.Position;
int count = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.Position = (int)proc.end;
count++;
break;
case SYM.S_END:
bits.Position = stop;
break;
default:
Console.WriteLine("{0,6}: {1:x2} {2}",
bits.Position, rec, (SYM)rec);
bits.Position = stop;
break;
}
}
if (count == 0) {
return null;
}
bits.Position = begin;
PdbFunction[] funcs = new PdbFunction[count];
int func = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
int offset = bits.Position;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.ReadUInt32(out proc.next);
bits.ReadUInt32(out proc.len);
bits.ReadUInt32(out proc.dbgStart);
bits.ReadUInt32(out proc.dbgEnd);
bits.ReadUInt32(out proc.token);
bits.ReadUInt32(out proc.off);
bits.ReadUInt16(out proc.seg);
bits.ReadUInt8(out proc.flags);
bits.ReadUInt16(out proc.retReg);
if (readStrings) {
bits.ReadCString(out proc.name);
}
else {
bits.SkipCString(out proc.name);
}
//Console.WriteLine("token={0:X8} [{1}::{2}]", proc.token, module, proc.name);
bits.Position = stop;
funcs[func++] = new PdbFunction(module, proc, bits);
break;
default: {
throw new PdbDebugException("Unknown SYMREC {0}", (SYM)rec);
// bits.Position = stop;
}
}
}
return funcs;
}
internal static void CountScopesAndSlots(BitAccess bits, uint limit,
out int scopes, out int slots)
{
int pos = bits.Position;
BlockSym32 block;
slots = 0;
scopes = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_BLOCK32: {
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
scopes++;
bits.Position = (int)block.end;
break;
}
case SYM.S_MANSLOT:
slots++;
bits.Position = stop;
break;
default:
bits.Position = stop;
break;
}
}
bits.Position = pos;
}
internal PdbFunction()
{
}
internal PdbFunction(string module, ManProcSym proc, BitAccess bits)
{
this.token = proc.token;
this.module = module;
this.name = proc.name;
this.flags = proc.flags;
this.segment = proc.seg;
this.address = proc.off;
this.length = proc.len;
this.slotToken = 0;
if (proc.seg != 1) {
throw new PdbDebugException("Segment is {0}, not 1.", proc.seg);
}
if (proc.parent != 0 || proc.next != 0) {
throw new PdbDebugException("Warning parent={0}, next={1}",
proc.parent, proc.next);
}
if (proc.dbgStart != 0 || proc.dbgEnd != 0) {
throw new PdbDebugException("Warning DBG start={0}, end={1}",
proc.dbgStart, proc.dbgEnd);
}
int scopeCount;
int slotCount;
CountScopesAndSlots(bits, proc.end, out scopeCount, out slotCount);
scopes = new PdbScope[scopeCount];
int scope = 0;
while (bits.Position < proc.end) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_OEM: { // 0x0404
OemSymbol oem;
bits.ReadGuid(out oem.idOem);
bits.ReadUInt32(out oem.typind);
// public byte[] rgl; // user data, force 4-byte alignment
if (oem.idOem == msilMetaData) {
metadata = new byte[stop - bits.Position];
bits.ReadBytes(metadata);
bits.Position = stop;
break;
}
else {
throw new PdbDebugException("OEM section: guid={0} ti={1}",
oem.idOem, oem.typind);
// bits.Position = stop;
}
}
case SYM.S_BLOCK32: {
BlockSym32 block = new BlockSym32();
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
bits.ReadUInt32(out block.len);
bits.ReadUInt32(out block.off);
bits.ReadUInt16(out block.seg);
bits.SkipCString(out block.name);
bits.Position = stop;
scopes[scope] = new PdbScope(block, bits, out slotToken);
bits.Position = (int)block.end;
break;
}
case SYM.S_UNAMESPACE:
bits.Position = stop;
break;
case SYM.S_END:
bits.Position = stop;
break;
default: {
throw new PdbDebugException("Unknown SYM: {0}", (SYM)rec);
// bits.Position = stop;
}
}
}
if (bits.Position != proc.end) {
throw new PdbDebugException("Not at S_END");
}
ushort esiz;
ushort erec;
bits.ReadUInt16(out esiz);
bits.ReadUInt16(out erec);
if (erec != (ushort)SYM.S_END) {
throw new PdbDebugException("Missing S_END");
}
}
internal class PdbFunctionsByAddress : IComparer
{
public int Compare(Object x, Object y)
{
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.segment < fy.segment) {
return -1;
}
else if (fx.segment > fy.segment) {
return 1;
}
else if (fx.address < fy.address) {
return -1;
}
else if (fx.address > fy.address) {
return 1;
}
else {
return 0;
}
}
}
internal class PdbFunctionsByToken : IComparer
{
public int Compare(Object x, Object y)
{
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.token < fy.token) {
return -1;
}
else if (fx.token > fy.token) {
return 1;
}
else {
return 0;
}
}
}
}
}
#endif
| |
//Copyright 2014 Spin Services Limited
//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 Moq;
using NUnit.Framework;
using SS.Integration.Adapter.Exceptions;
using SS.Integration.Adapter.MarketRules.Interfaces;
using SS.Integration.Adapter.Model;
using SS.Integration.Adapter.Model.Interfaces;
namespace SS.Integration.Adapter.Tests
{
[TestFixture]
public class SuspensionManagerTests
{
#region Constants
public const string SUSPENSION_MANAGER_CATEGORY = nameof(SuspensionManager);
#endregion
#region Properties
protected Mock<IStateProvider> StateProviderMock;
protected Mock<IAdapterPlugin> AdapterPluginMock;
#endregion
#region SetUp
[SetUp]
public void SetupTest()
{
StateProviderMock = new Mock<IStateProvider>();
AdapterPluginMock = new Mock<IAdapterPlugin>();
}
#endregion
#region Test Methods
/// <summary>
/// This test ensures we skip fixture suspension when markets state null
/// </summary>
[Test]
[Category(SUSPENSION_MANAGER_CATEGORY)]
public void SkipSuspensionWhenMarketsStateNull()
{
//Arrange
var fixture1 = new Fixture { Id = "fixture1Id" };
StateProviderMock.Setup(a =>
a.GetMarketsState(It.IsAny<string>()))
.Returns((IMarketStateCollection)null);
var suspensionManager =
new SuspensionManager(
StateProviderMock.Object,
AdapterPluginMock.Object);
//Act
suspensionManager.Suspend(fixture1);
//Assert
StateProviderMock.Verify(o =>
o.GetMarketsState(It.Is<string>(f => f.Equals(fixture1.Id))),
Times.Once);
AdapterPluginMock.Verify(o =>
o.Suspend(It.Is<string>(f => f.Equals(fixture1.Id))),
Times.Never);
}
/// <summary>
/// This test ensures we correctly execute fixture suspension
/// </summary>
[Test]
[Category(SUSPENSION_MANAGER_CATEGORY)]
public void SuspendFixtureTest()
{
//Arrange
var fixture1 = new Fixture { Id = "fixture1Id" };
var marketStateCollectionMock = new Mock<IMarketStateCollection>();
marketStateCollectionMock.SetupGet(o => o.FixtureId).Returns(fixture1.Id);
StateProviderMock.Setup(a =>
a.GetMarketsState(It.IsAny<string>()))
.Returns(marketStateCollectionMock.Object);
var suspensionManager =
new SuspensionManager(
StateProviderMock.Object,
AdapterPluginMock.Object);
//Act
suspensionManager.Suspend(fixture1, SuspensionReason.FIXTURE_DISPOSING);
suspensionManager.Suspend(fixture1, SuspensionReason.SUSPENSION);
suspensionManager.Suspend(fixture1, SuspensionReason.DISCONNECT_EVENT);
suspensionManager.Suspend(fixture1, SuspensionReason.FIXTURE_ERRORED);
suspensionManager.Suspend(fixture1, SuspensionReason.FIXTURE_DELETED);
//Assert
StateProviderMock.Verify(o =>
o.GetMarketsState(It.Is<string>(f => f.Equals(fixture1.Id))),
Times.Exactly(5));
AdapterPluginMock.Verify(o =>
o.Suspend(It.Is<string>(f => f.Equals(fixture1.Id))),
Times.Exactly(4));
AdapterPluginMock.Verify(o =>
o.ProcessStreamUpdate(It.Is<Fixture>(f => f.Id.Equals(fixture1.Id)), false),
Times.Once);
AdapterPluginMock.Verify(o =>
o.ProcessStreamUpdate(It.IsAny<Fixture>(), true),
Times.Never);
}
/// <summary>
/// This test ensures we throw plugin exception when plugin throws error
/// </summary>
[Test]
[Category(SUSPENSION_MANAGER_CATEGORY)]
public void SuspendFixtureThrowsPluginExceptionTest()
{
//Arrange
var fixture1 = new Fixture { Id = "fixture1Id" };
var marketStateCollectionMock = new Mock<IMarketStateCollection>();
marketStateCollectionMock.SetupGet(o => o.FixtureId).Returns(fixture1.Id);
StateProviderMock.Setup(a =>
a.GetMarketsState(It.IsAny<string>()))
.Returns(marketStateCollectionMock.Object);
AdapterPluginMock.Setup(o => o.Suspend(It.Is<string>(f => f.Equals(fixture1.Id)))).Throws<Exception>();
var suspensionManager =
new SuspensionManager(
StateProviderMock.Object,
AdapterPluginMock.Object);
//Act
void SuspendCall() => suspensionManager.Suspend(fixture1);
//Assert
Assert.Throws<PluginException>(SuspendCall);
StateProviderMock.Verify(o =>
o.GetMarketsState(It.Is<string>(f => f.Equals(fixture1.Id))),
Times.Once);
AdapterPluginMock.Verify(o =>
o.Suspend(It.Is<string>(f => f.Equals(fixture1.Id))),
Times.Once);
}
/// <summary>
/// This test ensures we correctly execute fixture unsuspention
/// </summary>
[Test]
[Category(SUSPENSION_MANAGER_CATEGORY)]
public void UnsuspendFixtureTest()
{
//Arrange
var fixture1 = new Fixture { Id = "fixture1Id" };
var marketStateMock = new Mock<IMarketState>();
marketStateMock.SetupGet(o => o.Id).Returns("market1Id");
marketStateMock.SetupGet(o => o.IsForcedSuspended).Returns(true);
var marketStateCollectionMock = new Mock<IUpdatableMarketStateCollection>();
marketStateCollectionMock.SetupGet(o => o.FixtureId).Returns(fixture1.Id);
marketStateCollectionMock.SetupGet(o => o.Markets).Returns(new[] { marketStateMock.Object.Id });
marketStateCollectionMock.SetupGet(o => o[It.IsAny<string>()]).Returns(marketStateMock.Object);
StateProviderMock.Setup(a =>
a.GetMarketsState(It.IsAny<string>()))
.Returns(marketStateCollectionMock.Object);
var suspensionManager =
new SuspensionManager(
StateProviderMock.Object,
AdapterPluginMock.Object);
//Act
suspensionManager.Unsuspend(fixture1);
//Assert
StateProviderMock.Verify(o =>
o.GetMarketsState(It.Is<string>(f => f.Equals(fixture1.Id))),
Times.Once);
AdapterPluginMock.Verify(o =>
o.UnSuspend(It.Is<Fixture>(f => f.Id.Equals(fixture1.Id))),
Times.Once);
AdapterPluginMock.Verify(o =>
o.ProcessStreamUpdate(It.Is<Fixture>(f => f.Id.Equals(fixture1.Id)), false),
Times.Once);
AdapterPluginMock.Verify(o =>
o.ProcessStreamUpdate(It.IsAny<Fixture>(), true),
Times.Never);
marketStateCollectionMock.Verify(o =>
o.OnMarketsForcedUnsuspension(It.IsAny<IEnumerable<IMarketState>>()),
Times.Once);
}
/// <summary>
/// This test ensures we throw plugin exception when plugin throws error
/// </summary>
[Test]
[Category(SUSPENSION_MANAGER_CATEGORY)]
public void UnsuspendFixtureThrowsPluginExceptionTest()
{
//Arrange
var fixture1 = new Fixture { Id = "fixture1Id" };
var marketStateMock = new Mock<IMarketState>();
marketStateMock.SetupGet(o => o.Id).Returns("market1Id");
marketStateMock.SetupGet(o => o.IsForcedSuspended).Returns(true);
var marketStateCollectionMock = new Mock<IUpdatableMarketStateCollection>();
marketStateCollectionMock.SetupGet(o => o.FixtureId).Returns(fixture1.Id);
marketStateCollectionMock.SetupGet(o => o.Markets).Returns(new[] { marketStateMock.Object.Id });
marketStateCollectionMock.SetupGet(o => o[It.IsAny<string>()]).Returns(marketStateMock.Object);
StateProviderMock.Setup(a =>
a.GetMarketsState(It.IsAny<string>()))
.Returns(marketStateCollectionMock.Object);
AdapterPluginMock.Setup(o => o.UnSuspend(It.Is<Fixture>(f => f.Id.Equals(fixture1.Id)))).Throws<Exception>();
var suspensionManager =
new SuspensionManager(
StateProviderMock.Object,
AdapterPluginMock.Object);
//Act
void UnsuspendCall() => suspensionManager.Unsuspend(fixture1);
//Assert
Assert.Throws<PluginException>(UnsuspendCall);
StateProviderMock.Verify(o =>
o.GetMarketsState(It.Is<string>(f => f.Equals(fixture1.Id))),
Times.Once);
AdapterPluginMock.Verify(o =>
o.UnSuspend(It.Is<Fixture>(f => f.Id.Equals(fixture1.Id))),
Times.Once);
AdapterPluginMock.Verify(o =>
o.ProcessStreamUpdate(It.Is<Fixture>(f => f.Id.Equals(fixture1.Id)), false),
Times.Once);
AdapterPluginMock.Verify(o =>
o.ProcessStreamUpdate(It.IsAny<Fixture>(), true),
Times.Never);
marketStateCollectionMock.Verify(o =>
o.OnMarketsForcedUnsuspension(It.IsAny<IEnumerable<IMarketState>>()),
Times.Once);
}
#endregion
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="IndexCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------
// <summary>
// </summary>
// ---------------------------------------------------------------------
namespace Microsoft.Database.Isam
{
using System;
using System.Collections;
using System.Globalization;
using Microsoft.Isam.Esent.Interop;
/// <summary>
/// A class containing information about the indices on a particular table.
/// It is usually used for metadata discovery.
/// </summary>
public class IndexCollection : DictionaryBase, IEnumerable
{
/// <summary>
/// The database
/// </summary>
private readonly IsamDatabase database;
/// <summary>
/// The table name
/// </summary>
private readonly string tableName;
/// <summary>
/// The cached index definition
/// </summary>
private string cachedIndexDefinition = null;
/// <summary>
/// The index definition
/// </summary>
private IndexDefinition indexDefinition = null;
/// <summary>
/// The index update identifier
/// </summary>
private long indexUpdateID = 0;
/// <summary>
/// The read only
/// </summary>
private bool readOnly = false;
/// <summary>
/// Initializes a new instance of the <see cref="IndexCollection"/> class.
/// </summary>
public IndexCollection()
{
this.database = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="IndexCollection"/> class.
/// </summary>
/// <param name="database">The database.</param>
/// <param name="tableName">Name of the table.</param>
internal IndexCollection(IsamDatabase database, string tableName)
{
this.database = database;
this.tableName = tableName;
this.readOnly = true;
}
/// <summary>
/// Gets the names.
/// </summary>
/// <value>
/// The names.
/// </value>
/// <exception cref="System.InvalidOperationException">the names of the indices in this index collection cannot be enumerated in this manner when accessing the table definition of an existing table</exception>
public ICollection Names
{
get
{
if (this.database != null)
{
// CONSIDER: should we provide an ICollection of our index names to avoid this wart?
throw new InvalidOperationException(
"the names of the indices in this index collection cannot be enumerated in this manner when accessing the table definition of an existing table");
}
else
{
return this.Dictionary.Keys;
}
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary" /> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.IDictionary" /> object has a fixed size; otherwise, false.</returns>
public bool IsFixedSize
{
get
{
return this.readOnly;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary" /> object is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.IDictionary" /> object is read-only; otherwise, false.</returns>
public bool IsReadOnly
{
get
{
return this.readOnly;
}
}
/// <summary>
/// Sets a value indicating whether [read only].
/// </summary>
/// <value>
/// <c>true</c> if [read only]; otherwise, <c>false</c>.
/// </value>
internal bool ReadOnly
{
set
{
this.readOnly = value;
}
}
/// <summary>
/// Fetches the Index Definition for the specified index name.
/// </summary>
/// <value>
/// The <see cref="IndexDefinition"/> corresponding to <paramref name="indexName"/>.
/// </value>
/// <param name="indexName">Name of the index.</param>
/// <returns>An <see cref="IndexDefinition"/> object.</returns>
public IndexDefinition this[string indexName]
{
get
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
JET_SESID sesid = this.database.IsamSession.Sesid;
if (this.cachedIndexDefinition != indexName.ToLower(CultureInfo.InvariantCulture)
|| this.indexUpdateID != DatabaseCommon.SchemaUpdateID)
{
JET_INDEXLIST indexList;
Api.JetGetIndexInfo(
sesid,
this.database.Dbid,
this.tableName,
indexName,
out indexList,
JET_IdxInfo.List);
try
{
this.indexDefinition = IndexDefinition.Load(this.database, this.tableName, indexList);
}
finally
{
Api.JetCloseTable(sesid, indexList.tableid);
}
this.cachedIndexDefinition = indexName.ToLower(CultureInfo.InvariantCulture);
this.indexUpdateID = DatabaseCommon.SchemaUpdateID;
}
return this.indexDefinition;
}
}
else
{
return (IndexDefinition)Dictionary[indexName.ToLower(CultureInfo.InvariantCulture)];
}
}
set
{
this.Dictionary[indexName.ToLower(CultureInfo.InvariantCulture)] = value;
}
}
/// <summary>
/// Fetches an enumerator containing all the indices on this table.
/// </summary>
/// <returns>An enumerator containing all the indices on this table.</returns>
/// <remarks>
/// This is the type safe version that may not work in other CLR
/// languages.
/// </remarks>
public new IndexEnumerator GetEnumerator()
{
if (this.database != null)
{
return new IndexEnumerator(this.database, this.tableName);
}
else
{
return new IndexEnumerator(this.Dictionary.GetEnumerator());
}
}
/// <summary>
/// Adds the specified index definition.
/// </summary>
/// <param name="indexDefinition">The index definition.</param>
public void Add(IndexDefinition indexDefinition)
{
this.Dictionary.Add(indexDefinition.Name.ToLower(CultureInfo.InvariantCulture), indexDefinition);
}
/// <summary>
/// Determines if the table contains an index with the given name.
/// </summary>
/// <param name="indexName">Name of the index.</param>
/// <returns>Whether the collection contains an index of name <paramref name="indexName"/>.</returns>
public bool Contains(string indexName)
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
bool exists = false;
try
{
int density;
Api.JetGetIndexInfo(
this.database.IsamSession.Sesid,
this.database.Dbid,
this.tableName,
indexName,
out density,
JET_IdxInfo.SpaceAlloc);
exists = true;
}
catch (EsentIndexNotFoundException)
{
}
return exists;
}
}
else
{
return Dictionary.Contains(indexName.ToLower(CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Removes the specified index name.
/// </summary>
/// <param name="indexName">Name of the index.</param>
public void Remove(string indexName)
{
Dictionary.Remove(indexName.ToLower(CultureInfo.InvariantCulture));
}
/// <summary>
/// Fetches an enumerator containing all the indices on this table
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
/// <remarks>
/// This is the standard version that will work with other CLR
/// languages.
/// </remarks>
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)this.GetEnumerator();
}
/// <summary>
/// Performs additional custom processes before clearing the contents of the <see cref="T:System.Collections.DictionaryBase" /> instance.
/// </summary>
protected override void OnClear()
{
this.CheckReadOnly();
}
/// <summary>
/// Performs additional custom processes before inserting a new element into the <see cref="T:System.Collections.DictionaryBase" /> instance.
/// </summary>
/// <param name="key">The key of the element to insert.</param>
/// <param name="value">The value of the element to insert.</param>
protected override void OnInsert(object key, object value)
{
this.CheckReadOnly();
}
/// <summary>
/// Performs additional custom processes before removing an element from the <see cref="T:System.Collections.DictionaryBase" /> instance.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <param name="value">The value of the element to remove.</param>
protected override void OnRemove(object key, object value)
{
this.CheckReadOnly();
}
/// <summary>
/// Performs additional custom processes before setting a value in the <see cref="T:System.Collections.DictionaryBase" /> instance.
/// </summary>
/// <param name="key">The key of the element to locate.</param>
/// <param name="oldValue">The old value of the element associated with <paramref name="key" />.</param>
/// <param name="newValue">The new value of the element associated with <paramref name="key" />.</param>
protected override void OnSet(object key, object oldValue, object newValue)
{
this.CheckReadOnly();
}
/// <summary>
/// Performs additional custom processes when validating the element with the specified key and value.
/// </summary>
/// <param name="key">The key of the element to validate.</param>
/// <param name="value">The value of the element to validate.</param>
/// <exception cref="System.ArgumentException">
/// key must be of type System.String;key
/// or
/// value must be of type IndexDefinition;value
/// or
/// key must match value.Name;key
/// </exception>
protected override void OnValidate(object key, object value)
{
if (!(key is string))
{
throw new ArgumentException("key must be of type System.String", "key");
}
if (!(value is IndexDefinition))
{
throw new ArgumentException("value must be of type IndexDefinition", "value");
}
if (((string)key).ToLower(CultureInfo.InvariantCulture)
!= ((IndexDefinition)value).Name.ToLower(CultureInfo.InvariantCulture))
{
throw new ArgumentException("key must match value.Name", "key");
}
}
/// <summary>
/// Checks the read only.
/// </summary>
/// <exception cref="System.NotSupportedException">this index collection cannot be changed</exception>
private void CheckReadOnly()
{
if (this.readOnly)
{
throw new NotSupportedException("this index collection cannot be changed");
}
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//using BitMatrix = com.google.zxing.common.BitMatrix;
//using Decoder = com.google.zxing.microqrcode.decoder.Decoder;
//using DecoderResult = com.google.zxing.common.DecoderResult;
//using Detector = com.google.zxing.microqrcode.detector.Detector;
//using DetectorResult = com.google.zxing.common.DetectorResult;
using System;
using System.Collections.Generic;
using ZXing.Common;
using ZXing.MicroQrCode.Internal;
namespace ZXing.MicroQrCode
{
/// <summary>
/// This implementation can detect and decode Micro QR Codes in an image.
/// </summary>
/// <author>
/// Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public class MicroQRCodeReader : Reader
{
/// <summary>
/// Gets the decoder.
/// </summary>
/// <returns></returns>
protected Decoder getDecoder()
{
return decoder;
}
//UPGRADE_NOTE: Final was removed from the declaration of 'NO_POINTS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0];
//UPGRADE_NOTE: Final was removed from the declaration of 'decoder '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private Decoder decoder = new Decoder();
/// <summary>
/// Locates and decodes a Micro QR code in an image.
///
/// <returns>a String representing the content encoded by the Micro QR code</returns>
/// </summary>
public Result decode(BinaryBitmap image)
{
return decode(image, null);
}
public virtual Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
{
DecoderResult decoderResult;
ResultPoint[] points;
//This was added to check if the barcode could be decoded without the detector.
//The detector logic was never written and it does not function.
//hints.Add(DecodeHintType.PURE_BARCODE,true);
if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
{
var bits = extractPureBits(image.BlackMatrix);
if (bits == null)
return null;
decoderResult = decoder.decode(bits, hints);
points = NO_POINTS;
}
else
{
//throw new System.NotImplementedException("Detector(image.BlackMatrix).detect(hints) Not Implemented...");
DetectorResult detectorResult = new Detector(image.BlackMatrix).detect(hints);
if (detectorResult == null)
return null;
decoderResult = decoder.decode(detectorResult.Bits, hints);
points = detectorResult.Points;
}
if (decoderResult != null && decoderResult.Text != null && decoderResult.RawBytes != null)
{
Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points,
BarcodeFormat.MICRO_QR_CODE);
if (decoderResult.ByteSegments != null)
{
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.ByteSegments);
}
if (decoderResult.ECLevel != null)
{
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.ECLevel.ToString());
}
return result;
}
return null;
}
/// <summary>
/// Resets any internal state the implementation has after a decode, to prepare it
/// for reuse.
/// </summary>
public void reset()
{
// do nothing
}
/// <summary>
/// This method detects a code in a "pure" image -- that is, pure monochrome image
/// which contains only an unrotated, unskewed, image of a code, with some white border
/// around it. This is a specialized method that works exceptionally fast in this special
/// case.
///
/// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" />
/// </summary>
private static BitMatrix extractPureBits(BitMatrix image)
{
int[] leftTopBlack = image.getTopLeftOnBit();
int[] rightBottomBlack = image.getBottomRightOnBit();
if (leftTopBlack == null || rightBottomBlack == null)
{
return null;
}
float moduleSize;
if (!MicroQRCodeReader.moduleSize(leftTopBlack, image, out moduleSize))
return null;
int top = leftTopBlack[1];
int bottom = rightBottomBlack[1];
int left = leftTopBlack[0];
int right = rightBottomBlack[0];
// Sanity check!
if (left >= right || top >= bottom)
{
return null;
}
if (bottom - top != right - left)
{
// Special case, where bottom-right module wasn't black so we found something else in the last row
// Assume it's a square, so use height as the width
right = left + (bottom - top);
if (right >= image.Width)
{
// Abort if that would not make sense -- off image
return null;
}
}
int matrixWidth = (int)Math.Round((right - left + 1) / moduleSize);
int matrixHeight = (int)Math.Round((bottom - top + 1) / moduleSize);
if (matrixWidth <= 0 || matrixHeight <= 0)
{
return null;
}
if (matrixHeight != matrixWidth)
{
// Only possibly decode square regions
return null;
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int nudge = (int)(moduleSize / 2.0f);
top += nudge;
left += nudge;
// But careful that this does not sample off the edge
// "right" is the farthest-right valid pixel location -- right+1 is not necessarily
// This is positive by how much the inner x loop below would be too large
int nudgedTooFarRight = left + (int)((matrixWidth - 1) * moduleSize) - right;
if (nudgedTooFarRight > 0)
{
if (nudgedTooFarRight > nudge)
{
// Neither way fits; abort
return null;
}
left -= nudgedTooFarRight;
}
// See logic above
int nudgedTooFarDown = top + (int)((matrixHeight - 1) * moduleSize) - bottom;
if (nudgedTooFarDown > 0)
{
if (nudgedTooFarDown > nudge)
{
// Neither way fits; abort
return null;
}
top -= nudgedTooFarDown;
}
// Now just read off the bits
BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
for (int y = 0; y < matrixHeight; y++)
{
int iOffset = top + (int)(y * moduleSize);
for (int x = 0; x < matrixWidth; x++)
{
if (image[left + (int)(x * moduleSize), iOffset])
{
bits[x, y] = true;
}
}
}
return bits;
}
private static bool moduleSize(int[] leftTopBlack, BitMatrix image, out float msize)
{
int height = image.Height;
int width = image.Width;
int x = leftTopBlack[0];
int y = leftTopBlack[1];
bool inBlack = true;
int transitions = 0;
while (x < width && y < height)
{
if (inBlack != image[x, y])
{
if (++transitions == 5)
{
break;
}
inBlack = !inBlack;
}
x++;
y++;
}
if (x == width || y == height)
{
msize = 0.0f;
return false;
}
msize = (x - leftTopBlack[0]) / 7.0f;
return true;
}
/// <summary>
/// This method detects a code in a "pure" image -- that is, pure monochrome image
/// which contains only an unrotated, unskewed, image of a code, with some white border
/// around it. This is a specialized method that works exceptionally fast in this special
/// case.
///
/// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" />
/// </summary>
private static BitMatrix extractPureBits(BitMatrix image, int topLeft, int bottomRight)
{
int[] leftTopBlack = new int[2] {topLeft, topLeft};
int[] rightBottomBlack = new int[2] {bottomRight, bottomRight};
if (leftTopBlack == null || rightBottomBlack == null)
{
return null;
}
float moduleSize;
if (!MicroQRCodeReader.moduleSize(leftTopBlack, image, out moduleSize))
return null;
int top = leftTopBlack[1];
int bottom = rightBottomBlack[1];
int left = leftTopBlack[0];
int right = rightBottomBlack[0];
// Sanity check!
if (left >= right || top >= bottom)
{
return null;
}
if (bottom - top != right - left)
{
// Special case, where bottom-right module wasn't black so we found something else in the last row
// Assume it's a square, so use height as the width
right = left + (bottom - top);
if (right >= image.Width)
{
// Abort if that would not make sense -- off image
return null;
}
}
int matrixWidth = (int) Math.Round((right - left + 1)/moduleSize);
int matrixHeight = (int) Math.Round((bottom - top + 1)/moduleSize);
if (matrixWidth <= 0 || matrixHeight <= 0)
{
return null;
}
if (matrixHeight != matrixWidth)
{
// Only possibly decode square regions
return null;
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int nudge = (int) (moduleSize/2.0f);
top += nudge;
left += nudge;
// But careful that this does not sample off the edge
// "right" is the farthest-right valid pixel location -- right+1 is not necessarily
// This is positive by how much the inner x loop below would be too large
int nudgedTooFarRight = left + (int) ((matrixWidth - 1)*moduleSize) - right;
if (nudgedTooFarRight > 0)
{
if (nudgedTooFarRight > nudge)
{
// Neither way fits; abort
return null;
}
left -= nudgedTooFarRight;
}
// See logic above
int nudgedTooFarDown = top + (int) ((matrixHeight - 1)*moduleSize) - bottom;
if (nudgedTooFarDown > 0)
{
if (nudgedTooFarDown > nudge)
{
// Neither way fits; abort
return null;
}
top -= nudgedTooFarDown;
}
// Now just read off the bits
BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
for (int y = 0; y < matrixHeight; y++)
{
int iOffset = top + (int) (y*moduleSize);
for (int x = 0; x < matrixWidth; x++)
{
if (image[left + (int) (x*moduleSize), iOffset])
{
bits[x, y] = true;
}
}
}
return bits;
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;
namespace Mono.Cecil.Mdb {
public sealed class MdbWriterProvider : ISymbolWriterProvider {
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
{
Mixin.CheckModule (module);
Mixin.CheckFileName (fileName);
return new MdbWriter (module, fileName);
}
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
{
throw new NotImplementedException ();
}
}
public sealed class MdbWriter : ISymbolWriter {
readonly ModuleDefinition module;
readonly MonoSymbolWriter writer;
readonly Dictionary<string, SourceFile> source_files;
public MdbWriter (ModuleDefinition module, string assembly)
{
this.module = module;
this.writer = new MonoSymbolWriter (assembly);
this.source_files = new Dictionary<string, SourceFile> ();
}
public ISymbolReaderProvider GetReaderProvider ()
{
return new MdbReaderProvider ();
}
SourceFile GetSourceFile (Document document)
{
var url = document.Url;
SourceFile source_file;
if (source_files.TryGetValue (url, out source_file))
return source_file;
var entry = writer.DefineDocument (url, null, document.Hash != null && document.Hash.Length == 16 ? document.Hash : null);
var compile_unit = writer.DefineCompilationUnit (entry);
source_file = new SourceFile (compile_unit, entry);
source_files.Add (url, source_file);
return source_file;
}
void Populate (Collection<SequencePoint> sequencePoints, int [] offsets,
int [] startRows, int [] endRows, int [] startCols, int [] endCols, out SourceFile file)
{
SourceFile source_file = null;
for (int i = 0; i < sequencePoints.Count; i++) {
var sequence_point = sequencePoints [i];
offsets [i] = sequence_point.Offset;
if (source_file == null)
source_file = GetSourceFile (sequence_point.Document);
startRows [i] = sequence_point.StartLine;
endRows [i] = sequence_point.EndLine;
startCols [i] = sequence_point.StartColumn;
endCols [i] = sequence_point.EndColumn;
}
file = source_file;
}
public void Write (MethodDebugInformation info)
{
var method = new SourceMethod (info.method);
var sequence_points = info.SequencePoints;
int count = sequence_points.Count;
if (count == 0)
return;
var offsets = new int [count];
var start_rows = new int [count];
var end_rows = new int [count];
var start_cols = new int [count];
var end_cols = new int [count];
SourceFile file;
Populate (sequence_points, offsets, start_rows, end_rows, start_cols, end_cols, out file);
var builder = writer.OpenMethod (file.CompilationUnit, 0, method);
for (int i = 0; i < count; i++) {
builder.MarkSequencePoint (
offsets [i],
file.CompilationUnit.SourceFile,
start_rows [i],
start_cols [i],
end_rows [i],
end_cols [i],
false);
}
if (info.scope != null)
WriteRootScope (info.scope, info);
writer.CloseMethod ();
}
void WriteRootScope (ScopeDebugInformation scope, MethodDebugInformation info)
{
WriteScopeVariables (scope);
if (scope.HasScopes)
WriteScopes (scope.Scopes, info);
}
void WriteScope (ScopeDebugInformation scope, MethodDebugInformation info)
{
writer.OpenScope (scope.Start.Offset);
WriteScopeVariables (scope);
if (scope.HasScopes)
WriteScopes (scope.Scopes, info);
writer.CloseScope (scope.End.IsEndOfMethod ? info.code_size : scope.End.Offset);
}
void WriteScopes (Collection<ScopeDebugInformation> scopes, MethodDebugInformation info)
{
for (int i = 0; i < scopes.Count; i++)
WriteScope (scopes [i], info);
}
void WriteScopeVariables (ScopeDebugInformation scope)
{
if (!scope.HasVariables)
return;
foreach (var variable in scope.variables)
if (!string.IsNullOrEmpty (variable.Name))
writer.DefineLocalVariable (variable.Index, variable.Name);
}
public ImageDebugHeader GetDebugHeader ()
{
return new ImageDebugHeader ();
}
public void Write ()
{
// Can't write it here since we need the final module MVID - which is only computed
// after the entire image of the assembly is written (since it's computed from the hash of that)
}
public void Dispose ()
{
writer.WriteSymbolFile (module.Mvid);
}
class SourceFile : ISourceFile {
readonly CompileUnitEntry compilation_unit;
readonly SourceFileEntry entry;
public SourceFileEntry Entry {
get { return entry; }
}
public CompileUnitEntry CompilationUnit {
get { return compilation_unit; }
}
public SourceFile (CompileUnitEntry comp_unit, SourceFileEntry entry)
{
this.compilation_unit = comp_unit;
this.entry = entry;
}
}
class SourceMethod : IMethodDef {
readonly MethodDefinition method;
public string Name {
get { return method.Name; }
}
public int Token {
get { return method.MetadataToken.ToInt32 (); }
}
public SourceMethod (MethodDefinition method)
{
this.method = method;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Drawing.Printing;
using System.Xml;
using fyiReporting.RDL;
using fyiReporting.RdlDesign.Resources;
using fyiReporting.RdlViewer;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for RdlEditPreview.
/// </summary>
internal class RdlEditPreview : System.Windows.Forms.UserControl
{
private System.Windows.Forms.TabControl tcEHP;
private System.Windows.Forms.TabPage tpEditor;
private System.Windows.Forms.TabPage tpBrowser;
private System.Windows.Forms.RichTextBox tbEditor;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private fyiReporting.RdlViewer.RdlViewer rdlPreview;
private System.Windows.Forms.TabPage tpDesign;
private DesignCtl dcDesign;
public delegate void RdlChangeHandler(object sender, EventArgs e);
public event RdlChangeHandler OnRdlChanged;
public event DesignCtl.HeightEventHandler OnHeightChanged;
public event RdlChangeHandler OnSelectionChanged;
public event RdlChangeHandler OnSelectionMoved;
public event RdlChangeHandler OnReportItemInserted;
public event RdlChangeHandler OnDesignTabChanged;
public event DesignCtl.OpenSubreportEventHandler OnOpenSubreport;
// When toggling between the items we need to track who has latest changes
string _DesignChanged; // last designer that triggered change
string _CurrentTab="design";
private DesignEditLines pbLines;
private DesignRuler dcTopRuler;
private DesignRuler dcLeftRuler;
int filePosition=0; // file position; for use with search
public RdlEditPreview()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
pbLines.Editor = tbEditor;
rdlPreview.Zoom=1; // force default zoom to 1
// initialize the design tab
dcTopRuler = new DesignRuler();
dcLeftRuler = new DesignRuler();
dcLeftRuler.Vertical = true; // need to set before setting Design property
dcDesign = new DesignCtl();
dcTopRuler.Design = dcDesign; // associate rulers with design ctl
dcLeftRuler.Design = dcDesign;
tpDesign.Controls.Add(dcTopRuler);
tpDesign.Controls.Add(dcLeftRuler);
tpDesign.Controls.Add(dcDesign);
// Top ruler
dcTopRuler.Height = 14;
dcTopRuler.Width = tpDesign.Width;
dcTopRuler.Dock = DockStyle.Top;
dcTopRuler.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
dcTopRuler.Enabled = false;
// Left ruler
dcLeftRuler.Width = 14;
dcLeftRuler.Height = tpDesign.Height;
dcLeftRuler.Dock = DockStyle.Left;
dcLeftRuler.Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top;
dcLeftRuler.Enabled = false;
dcTopRuler.Offset = dcLeftRuler.Width;
dcLeftRuler.Offset = dcTopRuler.Height;
// dcDesign.Dock = System.Windows.Forms.DockStyle.Bottom;
dcDesign.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
dcDesign.Location = new System.Drawing.Point(dcLeftRuler.Width, dcTopRuler.Height);
dcDesign.Name = "dcDesign";
dcDesign.Size = new System.Drawing.Size(tpDesign.Width-dcLeftRuler.Width, tpDesign.Height-dcTopRuler.Height);
dcDesign.TabIndex = 0;
dcDesign.ReportChanged += new System.EventHandler(dcDesign_ReportChanged);
dcDesign.HeightChanged += new DesignCtl.HeightEventHandler(dcDesign_HeightChanged);
dcDesign.SelectionChanged += new System.EventHandler(dcDesign_SelectionChanged);
dcDesign.SelectionMoved += new System.EventHandler(dcDesign_SelectionMoved);
dcDesign.ReportItemInserted += new System.EventHandler(dcDesign_ReportItemInserted);
dcDesign.OpenSubreport += new DesignCtl.OpenSubreportEventHandler(dcDesign_OpenSubreport);
tbEditor.SelectionChanged +=new EventHandler(tbEditor_SelectionChanged);
// adjust size of line box by measuring a large #
#if !MONO
using (Graphics g = this.CreateGraphics())
{
this.pbLines.Width = (int) (g.MeasureString("99999", tbEditor.Font).Width);
}
#endif
}
internal DesignCtl DesignCtl
{
get {return dcDesign;}
}
internal RdlViewer.RdlViewer PreviewCtl
{
get { return rdlPreview; }
}
internal DesignXmlDraw DrawCtl
{
get {return dcDesign.DrawCtl;}
}
public XmlDocument ReportDocument
{
get {return dcDesign.ReportDocument;}
}
internal string CurrentTab { get { return _CurrentTab; } }
internal string DesignTab
{
get {return _CurrentTab;}
set
{
switch (value)
{
case "design":
tcEHP.SelectedIndex = 0;
break;
case "edit":
tcEHP.SelectedIndex = 1;
break;
case "preview":
tcEHP.SelectedIndex = 2;
break;
}
}
}
internal void SetFocus()
{
switch (_CurrentTab)
{
case "edit":
tbEditor.Focus();
break;
case "preview":
rdlPreview.Focus();
break;
case "design":
dcDesign.SetFocus();
break;
}
}
internal void ShowEditLines(bool bShow)
{
pbLines.Visible = bShow;
}
internal void ShowPreviewWaitDialog(bool bShow)
{
rdlPreview.ShowWaitDialog = bShow;
}
internal bool ShowReportItemOutline
{
get {return dcDesign.ShowReportItemOutline;}
set {dcDesign.ShowReportItemOutline = value;}
}
override public string Text
{
get
{
if (_CurrentTab == "design")
return dcDesign.ReportSource;
else
return tbEditor.Text;
}
set
{
if (_CurrentTab == "edit")
tbEditor.Text = value;
else
{
dcDesign.ReportSource = value;
}
if (_CurrentTab == "preview")
{
_CurrentTab = "design";
tcEHP.SelectedIndex = 0; // Force current tab to design
}
}
}
public StyleInfo SelectedStyle
{
get {return dcDesign.SelectedStyle;}
}
public string SelectionName
{
get {return dcDesign.SelectionName;}
}
public PointF SelectionPosition
{
get {return dcDesign.SelectionPosition;}
}
public SizeF SelectionSize
{
get {return dcDesign.SelectionSize;}
}
public void ApplyStyleToSelected(string name, string v)
{
if (_CurrentTab == "design")
dcDesign.ApplyStyleToSelected(name, v);
}
public void SetSelectedText(string v)
{
if (_CurrentTab == "design")
dcDesign.SetSelectedText(v);
}
public bool CanEdit
{
get
{
return _CurrentTab == "edit" || _CurrentTab == "design"? true: false;
}
}
public bool Modified
{
get
{
return tbEditor.Modified;
}
set
{
_DesignChanged = _CurrentTab;
tbEditor.Modified = value;
}
}
public string UndoDescription
{
get
{
return _CurrentTab == "design"? dcDesign.UndoDescription: "";
}
}
public void StartUndoGroup(string description)
{
if (_CurrentTab == "design")
dcDesign.StartUndoGroup(description);
}
public void EndUndoGroup(bool keepChanges)
{
if (_CurrentTab == "design")
dcDesign.EndUndoGroup(keepChanges);
}
public bool CanUndo
{
get
{
switch (_CurrentTab)
{
case "design":
return dcDesign.CanUndo;
case "edit":
return tbEditor.CanUndo;
default:
return false;
}
}
}
public bool CanRedo
{
get
{
switch (_CurrentTab)
{
case "design":
return dcDesign.CanUndo;
case "edit":
return tbEditor.CanUndo;
default:
return false;
}
}
}
public int SelectionLength
{
get
{
switch (_CurrentTab)
{
case "design":
return dcDesign.SelectionCount;
case "edit":
return tbEditor.SelectionLength;
case "preview":
return rdlPreview.CanCopy ? 1 : 0;
default:
return 0;
}
}
}
public string SelectedText
{
get
{
switch (_CurrentTab)
{
case "design":
return dcDesign.SelectedText;
case "edit":
return tbEditor.SelectedText;
case "preview":
return rdlPreview.SelectText;
default:
return "";
}
}
set
{
if (_CurrentTab == "edit" && tbEditor.SelectionLength >= 0)
tbEditor.SelectedText = value;
else if (_CurrentTab == "design" && value.Length == 0)
dcDesign.Delete();
}
}
public void CleanUp()
{
}
public void ClearUndo()
{
switch (_CurrentTab)
{
case "design":
dcDesign.ClearUndo();
break;
case "edit":
tbEditor.ClearUndo();
break;
default:
break;
}
}
public void Undo()
{
switch (_CurrentTab)
{
case "design":
dcDesign.Undo();
break;
case "edit":
tbEditor.Undo();
break;
default:
break;
}
}
public void Redo()
{
switch (_CurrentTab)
{
case "design":
dcDesign.Redo();
break;
case "edit":
tbEditor.Redo();
break;
default:
break;
}
}
public void Cut()
{
switch (_CurrentTab)
{
case "design":
dcDesign.Cut();
break;
case "edit":
tbEditor.Cut();
break;
default:
break;
}
}
public void Copy()
{
switch (_CurrentTab)
{
case "design":
dcDesign.Copy();
break;
case "edit":
tbEditor.Copy();
break;
case "preview":
rdlPreview.Copy();
break;
default:
break;
}
}
public void Clear()
{
switch (_CurrentTab)
{
case "design":
dcDesign.Clear();
break;
case "edit":
tbEditor.Clear();
break;
default:
break;
}
}
public void Paste()
{
switch (_CurrentTab)
{
case "design":
dcDesign.Paste();
break;
case "edit":
PasteText();
break;
default:
break;
}
}
void PasteText()
{
// The Paste function of RTF carries too much information; formatting etc.
// We only allow pasting of text information
IDataObject iData = Clipboard.GetDataObject();
if (iData == null)
return;
if (!iData.GetDataPresent(DataFormats.Text))
return;
string t = (string) iData.GetData(DataFormats.Text);
this.tbEditor.SelectedText = t;
}
public void SelectAll()
{
switch (_CurrentTab)
{
case "design":
dcDesign.SelectAll();
break;
case "edit":
tbEditor.SelectAll();
break;
default:
break;
}
}
public string CurrentInsert
{
get {return dcDesign.CurrentInsert; }
set
{
dcDesign.CurrentInsert = value;
}
}
public int CurrentLine
{
get
{
int v = tbEditor.SelectionStart;
return this.tbEditor.GetLineFromCharIndex(v)+1;
}
}
public int CurrentCh
{
get
{
int v = tbEditor.SelectionStart;
int line = tbEditor.GetLineFromCharIndex(v);
// Go back a character at a time until you hit previous line
int c=0;
while (--v >= 0 && line == tbEditor.GetLineFromCharIndex(v))
c++;
return c+1;
}
}
public bool SelectionTool
{
get
{
if (_CurrentTab == "preview")
{
return rdlPreview.SelectTool;
}
else
return false;
}
set
{
if (_CurrentTab == "preview")
{
rdlPreview.SelectTool = value;
}
}
}
/// <summary>
/// Zoom
/// </summary>
public float Zoom
{
get {return this.rdlPreview.Zoom;}
set {this.rdlPreview.Zoom = value;}
}
/// <summary>
/// ZoomMode
/// </summary>
public ZoomEnum ZoomMode
{
get {return this.rdlPreview.ZoomMode;}
set {this.rdlPreview.ZoomMode = value;}
}
public void FindNext(Control ctl, string str, bool matchCase)
{
FindNext(ctl, str, matchCase, true);
}
public void FindNext(Control ctl, string str, bool matchCase, bool showEndMsg)
{
if (_CurrentTab != "edit")
return;
try
{
int nStart = tbEditor.Find(str, filePosition,
matchCase ? RichTextBoxFinds.MatchCase : RichTextBoxFinds.None);
if (nStart < 0)
{
if (showEndMsg)
MessageBox.Show(ctl, Strings.RdlEditPreview_ShowI_ReachedEndDocument);
filePosition = 0;
return;
}
int nLength = str.Length;
tbEditor.ScrollToCaret();
filePosition = nStart + nLength;
}
catch (Exception ex)
{
MessageBox.Show(string.Format(Strings.RdlEditPreview_Show_ErrorFind, ex.Message), Strings.RdlEditPreview_Show_InternalError);
filePosition = 0; // restart at 0
}
}
public void ReplaceNext(Control ctl, string str, string strReplace, bool matchCase)
{
if (_CurrentTab != "edit")
return;
try
{
int nStart = tbEditor.Find(str, filePosition,
matchCase? RichTextBoxFinds.MatchCase: RichTextBoxFinds.None);
int nLength = str.Length;
tbEditor.Text = tbEditor.Text.Remove(nStart, nLength);
tbEditor.Text = tbEditor.Text.Insert(nStart, strReplace);
tbEditor.Modified = true;
tbEditor.ScrollToCaret();
}
catch (Exception e)
{
e.ToString();
MessageBox.Show(ctl, Strings.RdlEditPreview_ShowI_ReachedEndDocument);
filePosition = 0;
}
}
public void ReplaceAll(Control ctl, string str, string strReplace, bool matchCase)
{
if (_CurrentTab != "edit")
return;
try
{
int nStart = tbEditor.Text.IndexOf(str, filePosition);
int nLength = str.Length;
tbEditor.Select(nStart, nLength);
tbEditor.Text= tbEditor.Text.Replace(str, strReplace);
tbEditor.Modified = true;
tbEditor.ScrollToCaret();
filePosition = nStart+nLength;
}
catch (Exception e)
{
e.ToString();
MessageBox.Show(ctl, Strings.RdlEditPreview_ShowI_ReachedEndDocument);
filePosition = 0;
}
}
public void Goto(Control ctl, int nLine)
{
if (_CurrentTab != "edit")
return;
int offset = 0;
nLine = Math.Min(Math.Max(0, nLine - 1), tbEditor.Lines.Length - 1); // don't go off the ends
offset = tbEditor.GetFirstCharIndexFromLine(nLine);
// Before .Net 2
// for ( int i = 0; i < nLine - 1 && i < tbEditor.Lines.Length; ++i )
// offset += this.tbEditor.Lines[i].Length + 1;
Control savectl = this.ActiveControl;
tbEditor.Focus();
tbEditor.Select( offset, this.tbEditor.Lines[nLine].Length);
this.ActiveControl = savectl;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RdlEditPreview));
this.tcEHP = new System.Windows.Forms.TabControl();
this.tpDesign = new System.Windows.Forms.TabPage();
this.tpEditor = new System.Windows.Forms.TabPage();
this.tbEditor = new System.Windows.Forms.RichTextBox();
this.pbLines = new fyiReporting.RdlDesign.DesignEditLines();
this.tpBrowser = new System.Windows.Forms.TabPage();
this.rdlPreview = new fyiReporting.RdlViewer.RdlViewer();
this.tcEHP.SuspendLayout();
this.tpEditor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbLines)).BeginInit();
this.tpBrowser.SuspendLayout();
this.SuspendLayout();
//
// tcEHP
//
resources.ApplyResources(this.tcEHP, "tcEHP");
this.tcEHP.Controls.Add(this.tpDesign);
this.tcEHP.Controls.Add(this.tpEditor);
this.tcEHP.Controls.Add(this.tpBrowser);
this.tcEHP.Name = "tcEHP";
this.tcEHP.SelectedIndex = 0;
this.tcEHP.SelectedIndexChanged += new System.EventHandler(this.tcEHP_SelectedIndexChanged);
//
// tpDesign
//
resources.ApplyResources(this.tpDesign, "tpDesign");
this.tpDesign.Name = "tpDesign";
this.tpDesign.Tag = "design";
//
// tpEditor
//
resources.ApplyResources(this.tpEditor, "tpEditor");
this.tpEditor.Controls.Add(this.tbEditor);
this.tpEditor.Controls.Add(this.pbLines);
this.tpEditor.Name = "tpEditor";
this.tpEditor.Tag = "edit";
//
// tbEditor
//
this.tbEditor.AcceptsTab = true;
resources.ApplyResources(this.tbEditor, "tbEditor");
this.tbEditor.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.tbEditor.HideSelection = false;
this.tbEditor.Name = "tbEditor";
this.tbEditor.TextChanged += new System.EventHandler(this.tbEditor_TextChanged);
//
// pbLines
//
resources.ApplyResources(this.pbLines, "pbLines");
this.pbLines.Name = "pbLines";
this.pbLines.TabStop = false;
//
// tpBrowser
//
resources.ApplyResources(this.tpBrowser, "tpBrowser");
this.tpBrowser.Controls.Add(this.rdlPreview);
this.tpBrowser.Name = "tpBrowser";
this.tpBrowser.Tag = "preview";
//
// rdlPreview
//
resources.ApplyResources(this.rdlPreview, "rdlPreview");
this.rdlPreview.Cursor = System.Windows.Forms.Cursors.Default;
this.rdlPreview.Folder = null;
this.rdlPreview.HighlightAll = false;
this.rdlPreview.HighlightAllColor = System.Drawing.Color.Fuchsia;
this.rdlPreview.HighlightCaseSensitive = false;
this.rdlPreview.HighlightItemColor = System.Drawing.Color.Aqua;
this.rdlPreview.HighlightPageItem = null;
this.rdlPreview.HighlightText = null;
this.rdlPreview.Name = "rdlPreview";
this.rdlPreview.PageCurrent = 1;
this.rdlPreview.Parameters = "";
this.rdlPreview.ReportName = null;
this.rdlPreview.ScrollMode = fyiReporting.RdlViewer.ScrollModeEnum.Continuous;
this.rdlPreview.SelectTool = false;
this.rdlPreview.ShowFindPanel = false;
this.rdlPreview.ShowParameterPanel = true;
this.rdlPreview.ShowWaitDialog = true;
this.rdlPreview.SourceFile = null;
this.rdlPreview.SourceRdl = null;
this.rdlPreview.UseTrueMargins = true;
this.rdlPreview.Zoom = 0.5690382F;
this.rdlPreview.ZoomMode = fyiReporting.RdlViewer.ZoomEnum.FitWidth;
//
// RdlEditPreview
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.tcEHP);
this.Name = "RdlEditPreview";
this.tcEHP.ResumeLayout(false);
this.tpEditor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pbLines)).EndInit();
this.tpBrowser.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void tbEditor_TextChanged(object sender, System.EventArgs e)
{
_DesignChanged = "edit";
if (OnRdlChanged != null)
{
OnRdlChanged(this, e);
}
}
private void dcDesign_ReportChanged(object sender, System.EventArgs e)
{
_DesignChanged = "design";
tbEditor.Modified = true;
if (OnRdlChanged != null)
{
OnRdlChanged(this, e);
}
}
private void dcDesign_HeightChanged(object sender, HeightEventArgs e)
{
if (OnHeightChanged != null)
{
OnHeightChanged(this, e);
}
}
private void dcDesign_ReportItemInserted(object sender, System.EventArgs e)
{
if (OnReportItemInserted != null)
{
OnReportItemInserted(this, e);
}
}
private void dcDesign_OpenSubreport(object sender, SubReportEventArgs e)
{
if (OnOpenSubreport != null)
{
OnOpenSubreport(this, e);
}
}
private void dcDesign_SelectionChanged(object sender, System.EventArgs e)
{
if (OnSelectionChanged != null)
{
OnSelectionChanged(this, e);
}
}
private void dcDesign_SelectionMoved(object sender, System.EventArgs e)
{
if (OnSelectionMoved != null)
{
OnSelectionMoved(this, e);
}
}
private void tcEHP_SelectedIndexChanged(object sender, System.EventArgs e)
{
TabControl tc = (TabControl) sender;
string tag = (string) tc.TabPages[tc.SelectedIndex].Tag;
// Sync up the various pane whenever they switch so the editor is always accurate
switch (_DesignChanged)
{ // Sync up the editor in every case
case "design":
// sync up the editor
tbEditor.Text = dcDesign.ReportSource;
tbEditor.Modified = true;
break;
case "edit":
case "preview":
break;
default: // this can happen the first time
if (tbEditor.Text.Length <= 0)
tbEditor.Text = dcDesign.ReportSource;
break;
}
// Below sync up the changed item
if (tag == "preview")
{
if (rdlPreview.SourceRdl != tbEditor.Text) // sync up preview
this.rdlPreview.SourceRdl = this.tbEditor.Text;
}
else if (tag == "design")
{
if (_DesignChanged != "design" && _DesignChanged != null)
{
try
{
dcDesign.ReportSource = tbEditor.Text;
}
catch (Exception ge)
{
MessageBox.Show(ge.Message, Strings.RdlEditPreview_Show_Report);
tc.SelectedIndex = 1; // Force current tab to edit syntax
return;
}
}
}
_CurrentTab = tag;
if (OnDesignTabChanged != null)
OnDesignTabChanged(this, e);
}
/// <summary>
/// Print the report.
/// </summary>
public void Print(PrintDocument pd)
{
this.rdlPreview.Print(pd);
}
public void SaveAs(string filename, OutputPresentationType type)
{
this.rdlPreview.SaveAs(filename, type);
}
public string GetRdlText()
{
if (_CurrentTab == "design")
return dcDesign.ReportSource;
else
return this.tbEditor.Text;
}
public void SetRdlText(string text)
{
if (_CurrentTab == "design")
{
try
{
dcDesign.ReportSource = text;
dcDesign.Refresh();
}
catch (Exception e)
{
MessageBox.Show(e.Message, Strings.RdlEditPreview_Show_Report);
this.tbEditor.Text = text;
tcEHP.SelectedIndex = 1; // Force current tab to edit syntax
_DesignChanged = "edit";
}
}
else
{
this.tbEditor.Text = text;
}
}
/// <summary>
/// Number of pages in the report.
/// </summary>
public int PageCount
{
get {return this.rdlPreview.PageCount;}
}
/// <summary>
/// Current page in view on report
/// </summary>
public int PageCurrent
{
get {return this.rdlPreview.PageCurrent;}
}
/// <summary>
/// Page height of the report.
/// </summary>
public float PageHeight
{
get {return this.rdlPreview.PageHeight;}
}
/// <summary>
/// Page width of the report.
/// </summary>
public float PageWidth
{
get {return this.rdlPreview.PageWidth;}
}
public fyiReporting.RdlViewer.RdlViewer Viewer
{
get {return this.rdlPreview;}
}
private void tbEditor_SelectionChanged(object sender, EventArgs e)
{
if (OnSelectionChanged != null)
{
OnSelectionChanged(this, e);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.Regions.Behaviors;
using Microsoft.Practices.ServiceLocation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Microsoft.Practices.Prism.PubSubEvents;
namespace Microsoft.Practices.Prism.MefExtensions.Tests
{
[TestClass]
public class DefaultPrismServiceRegistrarFixture
{
[TestMethod]
public void NullAggregateCatalogThrows()
{
try
{
DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(null);
Assert.Fail("Expected exception not thrown");
}
catch (Exception)
{
// no op
}
}
[TestMethod]
public void SingleSelectorItemsSourceSyncBehaviorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
foreach (var part in container.Catalog.Parts)
{
foreach (var export in part.ExportDefinitions)
{
System.Diagnostics.Debug.WriteLine(string.Format("Part contract name => '{0}'", export.ContractName));
}
}
var exportedValue = container.GetExportedValue<SelectorItemsSourceSyncBehavior>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleRegionLifetimeBehaviorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
foreach (var part in container.Catalog.Parts)
{
foreach (var export in part.ExportDefinitions)
{
System.Diagnostics.Debug.WriteLine(string.Format("Part contract name => '{0}'", export.ContractName));
}
}
var exportedValue = container.GetExportedValue<RegionMemberLifetimeBehavior>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleIRegionViewRegistryIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<IRegionViewRegistry>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleContentControlRegionAdapterIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<ContentControlRegionAdapter>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleIModuleInitializerIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
container.ComposeExportedValue<AggregateCatalog>(catalog);
SetupLoggerForTest(container);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<IModuleInitializer>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleIEventAggregatorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<IEventAggregator>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleSelectorRegionAdapterIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<SelectorRegionAdapter>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleBindRegionContextToDependencyObjectBehaviorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<BindRegionContextToDependencyObjectBehavior>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleIRegionManagerIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<IRegionManager>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleRegionAdapterMappingsIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<RegionAdapterMappings>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleItemsControlRegionAdapterIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<ItemsControlRegionAdapter>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleSyncRegionContextWithHostBehaviorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<SyncRegionContextWithHostBehavior>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleIRegionNavigationServiceIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<IRegionNavigationService>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleIRegionNavigationContentLoaderIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<IRegionNavigationContentLoader>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleRegionManagerRegistrationBehaviorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<RegionManagerRegistrationBehavior>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleIModuleManagerIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
container.ComposeExportedValue<IModuleCatalog>(new ModuleCatalog());
container.ComposeExportedValue<AggregateCatalog>(catalog);
SetupLoggerForTest(container);
SetupServiceLocator(container);
DumpExportsFromCompositionContainer(container);
var exportedValue = container.GetExportedValue<IModuleManager>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleDelayedRegionCreationBehaviorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<DelayedRegionCreationBehavior>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleAutoPopulateRegionBehaviorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<AutoPopulateRegionBehavior>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleRegionActiveAwareBehaviorIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<RegionActiveAwareBehavior>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleMefFileModuleTypeLoaderIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
container.ComposeExportedValue<AggregateCatalog>(catalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<MefFileModuleTypeLoader>();
Assert.IsNotNull(exportedValue);
}
[TestMethod]
public void SingleIRegionBehaviorFactoryIsRegisteredWithContainer()
{
AggregateCatalog catalog = new AggregateCatalog();
var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog);
CompositionContainer container = new CompositionContainer(newCatalog);
SetupServiceLocator(container);
var exportedValue = container.GetExportedValue<IRegionBehaviorFactory>();
Assert.IsNotNull(exportedValue);
}
private void DumpExportsFromCompositionContainer(CompositionContainer container)
{
foreach (var part in container.Catalog.Parts)
{
foreach (var export in part.ExportDefinitions)
{
System.Diagnostics.Debug.WriteLine(string.Format("Part contract name => '{0}'", export.ContractName));
}
}
}
private void SetupServiceLocator(CompositionContainer container)
{
container.ComposeExportedValue<IServiceLocator>(new MefServiceLocatorAdapter(container));
IServiceLocator serviceLocator = container.GetExportedValue<IServiceLocator>();
ServiceLocator.SetLocatorProvider(() => serviceLocator);
}
private static void SetupLoggerForTest(CompositionContainer container)
{
ILoggerFacade logger = new Mock<ILoggerFacade>().Object;
container.ComposeExportedValue<ILoggerFacade>(logger);
}
}
}
| |
/*
* 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
* 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;
namespace DocuSign.eSign.Model
{
/// <summary>
/// LockInformation
/// </summary>
[DataContract]
public partial class LockInformation : IEquatable<LockInformation>, IValidatableObject
{
public LockInformation()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="LockInformation" /> class.
/// </summary>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="LockDurationInSeconds">Sets the time, in seconds, until the lock expires when there is no activity on the envelope. If no value is entered, then the default value of 300 seconds is used. The maximum value is 1,800 seconds. The lock duration can be extended. .</param>
/// <param name="LockedByApp">Specifies the friendly name of the application that is locking the envelope..</param>
/// <param name="LockedByUser">LockedByUser.</param>
/// <param name="LockedUntilDateTime">The datetime until the envelope lock expires..</param>
/// <param name="LockToken">A unique identifier provided to the owner of the envelope lock. Used to prove ownership of the lock..</param>
/// <param name="LockType">The type of envelope lock. Currently \"edit\" is the only supported type..</param>
/// <param name="UseScratchPad">Reserved for future use. Indicates whether a scratchpad is used for editing information. .</param>
public LockInformation(ErrorDetails ErrorDetails = default(ErrorDetails), string LockDurationInSeconds = default(string), string LockedByApp = default(string), UserInfo LockedByUser = default(UserInfo), string LockedUntilDateTime = default(string), string LockToken = default(string), string LockType = default(string), string UseScratchPad = default(string))
{
this.ErrorDetails = ErrorDetails;
this.LockDurationInSeconds = LockDurationInSeconds;
this.LockedByApp = LockedByApp;
this.LockedByUser = LockedByUser;
this.LockedUntilDateTime = LockedUntilDateTime;
this.LockToken = LockToken;
this.LockType = LockType;
this.UseScratchPad = UseScratchPad;
}
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// Sets the time, in seconds, until the lock expires when there is no activity on the envelope. If no value is entered, then the default value of 300 seconds is used. The maximum value is 1,800 seconds. The lock duration can be extended.
/// </summary>
/// <value>Sets the time, in seconds, until the lock expires when there is no activity on the envelope. If no value is entered, then the default value of 300 seconds is used. The maximum value is 1,800 seconds. The lock duration can be extended. </value>
[DataMember(Name="lockDurationInSeconds", EmitDefaultValue=false)]
public string LockDurationInSeconds { get; set; }
/// <summary>
/// Specifies the friendly name of the application that is locking the envelope.
/// </summary>
/// <value>Specifies the friendly name of the application that is locking the envelope.</value>
[DataMember(Name="lockedByApp", EmitDefaultValue=false)]
public string LockedByApp { get; set; }
/// <summary>
/// Gets or Sets LockedByUser
/// </summary>
[DataMember(Name="lockedByUser", EmitDefaultValue=false)]
public UserInfo LockedByUser { get; set; }
/// <summary>
/// The datetime until the envelope lock expires.
/// </summary>
/// <value>The datetime until the envelope lock expires.</value>
[DataMember(Name="lockedUntilDateTime", EmitDefaultValue=false)]
public string LockedUntilDateTime { get; set; }
/// <summary>
/// A unique identifier provided to the owner of the envelope lock. Used to prove ownership of the lock.
/// </summary>
/// <value>A unique identifier provided to the owner of the envelope lock. Used to prove ownership of the lock.</value>
[DataMember(Name="lockToken", EmitDefaultValue=false)]
public string LockToken { get; set; }
/// <summary>
/// The type of envelope lock. Currently \"edit\" is the only supported type.
/// </summary>
/// <value>The type of envelope lock. Currently \"edit\" is the only supported type.</value>
[DataMember(Name="lockType", EmitDefaultValue=false)]
public string LockType { get; set; }
/// <summary>
/// Reserved for future use. Indicates whether a scratchpad is used for editing information.
/// </summary>
/// <value>Reserved for future use. Indicates whether a scratchpad is used for editing information. </value>
[DataMember(Name="useScratchPad", EmitDefaultValue=false)]
public string UseScratchPad { 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 LockInformation {\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" LockDurationInSeconds: ").Append(LockDurationInSeconds).Append("\n");
sb.Append(" LockedByApp: ").Append(LockedByApp).Append("\n");
sb.Append(" LockedByUser: ").Append(LockedByUser).Append("\n");
sb.Append(" LockedUntilDateTime: ").Append(LockedUntilDateTime).Append("\n");
sb.Append(" LockToken: ").Append(LockToken).Append("\n");
sb.Append(" LockType: ").Append(LockType).Append("\n");
sb.Append(" UseScratchPad: ").Append(UseScratchPad).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 LockInformation);
}
/// <summary>
/// Returns true if LockInformation instances are equal
/// </summary>
/// <param name="other">Instance of LockInformation to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(LockInformation other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.LockDurationInSeconds == other.LockDurationInSeconds ||
this.LockDurationInSeconds != null &&
this.LockDurationInSeconds.Equals(other.LockDurationInSeconds)
) &&
(
this.LockedByApp == other.LockedByApp ||
this.LockedByApp != null &&
this.LockedByApp.Equals(other.LockedByApp)
) &&
(
this.LockedByUser == other.LockedByUser ||
this.LockedByUser != null &&
this.LockedByUser.Equals(other.LockedByUser)
) &&
(
this.LockedUntilDateTime == other.LockedUntilDateTime ||
this.LockedUntilDateTime != null &&
this.LockedUntilDateTime.Equals(other.LockedUntilDateTime)
) &&
(
this.LockToken == other.LockToken ||
this.LockToken != null &&
this.LockToken.Equals(other.LockToken)
) &&
(
this.LockType == other.LockType ||
this.LockType != null &&
this.LockType.Equals(other.LockType)
) &&
(
this.UseScratchPad == other.UseScratchPad ||
this.UseScratchPad != null &&
this.UseScratchPad.Equals(other.UseScratchPad)
);
}
/// <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.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.LockDurationInSeconds != null)
hash = hash * 59 + this.LockDurationInSeconds.GetHashCode();
if (this.LockedByApp != null)
hash = hash * 59 + this.LockedByApp.GetHashCode();
if (this.LockedByUser != null)
hash = hash * 59 + this.LockedByUser.GetHashCode();
if (this.LockedUntilDateTime != null)
hash = hash * 59 + this.LockedUntilDateTime.GetHashCode();
if (this.LockToken != null)
hash = hash * 59 + this.LockToken.GetHashCode();
if (this.LockType != null)
hash = hash * 59 + this.LockType.GetHashCode();
if (this.UseScratchPad != null)
hash = hash * 59 + this.UseScratchPad.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Timerial.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// 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.Threading;
using Alachisoft.NCache.Config;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Caching.Topologies;
using Alachisoft.NCache.Caching.Topologies.Local;
using Alachisoft.NCache.Caching.Statistics;
using Alachisoft.NCache.Caching.AutoExpiration;
using Alachisoft.NCache.Caching.EvictionPolicies;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.Util;
using Alachisoft.NCache.Runtime.Events;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Runtime.Events;
#if !CLIENT
using Alachisoft.NCache.Caching.Topologies.Clustered;
#endif
namespace Alachisoft.NCache.Caching.Util
{
/// <summary>
/// Class to help in common cache operations
/// </summary>
internal class CacheHelper
{
/// <summary>
/// Returns the number of items in local instance of the cache.
/// </summary>
/// <param name="cache"></param>
/// <returns></returns>
public static long GetLocalCount(CacheBase cache)
{
if(cache != null && cache.InternalCache != null)
return (long)cache.InternalCache.Count;
return 0;
}
/// <summary>
/// Tells if the cache is a clustered cache or a local one
/// </summary>
/// <param name="cache"></param>
/// <returns></returns>
#if !CLIENT
public static bool IsClusteredCache(CacheBase cache)
{
if (cache == null)
return false;
else
return cache.GetType().IsSubclassOf(typeof(ClusterCacheBase));
}
#endif
/// <summary>
/// Merge the first entry i.e. c1 into c2
/// </summary>
/// <param name="c1"></param>
/// <param name="c2"></param>
/// <returns>returns merged entry c2</returns>
public static CacheEntry MergeEntries(CacheEntry c1, CacheEntry c2)
{
if (c1 != null && c1.Value is CallbackEntry)
{
CallbackEntry cbEtnry = null;
cbEtnry = c1.Value as CallbackEntry;
if (cbEtnry.ItemRemoveCallbackListener != null)
{
foreach (CallbackInfo cbInfo in cbEtnry.ItemRemoveCallbackListener)
c2.AddCallbackInfo(null, cbInfo);
}
if (cbEtnry.ItemUpdateCallbackListener != null)
{
foreach (CallbackInfo cbInfo in cbEtnry.ItemUpdateCallbackListener)
c2.AddCallbackInfo(cbInfo, null);
}
}
if (c1 != null && c1.EvictionHint != null)
{
if (c2.EvictionHint == null) c2.EvictionHint = c1.EvictionHint;
}
return c2;
}
public static EventCacheEntry CreateCacheEventEntry(ArrayList listeners, CacheEntry cacheEntry)
{
EventCacheEntry entry = null;
EventDataFilter maxFilter = EventDataFilter.None;
foreach (CallbackInfo cbInfo in listeners)
{
if (cbInfo.DataFilter > maxFilter) maxFilter = cbInfo.DataFilter;
if (maxFilter == EventDataFilter.DataWithMetadata) break;
}
return CreateCacheEventEntry(maxFilter, cacheEntry);
}
public static EventCacheEntry CreateCacheEventEntry(EventDataFilter? filter, CacheEntry cacheEntry)
{
if (filter != EventDataFilter.None && cacheEntry != null)
{
cacheEntry = (CacheEntry)cacheEntry.Clone();
EventCacheEntry entry = new EventCacheEntry(cacheEntry);
entry.Flags = cacheEntry.Flag;
if (filter == EventDataFilter.DataWithMetadata)
{
if (cacheEntry.Value is CallbackEntry)
{
entry.Value = ((CallbackEntry)cacheEntry.Value).Value;
}
else
entry.Value = cacheEntry.Value;
}
return entry;
}
return null;
}
public static bool ReleaseLock(CacheEntry existingEntry, CacheEntry newEntry)
{
if (CheckLockCompatibility(existingEntry, newEntry))
{
existingEntry.ReleaseLock();
newEntry.ReleaseLock();
return true;
}
return false;
}
public static bool CheckLockCompatibility(CacheEntry existingEntry, CacheEntry newEntry)
{
object lockId = null;
DateTime lockDate = new DateTime();
if (existingEntry.IsLocked(ref lockId, ref lockDate))
{
return existingEntry.LockId.Equals(newEntry.LockId);
}
return true;
}
/// <summary>
/// Gets the list of failed items.
/// </summary>
/// <param name="insertResults"></param>
/// <returns></returns>
public static Hashtable CompileInsertResult(Hashtable insertResults)
{
Hashtable failedTable = new Hashtable();
object key;
if (insertResults != null)
{
CacheInsResult result;
IDictionaryEnumerator ide = insertResults.GetEnumerator();
while (ide.MoveNext())
{
key = ide.Key;
if (ide.Value is Exception)
{
failedTable.Add(key, ide.Value);
}
if (ide.Value is CacheInsResultWithEntry)
{
result = ((CacheInsResultWithEntry)ide.Value).Result;
switch (result)
{
case CacheInsResult.Failure:
failedTable.Add(key, new OperationFailedException("Generic operation failure; not enough information is available."));
break;
case CacheInsResult.NeedsEviction:
failedTable.Add(key, new OperationFailedException("The cache is full and not enough items could be evicted."));
break;
}
}
}
}
return failedTable;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Data.Common;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient
{
internal sealed class SqlSequentialTextReader : System.IO.TextReader
{
private SqlDataReader _reader; // The SqlDataReader that we are reading data from
private readonly int _columnIndex; // The index of out column in the table
private readonly Encoding _encoding; // Encoding for this character stream
private readonly Decoder _decoder; // Decoder based on the encoding (NOTE: Decoders are stateful as they are designed to process streams of data)
private byte[] _leftOverBytes; // Bytes leftover from the last Read() operation - this can be null if there were no bytes leftover (Possible optimization: re-use the same array?)
private int _peekedChar; // The last character that we peeked at (or -1 if we haven't peeked at anything)
private Task _currentTask; // The current async task
private readonly CancellationTokenSource _disposalTokenSource; // Used to indicate that a cancellation is requested due to disposal
internal SqlSequentialTextReader(SqlDataReader reader, int columnIndex, Encoding encoding)
{
Debug.Assert(reader != null, "Null reader when creating sequential textreader");
Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential textreader");
Debug.Assert(encoding != null, "Null encoding when creating sequential textreader");
_reader = reader;
_columnIndex = columnIndex;
_encoding = encoding;
_decoder = encoding.GetDecoder();
_leftOverBytes = null;
_peekedChar = -1;
_currentTask = null;
_disposalTokenSource = new CancellationTokenSource();
}
internal int ColumnIndex
{
get { return _columnIndex; }
}
public override int Peek()
{
if (_currentTask != null)
{
throw ADP.AsyncOperationPending();
}
if (IsClosed)
{
throw ADP.ObjectDisposed(this);
}
if (!HasPeekedChar)
{
_peekedChar = Read();
}
Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), $"Bad peeked character: {_peekedChar}");
return _peekedChar;
}
public override int Read()
{
if (_currentTask != null)
{
throw ADP.AsyncOperationPending();
}
if (IsClosed)
{
throw ADP.ObjectDisposed(this);
}
int readChar = -1;
// If there is already a peeked char, then return it
if (HasPeekedChar)
{
readChar = _peekedChar;
_peekedChar = -1;
}
// If there is data available try to read a char
else
{
char[] tempBuffer = new char[1];
int charsRead = InternalRead(tempBuffer, 0, 1);
if (charsRead == 1)
{
readChar = tempBuffer[0];
}
}
Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), $"Bad read character: {readChar}");
return readChar;
}
public override int Read(char[] buffer, int index, int count)
{
ValidateReadParameters(buffer, index, count);
if (IsClosed)
{
throw ADP.ObjectDisposed(this);
}
if (_currentTask != null)
{
throw ADP.AsyncOperationPending();
}
int charsRead = 0;
int charsNeeded = count;
// Load in peeked char
if ((charsNeeded > 0) && (HasPeekedChar))
{
Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), $"Bad peeked character: {_peekedChar}");
buffer[index + charsRead] = (char)_peekedChar;
charsRead++;
charsNeeded--;
_peekedChar = -1;
}
// If we need more data and there is data available, read
charsRead += InternalRead(buffer, index + charsRead, charsNeeded);
return charsRead;
}
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
ValidateReadParameters(buffer, index, count);
TaskCompletionSource<int> completion = new TaskCompletionSource<int>();
if (IsClosed)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else
{
try
{
Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null);
if (original != null)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
}
else
{
bool completedSynchronously = true;
int charsRead = 0;
int adjustedIndex = index;
int charsNeeded = count;
// Load in peeked char
if ((HasPeekedChar) && (charsNeeded > 0))
{
// Take a copy of _peekedChar in case it is cleared during close
int peekedChar = _peekedChar;
if (peekedChar >= char.MinValue)
{
Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), $"Bad peeked character: {_peekedChar}");
buffer[adjustedIndex] = (char)peekedChar;
adjustedIndex++;
charsRead++;
charsNeeded--;
_peekedChar = -1;
}
}
int byteBufferUsed;
byte[] byteBuffer = PrepareByteBuffer(charsNeeded, out byteBufferUsed);
// Permit a 0 byte read in order to advance the reader to the correct column
if ((byteBufferUsed < byteBuffer.Length) || (byteBuffer.Length == 0))
{
int bytesRead;
var reader = _reader;
if (reader != null)
{
Task<int> getBytesTask = reader.GetBytesAsync(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed, Timeout.Infinite, _disposalTokenSource.Token, out bytesRead);
if (getBytesTask == null)
{
byteBufferUsed += bytesRead;
}
else
{
// We need more data - setup the callback, and mark this as not completed sync
completedSynchronously = false;
getBytesTask.ContinueWith((t) =>
{
_currentTask = null;
// If we completed but the textreader is closed, then report cancellation
if ((t.Status == TaskStatus.RanToCompletion) && (!IsClosed))
{
try
{
int bytesReadFromStream = t.Result;
byteBufferUsed += bytesReadFromStream;
if (byteBufferUsed > 0)
{
charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded);
}
completion.SetResult(charsRead);
}
catch (Exception ex)
{
completion.SetException(ex);
}
}
else if (IsClosed)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else if (t.Status == TaskStatus.Faulted)
{
if (t.Exception.InnerException is SqlException)
{
// ReadAsync can't throw a SqlException, so wrap it in an IOException
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException)));
}
else
{
completion.SetException(t.Exception.InnerException);
}
}
else
{
completion.SetCanceled();
}
}, TaskScheduler.Default);
}
if ((completedSynchronously) && (byteBufferUsed > 0))
{
// No more data needed, decode what we have
charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded);
}
}
else
{
// Reader is null, close must of happened in the middle of this read
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
}
if (completedSynchronously)
{
_currentTask = null;
if (IsClosed)
{
completion.SetCanceled();
}
else
{
completion.SetResult(charsRead);
}
}
}
}
catch (Exception ex)
{
// In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it
completion.TrySetException(ex);
Interlocked.CompareExchange(ref _currentTask, null, completion.Task);
throw;
}
}
return completion.Task;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Set the textreader as closed
SetClosed();
}
base.Dispose(disposing);
}
/// <summary>
/// Forces the TextReader to act as if it was closed
/// This does not actually close the stream, read off the rest of the data or dispose this
/// </summary>
internal void SetClosed()
{
_disposalTokenSource.Cancel();
_reader = null;
_peekedChar = -1;
// Wait for pending task
var currentTask = _currentTask;
if (currentTask != null)
{
((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
}
}
/// <summary>
/// Performs the actual reading and converting
/// NOTE: This assumes that buffer, index and count are all valid, we're not closed (!IsClosed) and that there is data left (IsDataLeft())
/// </summary>
/// <param name="buffer"></param>
/// <param name="index"></param>
/// <param name="count"></param>
/// <returns></returns>
private int InternalRead(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null, "Null output buffer");
Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), $"Bad count: {count} or index: {index}");
Debug.Assert(!IsClosed, "Can't read while textreader is closed");
try
{
int byteBufferUsed;
byte[] byteBuffer = PrepareByteBuffer(count, out byteBufferUsed);
byteBufferUsed += _reader.GetBytesInternalSequential(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed);
if (byteBufferUsed > 0)
{
return DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, index, count);
}
else
{
// Nothing to read, or nothing read
return 0;
}
}
catch (SqlException ex)
{
// Read can't throw a SqlException - so wrap it in an IOException
throw ADP.ErrorReadingFromStream(ex);
}
}
/// <summary>
/// Creates a byte array large enough to store all bytes for the characters in the current encoding, then fills it with any leftover bytes
/// </summary>
/// <param name="numberOfChars">Number of characters that are to be read</param>
/// <param name="byteBufferUsed">Number of bytes pre-filled by the leftover bytes</param>
/// <returns>A byte array of the correct size, pre-filled with leftover bytes</returns>
private byte[] PrepareByteBuffer(int numberOfChars, out int byteBufferUsed)
{
Debug.Assert(numberOfChars >= 0, "Can't prepare a byte buffer for negative characters");
byte[] byteBuffer;
if (numberOfChars == 0)
{
byteBuffer = Array.Empty<byte>();
byteBufferUsed = 0;
}
else
{
int byteBufferSize = _encoding.GetMaxByteCount(numberOfChars);
if (_leftOverBytes != null)
{
// If we have more leftover bytes than we need for this conversion, then just re-use the leftover buffer
if (_leftOverBytes.Length > byteBufferSize)
{
byteBuffer = _leftOverBytes;
byteBufferUsed = byteBuffer.Length;
}
else
{
// Otherwise, copy over the leftover buffer
byteBuffer = new byte[byteBufferSize];
Buffer.BlockCopy(_leftOverBytes, 0, byteBuffer, 0, _leftOverBytes.Length);
byteBufferUsed = _leftOverBytes.Length;
}
}
else
{
byteBuffer = new byte[byteBufferSize];
byteBufferUsed = 0;
}
}
return byteBuffer;
}
/// <summary>
/// Decodes the given bytes into characters, and stores the leftover bytes for later use
/// </summary>
/// <param name="inBuffer">Buffer of bytes to decode</param>
/// <param name="inBufferCount">Number of bytes to decode from the inBuffer</param>
/// <param name="outBuffer">Buffer to write the characters to</param>
/// <param name="outBufferOffset">Offset to start writing to outBuffer at</param>
/// <param name="outBufferCount">Maximum number of characters to decode</param>
/// <returns>The actual number of characters decoded</returns>
private int DecodeBytesToChars(byte[] inBuffer, int inBufferCount, char[] outBuffer, int outBufferOffset, int outBufferCount)
{
Debug.Assert(inBuffer != null, "Null input buffer");
Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), $"Bad inBufferCount: {inBufferCount}");
Debug.Assert(outBuffer != null, "Null output buffer");
Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), $"Bad outBufferCount: {outBufferCount} or outBufferOffset: {outBufferOffset}");
int charsRead;
int bytesUsed;
bool completed;
_decoder.Convert(inBuffer, 0, inBufferCount, outBuffer, outBufferOffset, outBufferCount, false, out bytesUsed, out charsRead, out completed);
// completed may be false and there is no spare bytes if the Decoder has stored bytes to use later
if ((!completed) && (bytesUsed < inBufferCount))
{
_leftOverBytes = new byte[inBufferCount - bytesUsed];
Buffer.BlockCopy(inBuffer, bytesUsed, _leftOverBytes, 0, _leftOverBytes.Length);
}
else
{
// If Convert() sets completed to true, then it must have used all of the bytes we gave it
Debug.Assert(bytesUsed >= inBufferCount, "Converted completed, but not all bytes were used");
_leftOverBytes = null;
}
Debug.Assert(((_reader == null) || (_reader.ColumnDataBytesRemaining() > 0) || (!completed) || (_leftOverBytes == null)), "Stream has run out of data and the decoder finished, but there are leftover bytes");
Debug.Assert(charsRead > 0, "Converted no chars. Bad encoding?");
return charsRead;
}
/// <summary>
/// True if this TextReader is supposed to be closed
/// </summary>
private bool IsClosed
{
get { return (_reader == null); }
}
/// <summary>
/// True if there is a peeked character available
/// </summary>
private bool HasPeekedChar
{
get { return (_peekedChar >= char.MinValue); }
}
/// <summary>
/// Checks the parameters passed into a Read() method are valid
/// </summary>
/// <param name="buffer"></param>
/// <param name="index"></param>
/// <param name="count"></param>
internal static void ValidateReadParameters(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw ADP.ArgumentNull(nameof(buffer));
}
if (index < 0)
{
throw ADP.ArgumentOutOfRange(nameof(index));
}
if (count < 0)
{
throw ADP.ArgumentOutOfRange(nameof(count));
}
try
{
if (checked(index + count) > buffer.Length)
{
throw ExceptionBuilder.InvalidOffsetLength();
}
}
catch (OverflowException)
{
// If we've overflowed when adding index and count, then they never would have fit into buffer anyway
throw ExceptionBuilder.InvalidOffsetLength();
}
}
}
internal sealed class SqlUnicodeEncoding : UnicodeEncoding
{
private static readonly SqlUnicodeEncoding s_singletonEncoding = new SqlUnicodeEncoding();
private SqlUnicodeEncoding() : base(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false)
{ }
public override Decoder GetDecoder()
{
return new SqlUnicodeDecoder();
}
public override int GetMaxByteCount(int charCount)
{
// SQL Server never sends a BOM, so we can assume that its 2 bytes per char
return charCount * 2;
}
public static Encoding SqlUnicodeEncodingInstance
{
get { return s_singletonEncoding; }
}
private sealed class SqlUnicodeDecoder : Decoder
{
public override int GetCharCount(byte[] bytes, int index, int count)
{
// SQL Server never sends a BOM, so we can assume that its 2 bytes per char
return count / 2;
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
// This method is required - simply call Convert()
int bytesUsed;
int charsUsed;
bool completed;
Convert(bytes, byteIndex, byteCount, chars, charIndex, chars.Length - charIndex, true, out bytesUsed, out charsUsed, out completed);
return charsUsed;
}
public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
{
// Assume 2 bytes per char and no BOM
charsUsed = Math.Min(charCount, byteCount / 2);
bytesUsed = charsUsed * 2;
completed = (bytesUsed == byteCount);
// BlockCopy uses offsets\length measured in bytes, not the actual array index
Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * 2, bytesUsed);
}
}
}
}
| |
using Lucene.Net.Support.Threading;
using System;
using System.Diagnostics;
using System.Threading;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// <see cref="DocumentsWriterPerThreadPool"/> controls <see cref="ThreadState"/> instances
/// and their thread assignments during indexing. Each <see cref="ThreadState"/> holds
/// a reference to a <see cref="DocumentsWriterPerThread"/> that is once a
/// <see cref="ThreadState"/> is obtained from the pool exclusively used for indexing a
/// single document by the obtaining thread. Each indexing thread must obtain
/// such a <see cref="ThreadState"/> to make progress. Depending on the
/// <see cref="DocumentsWriterPerThreadPool"/> implementation <see cref="ThreadState"/>
/// assignments might differ from document to document.
/// <para/>
/// Once a <see cref="DocumentsWriterPerThread"/> is selected for flush the thread pool
/// is reusing the flushing <see cref="DocumentsWriterPerThread"/>s <see cref="ThreadState"/> with a
/// new <see cref="DocumentsWriterPerThread"/> instance.
/// </summary>
internal abstract class DocumentsWriterPerThreadPool
#if FEATURE_CLONEABLE
: System.ICloneable
#endif
{
/// <summary>
/// <see cref="ThreadState"/> references and guards a
/// <see cref="Index.DocumentsWriterPerThread"/> instance that is used during indexing to
/// build a in-memory index segment. <see cref="ThreadState"/> also holds all flush
/// related per-thread data controlled by <see cref="DocumentsWriterFlushControl"/>.
/// <para/>
/// A <see cref="ThreadState"/>, its methods and members should only accessed by one
/// thread a time. Users must acquire the lock via <see cref="ReentrantLock.Lock()"/>
/// and release the lock in a finally block via <see cref="ReentrantLock.Unlock()"/>
/// (on the <see cref="ThreadState"/> instance) before accessing the state.
/// </summary>
internal sealed class ThreadState : ReentrantLock
{
internal DocumentsWriterPerThread dwpt;
// TODO this should really be part of DocumentsWriterFlushControl
// write access guarded by DocumentsWriterFlushControl
internal volatile bool flushPending = false;
// TODO this should really be part of DocumentsWriterFlushControl
// write access guarded by DocumentsWriterFlushControl
internal long bytesUsed = 0;
// guarded by Reentrant lock
internal bool isActive = true;
internal ThreadState(DocumentsWriterPerThread dpwt)
{
this.dwpt = dpwt;
}
/// <summary>
/// Resets the internal <see cref="DocumentsWriterPerThread"/> with the given one.
/// if the given DWPT is <c>null</c> this <see cref="ThreadState"/> is marked as inactive and should not be used
/// for indexing anymore. </summary>
/// <seealso cref="IsActive"/>
internal void Deactivate() // LUCENENET NOTE: Made internal because it is called outside of this context
{
//Debug.Assert(this.HeldByCurrentThread);
isActive = false;
Reset();
}
internal void Reset() // LUCENENET NOTE: Made internal because it is called outside of this context
{
//Debug.Assert(this.HeldByCurrentThread);
this.dwpt = null;
this.bytesUsed = 0;
this.flushPending = false;
}
/// <summary>
/// Returns <c>true</c> if this <see cref="ThreadState"/> is still open. This will
/// only return <c>false</c> iff the DW has been disposed and this
/// <see cref="ThreadState"/> is already checked out for flush.
/// </summary>
internal bool IsActive =>
//Debug.Assert(this.HeldByCurrentThread);
isActive;
internal bool IsInitialized =>
//Debug.Assert(this.HeldByCurrentThread);
IsActive && dwpt != null;
/// <summary>
/// Returns the number of currently active bytes in this ThreadState's
/// <see cref="DocumentsWriterPerThread"/>
/// </summary>
public long BytesUsedPerThread =>
//Debug.Assert(this.HeldByCurrentThread);
// public for FlushPolicy
bytesUsed;
/// <summary>
/// Returns this <see cref="ThreadState"/>s <see cref="DocumentsWriterPerThread"/>
/// </summary>
public DocumentsWriterPerThread DocumentsWriterPerThread =>
//Debug.Assert(this.HeldByCurrentThread);
// public for FlushPolicy
dwpt;
/// <summary>
/// Returns <c>true</c> iff this <see cref="ThreadState"/> is marked as flush
/// pending otherwise <c>false</c>
/// </summary>
public bool IsFlushPending => flushPending;
}
private ThreadState[] threadStates;
private volatile int numThreadStatesActive;
/// <summary>
/// Creates a new <see cref="DocumentsWriterPerThreadPool"/> with a given maximum of <see cref="ThreadState"/>s.
/// </summary>
internal DocumentsWriterPerThreadPool(int maxNumThreadStates)
{
if (maxNumThreadStates < 1)
{
throw new ArgumentException("maxNumThreadStates must be >= 1 but was: " + maxNumThreadStates);
}
threadStates = new ThreadState[maxNumThreadStates];
numThreadStatesActive = 0;
for (int i = 0; i < threadStates.Length; i++)
{
threadStates[i] = new ThreadState(null);
}
}
public virtual object Clone()
{
// We should only be cloned before being used:
if (numThreadStatesActive != 0)
{
throw new InvalidOperationException("clone this object before it is used!");
}
DocumentsWriterPerThreadPool clone;
clone = (DocumentsWriterPerThreadPool)base.MemberwiseClone();
clone.threadStates = new ThreadState[threadStates.Length];
for (int i = 0; i < threadStates.Length; i++)
{
clone.threadStates[i] = new ThreadState(null);
}
return clone;
}
/// <summary>
/// Returns the max number of <see cref="ThreadState"/> instances available in this
/// <see cref="DocumentsWriterPerThreadPool"/>
/// </summary>
public virtual int MaxThreadStates => threadStates.Length;
/// <summary>
/// Returns the active number of <see cref="ThreadState"/> instances.
/// </summary>
public virtual int NumThreadStatesActive => numThreadStatesActive; // LUCENENET NOTE: Changed from getActiveThreadState() because the name wasn't clear
/// <summary>
/// Returns a new <see cref="ThreadState"/> iff any new state is available otherwise
/// <c>null</c>.
/// <para/>
/// NOTE: the returned <see cref="ThreadState"/> is already locked iff non-<c>null</c>.
/// </summary>
/// <returns> a new <see cref="ThreadState"/> iff any new state is available otherwise
/// <c>null</c> </returns>
public virtual ThreadState NewThreadState()
{
lock (this)
{
if (numThreadStatesActive < threadStates.Length)
{
ThreadState threadState = threadStates[numThreadStatesActive];
threadState.@Lock(); // lock so nobody else will get this ThreadState
bool unlock = true;
try
{
if (threadState.IsActive)
{
// unreleased thread states are deactivated during DW#close()
numThreadStatesActive++; // increment will publish the ThreadState
Debug.Assert(threadState.dwpt == null);
unlock = false;
return threadState;
}
// unlock since the threadstate is not active anymore - we are closed!
Debug.Assert(AssertUnreleasedThreadStatesInactive());
return null;
}
finally
{
if (unlock)
{
// in any case make sure we unlock if we fail
threadState.Unlock();
}
}
}
return null;
}
}
private bool AssertUnreleasedThreadStatesInactive()
{
lock (this)
{
for (int i = numThreadStatesActive; i < threadStates.Length; i++)
{
Debug.Assert(threadStates[i].TryLock(), "unreleased threadstate should not be locked");
try
{
Debug.Assert(!threadStates[i].IsInitialized, "expected unreleased thread state to be inactive");
}
finally
{
threadStates[i].Unlock();
}
}
return true;
}
}
/// <summary>
/// Deactivate all unreleased threadstates
/// </summary>
internal virtual void DeactivateUnreleasedStates()
{
lock (this)
{
for (int i = numThreadStatesActive; i < threadStates.Length; i++)
{
ThreadState threadState = threadStates[i];
threadState.@Lock();
try
{
threadState.Deactivate();
}
finally
{
threadState.Unlock();
}
}
}
}
internal virtual DocumentsWriterPerThread Reset(ThreadState threadState, bool closed)
{
//Debug.Assert(threadState.HeldByCurrentThread);
DocumentsWriterPerThread dwpt = threadState.dwpt;
if (!closed)
{
threadState.Reset();
}
else
{
threadState.Deactivate();
}
return dwpt;
}
internal virtual void Recycle(DocumentsWriterPerThread dwpt)
{
// don't recycle DWPT by default
}
// you cannot subclass this without being in o.a.l.index package anyway, so
// the class is already pkg-private... fix me: see LUCENE-4013
public abstract ThreadState GetAndLock(Thread requestingThread, DocumentsWriter documentsWriter); // LUCENENET NOTE: Made public rather than internal
/// <summary>
/// Returns the <i>i</i>th active <seealso cref="ThreadState"/> where <i>i</i> is the
/// given ord.
/// </summary>
/// <param name="ord">
/// the ordinal of the <seealso cref="ThreadState"/> </param>
/// <returns> the <i>i</i>th active <seealso cref="ThreadState"/> where <i>i</i> is the
/// given ord. </returns>
internal virtual ThreadState GetThreadState(int ord)
{
return threadStates[ord];
}
/// <summary>
/// Returns the <see cref="ThreadState"/> with the minimum estimated number of threads
/// waiting to acquire its lock or <c>null</c> if no <see cref="ThreadState"/>
/// is yet visible to the calling thread.
/// </summary>
internal virtual ThreadState MinContendedThreadState()
{
ThreadState minThreadState = null;
int limit = numThreadStatesActive;
for (int i = 0; i < limit; i++)
{
ThreadState state = threadStates[i];
if (minThreadState == null || state.QueueLength < minThreadState.QueueLength)
{
minThreadState = state;
}
}
return minThreadState;
}
/// <summary>
/// Returns the number of currently deactivated <see cref="ThreadState"/> instances.
/// A deactivated <see cref="ThreadState"/> should not be used for indexing anymore.
/// </summary>
/// <returns> the number of currently deactivated <see cref="ThreadState"/> instances. </returns>
internal virtual int NumDeactivatedThreadStates()
{
int count = 0;
for (int i = 0; i < threadStates.Length; i++)
{
ThreadState threadState = threadStates[i];
threadState.@Lock();
try
{
if (!threadState.isActive)
{
count++;
}
}
finally
{
threadState.Unlock();
}
}
return count;
}
/// <summary>
/// Deactivates an active <see cref="ThreadState"/>. Inactive <see cref="ThreadState"/> can
/// not be used for indexing anymore once they are deactivated. This method should only be used
/// if the parent <see cref="DocumentsWriter"/> is closed or aborted.
/// </summary>
/// <param name="threadState"> the state to deactivate </param>
internal virtual void DeactivateThreadState(ThreadState threadState)
{
Debug.Assert(threadState.IsActive);
threadState.Deactivate();
}
}
}
| |
// <copyright file="ChangeMonitor.cs" company="Microsoft">
// Copyright (c) 2009 Microsoft Corporation. All rights reserved.
// </copyright>
using System;
using System.Runtime.Caching.Resources;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
// Every member of this class is thread-safe.
//
// Derived classes begin monitoring during construction, so that a user can know if the
// dependency changed any time after construction. For example, suppose we have a
// FileChangeMonitor class that derives from ChangeMonitor. A user might create an instance
// of FileChangeMonitor for an XML file, and then read the file to populate an object representation.
// The user would then cache the object with the FileChangeMonitor. The user could optionally check the
// HasChanged property of the FileChangeMonitor, to see if the XML file changed while the object
// was being populated, and if it had changed, they could call Dispose and start over, without
// inserting the item into the cache. However, in a multi-threaded environment, for cleaner, easier
// to maintain code, it's usually appropriate to just insert without checking HasChanged, since the
// cache implementer will handle this for you, and the next thread to attempt to get the object
// will recreate and insert it.
//
// The following contract must be followed by derived classes, cache implementers, and users of the
// derived class:
//
// 1. The constructor of a derived class must set UniqueId, begin monitoring for dependency
// changes, and call InitializationComplete before returning. If a dependency changes
// before initialization is complete, for example, if a dependent cache key is not found
// in the cache, the constructor must invoke OnChanged. The constructor can only call
// Dispose after InitializationComplete is called, because Dispose will throw
// InvalidOperationException if initialization is not complete.
// 2. Once constructed, the user must either insert the ChangeMonitor into an ObjectCache, or
// if they're not going to use it, they must call Dispose.
// 3. Once inserted into an ObjectCache, the ObjectCache implementation must ensure that the
// ChangeMonitor is eventually disposed. Even if the insert is invalid, and results in an
// exception being thrown, the ObjectCache implementation must call Dispose. If this we're not
// a requirement, users of the ChangeMonitor would need exception handling around each insert
// into the cache that carefully ensures the dependency is disposed. While this would work, we
// think it is better to put this burden on the ObjectCache implementer, since users are far more
// numerous than cache implementers.
// 4. After the ChangeMonitor is inserted into a cache, the ObjectCache implementer must call
// NotifyOnChanged, passing in an OnChangedCallback. NotifyOnChanged can only be called once,
// and will throw InvalidOperationException on subsequent calls. If the dependency has already
// changed, the OnChangedCallback will be called when NotifyOnChanged is called. Otherwise, the
// OnChangedCallback will be called exactly once, when OnChanged is invoked or when Dispose
// is invoked, which ever happens first.
// 5. The OnChangedCallback provided by the cache implementer should remove the cache entry, and specify
// a reason of CacheEntryRemovedReason.DependencyChanged. Care should be taken to remove the specific
// entry having this dependency, and not it's replacement, which will have the same key.
// 6. In general, it is okay for OnChanged to be called at any time. If OnChanged is called before
// NotifyOnChanged is called, the "state" from the original call to OnChanged will be saved, and the
// callback to NotifyOnChange will be called immediately when NotifyOnChanged is invoked.
// 7. A derived class must implement Dispose(bool disposing) to release all managed and unmanaged
// resources when "disposing" is true. Dispose(true) is only called once, when the instance is
// disposed. The derived class must not call Dispose(true) directly--it should only be called by
// the ChangeMonitor class, when disposed. Although a derived class could implement a finalizer and
// invoke Dispose(false), this is generally not necessary. Dependency monitoring is typically performed
// by a service that maintains a reference to the ChangeMonitor, preventing it from being garbage collected,
// and making finalizers useless. To help prevent leaks, when a dependency changes, OnChanged disposes
// the ChangeMonitor, unless initialization has not yet completed.
// 8. Dispose() must be called, and is designed to be called, in one of the following three ways:
// - The user must call Dispose() if they decide not to insert the ChangeMonitor into a cache. Otherwise,
// the ChangeMonitor will continue monitoring for changes and be unavailable for garbage collection.
// - The cache implementor is responsible for calling Dispose() once an attempt is made to insert it.
// Even if the insert throws, the cache implementor must dispose the dependency.
// Even if the entry is removed, the cache implementor must dispose the dependency.
// - The OnChanged method will automatically call Dispose if initialization is complete. Otherwise, when
// the derived class' constructor calls InitializationComplete, the instance will be automatically disposed.
//
// Before inserted into the cache, the user must ensure the dependency is disposed. Once inserted into the
// cache, the cache implementer must ensure that Dispose is called, even if the insert fails. After being inserted
// into a cache, the user should not dispose the dependency. When Dispose is called, it is treated as if the dependency
// changed, and OnChanged is automatically invoked.
// 9. HasChanged will be true after OnChanged is called by the derived class, regardless of whether an OnChangedCallback has been set
// by a call to NotifyOnChanged.
namespace System.Runtime.Caching {
public abstract class ChangeMonitor : IDisposable {
private const int INITIALIZED = 0x01; // initialization complete
private const int CHANGED = 0x02; // dependency changed
private const int INVOKED = 0x04; // OnChangedCallback has been invoked
private const int DISPOSED = 0x08; // Dispose(true) called, or about to be called
private readonly static object NOT_SET = new object();
private SafeBitVector32 _flags;
private OnChangedCallback _onChangedCallback;
private Object _onChangedState = NOT_SET;
// The helper routines (OnChangedHelper and DisposeHelper) are used to prevent
// an infinite loop, where Dispose calls OnChanged and OnChanged calls Dispose.
[SuppressMessage("Microsoft.Performance", "CA1816:DisposeMethodsShouldCallSuppressFinalize", Justification = "Grandfathered suppression from original caching code checkin")]
private void DisposeHelper() {
// if not initialized, return without doing anything.
if (_flags[INITIALIZED]) {
if (_flags.ChangeValue(DISPOSED, true)) {
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
// The helper routines (OnChangedHelper and DisposeHelper) are used to prevent
// an infinite loop, where Dispose calls OnChanged and OnChanged calls Dispose.
private void OnChangedHelper(Object state) {
_flags[CHANGED] = true;
// the callback is only invoked once, after NotifyOnChanged is called, so
// remember "state" on the first call and use it when invoking the callback
Interlocked.CompareExchange(ref _onChangedState, state, NOT_SET);
OnChangedCallback onChangedCallback = _onChangedCallback;
if (onChangedCallback != null) {
// only invoke the callback once
if (_flags.ChangeValue(INVOKED, true)) {
onChangedCallback(_onChangedState);
}
}
}
//
// protected members
//
// Derived classes must implement this. When "disposing" is true,
// all managed and unmanaged resources are disposed and any references to this
// object are released so that the ChangeMonitor can be garbage collected.
// It is guaranteed that ChangeMonitor.Dispose() will only invoke
// Dispose(bool disposing) once.
protected abstract void Dispose(bool disposing);
// Derived classes must call InitializationComplete
protected void InitializationComplete() {
_flags[INITIALIZED] = true;
// If the dependency has already changed, or someone tried to dispose us, then call Dispose now.
Dbg.Assert(_flags[INITIALIZED], "It is critical that INITIALIZED is set before CHANGED is checked below");
if (_flags[CHANGED]) {
Dispose();
}
}
// Derived classes call OnChanged when the dependency changes. Optionally,
// they may pass state which will be passed to the OnChangedCallback. The
// OnChangedCallback is only invoked once, and only after NotifyOnChanged is
// called by the cache implementer. OnChanged is also invoked when the instance
// is disposed, but only has an affect if the callback has not already been invoked.
protected void OnChanged(Object state) {
OnChangedHelper(state);
// OnChanged will also invoke Dispose, but only after initialization is complete
Dbg.Assert(_flags[CHANGED], "It is critical that CHANGED is set before INITIALIZED is checked below.");
if (_flags[INITIALIZED]) {
DisposeHelper();
}
}
//
// public members
//
// set to true when the dependency changes, specifically, when OnChanged is called.
public bool HasChanged { get { return _flags[CHANGED]; } }
// set to true when this instance is disposed, specifically, after
// Dispose(bool disposing) is called by Dispose().
public bool IsDisposed { get { return _flags[DISPOSED]; } }
// a unique ID representing this ChangeMonitor, typically consisting of
// the dependency names and last-modified times.
public abstract string UniqueId { get; }
// Dispose must be called to release the ChangeMonitor. In order to
// prevent derived classes from overriding Dispose, it is not an explicit
// interface implementation.
//
// Before cache insertion, if the user decides not to do a cache insert, they
// must call this to dispose the dependency; otherwise, the ChangeMonitor will
// be referenced and unable to be garbage collected until the dependency changes.
//
// After cache insertion, the cache implementer must call this when the cache entry
// is removed, for whatever reason. Even if an exception is thrown during insert.
//
// After cache insertion, the user should not call Dispose. However, since there's
// no way to prevent this, doing so will invoke the OnChanged event handler, if it
// hasn't already been invoked, and the cache entry will be notified as if the
// dependency has changed.
//
// Dispose() will only invoke the Dispose(bool disposing) method of derived classes
// once, the first time it is called. Subsequent calls to Dispose() perform no
// operation. After Dispose is called, the IsDisposed property will be true.
[SuppressMessage("Microsoft.Performance", "CA1816:DisposeMethodsShouldCallSuppressFinalize", Justification = "Grandfathered suppression from original caching code checkin")]
public void Dispose() {
OnChangedHelper(null);
// If not initialized, throw, so the derived class understands that it must call InitializeComplete before Dispose.
Dbg.Assert(_flags[CHANGED], "It is critical that CHANGED is set before INITIALIZED is checked below.");
if (!_flags[INITIALIZED]) {
throw new InvalidOperationException(R.Init_not_complete);
}
DisposeHelper();
}
// Cache implementers must call this to be notified of any dependency changes.
// NotifyOnChanged can only be invoked once, and will throw InvalidOperationException
// on subsequent calls. The OnChangedCallback is guaranteed to be called exactly once.
// It will be called when the dependency changes, or if it has already changed, it will
// be called immediately (on the same thread??).
public void NotifyOnChanged(OnChangedCallback onChangedCallback) {
if (onChangedCallback == null) {
throw new ArgumentNullException("onChangedCallback");
}
if (Interlocked.CompareExchange(ref _onChangedCallback, onChangedCallback, null) != null) {
throw new InvalidOperationException(R.Method_already_invoked);
}
// if it already changed, raise the event now.
if (_flags[CHANGED]) {
OnChanged(null);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.