context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Should;
using NUnit.Framework;
using System.Linq;
using Rhino.Mocks;
using System.Reflection;
namespace AutoMapper.UnitTests.Tests
{
public class StubMappingOptions : IMappingOptions
{
private INamingConvention _sourceMemberNamingConvention;
private INamingConvention _destinationMemberNamingConvention;
private IEnumerable<string> _prefixes = new List<string>();
private IEnumerable<string> _postfixes = new List<string>();
private IEnumerable<string> _destinationPrefixes = new List<string>();
private IEnumerable<string> _destinationPostfixes = new List<string>();
private IEnumerable<AliasedMember> _aliases = new List<AliasedMember>();
private Assembly[] _sourceExtensionMethodSearch = null;
public INamingConvention SourceMemberNamingConvention
{
get { return _sourceMemberNamingConvention; }
set { _sourceMemberNamingConvention = value; }
}
public INamingConvention DestinationMemberNamingConvention
{
get { return _destinationMemberNamingConvention; }
set { _destinationMemberNamingConvention = value; }
}
public IEnumerable<string> Prefixes
{
get { return _prefixes; }
}
public IEnumerable<string> Postfixes
{
get { return _postfixes; }
}
public IEnumerable<string> DestinationPrefixes
{
get { return _destinationPrefixes; }
}
public IEnumerable<string> DestinationPostfixes
{
get { return _destinationPostfixes; }
}
public IEnumerable<AliasedMember> Aliases
{
get { return _aliases; }
}
public bool ConstructorMappingEnabled
{
get { return true; }
}
public Assembly[] SourceExtensionMethodSearch
{
get { return _sourceExtensionMethodSearch; }
set { _sourceExtensionMethodSearch = value; }
}
}
public class When_constructing_type_maps_with_matching_property_names : SpecBase
{
private TypeMapFactory _factory;
public class Source
{
public int Value { get; set; }
public int SomeOtherValue { get; set; }
}
public class Destination
{
public int Value { get; set; }
public int SomeOtherValue { get; set; }
}
protected override void Establish_context()
{
_factory = new TypeMapFactory();
}
[Test]
public void Should_map_properties_with_same_name()
{
var mappingOptions = new StubMappingOptions();
mappingOptions.SourceMemberNamingConvention = new PascalCaseNamingConvention();
mappingOptions.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
var typeMap = _factory.CreateTypeMap(typeof(Source), typeof(Destination), mappingOptions, MemberList.Destination);
var propertyMaps = typeMap.GetPropertyMaps();
propertyMaps.Count().ShouldEqual(2);
}
}
public class When_using_a_custom_source_naming_convention : SpecBase
{
private TypeMapFactory _factory;
private TypeMap _map;
private IMappingOptions _mappingOptions;
private class Source
{
public SubSource some__source { get; set; }
}
private class SubSource
{
public int value { get; set; }
}
private class Destination
{
public int SomeSourceValue { get; set; }
}
protected override void Establish_context()
{
INamingConvention namingConvention = CreateStub<INamingConvention>();
namingConvention.Stub(nc => nc.SeparatorCharacter).Return("__");
_mappingOptions = new StubMappingOptions();
_mappingOptions.SourceMemberNamingConvention = namingConvention;
_mappingOptions.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
_factory = new TypeMapFactory();
}
protected override void Because_of()
{
_map = _factory.CreateTypeMap(typeof(Source), typeof(Destination), _mappingOptions, MemberList.Destination);
}
[Test]
public void Should_split_using_naming_convention_rules()
{
_map.GetPropertyMaps().Count().ShouldEqual(1);
}
}
public class When_using_a_custom_destination_naming_convention : SpecBase
{
private TypeMapFactory _factory;
private TypeMap _map;
private IMappingOptions _mappingOptions;
private class Source
{
public SubSource SomeSource { get; set; }
}
private class SubSource
{
public int Value { get; set; }
}
private class Destination
{
public int some__source__value { get; set; }
}
protected override void Establish_context()
{
INamingConvention namingConvention = CreateStub<INamingConvention>();
namingConvention.Stub(nc => nc.SplittingExpression).Return(new Regex(@"[\p{Ll}0-9]*(?=_?)"));
_mappingOptions = new StubMappingOptions();
_mappingOptions.SourceMemberNamingConvention = new PascalCaseNamingConvention();
_mappingOptions.DestinationMemberNamingConvention = namingConvention;
_factory = new TypeMapFactory();
}
protected override void Because_of()
{
_map = _factory.CreateTypeMap(typeof(Source), typeof(Destination), _mappingOptions, MemberList.Destination);
}
[Test]
public void Should_split_using_naming_convention_rules()
{
_map.GetPropertyMaps().Count().ShouldEqual(1);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
//
// Purpose: This class implements a set of methods for comparing
// strings.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
[Flags]
public enum CompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreSymbols = 0x00000004,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags.
StringSort = 0x20000000, // use string sort method
Ordinal = 0x40000000, // This flag can not be used with other flags.
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial class CompareInfo : IDeserializationCallback
{
// Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags.
private const CompareOptions ValidIndexMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if Compare() has the right flags.
private const CompareOptions ValidCompareMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Mask used to check if GetHashCodeOfString() has the right flags.
private const CompareOptions ValidHashCodeOfStringMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if we have the right flags.
private const CompareOptions ValidSortkeyCtorMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
//
// CompareInfos have an interesting identity. They are attached to the locale that created them,
// ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US.
// The interesting part is that since haw-US doesn't have its own sort, it has to point at another
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization)
[NonSerialized]
private String _sortName; // The name that defines our behavior
[OptionalField(VersionAdded = 3)]
private SortVersion m_SortVersion; // Do not rename (binary serialization)
private int culture; // Do not rename (binary serialization). The fields sole purpose is to support Desktop serialization.
internal CompareInfo(CultureInfo culture)
{
m_name = culture.m_name;
InitSort(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** Warning: The assembly versioning mechanism is dead!
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if culture is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
{
// Parameter checking.
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
Contract.EndContractBlock();
return GetCompareInfo(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** The purpose of this method is to provide version for CompareInfo tables.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if name is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(String name, Assembly assembly)
{
if (name == null || assembly == null)
{
throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
Contract.EndContractBlock();
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(name);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
** This method is provided for ease of integration with NLS-based software.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture.
**Exceptions:
** ArgumentException if culture is invalid.
============================================================================*/
// People really shouldn't be calling LCID versions, no custom support
public static CompareInfo GetCompareInfo(int culture)
{
if (CultureData.IsCustomCultureId(culture))
{
// Customized culture cannot be created by the LCID.
throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture.
**Exceptions:
** ArgumentException if name is invalid.
============================================================================*/
public static CompareInfo GetCompareInfo(String name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
public static unsafe bool IsSortable(char ch)
{
char* pChar = &ch;
return IsSortable(pChar, 1);
}
public static unsafe bool IsSortable(string text)
{
if (text == null)
{
// A null param is invalid here.
throw new ArgumentNullException(nameof(text));
}
if (0 == text.Length)
{
// A zero length string is not invalid, but it is also not sortable.
return (false);
}
fixed (char* pChar = text)
{
return IsSortable(pChar, text.Length);
}
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
m_name = null;
}
void IDeserializationCallback.OnDeserialization(object sender)
{
OnDeserialized();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
private void OnDeserialized()
{
// If we didn't have a name, use the LCID
if (m_name == null)
{
// From whidbey, didn't have a name
CultureInfo ci = CultureInfo.GetCultureInfo(this.culture);
m_name = ci.m_name;
}
else
{
InitSort(CultureInfo.GetCultureInfo(m_name));
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
// This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
Contract.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
}
///////////////////////////----- Name -----/////////////////////////////////
//
// Returns the name of the culture (well actually, of the sort).
// Very important for providing a non-LCID way of identifying
// what the sort is.
//
// Note that this name isn't dereferenced in case the CompareInfo is a different locale
// which is consistent with the behaviors of earlier versions. (so if you ask for a sort
// and the locale's changed behavior, then you'll get changed behavior, which is like
// what happens for a version update)
//
////////////////////////////////////////////////////////////////////////
public virtual String Name
{
get
{
Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set");
if (m_name == "zh-CHT" || m_name == "zh-CHS")
{
return m_name;
}
return _sortName;
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two strings with the given options. Returns 0 if the
// two strings are equal, a number less than 0 if string1 is less
// than string2, and a number greater than 0 if string1 is greater
// than string2.
//
////////////////////////////////////////////////////////////////////////
public virtual int Compare(String string1, String string2)
{
return (Compare(string1, string2, CompareOptions.None));
}
public unsafe virtual int Compare(String string1, String string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase);
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return String.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//Our paradigm is that null sorts less than any other string and
//that two nulls sort as equal.
if (string1 == null)
{
if (string2 == null)
{
return (0); // Equal
}
return (-1); // null < non-null
}
if (string2 == null)
{
return (1); // non-null > null
}
return CompareString(string1, 0, string1.Length, string2, 0, string2.Length, options);
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the specified regions of the two strings with the given
// options.
// Returns 0 if the two strings are equal, a number less than 0 if
// string1 is less than string2, and a number greater than 0 if
// string1 is greater than string2.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2)
{
return Compare(string1, offset1, length1, string2, offset2, length2, 0);
}
public unsafe virtual int Compare(String string1, int offset1, String string2, int offset2, CompareOptions options)
{
return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1,
string2, offset2, string2 == null ? 0 : string2.Length - offset2, options);
}
public unsafe virtual int Compare(String string1, int offset1, String string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, 0);
}
public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase);
if ((length1 != length2) && result == 0)
return (length1 > length2 ? 1 : -1);
return (result);
}
// Verify inputs
if (length1 < 0 || length2 < 0)
{
throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 < 0 || offset2 < 0)
{
throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength);
}
if (offset2 > (string2 == null ? 0 : string2.Length) - length2)
{
throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength);
}
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal,
nameof(options));
}
}
else if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//
// Check for the null case.
//
if (string1 == null)
{
if (string2 == null)
{
return (0);
}
return (-1);
}
if (string2 == null)
{
return (1);
}
if (options == CompareOptions.Ordinal)
{
return CompareOrdinal(string1, offset1, length1,
string2, offset2, length2);
}
return CompareString(string1, offset1, length1,
string2, offset2, length2,
options);
}
private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
int result = String.CompareOrdinal(string1, offset1, string2, offset2,
(length1 < length2 ? length1 : length2));
if ((length1 != length2) && result == 0)
{
return (length1 > length2 ? 1 : -1);
}
return (result);
}
//
// CompareOrdinalIgnoreCase compare two string oridnally with ignoring the case.
// it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by
// calling the OS.
//
internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
{
Debug.Assert(indexA + lengthA <= strA.Length);
Debug.Assert(indexB + lengthB <= strB.Length);
int length = Math.Min(lengthA, lengthB);
int range = length;
fixed (char* ap = strA) fixed (char* bp = strB)
{
char* a = ap + indexA;
char* b = bp + indexB;
while (length != 0 && (*a <= 0x80) && (*b <= 0x80))
{
int charA = *a;
int charB = *b;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
//Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
if (length == 0)
return lengthA - lengthB;
range -= length;
return CompareStringOrdinalIgnoreCase(a, lengthA - range, b, lengthB - range);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsPrefix
//
// Determines whether prefix is a prefix of string. If prefix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options)
{
if (source == null || prefix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
if (prefix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.StartsWith(prefix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
return StartsWith(source, prefix, options);
}
public virtual bool IsPrefix(String source, String prefix)
{
return (IsPrefix(source, prefix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IsSuffix
//
// Determines whether suffix is a suffix of string. If suffix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual bool IsSuffix(String source, String suffix, CompareOptions options)
{
if (source == null || suffix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
if (suffix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.EndsWith(suffix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
return EndsWith(source, suffix, options);
}
public virtual bool IsSuffix(String source, String suffix)
{
return (IsSuffix(source, suffix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IndexOf
//
// Returns the first index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// startIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual int IndexOf(String source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, String value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
public unsafe virtual int IndexOf(String source, String value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
public unsafe virtual int IndexOf(String source, char value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, String value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, char value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public unsafe virtual int IndexOf(String source, String value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public unsafe virtual int IndexOf(String source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, String value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, char value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
Contract.EndContractBlock();
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
return IndexOfCore(source, new string(value, 1), startIndex, count, options, null);
}
public unsafe virtual int IndexOf(String source, String value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex > source.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
// In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here.
// We return 0 if both source and value are empty strings for Everett compatibility too.
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
return IndexOfCore(source, value, startIndex, count, options, null);
}
// The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated
// and the caller is passing a valid matchLengthPtr pointer.
internal unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0);
Debug.Assert(matchLengthPtr != null);
*matchLengthPtr = 0;
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex >= source.Length)
{
return -1;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr);
}
////////////////////////////////////////////////////////////////////////
//
// LastIndexOf
//
// Returns the last index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// endIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual int LastIndexOf(String source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(String source, String value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(String source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, options);
}
public unsafe virtual int LastIndexOf(String source, String value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, options);
}
public unsafe virtual int LastIndexOf(String source, char value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public unsafe virtual int LastIndexOf(String source, String value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public unsafe virtual int LastIndexOf(String source, char value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public unsafe virtual int LastIndexOf(String source, String value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
return LastIndexOfCore(source, value.ToString(), startIndex, count, options);
}
public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return (value.Length == 0) ? 0 : -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
// If we are looking for nothing, just return 0
if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0)
return startIndex;
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
return LastIndexOfCore(source, value, startIndex, count, options);
}
////////////////////////////////////////////////////////////////////////
//
// GetSortKey
//
// Gets the SortKey for the given string with the given options.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual SortKey GetSortKey(String source, CompareOptions options)
{
return CreateSortKey(source, options);
}
public unsafe virtual SortKey GetSortKey(String source)
{
return CreateSortKey(source, CompareOptions.None);
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CompareInfo as the current
// instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
CompareInfo that = value as CompareInfo;
if (that != null)
{
return this.Name == that.Name;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CompareInfo. The hash code is guaranteed to be the same for
// CompareInfo A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCodeOfString
//
// This internal method allows a method that allows the equivalent of creating a Sortkey for a
// string from CompareInfo, and generate a hashcode value from it. It is not very convenient
// to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed.
//
// The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both
// the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects
// treat the string the same way, this implementation will treat them differently (the same way that
// Sortkey does at the moment).
//
// This method will never be made public itself, but public consumers of it could be created, e.g.:
//
// string.GetHashCode(CultureInfo)
// string.GetHashCode(CompareInfo)
// string.GetHashCode(CultureInfo, CompareOptions)
// string.GetHashCode(CompareInfo, CompareOptions)
// etc.
//
// (the methods above that take a CultureInfo would use CultureInfo.CompareInfo)
//
////////////////////////////////////////////////////////////////////////
internal int GetHashCodeOfString(string source, CompareOptions options)
{
//
// Parameter validation
//
if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if ((options & ValidHashCodeOfStringMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
Contract.EndContractBlock();
return GetHashCodeOfStringCore(source, options);
}
public virtual int GetHashCode(string source, CompareOptions options)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (options == CompareOptions.Ordinal)
{
return source.GetHashCode();
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return TextInfo.GetHashCodeOrdinalIgnoreCase(source);
}
//
// GetHashCodeOfString does more parameters validation. basically will throw when
// having Ordinal, OrdinalIgnoreCase and StringSort
//
return GetHashCodeOfString(source, options);
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// CompareInfo.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("CompareInfo - " + this.Name);
}
public SortVersion Version
{
get
{
if (m_SortVersion == null)
{
m_SortVersion = GetSortVersion();
}
return m_SortVersion;
}
}
public int LCID
{
get
{
return CultureInfo.GetCultureInfo(Name).LCID;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Add_Vector128_UInt64()
{
var test = new SimpleBinaryOpTest__Add_Vector128_UInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__Add_Vector128_UInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__Add_Vector128_UInt64 testClass)
{
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__Add_Vector128_UInt64 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__Add_Vector128_UInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__Add_Vector128_UInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Add(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__Add_Vector128_UInt64();
var result = AdvSimd.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__Add_Vector128_UInt64();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Add(
AdvSimd.LoadVector128((UInt64*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ulong)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using Signum.Engine.Processes;
using Signum.Entities.MachineLearning;
namespace Signum.Engine.MachineLearning;
public class AutoconfigureNeuralNetworkAlgorithm : Processes.IProcessAlgorithm
{
public void Execute(ExecutingProcess ep)
{
var conf = (AutoconfigureNeuralNetworkEntity)ep.Data!;
var initial = conf.InitialPredictor.Retrieve();
Random r = conf.Seed == null ?
new Random():
new Random(conf.Seed.Value);
var mutationProbability = conf.InitialMutationProbability;
List<PredictorEntity> population = 0.To(conf.Population).Select(p => initial.ConstructFrom(PredictorOperation.Clone)).ToList();
population.ForEach(p => Mutate(p, conf, mutationProbability, r));
Dictionary<PredictorEntity, double> evaluatedPopulation = EvaluatePopulation(ep, conf, population, 0);
for (int gen = 1; gen < conf.Generations + 1; gen++)
{
population = CrossOverPopulation(evaluatedPopulation, initial, conf, r);
population.ForEach(p => Mutate(p, conf, mutationProbability, r));
evaluatedPopulation = EvaluatePopulation(ep, conf, population, gen);
}
}
public List<PredictorEntity> CrossOverPopulation(Dictionary<PredictorEntity, double> evaluatedPopulation, PredictorEntity initial, AutoconfigureNeuralNetworkEntity opt, Random r)
{
var positiveSurvivors = evaluatedPopulation.ToDictionary(kvp => kvp.Key, kvp => 1 / (kvp.Value + 0.01));
var total = positiveSurvivors.Values.Sum();
PredictorEntity SelectRandomly()
{
var point = r.NextDouble() * total;
double acum = 0;
foreach (var kvp in positiveSurvivors!)
{
acum += kvp.Value;
if (point < acum)
return kvp.Key;
}
throw new InvalidOperationException("Out of range");
}
return 0.To(opt.Population).Select(i => CrossOver(initial.ConstructFrom(PredictorOperation.Clone), SelectRandomly(), SelectRandomly(), r, opt)).ToList();
}
private PredictorEntity CrossOver(PredictorEntity child, PredictorEntity father, PredictorEntity mother, Random r, AutoconfigureNeuralNetworkEntity conf)
{
var nnChild = (NeuralNetworkSettingsEntity)child.AlgorithmSettings;
var nnFather = (NeuralNetworkSettingsEntity)father.AlgorithmSettings;
var nnMother = (NeuralNetworkSettingsEntity)mother.AlgorithmSettings;
if (conf.ExploreLearner)
{
nnChild.Optimizer = r.NextBool() ? nnFather.Optimizer : nnMother.Optimizer;
}
if (conf.ExploreLearningValues)
{
nnChild.LearningRate = r.NextBool() ? nnFather.LearningRate : nnMother.LearningRate;
}
if (conf.ExploreHiddenLayers)
{
nnChild.HiddenLayers = nnFather.HiddenLayers.ZipOrDefault(nnMother.HiddenLayers, (h1, h2) => r.NextBool() ? h1 : h2).NotNull().ToMList();
}
if (conf.ExploreOutputLayer)
{
nnChild.OutputActivation = r.NextBool() ? nnFather.OutputActivation : nnMother.OutputActivation;
nnChild.OutputInitializer = r.NextBool() ? nnFather.OutputInitializer : nnMother.OutputInitializer;
}
return child;
}
public Dictionary<PredictorEntity, double> EvaluatePopulation(ExecutingProcess ep, AutoconfigureNeuralNetworkEntity conf, List<PredictorEntity> population, int gen)
{
var total = conf.Population * (conf.Generations + 1);
var evaluatedPopulation = new Dictionary<PredictorEntity, double>();
for (int i = 0; i < population.Count; i++)
{
ep.CancellationToken.ThrowIfCancellationRequested();
var current = gen * population.Count + i;
ep.ProgressChanged(current / (decimal)total);
var p = population[i];
double lastValidation = Evaluate(ep, p, onProgress: val => ep.ProgressChanged((current + val ?? 0) / (decimal)total));
evaluatedPopulation.Add(p, lastValidation);
}
return evaluatedPopulation;
}
private static double Evaluate(ExecutingProcess ep, PredictorEntity p, Action<decimal?> onProgress)
{
PredictorLogic.TrainSync(p, onReportProgres: (str, val) => onProgress(val));
return p.ResultValidation!.Loss!.Value;
}
//private static double EvaluateMock(ExecutingProcess ep, PredictorEntity p, Action<decimal?> onProgress)
//{
// var nns = (NeuralNetworkSettingsEntity)p.AlgorithmSettings;
// var ctx = Lite.Create<PredictorEntity>(1835).GetPredictContext();
// var mq = ctx.Predictor.MainQuery;
// var inputs = new PredictDictionary(ctx.Predictor)
// {
// MainQueryValues =
// {
// { mq.FindColumn(nameof(nns.Learner)), nns.Learner },
// { mq.FindColumn(nameof(nns.LearningRate)), nns.LearningRate },
// { mq.FindColumn(nameof(nns.LearningMomentum)), nns.LearningMomentum },
// { mq.FindColumn(nameof(nns.LearningVarianceMomentum)), nns.LearningVarianceMomentum },
// { mq.FindColumn(nameof(nns.LearningUnitGain)), nns.LearningUnitGain },
// }
// };
// var outputs = inputs.PredictBasic();
// var outValue = outputs.MainQueryValues.GetOrThrow(mq.FindColumn(nameof(ctx.Predictor.ResultValidation)));
// return Convert.ToDouble(outValue);
//}
private void Mutate(PredictorEntity predictor, AutoconfigureNeuralNetworkEntity conf, double mutationProbability, Random r)
{
var nns = (NeuralNetworkSettingsEntity)predictor.AlgorithmSettings;
if (conf.ExploreLearner)
{
if (r.NextDouble() < mutationProbability)
nns.Optimizer = r.NextElement(EnumExtensions.GetValues<TensorFlowOptimizer>());
}
if (conf.ExploreLearningValues)
{
double IncrementOrDecrement(double value)
{
var ratio = 1.1 + r.NextDouble() * 0.9;
return r.NextBool() ? value / ratio : value * ratio;
}
if (r.NextDouble() < mutationProbability)
nns.LearningRate = IncrementOrDecrement(nns.LearningRate);
}
if (conf.ExploreHiddenLayers)
{
if (r.NextDouble() < mutationProbability)
{
var shouldHidden = Math.Min(0, Math.Max(nns.HiddenLayers.Count + (r.NextBool() ? 1 : -1), conf.MaxLayers));
if (shouldHidden > nns.HiddenLayers.Count)
{
nns.HiddenLayers.Add(new NeuralNetworkHidenLayerEmbedded
{
Size = r.Next(conf.MaxNeuronsPerLayer),
Activation = r.NextElement(EnumExtensions.GetValues<NeuralNetworkActivation>()),
Initializer = r.NextElement(EnumExtensions.GetValues<NeuralNetworkInitializer>()),
});
}
else if (shouldHidden < nns.HiddenLayers.Count)
{
nns.HiddenLayers.RemoveAt(r.Next(nns.HiddenLayers.Count));
}
}
foreach (var hl in nns.HiddenLayers)
{
if (r.NextDouble() < mutationProbability)
hl.Size = (r.Next(conf.MinNeuronsPerLayer, conf.MaxNeuronsPerLayer) + hl.Size) / 2;
if (r.NextDouble() < mutationProbability)
hl.Activation = r.NextElement(EnumExtensions.GetValues<NeuralNetworkActivation>());
if (r.NextDouble() < mutationProbability)
hl.Initializer = r.NextElement(EnumExtensions.GetValues<NeuralNetworkInitializer>());
}
}
if (conf.ExploreOutputLayer)
{
if (r.NextDouble() < mutationProbability)
nns.OutputActivation = r.NextElement(EnumExtensions.GetValues<NeuralNetworkActivation>());
if (r.NextDouble() < mutationProbability)
nns.OutputInitializer = r.NextElement(EnumExtensions.GetValues<NeuralNetworkInitializer>());
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Site.Areas.KnowledgeManagement.Controllers
{
using System;
using System.Web.Mvc;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Routing;
using Adxstudio.Xrm.Diagnostics;
using Adxstudio.Xrm;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.ContentAccess;
using Adxstudio.Xrm.Core.Flighting;
using Adxstudio.Xrm.Data;
using Adxstudio.Xrm.KnowledgeArticles;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Security;
using Adxstudio.Xrm.Services.Query;
using Adxstudio.Xrm.Text;
using Adxstudio.Xrm.Web.Mvc;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Site.Areas.KnowledgeManagement.ViewModels;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Web;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk.Query;
using OrganizationServiceContextExtensions = Adxstudio.Xrm.Cms.OrganizationServiceContextExtensions;
[PortalView, PortalSecurity]
public class ArticleController : Controller
{
private const string ArticlesFetchXmlFormat = @"
<fetch mapping='logical'>
<entity name='knowledgearticle'>
<attribute name='articlepublicnumber' />
<attribute name='knowledgearticleid' />
<attribute name='title' />
<attribute name='keywords' />
<attribute name='createdon' />
<attribute name='statecode' />
<attribute name='statuscode' />
<attribute name='isinternal' />
<attribute name='isrootarticle' />
<attribute name='knowledgearticleviews' />
<attribute name='languagelocaleid' />
<link-entity name='languagelocale' from='languagelocaleid' to='languagelocaleid' visible='false' link-type='outer' alias='language_locale'>
<attribute name='localeid' />
<attribute name='code' />
<attribute name='region' />
<attribute name='name' />
<attribute name='language' />
</link-entity>
<filter type='and'>
<condition attribute='isrootarticle' operator='eq' value='0' />
<condition attribute='statecode' operator='eq' value='{0}' />
<condition attribute='isinternal' operator='eq' value='0' />
<condition attribute='articlepublicnumber' operator='eq' value='{1}' />
{2}
</filter>
</entity>
</fetch>";
/// <summary>The timespan to keep in cache.</summary>
private static readonly TimeSpan DefaultDuration = TimeSpan.FromHours(1);
[HttpGet]
public ActionResult Article(string number, string lang, int? page)
{
var serviceContext = PortalCrmConfigurationManager.CreateServiceContext();
// If the article is specifically being requested (via URL) in a language, multi-language is enabled, and the requested language
// is different than the context language, then update the context language to respect the language of the article being viewed.
// remove the old lang parameter and update url if necessary
var contextLanguageInfo = this.HttpContext.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
var needsRedirect = ContextLanguageInfo.DisplayLanguageCodeInUrl != contextLanguageInfo.RequestUrlHasLanguageCode
|| contextLanguageInfo.ContextLanguage.UsedAsFallback || !string.IsNullOrWhiteSpace(lang);
var llcc = !string.IsNullOrWhiteSpace(lang) ? lang : contextLanguageInfo.ContextLanguage.Code;
var activeLangauges = contextLanguageInfo.ActiveWebsiteLanguages;
if (!string.IsNullOrWhiteSpace(lang) && !activeLangauges.Any(l => l.Code.Equals(lang, StringComparison.InvariantCultureIgnoreCase)))
{
IWebsiteLanguage language;
if (ContextLanguageInfo.TryGetLanguageFromMapping(contextLanguageInfo.ActiveWebsiteLanguages, lang, out language))
{
llcc = language.UsedAsFallback && contextLanguageInfo.ContextLanguage.CrmLcid == language.CrmLcid
? contextLanguageInfo.ContextLanguage.Code
: language.Code;
}
}
var articleUrl = ContextLanguageInfo.DisplayLanguageCodeInUrl
? contextLanguageInfo.FormatUrlWithLanguage(overrideLanguageCode: llcc)
: contextLanguageInfo.AbsolutePathWithoutLanguageCode;
var queryParameters = new NameValueCollection(this.Request.QueryString);
articleUrl = articleUrl.Replace(queryParameters.Count == 1 ?
string.Format("?lang={0}", lang) : string.Format("lang={0}", lang),
string.Empty);
if (needsRedirect && articleUrl != Request.Url.PathAndQuery)
{
return Redirect(articleUrl);
}
}
string langCode;
var article = GetArticle(serviceContext, number, this.HttpContext.GetWebsite(), lang, out langCode);
if (article == null)
{
return View("ArticleUnavailable");
}
if (!Authorized(serviceContext, article))
{
return RedirectToAccessDeniedPage();
}
//Log Customer Journey Tracking
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CustomerJourneyTracking))
{
PortalTrackingTrace.TraceInstance.Log(Constants.Article, article.Id.ToString(), article.GetAttributeValue<string>("title"));
}
return GetArticleView(article, page, langCode);
}
[HttpPost, ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult CommentCreate(Guid id, string authorName, string authorEmail, string copy)
{
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
return new EmptyResult();
}
var context = PortalCrmConfigurationManager.CreateServiceContext();
var article = context.RetrieveSingle("knowledgearticle",
FetchAttribute.All,
new Condition("knowledgearticleid", ConditionOperator.Equal, id),
false,
false,
RequestFlag.AllowStaleData);
if (article == null || !Authorized(context, article))
{
return new EmptyResult();
}
var articleDataAdapter = new KnowledgeArticleDataAdapter(article) { ChronologicalComments = true };
var sanitizedCopy = SafeHtml.SafeHtmSanitizer.GetSafeHtml(copy ?? string.Empty);
TryAddComment(articleDataAdapter, authorName, authorEmail, sanitizedCopy);
var commentsViewModel = new ArticleCommentsViewModel()
{
Comments =
new PaginatedList<IComment>(PaginatedList.Page.Last, articleDataAdapter.SelectCommentCount(),
articleDataAdapter.SelectComments),
KnowledgeArticle = articleDataAdapter.Select()
};
RouteData.Values["action"] = "Article";
RouteData.Values["id"] = Guid.Empty;
return PartialView("Comments", commentsViewModel);
}
[HttpPost, ValidateInput(false)]
[AjaxValidateAntiForgeryToken]
public ActionResult RatingCreate(Guid id, int rating, int maxRating, int minRating)
{
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
return new EmptyResult();
}
var context = PortalCrmConfigurationManager.CreateServiceContext();
var article = context.RetrieveSingle("knowledgearticle",
FetchAttribute.All,
new Condition("knowledgearticleid", ConditionOperator.Equal, id),
false,
false,
RequestFlag.AllowStaleData);
if (article == null || !Authorized(context, article))
{
return new EmptyResult();
}
var articleDataAdapter = new KnowledgeArticleDataAdapter(article);
TryAddUpdateRating(articleDataAdapter, rating, maxRating, minRating);
var commentsViewModel = new ArticleCommentsViewModel()
{
KnowledgeArticle = articleDataAdapter.Select()
};
return PartialView("Rating", commentsViewModel.KnowledgeArticle);
}
[HttpGet]
public int GetArticleViewCount(Guid id)
{
var service = System.Web.HttpContext.Current.GetOrganizationService();
var entity = service.RetrieveSingle(
new EntityReference("knowledgearticle", id),
new ColumnSet("knowledgearticleviews"),
RequestFlag.AllowStaleData | RequestFlag.SkipDependencyCalculation,
DefaultDuration);
return entity.Attributes.Contains("knowledgearticleviews") ? entity.Attributes["knowledgearticleviews"] as int? ?? 0 : 0;
}
[HttpGet]
public decimal GetArticleRating(Guid id)
{
var service = System.Web.HttpContext.Current.GetOrganizationService();
var entity = service.RetrieveSingle(
new EntityReference("knowledgearticle", id),
new ColumnSet("rating"),
RequestFlag.AllowStaleData | RequestFlag.SkipDependencyCalculation,
DefaultDuration);
return entity.Attributes.Contains("rating") ? entity.Attributes["rating"] as decimal? ?? 0 : 0;
}
[HttpPost, ValidateInput(false)]
[AjaxValidateAntiForgeryToken]
public void CaseDeflectionCreate(Guid id, bool isRatingEnabled, string searchText)
{
var context = PortalCrmConfigurationManager.CreateServiceContext();
var article = context.RetrieveSingle("knowledgearticle",
FetchAttribute.All,
new Condition("knowledgearticleid", ConditionOperator.Equal, id),
false,
false,
RequestFlag.AllowStaleData);
var articleDataAdapter = new KnowledgeArticleDataAdapter(article);
articleDataAdapter.CreateUpdateCaseDeflection(article.Attributes["title"].ToString(), searchText, isRatingEnabled, context);
}
[HttpPost, ValidateInput(false)]
[AjaxValidateAntiForgeryToken]
public void IncrementViewCount(Guid id, Uri urlReferrer)
{
var articleEntity = new Entity("knowledgearticle", id);
var articleDataAdapter = new KnowledgeArticleDataAdapter(articleEntity) { ChronologicalComments = true };
articleDataAdapter.IncrementKnowledgeArticleViewCount(urlReferrer);
}
public static string GetPortalUri(string siteMarkerName)
{
var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
var page = portalContext.ServiceContext.GetPageBySiteMarkerName(portalContext.Website, siteMarkerName);
return page == null ? string.Empty : new UrlBuilder(portalContext.ServiceContext.GetUrl(page)).Path;
}
private ActionResult RedirectToAccessDeniedPage()
{
var serviceContext = PortalCrmConfigurationManager.CreatePortalContext();
var page = serviceContext.ServiceContext.GetPageBySiteMarkerName(serviceContext.Website, AccessDeniedSiteMarker);
if (page == null)
{
throw new Exception(
ResourceManager.GetString("Contact_System_Administrator_Required_Site_Marker_Missing_Exception")
.FormatWith(PageNotFoundSiteMarker));
}
var path = OrganizationServiceContextExtensions.GetUrl(serviceContext.ServiceContext, page);
if (path == null)
{
throw new Exception("Please contact your System Administrator. Unable to build URL for Site Marker {0}.".FormatWith(PageNotFoundSiteMarker));
}
return Redirect(path);
}
private ActionResult GetArticleView(Entity articleEntity, int? page, string code)
{
var articleViewModel = new ArticleViewModel(articleEntity, page, code);
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.KnowledgeArticle, this.HttpContext, "read_article", 1, articleEntity.ToEntityReference(), "read");
}
return View("Article", articleViewModel);
}
private bool TryAddComment(IKnowledgeArticleDataAdapter dataAdapter, string authorName, string authorEmail, string content)
{
if (!Request.IsAuthenticated)
{
if (string.IsNullOrWhiteSpace(authorName))
{
ModelState.AddModelError("authorName", ResourceManager.GetString("Name_Required_Error"));
}
if (string.IsNullOrWhiteSpace(authorEmail))
{
ModelState.AddModelError("authorEmail", ResourceManager.GetString("Email_Required_Error"));
}
}
if (string.IsNullOrWhiteSpace(content) || string.IsNullOrWhiteSpace(StringHelper.GetCommentTitleFromContent(content)))
{
ModelState.AddModelError("content", ResourceManager.GetString("Comment_Required_Error"));
}
if (!ModelState.IsValid)
{
return false;
}
dataAdapter.CreateComment(content, authorName, authorEmail);
return true;
}
private bool TryAddUpdateRating(IKnowledgeArticleDataAdapter dataAdapter, int rating, int maxRating, int minRating)
{
if (!ModelState.IsValid)
{
return false;
}
dataAdapter.CreateUpdateRating(rating, maxRating, minRating, HttpContext.Profile.UserName);
return true;
}
private static bool Authorized(OrganizationServiceContext serviceContext, Entity entity)
{
var entityPermissionProvider = new CrmEntityPermissionProvider();
return entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Read, entity);
}
private static Entity GetArticle(OrganizationServiceContext serviceContext, string number, CrmWebsite website, string lang, out string languageLocaleCode)
{
const int published = 3;
var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
languageLocaleCode = lang;
// If language locale code is NOT provided and multi-language is enabled, then use the context website language.
var contextLanguageInfo = System.Web.HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled && string.IsNullOrWhiteSpace(languageLocaleCode))
{
languageLocaleCode = contextLanguageInfo.ContextLanguage.Code;
}
// If language locale code is NOT provided and we're not using multi-language, fall back to site setting.
else if (string.IsNullOrWhiteSpace(languageLocaleCode))
{
languageLocaleCode = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website,
"KnowledgeManagement/Article/Language");
}
var optionalLanguageCondition = string.IsNullOrWhiteSpace(languageLocaleCode) ? string.Empty : string.Format("<condition entityname='language_locale' attribute='code' operator='eq' value = '{0}' />", languageLocaleCode);
var articlesFetchXml = string.Format(ArticlesFetchXmlFormat, published, number, optionalLanguageCondition);
var fetchArticles = Fetch.Parse(articlesFetchXml);
var settings = website.Settings;
var productFilteringOn = settings.Get<bool>(ProductFilteringSiteSettingName);
var calFilteringOn = settings.Get<bool>(CalEnabledSiteSettingName);
if (calFilteringOn)
{
// Apply CAL filtering
var contentAccessLevelProvider = new ContentAccessLevelProvider();
contentAccessLevelProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetchArticles);
}
if (productFilteringOn)
{
// Apply Product filtering
var productAccessProvider = new ProductAccessProvider();
productAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetchArticles);
}
var article = serviceContext.RetrieveSingle(fetchArticles, false, false, RequestFlag.AllowStaleData);
return article;
}
private const string PageNotFoundSiteMarker = "Page Not Found";
private const string AccessDeniedSiteMarker = "Access Denied";
private const string ProductFilteringSiteSettingName = "ProductFiltering/Enabled";
private const string CalEnabledSiteSettingName = "KnowledgeManagement/ContentAccessLevel/Enabled";
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Baseline;
using Marten.Services;
using Marten.Services.Json;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
namespace Marten.Testing.Linq
{
public class invoking_query_with_select_Tests: IntegrationContext
{
#region sample_one_field_projection
[Fact]
public void use_select_in_query_for_one_field()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => x.FirstName)
.ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom");
}
#endregion sample_one_field_projection
[Fact]
public void use_select_in_query_for_one_field_and_first()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => x.FirstName)
.First().ShouldBe("Bill");
}
[Fact]
public async Task use_select_in_query_for_one_field_async()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
await theSession.SaveChangesAsync();
var names = await theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => x.FirstName).ToListAsync();
names.ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom");
}
[Fact]
public void use_select_to_another_type()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => new UserName { Name = x.FirstName })
.ToArray()
.Select(x => x.Name)
.ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom");
}
[Fact]
public void use_select_to_another_type_as_json()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
// Postgres sticks some extra spaces into the JSON string
#region sample_AsJson-plus-Select-1
theSession
.Query<User>()
.OrderBy(x => x.FirstName)
// Transform the User class to a different type
.Select(x => new UserName { Name = x.FirstName })
.AsJson()
.First()
.ShouldBe("{\"Name\": \"Bill\"}");
#endregion sample_AsJson-plus-Select-1
}
#region sample_get_first_projection
[Fact]
public void use_select_to_another_type_with_first()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => new UserName { Name = x.FirstName })
.FirstOrDefault()
?.Name.ShouldBe("Bill");
}
#endregion sample_get_first_projection
[Fact]
public void use_select_to_anonymous_type_with_first_as_json()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
#region sample_AsJson-plus-Select-2
theSession
.Query<User>()
.OrderBy(x => x.FirstName)
// Transform to an anonymous type
.Select(x => new { Name = x.FirstName })
// Select only the raw JSON
.AsJson()
.FirstOrDefault()
.ShouldBe("{\"Name\": \"Bill\"}");
#endregion sample_AsJson-plus-Select-2
}
[Fact]
public void use_select_to_anonymous_type_with_to_json_array()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => new { Name = x.FirstName })
.ToJsonArray()
.ShouldBe("[{\"Name\": \"Bill\"},{\"Name\": \"Hank\"},{\"Name\": \"Sam\"},{\"Name\": \"Tom\"}]");
}
[Fact]
public async Task use_select_to_another_type_async()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
var users = await theSession
.Query<User>()
.OrderBy(x => x.FirstName)
.Select(x => new UserName { Name = x.FirstName })
.ToListAsync();
users.Select(x => x.Name)
.ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom");
}
[Fact]
public void use_select_to_another_type_as_to_json_array()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
var users = theSession
.Query<User>()
.OrderBy(x => x.FirstName)
.Select(x => new UserName { Name = x.FirstName })
.ToJsonArray();
users.ShouldBe("[{\"Name\": \"Bill\"},{\"Name\": \"Hank\"},{\"Name\": \"Sam\"},{\"Name\": \"Tom\"}]");
}
#region sample_anonymous_type_projection
[Fact]
public void use_select_to_transform_to_an_anonymous_type()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => new { Name = x.FirstName })
.ToArray()
.Select(x => x.Name)
.ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom");
}
#endregion sample_anonymous_type_projection
[Fact]
public void use_select_with_multiple_fields_in_anonymous()
{
theSession.Store(new User { FirstName = "Hank", LastName = "Aaron" });
theSession.Store(new User { FirstName = "Bill", LastName = "Laimbeer" });
theSession.Store(new User { FirstName = "Sam", LastName = "Mitchell" });
theSession.Store(new User { FirstName = "Tom", LastName = "Chambers" });
theSession.SaveChanges();
var users = theSession.Query<User>().Select(x => new { First = x.FirstName, Last = x.LastName }).ToList();
users.Count.ShouldBe(4);
users.Each(x =>
{
SpecificationExtensions.ShouldNotBeNull(x.First);
SpecificationExtensions.ShouldNotBeNull(x.Last);
});
}
#region sample_other_type_projection
[SerializerTypeTargetedFact(RunFor = SerializerType.Newtonsoft)]
public void use_select_with_multiple_fields_to_other_type()
{
theSession.Store(new User { FirstName = "Hank", LastName = "Aaron" });
theSession.Store(new User { FirstName = "Bill", LastName = "Laimbeer" });
theSession.Store(new User { FirstName = "Sam", LastName = "Mitchell" });
theSession.Store(new User { FirstName = "Tom", LastName = "Chambers" });
theSession.SaveChanges();
var users = theSession.Query<User>().Select(x => new User2 { First = x.FirstName, Last = x.LastName }).ToList();
users.Count.ShouldBe(4);
users.Each(x =>
{
SpecificationExtensions.ShouldNotBeNull(x.First);
SpecificationExtensions.ShouldNotBeNull(x.Last);
});
}
#endregion sample_other_type_projection
public class User2
{
public string First;
public string Last;
}
[SerializerTypeTargetedFact(RunFor = SerializerType.Newtonsoft)]
public void use_select_with_multiple_fields_to_other_type_using_constructor()
{
theSession.Store(new User { FirstName = "Hank", LastName = "Aaron" });
theSession.Store(new User { FirstName = "Bill", LastName = "Laimbeer" });
theSession.Store(new User { FirstName = "Sam", LastName = "Mitchell" });
theSession.Store(new User { FirstName = "Tom", LastName = "Chambers" });
theSession.SaveChanges();
var users = theSession.Query<User>()
.Select(x => new UserDto(x.FirstName, x.LastName))
.ToList();
users.Count.ShouldBe(4);
users.Each(x =>
{
SpecificationExtensions.ShouldNotBeNull(x.FirstName);
SpecificationExtensions.ShouldNotBeNull(x.LastName);
});
}
[SerializerTypeTargetedFact(RunFor = SerializerType.Newtonsoft)]
public void use_select_with_multiple_fields_to_other_type_using_constructor_and_properties()
{
theSession.Store(new User { FirstName = "Hank", LastName = "Aaron", Age = 20 });
theSession.Store(new User { FirstName = "Bill", LastName = "Laimbeer", Age = 40 });
theSession.Store(new User { FirstName = "Sam", LastName = "Mitchell", Age = 60 });
theSession.Store(new User { FirstName = "Tom", LastName = "Chambers", Age = 80 });
theSession.SaveChanges();
var users = theSession.Query<User>()
.Select(x => new UserDto(x.FirstName, x.LastName) { YearsOld = x.Age })
.ToList();
users.Count.ShouldBe(4);
users.Each(x =>
{
SpecificationExtensions.ShouldNotBeNull(x.FirstName);
SpecificationExtensions.ShouldNotBeNull(x.LastName);
SpecificationExtensions.ShouldBeGreaterThan(x.YearsOld, 0);
});
}
public class UserDto
{
public UserDto(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string FirstName { get; }
public string LastName { get; }
public int YearsOld { get; set; }
}
[Fact]
public async Task use_select_to_transform_to_an_anonymous_type_async()
{
theSession.Store(new User { FirstName = "Hank" });
theSession.Store(new User { FirstName = "Bill" });
theSession.Store(new User { FirstName = "Sam" });
theSession.Store(new User { FirstName = "Tom" });
theSession.SaveChanges();
var users = await theSession
.Query<User>()
.OrderBy(x => x.FirstName)
.Select(x => new { Name = x.FirstName })
.ToListAsync();
users
.Select(x => x.Name)
.ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom");
}
#region sample_deep_properties_projection
[Fact]
public void transform_with_deep_properties()
{
var targets = Target.GenerateRandomData(100).ToArray();
theStore.BulkInsert(targets);
var actual = theSession.Query<Target>().Where(x => x.Number == targets[0].Number).Select(x => x.Inner.Number).ToList().Distinct();
var expected = targets.Where(x => x.Number == targets[0].Number).Select(x => x.Inner.Number).Distinct();
actual.ShouldHaveTheSameElementsAs(expected);
}
#endregion sample_deep_properties_projection
[SerializerTypeTargetedFact(RunFor = SerializerType.Newtonsoft)]
public void transform_with_deep_properties_to_anonymous_type()
{
var target = Target.Random(true);
theSession.Store(target);
theSession.SaveChanges();
var actual = theSession.Query<Target>()
.Where(x => x.Id == target.Id)
.Select(x => new { x.Id, x.Number, InnerNumber = x.Inner.Number })
.First();
actual.Id.ShouldBe(target.Id);
actual.Number.ShouldBe(target.Number);
actual.InnerNumber.ShouldBe(target.Inner.Number);
}
[SerializerTypeTargetedFact(RunFor = SerializerType.Newtonsoft)]
public void transform_with_deep_properties_to_type_using_constructor()
{
var target = Target.Random(true);
theSession.Store(target);
theSession.SaveChanges();
var actual = theSession.Query<Target>()
.Where(x => x.Id == target.Id)
.Select(x => new FlatTarget(x.Id, x.Number, x.Inner.Number))
.First();
actual.Id.ShouldBe(target.Id);
actual.Number.ShouldBe(target.Number);
actual.InnerNumber.ShouldBe(target.Inner.Number);
}
public class FlatTarget
{
public FlatTarget(Guid id, int number, int innerNumber)
{
Id = id;
Number = number;
InnerNumber = innerNumber;
}
public Guid Id { get; }
public int Number { get; }
public int InnerNumber { get; }
}
public invoking_query_with_select_Tests(DefaultStoreFixture fixture) : base(fixture)
{
}
}
public class UserName
{
public string Name { get; set; }
}
}
| |
/******************************************************************************
* Copyright (c) 2013-2014, Justin Bengtson
* Copyright (c) 2014-2015, Maik Schreiber
* Copyright (c) 2015-2016, George Sedov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 UnityEngine;
using KSP.Localization;
namespace KSPPreciseManeuver {
[KSPAddon (KSPAddon.Startup.Flight, false)]
internal class PreciseManeuver : MonoBehaviour {
private MainWindow mainWindow = new MainWindow();
private PreciseManeuverHotkeys hotkeys = new PreciseManeuverHotkeys();
private PreciseManeuverConfig config = PreciseManeuverConfig.Instance;
private NodeManager manager = NodeManager.Instance;
private UI.DraggableWindow m_KeybindingsWindow = null;
private GameObject m_KeybindingsWindowObject = null;
private UI.DraggableWindow m_MainWindow = null;
private GameObject m_MainWindowObject = null;
private GameObject m_WindowPrefab = PreciseManeuverConfig.Instance.Prefabs.LoadAsset<GameObject> ("PreciseManeuverWindow");
internal void Start () {
GameEvents.onManeuverNodeSelected.Add (new EventVoid.OnEvent (manager.SearchNewGizmo));
KACWrapper.InitKACWrapper ();
}
internal void OnDestroy() {
GameEvents.onManeuverNodeSelected.Remove (new EventVoid.OnEvent (manager.SearchNewGizmo));
}
internal void OnDisable () {
CloseKeybindingsWindow ();
CloseMainWindow ();
config.SaveConfig ();
}
internal void Update () {
if (!NodeTools.PatchedConicsUnlocked)
return;
if (config.ShowKeymapperWindow && config.UiActive && MapView.MapIsEnabled)
OpenKeybindingsWindow ();
else
CloseKeybindingsWindow ();
if (config.ShowMainWindow && config.UiActive && CanShowNodeEditor)
OpenMainWindow ();
else
CloseMainWindow ();
if (m_KeybindingsWindowObject != null)
hotkeys.ProcessHotkeySet ();
if (!FlightDriver.Pause && CanShowNodeEditor) {
hotkeys.ProcessGlobalHotkeys ();
if (m_MainWindowObject != null) {
hotkeys.ProcessRegularHotkeys ();
manager.UpdateNodes ();
}
}
if (m_MainWindowObject == null) {
manager.Clear ();
}
}
#region MainWindow
private void OpenMainWindow () {
// fade in if already open
if (m_MainWindow != null) {
m_MainWindow.MoveToBackground (config.IsInBackground);
if (m_MainWindow.IsFadingOut)
m_MainWindow.FadeIn ();
if (config.ModulesChanged)
mainWindow.UpdateMainWindow (m_MainWindow);
return;
}
if (m_WindowPrefab == null || m_MainWindowObject != null)
return;
// create object
Vector3 pos = new Vector3(config.MainWindowPos.x, config.MainWindowPos.y, MainCanvasUtil.MainCanvasRect.position.z);
m_MainWindowObject = Instantiate (m_WindowPrefab);
if (m_MainWindowObject == null)
return;
m_MainWindow = m_MainWindowObject.GetComponent<UI.DraggableWindow> ();
if (m_MainWindow != null) {
m_MainWindow.SetTitle (Localizer.Format ("precisemaneuver_caption"));
m_MainWindow.SetMainCanvasTransform (MainCanvasUtil.MainCanvasRect);
mainWindow.ClearMainWindow ();
mainWindow.UpdateMainWindow (m_MainWindow);
// should be done before moving to background
GUIComponentManager.ReplaceLabelsWithTMPro (m_MainWindowObject);
m_MainWindow.MoveToBackground (config.IsInBackground);
m_MainWindow.setWindowInputLock = SetWindow1InputLock;
m_MainWindow.resetWindowInputLock = ResetWindow1InputLock;
}
GUIComponentManager.ProcessStyle (m_MainWindowObject);
// set object as a child of the main canvas
m_MainWindowObject.transform.SetParent (MainCanvasUtil.MainCanvas.transform);
m_MainWindowObject.transform.position = pos;
// do the scaling after the parent has been set
ScaleMainWindow ();
config.ListenToScaleChange (ScaleMainWindow);
}
private void ScaleMainWindow () {
if (m_MainWindowObject == null)
return;
m_MainWindowObject.GetComponent<RectTransform> ().localScale = Vector3.one * config.GUIScale;
}
private void CloseMainWindow () {
if (m_MainWindow != null) {
if (!m_MainWindow.IsFadingOut) {
config.MainWindowPos = m_MainWindow.WindowPosition;
m_MainWindow.FadeClose ();
config.RemoveListener (ScaleMainWindow);
ResetWindow1InputLock ();
}
} else if (m_MainWindowObject != null) {
Destroy (m_MainWindowObject);
mainWindow.ClearMainWindow ();
config.RemoveListener (ScaleMainWindow);
ResetWindow1InputLock ();
}
}
#endregion
#region KeybindingsWindow
private void OpenKeybindingsWindow () {
// fade in if already open
if (m_KeybindingsWindow != null) {
if (m_KeybindingsWindow.IsFadingOut)
m_KeybindingsWindow.FadeIn ();
return;
}
if (m_WindowPrefab == null || m_KeybindingsWindowObject != null)
return;
// create window object
Vector3 pos = new Vector3(config.KeymapperWindowPos.x, config.KeymapperWindowPos.y, MainCanvasUtil.MainCanvasRect.position.z);
m_KeybindingsWindowObject = Instantiate (m_WindowPrefab);
if (m_KeybindingsWindowObject == null)
return;
// populate window
m_KeybindingsWindow = m_KeybindingsWindowObject.GetComponent<UI.DraggableWindow> ();
if (m_KeybindingsWindow != null) {
m_KeybindingsWindow.SetTitle (Localizer.Format ("precisemaneuver_keybindings_caption"));
m_KeybindingsWindow.SetMainCanvasTransform (MainCanvasUtil.MainCanvasRect);
hotkeys.FillKeymapperWindow (m_KeybindingsWindow);
m_KeybindingsWindow.setWindowInputLock = SetWindow2InputLock;
m_KeybindingsWindow.resetWindowInputLock = ResetWindow2InputLock;
}
GUIComponentManager.ProcessStyle (m_KeybindingsWindowObject);
GUIComponentManager.ProcessLocalization (m_KeybindingsWindowObject);
GUIComponentManager.ReplaceLabelsWithTMPro (m_KeybindingsWindowObject);
// set object as a child of the main canvas
m_KeybindingsWindowObject.transform.SetParent (MainCanvasUtil.MainCanvas.transform);
m_KeybindingsWindowObject.transform.position = pos;
}
private void CloseKeybindingsWindow () {
if (m_KeybindingsWindow != null) {
if (!m_KeybindingsWindow.IsFadingOut) {
config.KeymapperWindowPos = m_KeybindingsWindow.WindowPosition;
m_KeybindingsWindow.FadeClose ();
ResetWindow2InputLock ();
}
} else if (m_KeybindingsWindowObject != null) {
Destroy (m_KeybindingsWindowObject);
ResetWindow2InputLock ();
}
}
#endregion
private void SetWindow1InputLock () {
InputLockManager.SetControlLock (ControlTypes.MAP_UI, "PreciseManeuverWindow1ControlLock");
}
private void ResetWindow1InputLock () {
InputLockManager.RemoveControlLock ("PreciseManeuverWindow1ControlLock");
}
private void SetWindow2InputLock () {
InputLockManager.SetControlLock (ControlTypes.MAP_UI, "PreciseManeuverWindow2ControlLock");
}
private void ResetWindow2InputLock () {
InputLockManager.RemoveControlLock ("PreciseManeuverWindow2ControlLock");
}
private bool CanShowNodeEditor {
get {
if (!NodeTools.PatchedConicsUnlocked)
return false;
PatchedConicSolver solver = FlightGlobals.ActiveVessel.patchedConicSolver;
return (FlightGlobals.ActiveVessel != null) && MapView.MapIsEnabled && (solver != null) && (solver.maneuverNodes.Count > 0);
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Xaml.Actipro.Xaml.ActiproPublic
File: ExchangeEditor.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Xaml
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Text.RegularExpressions;
using System.Linq.Expressions;
using Ecng.Common;
using Ecng.Configuration;
using Ecng.Xaml;
using StockSharp.BusinessEntities;
using StockSharp.Localization;
/// <summary>
/// Editor of exchange boards.
/// </summary>
public partial class ExchangeEditor
{
private IExchangeInfoProvider Provider { get; }
/// <summary>
/// List of exchanges.
/// </summary>
public ObservableCollection<Exchange> Exchanges { get; }
private ExchangeEditorViewModel ViewModel => (ExchangeEditorViewModel)DataContext;
private static readonly Regex _checkCodeRegex = new Regex("^[a-z0-9]{1,15}$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private string _selectedExchangeName;
/// <summary>
/// The name of the selected exchange.
/// </summary>
public string SelectedExchangeName
{
get
{
return _selectedExchangeName;
}
private set
{
if (_selectedExchangeName == value)
return;
_selectedExchangeName = value;
SelectedExchangeChanged.SafeInvoke();
}
}
/// <summary>
/// The selected exchange change event .
/// </summary>
public event Action SelectedExchangeChanged;
/// <summary>
/// Initializes a new instance of the <see cref="ExchangeEditor"/>.
/// </summary>
public ExchangeEditor()
{
Provider = ConfigManager.GetService<IExchangeInfoProvider>();
Exchanges = new ObservableCollection<Exchange>(Provider.Exchanges);
InitializeComponent();
var vm = new ExchangeEditorViewModel(this, Provider);
vm.DataChanged += VmOnDataChanged;
DataContext = vm;
Provider.ExchangeAdded += ProviderOnExchangeAdded;
}
private void ProviderOnExchangeAdded(Exchange exchange)
{
Dispatcher.GuiAsync(() =>
{
//using (Dispatcher.DisableProcessing())
//{
//var selectedVal = CbExchangeName.SelectedValue as string ?? CbExchangeName.Text.Trim();
//Exchanges.Clear();
Exchanges.Add(exchange);
CbExchangeName.SelectedItem = exchange;
//if(!SelectedExchangeName.IsEmpty())
SetExchange(exchange.Name);
//}
});
}
/// <summary>
/// To set edited exchange.
/// </summary>
/// <param name="exchangeName">The code of edited exchange. The exchange for editing is loaded from <see cref="IExchangeInfoProvider"/>.</param>
public void SetExchange(string exchangeName)
{
if (exchangeName.IsEmpty())
{
ResetEditor();
return;
}
ViewModel.SetExchange(exchangeName);
SelectedExchangeName = ViewModel.ExchangeName;
CbExchangeName.SelectedItem = Exchanges.FirstOrDefault(e => e.Name == SelectedExchangeName);
}
internal Exchange GetSelectedExchange()
{
return ViewModel.Exchange;
}
private void AutoCompleteSelector_OnKeyDown(object sender, KeyEventArgs e)
{
((ComboBox)sender).IsDropDownOpen = true;
}
private void ExchangeSelector_OnSelectionChanged(object sender, EventArgs e)
{
var cb = (ComboBox)sender;
if (cb.IsDropDownOpen)
return;
var curText = cb.SelectedValue as string ?? cb.Text.Trim();
if (curText.IsEmpty())
return;
ViewModel.SetExchange(curText);
SelectedExchangeName = ViewModel.ExchangeName;
}
private void ResetEditor()
{
ViewModel.SetExchange(null);
SelectedExchangeName = null;
CbExchangeName.SelectedItem = null;
CbExchangeName.Text = string.Empty;
}
private void CodeBox_Loaded(object sender, RoutedEventArgs e)
{
var cb = (ComboBox)sender;
var tb = cb.Template.FindName("PART_EditableTextBox", cb) as TextBox;
if(tb == null)
return;
DataObject.AddPastingHandler(tb, CheckPasteFormat);
tb.CharacterCasing = CharacterCasing.Upper;
tb.PreviewTextInput += (o, args) =>
{
var newText = tb.Text + args.Text;
if(!_checkCodeRegex.IsMatch(newText))
args.Handled = true;
};
}
private static void CheckPasteFormat(object sender, DataObjectPastingEventArgs args)
{
var tb = (TextBox)sender;
var str = args.DataObject.GetData(typeof(string)) as string;
var newStr = tb.Text + str;
if (!_checkCodeRegex.IsMatch(newStr))
args.CancelCommand();
}
private void VmOnDataChanged()
{
ViewModel.SaveExchange();
}
}
class ExchangeEditorViewModel : ViewModelBase
{
#region commands definition
private ICommand _commandAddNewExchange;
public ICommand CommandAddNewExchange
{
get { return _commandAddNewExchange ?? (_commandAddNewExchange = new DelegateCommand(o => CmdAddNewExchange(), o => true)); }
}
#endregion
private Exchange _exchange;
private bool _isNew;
private string _exchangeRusName, _exchangeEngName, _saveErrorMessage;
private CountryCodes? _countryCode;
private readonly ExchangeEditor _editor;
private bool _updatingModel;
public event Action DataChanged;
private IExchangeInfoProvider Provider { get; }
private IEnumerable<Exchange> Exchanges => _editor.Exchanges;
public ExchangeEditorViewModel(ExchangeEditor editor, IExchangeInfoProvider provider)
{
if (editor == null)
throw new ArgumentNullException(nameof(editor));
if (provider == null)
throw new ArgumentNullException(nameof(provider));
_editor = editor;
Provider = provider;
_isNew = true;
}
public void SetExchange(string exchangeName)
{
if (exchangeName.IsEmpty())
{
Reset();
}
else
{
exchangeName = exchangeName.ToUpperInvariant();
ExchangeName = exchangeName;
Exchange = Exchanges.FirstOrDefault(e => e.Name == exchangeName);
if (Exchange != null)
LoadFromExchange();
else
{
Reset();
ExchangeName = exchangeName;
}
}
IsNew = Exchange == null;
SaveErrorMessage = IsNew ? LocalizedStrings.Str1460 : null;
}
private void LoadFromExchange()
{
_updatingModel = true;
try
{
ExchangeRusName = Exchange.RusName;
ExchangeEngName = Exchange.EngName;
CountryCode = Exchange.CountryCode;
}
finally
{
_updatingModel = false;
}
}
private void Reset()
{
_updatingModel = true;
try
{
Exchange = null;
ExchangeName = ExchangeRusName = ExchangeEngName = string.Empty;
CountryCode = null;
IsNew = true;
}
finally
{
_updatingModel = false;
}
}
#region exchange parameters
public Exchange Exchange
{
get { return _exchange; }
private set { SetField(ref _exchange, value, () => Exchange, vmDataChanged: false); }
}
public string ExchangeName { get; private set; }
public bool IsNew
{
get { return _isNew; }
private set { SetField(ref _isNew, value, () => IsNew, vmDataChanged: false); }
}
public string ExchangeRusName
{
get { return _exchangeRusName; }
set { SetField(ref _exchangeRusName, value, () => ExchangeRusName); }
}
public string ExchangeEngName
{
get { return _exchangeEngName; }
set { SetField(ref _exchangeEngName, value, () => ExchangeEngName); }
}
public CountryCodes? CountryCode
{
get { return _countryCode; }
set { SetField(ref _countryCode, value, () => CountryCode); }
}
public string SaveErrorMessage
{
get { return _saveErrorMessage; }
set { SetField(ref _saveErrorMessage, value, () => SaveErrorMessage, vmDataChanged: false); }
}
#endregion
#region commands implementation
private void CmdAddNewExchange()
{
if (!IsNew || !IsExchangeDataValid())
return;
Exchange = CreateExchangeFromData();
IsNew = false;
SaveErrorMessage = null;
Provider.Save(Exchange);
}
#endregion
private bool IsExchangeDataValid()
{
if (ExchangeName.IsEmpty())
SaveErrorMessage = LocalizedStrings.Str1461;
else if (ExchangeRusName.IsEmpty())
SaveErrorMessage = LocalizedStrings.Str1462;
else if (ExchangeEngName.IsEmpty())
SaveErrorMessage = LocalizedStrings.Str1463;
else if (CountryCode == null)
SaveErrorMessage = LocalizedStrings.Str1464;
else
return true;
return false;
}
public void SaveExchange()
{
if (IsNew || Exchange == null || !IsExchangeDataValid())
return;
var ex = CreateExchangeFromData();
ex.Name = Exchange.Name;
Provider.Save(ex);
}
private Exchange CreateExchangeFromData()
{
return new Exchange
{
Name = ExchangeName,
RusName = ExchangeRusName,
EngName = ExchangeEngName,
CountryCode = CountryCode,
};
}
private void SetField<T>(ref T field, T value, Expression<Func<T>> selectorExpression, bool vmDataChanged = true)
{
var changed = base.SetField(ref field, value, selectorExpression);
if (!_updatingModel && vmDataChanged && changed)
DataChanged.SafeInvoke();
}
}
}
| |
//
// - PropertyNodeCollection.cs -
//
// Copyright 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// 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.Collections.Generic;
using System.Linq;
using Carbonfrost.Commons.Shared;
namespace Carbonfrost.Commons.PropertyTrees {
public abstract class PropertyNodeCollection : IList<PropertyNode>, IList {
public virtual PropertyNode this[QualifiedName name] {
get {
if (name == null)
throw new ArgumentNullException("name");
foreach (var t in this) {
if (name == t.QualifiedName)
return t;
}
return null;
}
}
public virtual PropertyNode this[string name, string ns] {
get {
if (name == null)
throw new ArgumentNullException("name"); // $NON-NLS-1
if (name.Length == 0)
throw Failure.EmptyString("name"); // $NON-NLS-1
ns = ns ?? string.Empty;
return this[QualifiedName.Create(ns, name)];
}
}
public virtual PropertyNode this[string name] {
get {
return this[name, null];
}
}
public virtual PropertyNode this[int index] {
get {
if (index < 0 || index > this.Count)
throw Failure.IndexOutOfRange("index", index, 0, this.Count - 1);
foreach (var t in this) {
if (index-- == 0)
return t;
}
return null;
}
}
// IList<PropertyNode> implementation
PropertyNode IList<PropertyNode>.this[int index] {
get { return this[index]; }
set { throw Failure.ReadOnlyCollection(); } }
public abstract int Count { get; }
public virtual bool IsReadOnly { get { return false; } }
public virtual int IndexOf(PropertyNode item) {
if (item == null)
throw new ArgumentNullException("item"); // $NON-NLS-1
int index = 0;
foreach (var pn in this) {
if (object.Equals(pn, item))
return index;
index++;
}
return -1;
}
public virtual int IndexOf(QualifiedName name) {
if (name == null)
throw new ArgumentNullException("name");
int index = 0;
foreach (var pn in this) {
if (pn.QualifiedName == name)
return index;
index++;
}
return -1;
}
void IList<PropertyNode>.Insert(int index, PropertyNode item) {
throw Failure.ReadOnlyCollection();
}
void IList<PropertyNode>.RemoveAt(int index) {
throw Failure.ReadOnlyCollection();
}
void ICollection<PropertyNode>.Add(PropertyNode item) {
throw Failure.ReadOnlyCollection();
}
void ICollection<PropertyNode>.Clear() {
throw Failure.ReadOnlyCollection();
}
public virtual bool Contains(PropertyNode item) {
return IndexOf(item) >= 0;
}
public bool Contains(string ns, string name) {
return IndexOf(QualifiedName.Create(ns, name)) >= 0;
}
public bool Contains(string name) {
return IndexOf(NamespaceUri.Default + name) >= 0;
}
public virtual bool Contains(QualifiedName name) {
return IndexOf(name) >= 0;
}
public virtual void CopyTo(PropertyNode[] array, int arrayIndex) {
if (array == null)
throw new ArgumentNullException("array"); // $NON-NLS-1
if (array.Rank != 1)
throw Failure.RankNotOne("array"); // $NON-NLS-1
if (arrayIndex < 0 || arrayIndex >= array.Length)
throw Failure.IndexOutOfRange("arrayIndex", arrayIndex, 0, array.Length - 1); // $NON-NLS-1
if (arrayIndex + this.Count > array.Length)
throw Failure.NotEnoughSpaceInArray("arrayIndex", arrayIndex); // $NON-NLS-1
foreach (var t in this)
array[arrayIndex++] = t;
}
bool ICollection<PropertyNode>.Remove(PropertyNode item) {
throw Failure.ReadOnlyCollection();
}
public abstract IEnumerator<PropertyNode> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
object IList.this[int index] {
get {
return this[index];
}
set {
throw Failure.ReadOnlyCollection();
}
}
bool IList.IsFixedSize {
get { return false; } }
object ICollection.SyncRoot {
get { return null; } }
bool ICollection.IsSynchronized {
get { return false; } }
int IList.Add(object value) {
throw Failure.ReadOnlyCollection();
}
bool IList.Contains(object value) {
throw Failure.ReadOnlyCollection();
}
int IList.IndexOf(object value) {
if (value == null)
throw new ArgumentNullException("value");
PropertyNode node = value as PropertyNode;
if (node == null)
return -1;
int index = 0;
foreach (var current in this) {
if (node == current)
return index;
index++;
}
return -1;
}
void IList.Insert(int index, object value) {
throw Failure.ReadOnlyCollection();
}
void IList.Remove(object value) {
throw Failure.ReadOnlyCollection();
}
void ICollection.CopyTo(Array array, int index) {
this.ToArray().CopyTo(array, index);
}
void IList.RemoveAt(int index) {
throw Failure.ReadOnlyCollection();
}
void IList.Clear() {
throw Failure.ReadOnlyCollection();
}
}
}
| |
#region Copyright (c) 2009 S. van Deursen
/* The CuttingEdge.Conditions library enables developers to validate pre- and postconditions in a fluent
* manner.
*
* To contact me, please visit my blog at http://www.cuttingedge.it/blogs/steven/
*
* Copyright (c) 2009 S. van Deursen
*
* 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
// NOTE: Some methods and properties are decorated with the EditorBrowsableAttribute to prevent those methods
// and properties from showing up in IntelliSense. These members will not be used by users that try to
// validate arguments and are therefore misleading.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace CuttingEdge.Conditions
{
/// <summary>
/// Enables validation of pre- and postconditions. This class isn't used directly by developers. Instead
/// the class should be created by the <see cref="Condition.Requires{T}(T)">Requires</see> and
/// <see cref="Condition.Ensures{T}(T)">Ensures</see> extension methods.
/// </summary>
/// <typeparam name="T">The type of the argument to be validated</typeparam>
/// <example>
/// The following example shows how to use <b>CuttingEdge.Conditions</b>.
/// <code><![CDATA[
/// using System.Collections;
///
/// using CuttingEdge.Conditions;
///
/// public class ExampleClass
/// {
/// private enum StateType { Uninitialized = 0, Initialized };
///
/// private StateType currentState;
///
/// public ICollection GetData(int? id, string xml, IEnumerable col)
/// {
/// // Check all preconditions:
/// Condition.Requires(id, "id")
/// .IsNotNull() // throws ArgumentNullException on failure
/// .IsInRange(1, 999) // ArgumentOutOfRangeException on failure
/// .IsNotEqualTo(128); // throws ArgumentException on failure
///
/// Condition.Requires(xml, "xml")
/// .StartsWith("<data>") // throws ArgumentException on failure
/// .EndsWith("</data>"); // throws ArgumentException on failure
///
/// Condition.Requires(col, "col")
/// .IsNotNull() // throws ArgumentNullException on failure
/// .IsEmpty(); // throws ArgumentException on failure
///
/// // Do some work
///
/// // Example: Call a method that should return a not null ICollection
/// object result = BuildResults(xml, col);
///
/// // Check all postconditions:
/// // A PostconditionException will be thrown at failure.
/// Condition.Ensures(result, "result")
/// .IsNotNull()
/// .IsOfType(typeof(ICollection));
///
/// return result as ICollection;
/// }
/// }
/// ]]></code>
/// The following code examples shows how to extend the library with your own 'Invariant' entry point
/// method. The first example shows a class with an Add method that validates the class state (the
/// class invariants) before adding the <b>Person</b> object to the internal array and that code should
/// throw an <see cref="InvalidOperationException"/>.
/// <code><![CDATA[
/// using CuttingEdge.Conditions;
///
/// public class Person { }
///
/// public class PersonCollection
/// {
/// public PersonCollection(int capicity)
/// {
/// this.Capacity = capicity;
/// }
///
/// public void Add(Person person)
/// {
/// // Throws a ArgumentNullException when person == null
/// Condition.Requires(person, "person").IsNotNull();
///
/// // Throws an InvalidOperationException on failure
/// Invariants.Invariant(this.Count, "Count").IsLessOrEqual(this.Capacity);
///
/// this.AddInternal(person);
/// }
///
/// public int Count { get; private set; }
/// public int Capacity { get; private set; }
///
/// private void AddInternal(Person person)
/// {
/// // some logic here
/// }
///
/// public bool Contains(Person person)
/// {
/// // some logic here
/// return false;
/// }
/// }
/// ]]></code>
/// The following code example will show the implementation of the <b>Invariants</b> class.
/// <code><![CDATA[
/// using System;
/// using CuttingEdge.Conditions;
///
/// namespace MyCompanyRootNamespace
/// {
/// public static class Invariants
/// {
/// public static ConditionValidator<T> Invariant<T>(T value)
/// {
/// return new InvariantValidator<T>("value", value);
/// }
///
/// public static ConditionValidator<T> Invariant<T>(T value, string argumentName)
/// {
/// return new InvariantValidator<T>(argumentName, value);
/// }
///
/// // Internal class that inherits from ConditionValidator<T>
/// sealed class InvariantValidator<T> : ConditionValidator<T>
/// {
/// public InvariantValidator(string argumentName, T value)
/// : base(argumentName, value)
/// {
/// }
///
/// protected override void ThrowExceptionCore(string condition,
/// string additionalMessage, ConstraintViolationType type)
/// {
/// string exceptionMessage = string.Format("Invariant '{0}' failed.", condition);
///
/// if (!String.IsNullOrEmpty(additionalMessage))
/// {
/// exceptionMessage += " " + additionalMessage;
/// }
///
/// // Optionally, the 'type' parameter can be used, but never throw an exception
/// // when the value of 'type' is unknown or unvalid.
/// throw new InvalidOperationException(exceptionMessage);
/// }
/// }
/// }
/// }
/// ]]></code>
/// </example>
[DebuggerDisplay("{GetType().Name} ( ArgumentName: {ArgumentName}, Value: {Value} )")]
public abstract class ConditionValidator<T>
{
/// <summary>Gets the value of the argument.</summary>
[EditorBrowsable(EditorBrowsableState.Never)] // see top of page for note on this attribute.
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification =
"We chose to make the Value a public field, so the Extension methods can use it, without we " +
"have to worry about extra method calls.")]
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",
Justification = "The rule is correct. We tried to make ConditionValidator<T> immutable, but " +
"the validated type T can indeed be mutable (a collection for example). However, for us it's " +
"enough to be sure that the value or the reference to the value won't change.")]
public readonly T Value;
private readonly string argumentName;
/// <summary>Initializes a new instance of the <see cref="ConditionValidator{T}"/> class.</summary>
/// <param name="argumentName">The name of the argument to be validated</param>
/// <param name="value">The value of the argument to be validated</param>
protected ConditionValidator(string argumentName, T value)
{
// This constructor is internal. It is not useful for a user to inherit from this class.
// When this ctor is made protected, so should be the BuildException method.
this.Value = value;
this.argumentName = argumentName;
}
/// <summary>Gets the name of the argument.</summary>
[EditorBrowsable(EditorBrowsableState.Never)] // see top of page for note on this attribute.
public string ArgumentName
{
get { return this.argumentName; }
}
/// <summary>
/// Determines whether the specified System.Object is equal to the current System.Object.
/// </summary>
/// <param name="obj">The System.Object to compare with the current System.Object.</param>
/// <returns>
/// true if the specified System.Object is equal to the current System.Object; otherwise, false.
/// </returns>
[EditorBrowsable(EditorBrowsableState.Never)] // see top of page for note on this attribute.
[Obsolete("This method is not part of the conditions framework. Please use the IsEqualTo method.", true)]
#pragma warning disable 809 // Remove the Obsolete attribute from the overriding member, or add it to the ...
public override bool Equals(object obj)
#pragma warning restore 809
{
return base.Equals(obj);
}
/// <summary>Returns the hash code of the current instance.</summary>
/// <returns>The hash code of the current instance.</returns>
[EditorBrowsable(EditorBrowsableState.Never)] // see top of page for note on this attribute.
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the <see cref="ConditionValidator{T}"/>.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents the <see cref="ConditionValidator{T}"/>.
/// </returns>
[EditorBrowsable(EditorBrowsableState.Never)] // see top of page for note on this attribute.
public override string ToString()
{
return base.ToString();
}
/// <summary>Gets the <see cref="System.Type"/> of the current instance.</summary>
/// <returns>The <see cref="System.Type"/> instance that represents the exact runtime
/// type of the current instance.</returns>
[EditorBrowsable(EditorBrowsableState.Never)] // see top of page for note on this attribute.
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification =
"This FxCop warning is valid, but this method is used to be able to attach an " +
"EditorBrowsableAttrubute to the GetType method, which will hide the method when the user " +
"browses the methods of the ConditionValidator class with IntelliSense. The GetType method has " +
"no value for the user who will only use this class for validation.")]
public new Type GetType()
{
return base.GetType();
}
/// <summary>Throws an exception.</summary>
/// <param name="condition">Describes the condition that doesn't hold, e.g., "Value should not be
/// null".</param>
/// <param name="additionalMessage">An additional message that will be appended to the exception
/// message, e.g. "The actual value is 3.". This value may be null or empty.</param>
/// <param name="type">Gives extra information on the exception type that must be build. The actual
/// implementation of the validator may ignore some or all values.</param>
[EditorBrowsable(EditorBrowsableState.Never)] // see top of page for note on this attribute.
public void ThrowException(string condition, string additionalMessage, ConstraintViolationType type)
{
this.ThrowExceptionCore(condition, additionalMessage, type);
}
/// <summary>Throws an exception.</summary>
/// <param name="condition">Describes the condition that doesn't hold, e.g., "Value should not be
/// null".</param>
[EditorBrowsable(EditorBrowsableState.Never)] // see top of page for note on this attribute.
public void ThrowException(string condition)
{
this.ThrowExceptionCore(condition, null, ConstraintViolationType.Default);
}
internal void ThrowException(string condition, string additionalMessage)
{
this.ThrowExceptionCore(condition, additionalMessage, ConstraintViolationType.Default);
}
internal void ThrowException(string condition, ConstraintViolationType type)
{
this.ThrowExceptionCore(condition, null, type);
}
/// <summary>Throws an exception.</summary>
/// <param name="condition">Describes the condition that doesn't hold, e.g., "Value should not be
/// null".</param>
/// <param name="additionalMessage">An additional message that will be appended to the exception
/// message, e.g. "The actual value is 3.". This value may be null or empty.</param>
/// <param name="type">Gives extra information on the exception type that must be build. The actual
/// implementation of the validator may ignore some or all values.</param>
/// <remarks>
/// Implement this method when deriving from <see cref="ConditionValidator{T}"/>.
/// The implementation should at least build the exception message from the
/// <paramref name="condition"/> and optional <paramref name="additionalMessage"/>. Usage of the
/// <paramref name="type"/> is completely optional, but the implementation should at least be flexible
/// and be able to handle unknown <see cref="ConstraintViolationType"/> values. Values may be added
/// in future releases.
/// </remarks>
/// <example>
/// For an example see the documentation for <see cref="ConditionValidator{T}"/>.
/// </example>
protected abstract void ThrowExceptionCore(string condition, string additionalMessage,
ConstraintViolationType type);
}
}
| |
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using CsCheck;
namespace ImTools.UnitTests
{
[TestFixture]
public class ImHashMap234Tests
{
[Test]
public void Adding_to_ImHashMap_and_checking_the_tree_shape_on_each_addition()
{
var m = ImHashMap<int, string>.Empty;
Assert.AreEqual(null, m.GetValueOrDefault(0));
Assert.AreEqual(null, m.GetValueOrDefault(13));
Assert.IsEmpty(m.Enumerate());
Assert.AreEqual(0, m.Count());
m = m.AddOrUpdate(1, "a");
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(1, m.Count());
Assert.AreSame(m, m.AddOrKeep(1, "aa"));
var mr = m.Remove(1);
Assert.AreSame(ImHashMap<int, string>.Empty, mr);
Assert.AreEqual(0, mr.Count());
m = m.AddOrUpdate(2, "b");
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1, 2 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(2, m.Count());
Assert.AreSame(m, m.AddOrKeep(1, "aa").AddOrKeep(2, "bb"));
Assert.AreSame(m, m.Remove(0));
mr = m.Remove(2);
Assert.AreEqual("a", mr.GetValueOrDefault(1));
Assert.AreEqual(1, mr.Count());
m = m.AddOrUpdate(3, "c");
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(3, m.Count());
Assert.AreSame(m, m.AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
Assert.AreSame(m, m.Remove(0));
mr = m.Remove(2);
Assert.AreEqual("a", mr.GetValueOrDefault(1));
Assert.AreEqual("c", mr.GetValueOrDefault(3));
Assert.AreEqual(2, mr.Count());
m = m.AddOrUpdate(4, "d");
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual("d", m.GetValueOrDefault(4));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(4, m.Count());
Assert.AreSame(m, m.AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
Assert.AreSame(m, m.Remove(0));
m = m.AddOrUpdate(5, "e");
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual("d", m.GetValueOrDefault(4));
Assert.AreEqual("e", m.GetValueOrDefault(5));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(5, m.Count());
Assert.AreSame(m, m.AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
Assert.AreSame(m, m.Remove(0));
m = m.AddOrUpdate(6, "6");
Assert.AreEqual("6", m.GetValueOrDefault(6));
Assert.AreEqual("e", m.GetValueOrDefault(5));
Assert.AreEqual("d", m.GetValueOrDefault(4));
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(10));
Assert.AreSame(m, m.AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(6, m.Count());
m = m.AddOrUpdate(7, "7");
Assert.AreEqual("7", m.GetValueOrDefault(7));
m = m.AddOrUpdate(8, "8");
Assert.AreEqual("8", m.GetValueOrDefault(8));
m = m.AddOrUpdate(9, "9");
Assert.AreEqual("9", m.GetValueOrDefault(9));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(9, m.Count());
m = m.AddOrUpdate(10, "10");
Assert.AreEqual("10", m.GetValueOrDefault(10));
Assert.AreEqual("9", m.GetValueOrDefault(9));
Assert.AreEqual("8", m.GetValueOrDefault(8));
Assert.AreEqual("7", m.GetValueOrDefault(7));
Assert.AreEqual("6", m.GetValueOrDefault(6));
Assert.AreEqual("e", m.GetValueOrDefault(5));
Assert.AreEqual("d", m.GetValueOrDefault(4));
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(11));
Assert.AreSame(m, m.AddOrKeep(8, "8!").AddOrKeep(5, "5!").AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(10, m.Count());
m = m.AddOrUpdate(11, "11");
m = m.AddOrUpdate(12, "12");
m = m.AddOrUpdate(13, "13");
Assert.AreEqual("11", m.GetValueOrDefault(11));
Assert.AreEqual("12", m.GetValueOrDefault(12));
Assert.AreEqual("13", m.GetValueOrDefault(13));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(13, m.Count());
m = m.AddOrUpdate(14, "14");
Assert.AreEqual("14", m.GetValueOrDefault(14));
Assert.AreEqual(14, m.Count());
m = m.AddOrUpdate(15, "15");
m = m.AddOrUpdate(16, "16");
m = m.AddOrUpdate(17, "17");
Assert.AreEqual("15", m.GetValueOrDefault(15));
Assert.AreEqual("16", m.GetValueOrDefault(16));
Assert.AreEqual("17", m.GetValueOrDefault(17));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(17, m.Count());
m = m.AddOrUpdate(18, "18");
Assert.AreEqual("18", m.GetValueOrDefault(18));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(18, m.Count());
var r = m.Remove(18).Remove(17).Remove(16);
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, r.Enumerate().Select(x => x.Hash));
Assert.IsNull(r.GetValueOrDefault(16));
var rr = r.Remove(16);
Assert.AreSame(r, rr);
m = m.AddOrUpdate(18, "18");
m = m.AddOrKeep(18, "18");
Assert.AreEqual("18", m.GetValueOrDefault(18));
m = m.AddOrUpdate(19, "19").AddOrUpdate(20, "20").AddOrUpdate(21, "21").AddOrUpdate(22, "22").AddOrUpdate(23, "23");
rr = m.Remove(25).Remove(21);
Assert.IsNull(rr.GetValueOrDefault(21));
}
[Test]
public void Adding_to_ImMap_and_checking_the_tree_shape_on_each_addition()
{
var m = ImMap<string>.Empty;
Assert.AreEqual(null, m.GetValueOrDefault(0));
Assert.AreEqual(null, m.GetValueOrDefault(13));
Assert.IsEmpty(m.Enumerate());
Assert.AreEqual(0, m.Count());
m = m.AddOrUpdate(1, "a");
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(1, m.Count());
Assert.AreSame(m, m.AddOrKeep(1, "aa"));
var mr = m.Remove(1);
Assert.AreSame(ImMap<string>.Empty, mr);
Assert.AreEqual(0, mr.Count());
m = m.AddOrUpdate(2, "b");
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1, 2 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(2, m.Count());
Assert.AreSame(m, m.AddOrKeep(1, "aa").AddOrKeep(2, "bb"));
Assert.AreSame(m, m.Remove(0));
mr = m.Remove(2);
Assert.AreEqual("a", mr.GetValueOrDefault(1));
Assert.AreEqual(1, mr.Count());
m = m.AddOrUpdate(3, "c");
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(3, m.Count());
Assert.AreSame(m, m.AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
Assert.AreSame(m, m.Remove(0));
mr = m.Remove(2);
Assert.AreEqual("a", mr.GetValueOrDefault(1));
Assert.AreEqual("c", mr.GetValueOrDefault(3));
Assert.AreEqual(2, mr.Count());
m = m.AddOrUpdate(4, "d");
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual("d", m.GetValueOrDefault(4));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(4, m.Count());
Assert.AreSame(m, m.AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
Assert.AreSame(m, m.Remove(0));
m = m.AddOrUpdate(5, "e");
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual("d", m.GetValueOrDefault(4));
Assert.AreEqual("e", m.GetValueOrDefault(5));
Assert.AreEqual(null, m.GetValueOrDefault(10));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(5, m.Count());
Assert.AreSame(m, m.AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
Assert.AreSame(m, m.Remove(0));
m = m.AddOrUpdate(6, "6");
Assert.AreEqual("6", m.GetValueOrDefault(6));
Assert.AreEqual("e", m.GetValueOrDefault(5));
Assert.AreEqual("d", m.GetValueOrDefault(4));
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(10));
Assert.AreSame(m, m.AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(6, m.Count());
m = m.AddOrUpdate(7, "7");
Assert.AreEqual("7", m.GetValueOrDefault(7));
m = m.AddOrUpdate(8, "8");
Assert.AreEqual("8", m.GetValueOrDefault(8));
m = m.AddOrUpdate(9, "9");
Assert.AreEqual("9", m.GetValueOrDefault(9));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(9, m.Count());
mr = m.Remove(9);
Assert.IsNull(mr.GetValueOrDefault(9));
m = m.AddOrUpdate(10, "10");
Assert.AreEqual("10", m.GetValueOrDefault(10));
Assert.AreEqual("9", m.GetValueOrDefault(9));
Assert.AreEqual("8", m.GetValueOrDefault(8));
Assert.AreEqual("7", m.GetValueOrDefault(7));
Assert.AreEqual("6", m.GetValueOrDefault(6));
Assert.AreEqual("e", m.GetValueOrDefault(5));
Assert.AreEqual("d", m.GetValueOrDefault(4));
Assert.AreEqual("c", m.GetValueOrDefault(3));
Assert.AreEqual("b", m.GetValueOrDefault(2));
Assert.AreEqual("a", m.GetValueOrDefault(1));
Assert.AreEqual(null, m.GetValueOrDefault(11));
Assert.AreSame(m, m.AddOrKeep(8, "8!").AddOrKeep(5, "5!").AddOrKeep(3, "aa").AddOrKeep(2, "bb").AddOrKeep(1, "cc"));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(10, m.Count());
m = m.AddOrUpdate(11, "11");
m = m.AddOrUpdate(12, "12");
m = m.AddOrUpdate(13, "13");
Assert.AreEqual("11", m.GetValueOrDefault(11));
Assert.AreEqual("12", m.GetValueOrDefault(12));
Assert.AreEqual("13", m.GetValueOrDefault(13));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(13, m.Count());
m = m.AddOrUpdate(14, "14");
Assert.AreEqual("14", m.GetValueOrDefault(14));
Assert.AreEqual(14, m.Count());
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, m.Enumerate().Select(x => x.Hash));
m = m.AddOrUpdate(15, "15");
m = m.AddOrUpdate(16, "16");
m = m.AddOrUpdate(17, "17");
Assert.AreEqual("15", m.GetValueOrDefault(15));
Assert.AreEqual("16", m.GetValueOrDefault(16));
Assert.AreEqual("17", m.GetValueOrDefault(17));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(17, m.Count());
m = m.AddOrUpdate(18, "18");
Assert.AreEqual("18", m.GetValueOrDefault(18));
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }, m.Enumerate().Select(x => x.Hash));
Assert.AreEqual(18, m.Count());
var r = m.Remove(18).Remove(17).Remove(16);
CollectionAssert.AreEquivalent(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, r.Enumerate().Select(x => x.Hash));
Assert.IsNull(r.GetValueOrDefault(16));
var rr = r.Remove(16);
Assert.AreSame(r, rr);
m = m.AddOrUpdate(18, "18");
m = m.AddOrKeep(18, "18");
Assert.AreEqual("18", m.GetValueOrDefault(18));
m = m.AddOrUpdate(19, "19").AddOrUpdate(20, "20").AddOrUpdate(21, "21").AddOrUpdate(22, "22").AddOrUpdate(23, "23");
rr = m.Remove(25).Remove(21);
Assert.IsNull(rr.GetValueOrDefault(21));
}
public class XKey<K>
{
public K Key;
public XKey(K k) => Key = k;
public override int GetHashCode() => 1;
public override bool Equals(object o) => o is XKey<K> x && Key.Equals(x.Key);
}
public static XKey<K> Xk<K>(K key) => new XKey<K>(key);
[Test]
public void Adding_the_conflicting_keys_should_be_fun()
{
var m = ImHashMap<XKey<int>, string>.Empty;
Assert.AreEqual(null, m.GetValueOrDefault(Xk(0)));
Assert.AreEqual(null, m.GetValueOrDefault(Xk(13)));
m = m.AddOrUpdate(Xk(1), "a");
m = m.AddOrUpdate(Xk(2), "b");
Assert.AreNotEqual(typeof(ImHashMapEntry<XKey<int>, string>), m.GetType());
Assert.AreEqual("a", m.GetValueOrDefault(Xk(1)));
Assert.AreEqual("b", m.GetValueOrDefault(Xk(2)));
Assert.AreEqual(null, m.GetValueOrDefault(Xk(10)));
var mr = m.Remove(Xk(1));
Assert.AreNotEqual(typeof(ImHashMapEntry<XKey<int>, string>), m.GetType());
Assert.AreEqual(null, mr.GetValueOrDefault(Xk(1)));
Assert.AreEqual("b", mr.GetValueOrDefault(Xk(2)));
m = m.AddOrUpdate(Xk(3), "c");
mr = m.Remove(Xk(2));
Assert.AreNotEqual(typeof(ImHashMapEntry<XKey<int>, string>), m.GetType());
Assert.AreEqual("a", mr.GetValueOrDefault(Xk(1)));
Assert.AreEqual(null, mr.GetValueOrDefault(Xk(2)));
Assert.AreEqual("c", mr.GetValueOrDefault(Xk(3)));
}
[Test]
public void Adding_1000_keys_and_randomly_checking()
{
var m = ImHashMap<int, int>.Empty;
for (var i = 0; i < 5000; i++)
{
m = m.AddOrUpdate(i, i);
}
Assert.AreEqual(1, m.GetValueOrDefault(1));
Assert.AreEqual(0, m.GetValueOrDefault(0));
Assert.AreEqual(13, m.GetValueOrDefault(13));
Assert.AreEqual(66, m.GetValueOrDefault(66));
Assert.AreEqual(555, m.GetValueOrDefault(555));
Assert.AreEqual(333, m.GetValueOrDefault(333));
Assert.AreEqual(999, m.GetValueOrDefault(999));
// non-existing keys
Assert.AreEqual(0, m.GetValueOrDefault(10000));
Assert.AreEqual(0, m.GetValueOrDefault(-1));
}
[Test]
public void Adding_1000_keys_descending_and_randomly_checking()
{
var m = ImHashMap<int, int>.Empty;
for (var i = 5000 - 1; i >= 0; i--)
{
m = m.AddOrUpdate(i, i);
}
Assert.AreEqual(1, m.GetValueOrDefault(1));
Assert.AreEqual(0, m.GetValueOrDefault(0));
Assert.AreEqual(13, m.GetValueOrDefault(13));
Assert.AreEqual(66, m.GetValueOrDefault(66));
Assert.AreEqual(555, m.GetValueOrDefault(555));
Assert.AreEqual(333, m.GetValueOrDefault(333));
Assert.AreEqual(999, m.GetValueOrDefault(999));
// non-existing keys
Assert.AreEqual(0, m.GetValueOrDefault(10000));
Assert.AreEqual(0, m.GetValueOrDefault(-1));
}
[Test]
public void ImHashMap_AddOrUpdate_random_items_and_randomly_checking_CsCheck()
{
const int upperBound = 100000;
Gen.Int[0, upperBound].Array.Sample(items =>
{
var m = ImHashMap<int, int>.Empty;
foreach (int n in items)
{
m = m.AddOrUpdate(n, n);
Assert.AreEqual(n, m.GetValueOrDefault(n));
}
foreach (int n in items)
Assert.AreEqual(n, m.GetValueOrDefault(n));
// non-existing keys
Assert.AreEqual(0, m.GetValueOrDefault(upperBound + 1));
Assert.AreEqual(0, m.GetValueOrDefault(-1));
},
iter: 5000);
}
[Test]
public void ImMap_AddOrUpdate_random_items_and_randomly_checking_CsCheck()
{
const int upperBound = 100000;
Gen.Int[0, upperBound].Array.Sample(items =>
{
var m = ImMap<int>.Empty;
foreach (int n in items)
{
m = m.AddOrUpdate(n, n);
Assert.AreEqual(n, m.GetValueOrDefault(n));
}
foreach (int n in items)
Assert.AreEqual(n, m.GetValueOrDefault(n));
// non-existing keys
Assert.AreEqual(0, m.GetValueOrDefault(upperBound + 1));
Assert.AreEqual(0, m.GetValueOrDefault(-1));
},
iter: 5000);
}
[Test]
public void ImMap_AddOrUpdate_random_items_and_randomly_checking_CsCheck_FailedCase2()
{
var items = new[] { 81827, 98388, 55336, 13449, 96388, 3895, 7794, 98331, 44532, 94862, 89412, 25144, 18434, 44532, 58167 };
var m = ImMap<int>.Empty;
foreach (int n in items)
{
m = m.AddOrUpdate(n, n);
Assert.AreEqual(n, m.GetValueOrDefault(n));
}
foreach (int n in items)
Assert.AreEqual(n, m.GetValueOrDefault(n));
}
[Test]
public void ImMap_AddOrUpdate_random_items_and_randomly_checking_CsCheck_FiledCase1()
{
var hashes = new[] { 98470, 31912, 32917, 40383, 23438, 70273, 47956, 43609, 10213, 2236, 20614 };
var m = ImMap<int>.Empty;
foreach (int h in hashes)
{
m = m.AddOrUpdate(h, h);
Assert.AreEqual(h, m.GetValueOrDefault(h));
}
foreach (int h in hashes)
Assert.AreEqual(h, m.GetValueOrDefault(h));
// non-existing keys
Assert.AreEqual(0, m.GetValueOrDefault(0));
Assert.AreEqual(0, m.GetValueOrDefault(-1));
}
[Test]
public void AddOrUpdate_random_items_and_randomly_checking_CsCheck_shrinked()
{
const int upperBound = 100000;
Gen.Int[0, upperBound].Array.Sample(items =>
{
var m = ImHashMap<int, int>.Empty;
foreach (int n in items)
{
m = m.AddOrUpdate(n, n);
Assert.AreEqual(n, m.GetValueOrDefault(n));
}
for (int i = 0; i < items.Length; ++i)
{
var n = items[i];
var x = m.GetValueOrDefault(n);
if (x != n)
{
if (i + 1 != items.Length)
Debug.WriteLine($"Not at end i = {i}");
Debug.WriteLine($"Array = {string.Join(", ", items)}");
}
Assert.AreEqual(n, x);
}
// non-existing keys
Assert.AreEqual(0, m.GetValueOrDefault(upperBound + 1));
Assert.AreEqual(0, m.GetValueOrDefault(-1));
},
iter: 5000, seed: "0ZPySr9kwyWr");
}
[Test]
public void AddOrUpdate_problematic_shrinked_set_case1__repeated_item()
{
var items = new[] { 85213, 8184, 14819, 38204, 1738, 6752, 38204, 22310, 86961, 33016, 72555, 25102 };
var m = ImHashMap<int, int>.Empty;
foreach (var i in items)
m = m.AddOrUpdate(i, i);
foreach (var i in items)
Assert.AreEqual(i, m.GetValueOrDefault(i));
}
[Test]
public void AddOrUpdate_problematic_shrinked_set_case2__repeated_hash_erased()
{
var items = new[] {
45751, 6825, 44599, 79942, 73380, 8408, 34126, 51224, 14463, 71529, 46775, 74893, 80615, 78504, 29401, 60789, 14050,
67780, 52369, 16486, 48124, 46939, 43229, 58359, 61378, 31969, 79905, 37405, 37259, 66683, 58359, 87401, 42175 };
var m = ImHashMap<int, int>.Empty;
foreach (var i in items)
{
m = m.AddOrUpdate(i, i);
Assert.AreEqual(i, m.GetValueOrDefault(i));
}
foreach (var i in items)
Assert.AreEqual(i, m.GetValueOrDefault(i));
}
[Test]
public void AddOrUpdate_problematic_shrinked_set_case3()
{
var items = new[] { 87173, 99053, 63922, 20879, 77178, 95518, 16692, 60819, 29881, 69987, 24798, 67743 };
var m = ImHashMap<int, int>.Empty;
foreach (var i in items)
m = m.AddOrUpdate(i, i);
foreach (var i in items)
Assert.AreEqual(i, m.GetValueOrDefault(i));
}
[Test]
public void AddOrUpdate_problematic_shrinked_set_case4()
{
var items = new[] { 78290, 97898, 23194, 12403, 27002, 78600, 92105, 76902, 90802, 84883, 78290, 18374 };
var m = ImHashMap<int, int>.Empty;
foreach (var i in items)
m = m.AddOrUpdate(i, i);
foreach (var i in items)
Assert.AreEqual(i, m.GetValueOrDefault(i));
}
[Test]
public void Enumerate_should_work_for_the_randomized_input()
{
var uniqueItems = new[] {
45751, 6825, 44599, 79942, 73380, 8408, 34126, 51224, 14463, 71529, 46775, 74893, 80615, 78504, 29401, 60789, 14050,
67780, 52369, 16486, 48124, 46939, 43229, 58359, 61378, 31969, 79905, 37405, 37259, 66683, 87401, 42175 };
var m = ImHashMap<int, int>.Empty;
foreach (var i in uniqueItems)
m = m.AddOrUpdate(i, i);
CollectionAssert.AreEqual(uniqueItems.OrderBy(x => x), m.Enumerate().Select(x => x.Hash));
}
[Test]
public void Enumerate_should_work_for_the_randomized_input_2()
{
var uniqueItems = new[] {
17883, 23657, 24329, 29524, 55791, 66175, 67389, 74867, 74946, 81350, 94477, 70414, 26499 };
var m = ImHashMap<int, int>.Empty;
foreach (var i in uniqueItems)
m = m.AddOrUpdate(i, i);
CollectionAssert.AreEqual(uniqueItems.OrderBy(x => x), m.Enumerate().ToArray().Select(x => x.Hash));
}
[Test]
public void ImMap_Enumerate_should_work_for_the_randomized_input()
{
var uniqueItems = new[] {
45751, 6825, 44599, 79942, 73380, 8408, 34126, 51224, 14463, 71529, 46775, 74893, 80615, 78504, 29401, 60789, 14050,
67780, 52369, 16486, 48124, 46939, 43229, 58359, 61378, 31969, 79905, 37405, 37259, 66683, 87401, 42175 };
var m = ImMap<int>.Empty;
foreach (var i in uniqueItems)
m = m.AddOrUpdate(i, i);
CollectionAssert.AreEqual(uniqueItems.OrderBy(x => x), m.Enumerate().Select(x => x.Hash));
}
[Test]
public void ImMap_Enumerate_should_work_for_the_randomized_input_2()
{
var uniqueItems = new[] {
17883, 23657, 24329, 29524, 55791, 66175, 67389, 74867, 74946, 81350, 94477, 70414, 26499 };
var m = ImMap<int>.Empty;
foreach (var i in uniqueItems)
m = m.AddOrUpdate(i, i);
CollectionAssert.AreEqual(uniqueItems.OrderBy(x => x), m.Enumerate().ToArray().Select(x => x.Hash));
}
[Test]
public void Enumerate_should_work_for_the_randomized_input_3()
{
var uniqueItems = new int[] { 65347, 87589, 89692, 92562, 97319, 58955 };
var m = ImHashMap<int, int>.Empty;
foreach (var i in uniqueItems)
m = m.AddOrUpdate(i, i);
CollectionAssert.AreEqual(uniqueItems.OrderBy(x => x), m.Enumerate().ToArray().Select(x => x.Hash));
}
[Test]
public void ImHashMap_AddOrKeep_random_items_and_randomly_checking_CsCheck()
{
const int upperBound = 100000;
Gen.Int[0, upperBound].Array.Sample(items =>
{
var m = ImHashMap<int, int>.Empty;
foreach (int n in items)
{
m = m.AddOrKeep(n, n);
Assert.AreEqual(n, m.GetValueOrDefault(n));
}
foreach (int n in items)
Assert.AreEqual(n, m.GetValueOrDefault(n));
// non-existing keys
Assert.AreEqual(0, m.GetValueOrDefault(upperBound + 1));
Assert.AreEqual(0, m.GetValueOrDefault(-1));
},
iter: 5000);
}
static Gen<(ImHashMap<int, int>, int[])> GenImHashMap(int upperBound) =>
Gen.Int[0, upperBound].ArrayUnique.SelectMany(keys =>
Gen.Int.Array[keys.Length].Select(values =>
{
var m = ImHashMap<int, int>.Empty;
for (int i = 0; i < keys.Length; i++)
m = m.AddOrUpdate(keys[i], values[i]);
return (map: m, keys: keys);
}));
static Gen<(ImMap<int>, int[])> GenImMap(int upperBound) =>
Gen.Int[0, upperBound].ArrayUnique.SelectMany(hashes =>
Gen.Int.Array[hashes.Length].Select(values =>
{
var m = ImMap<int>.Empty;
for (int i = 0; i < hashes.Length; i++)
m = m.AddOrUpdate(hashes[i], values[i]);
return (map: m, hashes: hashes);
}));
// https://www.youtube.com/watch?v=G0NUOst-53U&feature=youtu.be&t=1639
[Test]
public void ImHashMap_AddOrUpdate_metamorphic()
{
const int upperBound = 100_000;
Gen.Select(GenImHashMap(upperBound), Gen.Int[0, upperBound], Gen.Int, Gen.Int[0, upperBound], Gen.Int)
.Sample(t =>
{
var ((m, _), k1, v1, k2, v2) = t;
var m1 = m.AddOrUpdate(k1, v1).AddOrUpdate(k2, v2);
var m2 = k1 == k2 ? m.AddOrUpdate(k2, v2) : m.AddOrUpdate(k2, v2).AddOrUpdate(k1, v1);
var e1 = m1.Enumerate().OrderBy(i => i.Hash);
var e2 = m2.Enumerate().OrderBy(i => i.Hash);
CollectionAssert.AreEqual(e1.Select(x => x.Hash), e2.Select(x => x.Hash));
},
iter: 5000);
}
[Test]
public void ImMap_AddOrUpdate_metamorphic()
{
const int upperBound = 100_000;
Gen.Select(GenImMap(upperBound), Gen.Int[0, upperBound], Gen.Int, Gen.Int[0, upperBound], Gen.Int)
.Sample(t =>
{
var ((m, _), k1, v1, k2, v2) = t;
var m1 = m.AddOrUpdate(k1, v1).AddOrUpdate(k2, v2);
var m2 = k1 == k2 ? m.AddOrUpdate(k2, v2) : m.AddOrUpdate(k2, v2).AddOrUpdate(k1, v1);
var e1 = m1.Enumerate().OrderBy(i => i.Hash);
var e2 = m2.Enumerate().OrderBy(i => i.Hash);
CollectionAssert.AreEqual(e1.Select(x => x.Hash), e2.Select(x => x.Hash));
},
iter: 5000);
}
[Test]
public void ImHashMap_Remove_metamorphic()
{
const int upperBound = 100_000;
Gen.Select(GenImHashMap(upperBound), Gen.Int[0, upperBound], Gen.Int, Gen.Int[0, upperBound], Gen.Int)
.Sample(t =>
{
var ((m, _), k1, v1, k2, v2) = t;
m = m.AddOrUpdate(k1, v1).AddOrUpdate(k2, v2);
var m1 = m.Remove(k1).Remove(k2);
var m2 = m.Remove(k2).Remove(k1);
var e1 = m1.Enumerate().Select(x => x.Hash);
var e2 = m2.Enumerate().Select(x => x.Hash);
CollectionAssert.AreEqual(e1, e2);
},
iter: 5000);
}
[Test]
public void ImMap_Remove_metamorphic()
{
const int upperBound = 100_000;
Gen.Select(GenImMap(upperBound), Gen.Int[0, upperBound], Gen.Int, Gen.Int[0, upperBound], Gen.Int)
.Sample(t =>
{
var ((m, _), k1, v1, k2, v2) = t;
m = m.AddOrUpdate(k1, v1).AddOrUpdate(k2, v2);
var m1 = m.Remove(k1).Remove(k2);
var m2 = m.Remove(k2).Remove(k1);
var e1 = m1.Enumerate().Select(x => x.Hash);
var e2 = m2.Enumerate().Select(x => x.Hash);
CollectionAssert.AreEqual(e1, e2);
},
iter: 5000);
}
[Test]
public void ImMap_Remove_metamorphic_failure_case_with_Branch2Plus1()
{
const int upperBound = 100_000;
Gen.Select(GenImMap(upperBound), Gen.Int[0, upperBound], Gen.Int, Gen.Int[0, upperBound], Gen.Int)
.Sample(t =>
{
var ((m, _), k1, v1, k2, v2) = t;
m = m.AddOrUpdate(k1, v1).AddOrUpdate(k2, v2);
var m1 = m.Remove(k1).Remove(k2);
var m2 = m.Remove(k2).Remove(k1);
var e1 = m1.Enumerate().Select(x => x.Hash);
var e2 = m2.Enumerate().Select(x => x.Hash);
CollectionAssert.AreEqual(e1, e2);
},
iter: 5000, seed: "1wsRNkSYY1N4");
}
[Test]
public void AddOrUpdate_metamorphic_shrinked_manually_case_1()
{
var baseItems = new int[4] { 65347, 87589, 89692, 92562 };
var m1 = ImHashMap<int, int>.Empty;
var m2 = ImHashMap<int, int>.Empty;
foreach (var x in baseItems)
{
m1 = m1.AddOrUpdate(x, x);
m2 = m2.AddOrUpdate(x, x);
}
m1 = m1.AddOrUpdate(58955, 42);
m1 = m1.AddOrUpdate(97319, 43);
m2 = m2.AddOrUpdate(97319, 43);
m2 = m2.AddOrUpdate(58955, 42);
var e1 = m1.Enumerate().OrderBy(i => i.Hash);
var e2 = m2.Enumerate().OrderBy(i => i.Hash);
CollectionAssert.AreEqual(e1.Select(x => x.Hash), e2.Select(x => x.Hash));
}
[Test]
public void AddOrUpdate_metamorphic_shrinked_manually_case_2()
{
var baseItems = new int[6] {4527, 58235, 65127, 74715, 81974, 89123};
var m1 = ImHashMap<int, int>.Empty;
var m2 = ImHashMap<int, int>.Empty;
foreach (var x in baseItems)
{
m1 = m1.AddOrUpdate(x, x);
m2 = m2.AddOrUpdate(x, x);
}
m1 = m1.AddOrUpdate(35206, 42);
m1 = m1.AddOrUpdate(83178, 43);
m2 = m2.AddOrUpdate(83178, 43);
m2 = m2.AddOrUpdate(35206, 42);
var e1 = m1.Enumerate().OrderBy(i => i.Hash).Select(x => x.Hash).ToArray();
var e2 = m2.Enumerate().OrderBy(i => i.Hash).Select(x => x.Hash).ToArray();
CollectionAssert.AreEqual(e1, e2);
}
[Test]
public void AddOrUpdate_metamorphic_shrinked_manually_case_3()
{
var baseItems = new int[] { 65347, 87589, 89692, 92562 };
var m1 = ImHashMap<int, int>.Empty;
var m2 = ImHashMap<int, int>.Empty;
foreach (var x in baseItems)
{
m1 = m1.AddOrUpdate(x, x);
m2 = m2.AddOrUpdate(x, x);
}
m1 = m1.AddOrUpdate(97319, 42);
m1 = m1.AddOrUpdate(58955, 43);
m2 = m2.AddOrUpdate(58955, 43);
m2 = m2.AddOrUpdate(97319, 42);
var e1 = m1.Enumerate().ToArray().OrderBy(i => i.Hash).Select(x => x.Hash).ToArray();
var e2 = m2.Enumerate().ToArray().OrderBy(i => i.Hash).Select(x => x.Hash).ToArray();
CollectionAssert.AreEqual(e1, e2);
}
[Test]
public void ImHashMap_AddOrUpdate_ModelBased()
{
const int upperBound = 100000;
Gen.SelectMany(GenImHashMap(upperBound), m =>
Gen.Select(Gen.Const(m.Item1), Gen.Int[0, upperBound], Gen.Int, Gen.Const(m.Item2)))
.Sample(t =>
{
var dic1 = t.V0.ToDictionary();
dic1[t.V1] = t.V2;
var dic2 = t.V0.AddOrUpdate(t.V1, t.V2).ToDictionary();
CollectionAssert.AreEqual(dic1, dic2);
}
, iter: 1000
, print: t => t + "\n" + string.Join("\n", t.V0.Enumerate()));
}
[Test]
public void ImMap_AddOrUpdate_ModelBased()
{
const int upperBound = 100000;
Gen.SelectMany(GenImMap(upperBound), m =>
Gen.Select(Gen.Const(m.Item1), Gen.Int[0, upperBound], Gen.Int, Gen.Const(m.Item2)))
.Sample(t =>
{
var dic1 = t.V0.ToDictionary();
dic1[t.V1] = t.V2;
var dic2 = t.V0.AddOrUpdate(t.V1, t.V2).ToDictionary();
CollectionAssert.AreEqual(dic1, dic2);
}
, iter: 1000
, print: t => t + "\nhashes: {" + string.Join(", ", t.V3) + "}");
}
[Test]
public void ImMap_AddOrUpdate_ModelBased_FailedCase1()
{
var hashes = new[] { 73341, 68999, 1354, 50830, 94661, 21594, 27007, 21894, 35166, 68934 };
var added = 22189;
var map = ImMap<int>.Empty;
foreach (var h in hashes)
map = map.AddOrUpdate(h, h);
var dic1 = map.ToDictionary();
dic1[added] = added;
map = map.AddOrUpdate(added, added);
var dic2 = map.ToDictionary();
CollectionAssert.AreEqual(dic1, dic2);
}
[Test]
public void ImHashMap_Remove_ModelBased()
{
const int upperBound = 100000;
Gen.SelectMany(GenImHashMap(upperBound), m =>
Gen.Select(Gen.Const(m.Item1), Gen.Int[0, upperBound], Gen.Int, Gen.Const(m.Item2)))
.Sample(t =>
{
var dic1 = t.V0.ToDictionary();
if (dic1.ContainsKey(t.V1))
dic1.Remove(t.V1);
var map = t.V0.AddOrUpdate(t.V1, t.V2).Remove(t.V1);
// Assert.AreEqual(t.V0.Remove(t.V1).Count(), map.Count());
var dic2 = map.ToDictionary();
CollectionAssert.AreEqual(dic1, dic2);
}
, iter: 1000
, print: t =>
"\noriginal: " + t.V0 +
"\nadded: " + t.V1 +
"\nkeys: {" + string.Join(", ", t.V3) + "}");
}
[Test]
public void ImHashMap_Remove_ModelBased_FailedCase1()
{
var hashes = new int[7] { 26716, 80399, 13634, 25950, 56351, 51074, 46591 };
var added = 66928;
var map = ImMap<int>.Empty;
foreach (var n in hashes)
map = map.AddOrUpdate(n, n);
var dic1 = map.ToDictionary();
if (dic1.ContainsKey(added))
dic1.Remove(added);
var dic2 = map.AddOrUpdate(added, added).Remove(added).ToDictionary();
CollectionAssert.AreEqual(dic1, dic2);
}
[Test]
public void ImMap_Remove_ModelBased()
{
const int upperBound = 100000;
Gen.SelectMany(GenImMap(upperBound), m =>
Gen.Select(Gen.Const(m.Item1), Gen.Int[0, upperBound], Gen.Int, Gen.Const(m.Item2)))
.Sample(t =>
{
var dic1 = t.V0.ToDictionary();
if (dic1.ContainsKey(t.V1))
dic1.Remove(t.V1);
var map = t.V0.AddOrUpdate(t.V1, t.V2).Remove(t.V1);
Assert.AreEqual(t.V0.Remove(t.V1).Count(), map.Count());
var dic2 = map.ToDictionary();
CollectionAssert.AreEqual(dic1, dic2);
}
, iter: 1000
, print: t => t + "\n" + "keys: {" + string.Join(", ", t.V3) + "}");
}
[Test]
public void ImMap_Remove_ModelBased_FailedCase1()
{
var hashes = new int[10] {22063, 17962, 90649, 8112, 30393, 94009, 60740, 80192, 11026, 19570};
var added = 29210;
var map = ImMap<int>.Empty;
foreach (var n in hashes)
map = map.AddOrUpdate(n, n);
var result = map.AddOrUpdate(added, added);
result = result.Remove(added);
CollectionAssert.AreEqual(map.Enumerate().Select(x => x.Hash), result.Enumerate().Select(x => x.Hash));
}
}
}
| |
namespace java.lang
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Short : java.lang.Number, Comparable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Short()
{
InitJNI();
}
internal Short(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _equals13111;
public sealed override bool equals(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Short._equals13111, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._equals13111, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _toString13112;
public static global::java.lang.String toString(short arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Short.staticClass, global::java.lang.Short._toString13112, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _toString13113;
public sealed override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.Short._toString13113)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._toString13113)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _hashCode13114;
public sealed override int hashCode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Short._hashCode13114);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._hashCode13114);
}
internal static global::MonoJavaBridge.MethodId _reverseBytes13115;
public static short reverseBytes(short arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticShortMethod(java.lang.Short.staticClass, global::java.lang.Short._reverseBytes13115, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _compareTo13116;
public int compareTo(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Short._compareTo13116, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._compareTo13116, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _compareTo13117;
public int compareTo(java.lang.Short arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Short._compareTo13117, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._compareTo13117, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _valueOf13118;
public static global::java.lang.Short valueOf(short arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Short.staticClass, global::java.lang.Short._valueOf13118, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Short;
}
internal static global::MonoJavaBridge.MethodId _valueOf13119;
public static global::java.lang.Short valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Short.staticClass, global::java.lang.Short._valueOf13119, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Short;
}
internal static global::MonoJavaBridge.MethodId _valueOf13120;
public static global::java.lang.Short valueOf(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Short.staticClass, global::java.lang.Short._valueOf13120, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Short;
}
internal static global::MonoJavaBridge.MethodId _decode13121;
public static global::java.lang.Short decode(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Short.staticClass, global::java.lang.Short._decode13121, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Short;
}
internal static global::MonoJavaBridge.MethodId _byteValue13122;
public sealed override byte byteValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallByteMethod(this.JvmHandle, global::java.lang.Short._byteValue13122);
else
return @__env.CallNonVirtualByteMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._byteValue13122);
}
internal static global::MonoJavaBridge.MethodId _shortValue13123;
public sealed override short shortValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallShortMethod(this.JvmHandle, global::java.lang.Short._shortValue13123);
else
return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._shortValue13123);
}
internal static global::MonoJavaBridge.MethodId _intValue13124;
public sealed override int intValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Short._intValue13124);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._intValue13124);
}
internal static global::MonoJavaBridge.MethodId _longValue13125;
public sealed override long longValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::java.lang.Short._longValue13125);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._longValue13125);
}
internal static global::MonoJavaBridge.MethodId _floatValue13126;
public sealed override float floatValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::java.lang.Short._floatValue13126);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._floatValue13126);
}
internal static global::MonoJavaBridge.MethodId _doubleValue13127;
public sealed override double doubleValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallDoubleMethod(this.JvmHandle, global::java.lang.Short._doubleValue13127);
else
return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::java.lang.Short.staticClass, global::java.lang.Short._doubleValue13127);
}
internal static global::MonoJavaBridge.MethodId _parseShort13128;
public static short parseShort(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticShortMethod(java.lang.Short.staticClass, global::java.lang.Short._parseShort13128, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _parseShort13129;
public static short parseShort(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticShortMethod(java.lang.Short.staticClass, global::java.lang.Short._parseShort13129, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _Short13130;
public Short(short arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Short.staticClass, global::java.lang.Short._Short13130, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Short13131;
public Short(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Short.staticClass, global::java.lang.Short._Short13131, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static short MIN_VALUE
{
get
{
return -32768;
}
}
public static short MAX_VALUE
{
get
{
return 32767;
}
}
internal static global::MonoJavaBridge.FieldId _TYPE13132;
public static global::java.lang.Class TYPE
{
get
{
return default(global::java.lang.Class);
}
}
public static int SIZE
{
get
{
return 16;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.Short.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Short"));
global::java.lang.Short._equals13111 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "equals", "(Ljava/lang/Object;)Z");
global::java.lang.Short._toString13112 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Short.staticClass, "toString", "(S)Ljava/lang/String;");
global::java.lang.Short._toString13113 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "toString", "()Ljava/lang/String;");
global::java.lang.Short._hashCode13114 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "hashCode", "()I");
global::java.lang.Short._reverseBytes13115 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Short.staticClass, "reverseBytes", "(S)S");
global::java.lang.Short._compareTo13116 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "compareTo", "(Ljava/lang/Object;)I");
global::java.lang.Short._compareTo13117 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "compareTo", "(Ljava/lang/Short;)I");
global::java.lang.Short._valueOf13118 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Short.staticClass, "valueOf", "(S)Ljava/lang/Short;");
global::java.lang.Short._valueOf13119 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Short.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/Short;");
global::java.lang.Short._valueOf13120 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Short.staticClass, "valueOf", "(Ljava/lang/String;I)Ljava/lang/Short;");
global::java.lang.Short._decode13121 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Short.staticClass, "decode", "(Ljava/lang/String;)Ljava/lang/Short;");
global::java.lang.Short._byteValue13122 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "byteValue", "()B");
global::java.lang.Short._shortValue13123 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "shortValue", "()S");
global::java.lang.Short._intValue13124 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "intValue", "()I");
global::java.lang.Short._longValue13125 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "longValue", "()J");
global::java.lang.Short._floatValue13126 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "floatValue", "()F");
global::java.lang.Short._doubleValue13127 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "doubleValue", "()D");
global::java.lang.Short._parseShort13128 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Short.staticClass, "parseShort", "(Ljava/lang/String;I)S");
global::java.lang.Short._parseShort13129 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Short.staticClass, "parseShort", "(Ljava/lang/String;)S");
global::java.lang.Short._Short13130 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "<init>", "(S)V");
global::java.lang.Short._Short13131 = @__env.GetMethodIDNoThrow(global::java.lang.Short.staticClass, "<init>", "(Ljava/lang/String;)V");
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: MediaElement.cs
//
// Description: Contains the MediaElement class.
//
// History:
// 07/28/2003 : [....] - Added
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Utility;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Automation.Peers;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using System.Windows.Markup;
namespace System.Windows.Controls
{
/// <summary>
/// States that can be applied to the media element automatically when the
/// MediaElement is loaded or unloaded.
/// </summary>
public enum MediaState : int
{
/// <summary>
/// The media element should be controlled manually, either by its associated
/// clock, or by directly calling the Play/Pause etc. on the media element.
/// </summary>
Manual = 0,
/// <summary>
/// The media element should play.
/// </summary>
Play = 1,
/// <summary>
/// The media element should close. This stops all media processing and releases
/// any video memory held by the media element.
/// </summary>
Close = 2,
/// <summary>
/// The media element should pause.
/// </summary>
Pause = 3,
/// <summary>
/// The media element should stop.
/// </summary>
Stop = 4
}
/// <summary>
/// Media Element
/// </summary>
[Localizability(LocalizationCategory.NeverLocalize)]
public class MediaElement : FrameworkElement, IUriContext
{
#region Constructors
/// <summary>
/// Default DependencyObject constructor
/// </summary>
/// <remarks>
/// Automatic determination of current Dispatcher. Use alternative constructor
/// that accepts a Dispatcher for best performance.
/// </remarks>
public MediaElement() : base()
{
Initialize();
}
static MediaElement()
{
Style style = CreateDefaultStyles();
StyleProperty.OverrideMetadata(typeof(MediaElement), new FrameworkPropertyMetadata(style));
//
// The Stretch & StretchDirection properties are AddOwner'ed from a class which is not
// base class for MediaElement so the metadata with flags get lost. We need to override them
// here to make it work again.
//
StretchProperty.OverrideMetadata(
typeof(MediaElement),
new FrameworkPropertyMetadata(
Stretch.Uniform,
FrameworkPropertyMetadataOptions.AffectsMeasure
)
);
StretchDirectionProperty.OverrideMetadata(
typeof(MediaElement),
new FrameworkPropertyMetadata(
StretchDirection.Both,
FrameworkPropertyMetadataOptions.AffectsMeasure
)
);
}
private static Style CreateDefaultStyles()
{
Style style = new Style(typeof(MediaElement), null);
style.Setters.Add (new Setter(FlowDirectionProperty, FlowDirection.LeftToRight));
style.Seal();
return style;
}
#endregion
#region Public Properties
/// <summary>
/// DependencyProperty for MediaElement Source property.
/// </summary>
/// <seealso cref="MediaElement.Source" />
/// This property is cached (_source).
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(
"Source",
typeof(Uri),
typeof(MediaElement),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(AVElementHelper.OnSourceChanged)));
/// <summary>
/// The DependencyProperty for the MediaElement.Volume property.
/// </summary>
public static readonly DependencyProperty VolumeProperty
= DependencyProperty.Register(
"Volume",
typeof(double),
typeof(MediaElement),
new FrameworkPropertyMetadata(
0.5,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(VolumePropertyChanged)));
/// <summary>
/// The DependencyProperty for the MediaElement.Balance property.
/// </summary>
public static readonly DependencyProperty BalanceProperty
= DependencyProperty.Register(
"Balance",
typeof(double),
typeof(MediaElement),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(BalancePropertyChanged)));
/// <summary>
/// The DependencyProperty for the MediaElement.IsMuted property.
/// </summary>
public static readonly DependencyProperty IsMutedProperty
= DependencyProperty.Register(
"IsMuted",
typeof(bool),
typeof(MediaElement),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(IsMutedPropertyChanged)));
/// <summary>
/// The DependencyProperty for the MediaElement.ScrubbingEnabled property.
/// </summary>
public static readonly DependencyProperty ScrubbingEnabledProperty
= DependencyProperty.Register(
"ScrubbingEnabled",
typeof(bool),
typeof(MediaElement),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(ScrubbingEnabledPropertyChanged)));
/// <summary>
/// The DependencyProperty for the MediaElement.UnloadedBehavior property.
/// </summary>
public static readonly DependencyProperty UnloadedBehaviorProperty
= DependencyProperty.Register(
"UnloadedBehavior",
typeof(MediaState),
typeof(MediaElement),
new FrameworkPropertyMetadata(
MediaState.Close,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(UnloadedBehaviorPropertyChanged)));
/// <summary>
/// The DependencyProperty for the MediaElement.LoadedBehavior property.
/// </summary>
public static readonly DependencyProperty LoadedBehaviorProperty
= DependencyProperty.Register(
"LoadedBehavior",
typeof(MediaState),
typeof(MediaElement),
new FrameworkPropertyMetadata(
MediaState.Play,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(LoadedBehaviorPropertyChanged)));
/// <summary>
/// Gets/Sets the Source on this MediaElement.
///
/// The Source property is the Uri of the media to be played.
/// </summary>
public Uri Source
{
get { return (Uri)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
/// <summary>
/// Media Clock associated with this MediaElement.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public MediaClock Clock
{
get
{
return _helper.Clock;
}
set
{
_helper.SetClock(value);
}
}
/// <summary>
/// Requests the the media is played. This method only has an effect if the current
/// media element state is manual.
/// </summary>
public
void
Play()
{
_helper.SetState(MediaState.Play);
}
/// <summary>
/// Requests the the media is paused. This method only has an effect if the current
/// media element state is manual.
/// </summary>
public
void
Pause()
{
_helper.SetState(MediaState.Pause);
}
/// <summary>
/// Requests the the media is stopped. This method only has an effect if the current
/// media element state is manual.
/// </summary>
public
void
Stop()
{
_helper.SetState(MediaState.Stop);
}
/// <summary>
/// Requests the the media is Closed. This method only has an effect if the current
/// media element state is manual.
/// </summary>
public
void
Close()
{
_helper.SetState(MediaState.Close);
}
/// <summary>
/// DependencyProperty for Stretch property.
/// </summary>
/// <seealso cref="MediaElement.Stretch" />
/// This property is cached and grouped (AspectRatioGroup)
public static readonly DependencyProperty StretchProperty =
Viewbox.StretchProperty.AddOwner(typeof(MediaElement));
/// <summary>
/// DependencyProperty for StretchDirection property.
/// </summary>
/// <seealso cref="Viewbox.Stretch" />
public static readonly DependencyProperty StretchDirectionProperty =
Viewbox.StretchDirectionProperty.AddOwner(typeof(MediaElement));
/// <summary>
/// Gets/Sets the Stretch on this MediaElement.
/// The Stretch property determines how large the MediaElement will be drawn.
/// </summary>
/// <seealso cref="MediaElement.StretchProperty" />
public Stretch Stretch
{
get { return (Stretch) GetValue(StretchProperty); }
set { SetValue(StretchProperty, value); }
}
/// <summary>
/// Gets/Sets the stretch direction of the Viewbox, which determines the restrictions on
/// scaling that are applied to the content inside the Viewbox. For instance, this property
/// can be used to prevent the content from being smaller than its native size or larger than
/// its native size.
/// </summary>
/// <seealso cref="Viewbox.StretchDirectionProperty" />
public StretchDirection StretchDirection
{
get { return (StretchDirection) GetValue(StretchDirectionProperty); }
set { SetValue(StretchDirectionProperty, value); }
}
/// <summary>
/// Gets/Sets the Volume property on the MediaElement.
/// </summary>
public double Volume
{
get
{
return (double) GetValue(VolumeProperty);
}
set
{
SetValue(VolumeProperty, value);
}
}
/// <summary>
/// Gets/Sets the Balance property on the MediaElement.
/// </summary>
public double Balance
{
get
{
return (double) GetValue(BalanceProperty);
}
set
{
SetValue(BalanceProperty, value);
}
}
/// <summary>
/// Gets/Sets the IsMuted property on the MediaElement.
/// </summary>
public bool IsMuted
{
get
{
return (bool) GetValue(IsMutedProperty);
}
set
{
SetValue(IsMutedProperty, value);
}
}
/// <summary>
/// Gets/Sets the ScrubbingEnabled property on the MediaElement.
/// </summary>
public bool ScrubbingEnabled
{
get
{
return (bool) GetValue(ScrubbingEnabledProperty);
}
set
{
SetValue(ScrubbingEnabledProperty, value);
}
}
/// <summary>
/// Specifies how the underlying media should behave when the given
/// MediaElement is unloaded, the default behavior is to Close the
/// media.
/// </summary>
public MediaState UnloadedBehavior
{
get
{
return (MediaState)GetValue(UnloadedBehaviorProperty);
}
set
{
SetValue(UnloadedBehaviorProperty, value);
}
}
/// <summary>
/// Specifies the behavior that the media element should have when it
/// is loaded. The default behavior is that it is under manual control
/// (i.e. the caller should call methods such as Play in order to play
/// the media). If a source is set, then the default behavior changes to
/// to be playing the media. If a source is set and a loaded behavior is
/// also set, then the loaded behavior takes control.
/// </summary>
public MediaState LoadedBehavior
{
get
{
return (MediaState)GetValue(LoadedBehaviorProperty);
}
set
{
SetValue(LoadedBehaviorProperty, value);
}
}
/// <summary>
/// Returns whether the given media can be paused. This is only valid
/// after the MediaOpened event has fired.
/// </summary>
public bool CanPause
{
get
{
return _helper.Player.CanPause;
}
}
/// <summary>
/// Returns whether the given media is currently being buffered. This
/// applies to network accessed media only.
/// </summary>
public bool IsBuffering
{
get
{
return _helper.Player.IsBuffering;
}
}
/// <summary>
/// Returns the download progress of the media.
/// </summary>
public double DownloadProgress
{
get
{
return _helper.Player.DownloadProgress;
}
}
/// <summary>
/// Returns the buffering progress of the media.
/// </summary>
public double BufferingProgress
{
get
{
return _helper.Player.BufferingProgress;
}
}
/// <summary>
/// Returns the natural height of the media in the video. Only valid after
/// the MediaOpened event has fired.
/// </summary>
public Int32 NaturalVideoHeight
{
get
{
return _helper.Player.NaturalVideoHeight;
}
}
/// <summary>
/// Returns the natural width of the media in the video. Only valid after
/// the MediaOpened event has fired.
/// </summary>
public Int32 NaturalVideoWidth
{
get
{
return _helper.Player.NaturalVideoWidth;
}
}
/// <summary>
/// Returns whether the given media has audio. Only valid after the
/// MediaOpened event has fired.
/// </summary>
public bool HasAudio
{
get
{
return _helper.Player.HasAudio;
}
}
/// <summary>
/// Returns whether the given media has video. Only valid after the
/// MediaOpened event has fired.
/// </summary>
public bool HasVideo
{
get
{
return _helper.Player.HasVideo;
}
}
/// <summary>
/// Returns the natural duration of the media. Only valid after the
/// MediaOpened event has fired.
/// </summary>
public Duration NaturalDuration
{
get
{
return _helper.Player.NaturalDuration;
}
}
/// <summary>
/// Returns the current position of the media. This is only valid
/// adter the MediaOpened event has fired.
/// </summary>
public TimeSpan Position
{
get
{
return _helper.Position;
}
set
{
_helper.SetPosition(value);
}
}
/// <summary>
/// Allows the speed ration of the media to be controlled.
/// </summary>
public double SpeedRatio
{
get
{
return _helper.SpeedRatio;
}
set
{
_helper.SetSpeedRatio(value);
}
}
/// <summary>
/// MediaFailedEvent is a routed event.
/// </summary>
public static readonly RoutedEvent MediaFailedEvent =
EventManager.RegisterRoutedEvent(
"MediaFailed",
RoutingStrategy.Bubble,
typeof(EventHandler<ExceptionRoutedEventArgs>),
typeof(MediaElement));
/// <summary>
/// Raised when there is a failure in media.
/// </summary>
public event EventHandler<ExceptionRoutedEventArgs> MediaFailed
{
add { AddHandler(MediaFailedEvent, value); }
remove { RemoveHandler(MediaFailedEvent, value); }
}
/// <summary>
/// MediaOpened is a routed event.
/// </summary>
public static readonly RoutedEvent MediaOpenedEvent =
EventManager.RegisterRoutedEvent(
"MediaOpened",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MediaElement));
/// <summary>
/// Raised when the media is opened
/// </summary>
public event RoutedEventHandler MediaOpened
{
add { AddHandler(MediaOpenedEvent, value); }
remove { RemoveHandler(MediaOpenedEvent, value); }
}
/// <summary>
/// BufferingStarted is a routed event.
/// </summary>
public static readonly RoutedEvent BufferingStartedEvent =
EventManager.RegisterRoutedEvent(
"BufferingStarted",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MediaElement));
/// <summary>
/// Raised when buffering starts on the corresponding media.
/// </summary>
public event RoutedEventHandler BufferingStarted
{
add { AddHandler(BufferingStartedEvent, value); }
remove { RemoveHandler(BufferingStartedEvent, value); }
}
/// <summary>
/// BufferingEnded is a routed event.
/// </summary>
public static readonly RoutedEvent BufferingEndedEvent =
EventManager.RegisterRoutedEvent(
"BufferingEnded",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MediaElement));
/// <summary>
/// Raised when buffering ends on the corresponding media.
/// </summary>
public event RoutedEventHandler BufferingEnded
{
add { AddHandler(BufferingEndedEvent, value); }
remove { RemoveHandler(BufferingEndedEvent, value); }
}
/// <summary>
/// ScriptCommand is a routed event.
/// </summary>
public static readonly RoutedEvent ScriptCommandEvent =
EventManager.RegisterRoutedEvent(
"ScriptCommand",
RoutingStrategy.Bubble,
typeof(EventHandler<MediaScriptCommandRoutedEventArgs>),
typeof(MediaElement));
/// <summary>
/// Raised when a script command in the media is encountered during playback.
/// </summary>
public event EventHandler<MediaScriptCommandRoutedEventArgs> ScriptCommand
{
add { AddHandler(ScriptCommandEvent, value); }
remove { RemoveHandler(ScriptCommandEvent, value); }
}
/// <summary>
/// MediaEnded is a routed event
/// </summary>
public static readonly RoutedEvent MediaEndedEvent =
EventManager.RegisterRoutedEvent(
"MediaEnded",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MediaElement));
/// <summary>
/// Raised when the corresponding media ends.
/// </summary>
public event RoutedEventHandler MediaEnded
{
add { AddHandler(MediaEndedEvent, value); }
remove { RemoveHandler(MediaEndedEvent, value); }
}
#endregion
#region IUriContext implementation
/// <summary>
/// Base Uri to use when resolving relative Uri's
/// </summary>
Uri IUriContext.BaseUri
{
get
{
return _helper.BaseUri;
}
set
{
_helper.BaseUri = value;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new MediaElementAutomationPeer(this);
}
/// <summary>
/// Override for <seealso cref="FrameworkElement.MeasureOverride" />.
/// </summary>
protected override Size MeasureOverride(Size availableSize)
{
return MeasureArrangeHelper(availableSize);
}
/// <summary>
/// Override for <seealso cref="FrameworkElement.ArrangeOverride" />.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
return MeasureArrangeHelper(finalSize);
}
//
// protected override void OnArrange(Size arrangeSize)
// Because MediaElement does not have children and it is inexpensive to compute it's alignment/size,
// it does not need an OnArrange override. It will simply use its own RenderSize (set when its
// Arrange is called) in OnRender.
//
/// <summary>
/// OnRender is called when the Visual is notified that its contents need to be rendered
/// This lets the MediaElement element know that it needs to render its contents in the given
/// DrawingContext
/// </summary>
/// <param name="drawingContext">
/// The DrawingContext to render the video to
/// </param>
protected override void OnRender(DrawingContext drawingContext)
{
// if nobody set a source on us, then the clock will be null, so we don't render
// anything
if (_helper.Player == null)
{
return;
}
drawingContext.DrawVideo(_helper.Player, new Rect(new Point(), RenderSize));
return;
}
#endregion Protected Methods
#region Internal Properties / Methods
/// <summary>
/// Return the helper object.
/// </summary>
internal AVElementHelper Helper
{
get
{
return _helper;
}
}
#endregion
#region Private Methods
/// <summary>
/// Initialization
/// </summary>
private void Initialize()
{
_helper = new AVElementHelper(this);
}
/// <summary>
/// Contains the code common for MeasureOverride and ArrangeOverride.
/// </summary>
/// <param name="inputSize">input size is the parent-provided space that Video should use to "fit in", according to other properties.</param>
/// <returns>MediaElement's desired size.</returns>
private Size MeasureArrangeHelper(Size inputSize)
{
MediaPlayer mediaPlayer = _helper.Player;
if (mediaPlayer == null)
{
return new Size();
}
Size naturalSize = new Size((double)mediaPlayer.NaturalVideoWidth, (double)mediaPlayer.NaturalVideoHeight);
//get computed scale factor
Size scaleFactor = Viewbox.ComputeScaleFactor(inputSize,
naturalSize,
this.Stretch,
this.StretchDirection);
// Returns our minimum size & sets DesiredSize.
return new Size(naturalSize.Width * scaleFactor.Width, naturalSize.Height * scaleFactor.Height);
}
private static void VolumePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.IsASubPropertyChange)
{
return;
}
MediaElement target = ((MediaElement) d);
if (target != null)
{
target._helper.SetVolume((double)e.NewValue);
}
}
private static void BalancePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.IsASubPropertyChange)
{
return;
}
MediaElement target = ((MediaElement) d);
if (target != null)
{
target._helper.SetBalance((double)e.NewValue);
}
}
private static void IsMutedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.IsASubPropertyChange)
{
return;
}
MediaElement target = ((MediaElement) d);
if (target != null)
{
target._helper.SetIsMuted((bool)e.NewValue);
}
}
private static void ScrubbingEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.IsASubPropertyChange)
{
return;
}
MediaElement target = ((MediaElement) d);
if (target != null)
{
target._helper.SetScrubbingEnabled((bool)e.NewValue);
}
}
private static
void
UnloadedBehaviorPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e
)
{
if (e.IsASubPropertyChange)
{
return;
}
MediaElement target = (MediaElement)d;
if (target != null)
{
target._helper.SetUnloadedBehavior((MediaState)e.NewValue);
}
}
private static
void
LoadedBehaviorPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e
)
{
if (e.IsASubPropertyChange)
{
return;
}
MediaElement target = (MediaElement)d;
if (target != null)
{
target._helper.SetLoadedBehavior((MediaState)e.NewValue);
}
}
internal
void
OnMediaFailed(
object sender,
ExceptionEventArgs args
)
{
RaiseEvent(
new ExceptionRoutedEventArgs(
MediaFailedEvent,
this,
args.ErrorException));
}
internal
void
OnMediaOpened(
object sender,
EventArgs args
)
{
RaiseEvent(new RoutedEventArgs(MediaOpenedEvent, this));
}
internal
void
OnBufferingStarted(
object sender,
EventArgs args
)
{
RaiseEvent(new RoutedEventArgs(BufferingStartedEvent, this));
}
internal
void
OnBufferingEnded(
object sender,
EventArgs args
)
{
RaiseEvent(new RoutedEventArgs(BufferingEndedEvent, this));
}
internal
void
OnMediaEnded(
object sender,
EventArgs args
)
{
RaiseEvent(new RoutedEventArgs(MediaEndedEvent, this));
}
internal
void
OnScriptCommand(
object sender,
MediaScriptCommandEventArgs args
)
{
RaiseEvent(
new MediaScriptCommandRoutedEventArgs(
ScriptCommandEvent,
this,
args.ParameterType,
args.ParameterValue));
}
#endregion
#region Data Members
/// <summary>
/// Helper object
/// </summary>
private AVElementHelper _helper;
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt640()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt640();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt640
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector64<UInt64> value = Vector64.Create(values[0]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt64 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt64.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
Vector64<UInt64> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt64.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector64<UInt64> value = Vector64.Create(values[0]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.GetElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt64)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt64.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
object result2 = typeof(Vector64)
.GetMethod(nameof(Vector64.WithElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector64<UInt64>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt64.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt64 result, UInt64[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector64<UInt64.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector64<UInt64> result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
UInt64[] resultElements = new UInt64[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt64[] result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt64.WithElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Authentication;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RedditSharp.Things
{
public class Post : VotableThing
{
private const string CommentUrl = "/api/comment";
private const string RemoveUrl = "/api/remove";
private const string DelUrl = "/api/del";
private const string GetCommentsUrl = "/comments/{0}.json";
private const string ApproveUrl = "/api/approve";
private const string EditUserTextUrl = "/api/editusertext";
private const string HideUrl = "/api/hide";
private const string UnhideUrl = "/api/unhide";
private const string SetFlairUrl = "/api/flair";
private const string MarkNSFWUrl = "/api/marknsfw";
private const string UnmarkNSFWUrl = "/api/unmarknsfw";
private const string ContestModeUrl = "/api/set_contest_mode";
[JsonIgnore]
private Reddit Reddit { get; set; }
[JsonIgnore]
private IWebAgent WebAgent { get; set; }
public Post Init(Reddit reddit, JToken post, IWebAgent webAgent)
{
CommonInit(reddit, post, webAgent);
JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings);
return this;
}
public async Task<Post> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent)
{
CommonInit(reddit, post, webAgent);
await Task.Factory.StartNew(() => JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings));
return this;
}
private void CommonInit(Reddit reddit, JToken post, IWebAgent webAgent)
{
base.Init(reddit, webAgent, post);
Reddit = reddit;
WebAgent = webAgent;
}
[JsonProperty("author")]
public string AuthorName { get; set; }
[JsonIgnore]
public RedditUser Author
{
get
{
return Reddit.GetUser(AuthorName);
}
}
public Comment[] Comments
{
get
{
return ListComments().ToArray();
}
}
[JsonProperty("approved_by")]
public string ApprovedBy { get; set; }
[JsonProperty("author_flair_css_class")]
public string AuthorFlairCssClass { get; set; }
[JsonProperty("author_flair_text")]
public string AuthorFlairText { get; set; }
[JsonProperty("banned_by")]
public string BannedBy { get; set; }
[JsonProperty("domain")]
public string Domain { get; set; }
[JsonProperty("edited")]
public bool Edited { get; set; }
[JsonProperty("is_self")]
public bool IsSelfPost { get; set; }
[JsonProperty("link_flair_css_class")]
public string LinkFlairCssClass { get; set; }
[JsonProperty("link_flair_text")]
public string LinkFlairText { get; set; }
[JsonProperty("num_comments")]
public int CommentCount { get; set; }
[JsonProperty("over_18")]
public bool NSFW { get; set; }
[JsonProperty("permalink")]
[JsonConverter(typeof(UrlParser))]
public Uri Permalink { get; set; }
[JsonProperty("score")]
public int Score { get; set; }
[JsonProperty("selftext")]
public string SelfText { get; set; }
[JsonProperty("selftext_html")]
public string SelfTextHtml { get; set; }
[JsonProperty("subreddit")]
public string Subreddit { get; set; }
[JsonProperty("thumbnail")]
[JsonConverter(typeof(UrlParser))]
public Uri Thumbnail { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("url")]
[JsonConverter(typeof(UrlParser))]
public Uri Url { get; set; }
[JsonProperty("num_reports")]
public int? Reports { get; set; }
public Comment Comment(string message)
{
if (Reddit.User == null)
throw new AuthenticationException("No user logged in.");
var request = WebAgent.CreatePost(CommentUrl);
var stream = request.GetRequestStream();
WebAgent.WritePostBody(stream, new
{
text = message,
thing_id = FullName,
uh = Reddit.User.Modhash,
api_type = "json"
});
stream.Close();
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(data);
if (json["json"]["ratelimit"] != null)
throw new RateLimitException(TimeSpan.FromSeconds(json["json"]["ratelimit"].ValueOrDefault<double>()));
return new Comment().Init(Reddit, json["json"]["data"]["things"][0], WebAgent, this);
}
private string SimpleAction(string endpoint)
{
if (Reddit.User == null)
throw new AuthenticationException("No user logged in.");
var request = WebAgent.CreatePost(endpoint);
var stream = request.GetRequestStream();
WebAgent.WritePostBody(stream, new
{
id = FullName,
uh = Reddit.User.Modhash
});
stream.Close();
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
return data;
}
private string SimpleActionToggle(string endpoint, bool value)
{
if (Reddit.User == null)
throw new AuthenticationException("No user logged in.");
var request = WebAgent.CreatePost(endpoint);
var stream = request.GetRequestStream();
WebAgent.WritePostBody(stream, new
{
id = FullName,
state = value,
uh = Reddit.User.Modhash
});
stream.Close();
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
return data;
}
public void Approve()
{
var data = SimpleAction(ApproveUrl);
}
public void Remove()
{
RemoveImpl(false);
}
public void RemoveSpam()
{
RemoveImpl(true);
}
private void RemoveImpl(bool spam)
{
var request = WebAgent.CreatePost(RemoveUrl);
var stream = request.GetRequestStream();
WebAgent.WritePostBody(stream, new
{
id = FullName,
spam = spam,
uh = Reddit.User.Modhash
});
stream.Close();
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
}
public void Del()
{
var data = SimpleAction(ApproveUrl);
}
public void Hide()
{
var data = SimpleAction(HideUrl);
}
public void Unhide()
{
var data = SimpleAction(UnhideUrl);
}
public void MarkNSFW()
{
var data = SimpleAction(MarkNSFWUrl);
}
public void UnmarkNSFW()
{
var data = SimpleAction(UnmarkNSFWUrl);
}
public void ContestMode(bool state)
{
var data = SimpleActionToggle(ContestModeUrl, state);
}
#region Obsolete Getter Methods
[Obsolete("Use Comments property instead")]
public Comment[] GetComments()
{
return Comments;
}
#endregion Obsolete Getter Methods
/// <summary>
/// Replaces the text in this post with the input text.
/// </summary>
/// <param name="newText">The text to replace the post's contents</param>
public void EditText(string newText)
{
if (Reddit.User == null)
throw new Exception("No user logged in.");
if (!IsSelfPost)
throw new Exception("Submission to edit is not a self-post.");
var request = WebAgent.CreatePost(EditUserTextUrl);
WebAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
text = newText,
thing_id = FullName,
uh = Reddit.User.Modhash
});
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
JToken json = JToken.Parse(result);
if (json["json"].ToString().Contains("\"errors\": []"))
SelfText = newText;
else
throw new Exception("Error editing text.");
}
public void Update()
{
JToken post = Reddit.GetToken(this.Url);
JsonConvert.PopulateObject(post["data"].ToString(), this, Reddit.JsonSerializerSettings);
}
public void SetFlair(string flairText, string flairClass)
{
if (Reddit.User == null)
throw new Exception("No user logged in.");
var request = WebAgent.CreatePost(SetFlairUrl);
WebAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
r = Subreddit,
css_class = flairClass,
link = FullName,
//name = Name,
text = flairText,
uh = Reddit.User.Modhash
});
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(result);
LinkFlairText = flairText;
}
public List<Comment> ListComments(int? limit = null)
{
var url = string.Format(GetCommentsUrl, Id);
if (limit.HasValue)
{
var query = HttpUtility.ParseQueryString(string.Empty);
query.Add("limit", limit.Value.ToString());
url = string.Format("{0}?{1}", url, query);
}
var request = WebAgent.CreateGet(url);
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JArray.Parse(data);
var postJson = json.Last()["data"]["children"];
var comments = new List<Comment>();
foreach (var comment in postJson)
{
comments.Add(new Comment().Init(Reddit, comment, WebAgent, this));
}
return comments;
}
}
}
| |
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2007 May 1
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code used to implement incremental BLOB I/O.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include "vdbeInt.h"
#if !SQLITE_OMIT_INCRBLOB
/*
** Valid sqlite3_blob* handles point to Incrblob structures.
*/
typedef struct Incrblob Incrblob;
struct Incrblob {
int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
int nByte; /* Size of open blob, in bytes */
int iOffset; /* Byte offset of blob in cursor data */
BtCursor *pCsr; /* Cursor pointing at blob row */
sqlite3_stmt *pStmt; /* Statement holding cursor open */
sqlite3 db; /* The associated database */
};
/*
** Open a blob handle.
*/
int sqlite3_blob_open(
sqlite3* db, /* The database connection */
string zDb, /* The attached database containing the blob */
string zTable, /* The table containing the blob */
string zColumn, /* The column containing the blob */
sqlite_int64 iRow, /* The row containing the glob */
int flags, /* True -> read/write access, false -> read-only */
sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
){
int nAttempt = 0;
int iCol; /* Index of zColumn in row-record */
/* This VDBE program seeks a btree cursor to the identified
** db/table/row entry. The reason for using a vdbe program instead
** of writing code to use the b-tree layer directly is that the
** vdbe program will take advantage of the various transaction,
** locking and error handling infrastructure built into the vdbe.
**
** After seeking the cursor, the vdbe executes an OP_ResultRow.
** Code external to the Vdbe then "borrows" the b-tree cursor and
** uses it to implement the blob_read(), blob_write() and
** blob_bytes() functions.
**
** The sqlite3_blob_close() function finalizes the vdbe program,
** which closes the b-tree cursor and (possibly) commits the
** transaction.
*/
static const VdbeOpList openBlob[] = {
{OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
{OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
{OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
/* One of the following two instructions is replaced by an OP_Noop. */
{OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
{OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
{OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
{OP_NotExists, 0, 9, 1}, /* 6: Seek the cursor */
{OP_Column, 0, 0, 1}, /* 7 */
{OP_ResultRow, 1, 0, 0}, /* 8 */
{OP_Close, 0, 0, 0}, /* 9 */
{OP_Halt, 0, 0, 0}, /* 10 */
};
Vdbe *v = 0;
int rc = SQLITE_OK;
string zErr = 0;
Table *pTab;
Parse *pParse;
*ppBlob = 0;
sqlite3_mutex_enter(db->mutex);
pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
if( pParse==0 ){
rc = SQLITE_NOMEM;
goto blob_open_out;
}
do {
memset(pParse, 0, sizeof(Parse));
pParse->db = db;
sqlite3BtreeEnterAll(db);
pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
if( pTab && IsVirtual(pTab) ){
pTab = 0;
sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
}
#if !SQLITE_OMIT_VIEW
if( pTab && pTab->pSelect ){
pTab = 0;
sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
}
#endif
if( null==pTab ){
if( pParse->zErrMsg ){
sqlite3DbFree(db, zErr);
zErr = pParse->zErrMsg;
pParse->zErrMsg = 0;
}
rc = SQLITE_ERROR;
sqlite3BtreeLeaveAll(db);
goto blob_open_out;
}
/* Now search pTab for the exact column. */
for(iCol=0; iCol < pTab->nCol; iCol++) {
if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
break;
}
}
if( iCol==pTab->nCol ){
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
rc = SQLITE_ERROR;
sqlite3BtreeLeaveAll(db);
goto blob_open_out;
}
/* If the value is being opened for writing, check that the
** column is not indexed, and that it is not part of a foreign key.
** It is against the rules to open a column to which either of these
** descriptions applies for writing. */
if( flags ){
string zFault = 0;
Index *pIdx;
#if !SQLITE_OMIT_FOREIGN_KEY
if( db->flags&SQLITE_ForeignKeys ){
/* Check that the column is not part of an FK child key definition. It
** is not necessary to check if it is part of a parent key, as parent
** key columns must be indexed. The check below will pick up this
** case. */
FKey *pFKey;
for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
int j;
for(j=0; j<pFKey->nCol; j++){
if( pFKey->aCol[j].iFrom==iCol ){
zFault = "foreign key";
}
}
}
}
#endif
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
int j;
for(j=0; j<pIdx->nColumn; j++){
if( pIdx->aiColumn[j]==iCol ){
zFault = "indexed";
}
}
}
if( zFault ){
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
rc = SQLITE_ERROR;
sqlite3BtreeLeaveAll(db);
goto blob_open_out;
}
}
v = sqlite3VdbeCreate(db);
if( v ){
int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
flags = !!flags; /* flags = (flags ? 1 : 0); */
/* Configure the OP_Transaction */
sqlite3VdbeChangeP1(v, 0, iDb);
sqlite3VdbeChangeP2(v, 0, flags);
/* Configure the OP_VerifyCookie */
sqlite3VdbeChangeP1(v, 1, iDb);
sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
/* Make sure a mutex is held on the table to be accessed */
sqlite3VdbeUsesBtree(v, iDb);
/* Configure the OP_TableLock instruction */
#if SQLITE_OMIT_SHARED_CACHE
sqlite3VdbeChangeToNoop(v, 2, 1);
#else
sqlite3VdbeChangeP1(v, 2, iDb);
sqlite3VdbeChangeP2(v, 2, pTab->tnum);
sqlite3VdbeChangeP3(v, 2, flags);
sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
#endif
/* Remove either the OP_OpenWrite or OpenRead. Set the P2
** parameter of the other to pTab->tnum. */
sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
sqlite3VdbeChangeP3(v, 3 + flags, iDb);
/* Configure the number of columns. Configure the cursor to
** think that the table has one more column than it really
** does. An OP_Column to retrieve this imaginary column will
** always return an SQL NULL. This is useful because it means
** we can invoke OP_Column to fill in the vdbe cursors type
** and offset cache without causing any IO.
*/
sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
sqlite3VdbeChangeP2(v, 7, pTab->nCol);
if( null==db->mallocFailed ){
pParse->nVar = 1;
pParse->nMem = 1;
pParse->nTab = 1;
sqlite3VdbeMakeReady(v, pParse);
}
}
sqlite3BtreeLeaveAll(db);
goto blob_open_out;
}
sqlite3_bind_int64((sqlite3_stmt )v, 1, iRow);
rc = sqlite3_step((sqlite3_stmt )v);
if( rc!=SQLITE_ROW ){
nAttempt++;
rc = sqlite3_finalize((sqlite3_stmt )v);
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
v = 0;
}
} while( nAttempt<5 && rc==SQLITE_SCHEMA );
if( rc==SQLITE_ROW ){
/* The row-record has been opened successfully. Check that the
** column in question contains text or a blob. If it contains
** text, it is up to the caller to get the encoding right.
*/
Incrblob *pBlob;
u32 type = v->apCsr[0]->aType[iCol];
if( type<12 ){
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, "cannot open value of type %s",
type==0?"null": type==7?"real": "integer"
);
rc = SQLITE_ERROR;
goto blob_open_out;
}
pBlob = (Incrblob )sqlite3DbMallocZero(db, sizeof(Incrblob));
if( db->mallocFailed ){
sqlite3DbFree(db, ref pBlob);
goto blob_open_out;
}
pBlob->flags = flags;
pBlob->pCsr = v->apCsr[0]->pCursor;
sqlite3BtreeEnterCursor(pBlob->pCsr);
sqlite3BtreeCacheOverflow(pBlob->pCsr);
sqlite3BtreeLeaveCursor(pBlob->pCsr);
pBlob->pStmt = (sqlite3_stmt )v;
pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
pBlob->db = db;
*ppBlob = (sqlite3_blob )pBlob;
rc = SQLITE_OK;
}else if( rc==SQLITE_OK ){
sqlite3DbFree(db, zErr);
zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
rc = SQLITE_ERROR;
}
blob_open_out:
if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
sqlite3VdbeFinalize(v);
}
sqlite3Error(db, rc, zErr);
sqlite3DbFree(db, zErr);
sqlite3StackFree(db, pParse);
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** Close a blob handle that was previously created using
** sqlite3_blob_open().
*/
int sqlite3_blob_close(sqlite3_blob *pBlob){
Incrblob *p = (Incrblob )pBlob;
int rc;
sqlite3 db;
if( p ){
db = p->db;
sqlite3_mutex_enter(db->mutex);
rc = sqlite3_finalize(p->pStmt);
sqlite3DbFree(db, ref p);
sqlite3_mutex_leave(db->mutex);
}else{
rc = SQLITE_OK;
}
return rc;
}
/*
** Perform a read or write operation on a blob
*/
static int blobReadWrite(
sqlite3_blob *pBlob,
void *z,
int n,
int iOffset,
int (*xCall)(BtCursor*, u32, u32, void)
){
int rc;
Incrblob *p = (Incrblob )pBlob;
Vdbe *v;
sqlite3 db;
if( p==0 ) return SQLITE_MISUSE_BKPT();
db = p->db;
sqlite3_mutex_enter(db->mutex);
v = (Vdbe)p->pStmt;
if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
/* Request is out of range. Return a transient error. */
rc = SQLITE_ERROR;
sqlite3Error(db, SQLITE_ERROR, 0);
} else if( v==0 ){
/* If there is no statement handle, then the blob-handle has
** already been invalidated. Return SQLITE_ABORT in this case.
*/
rc = SQLITE_ABORT;
}else{
/* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
** returned, clean-up the statement handle.
*/
Debug.Assert( db == v->db );
sqlite3BtreeEnterCursor(p->pCsr);
rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
sqlite3BtreeLeaveCursor(p->pCsr);
if( rc==SQLITE_ABORT ){
sqlite3VdbeFinalize(v);
p->pStmt = null;
}else{
db->errCode = rc;
v->rc = rc;
}
}
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** Read data from a blob handle.
*/
int sqlite3_blob_read(sqlite3_blob *pBlob, object *z, int n, int iOffset){
return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
}
/*
** Write data to a blob handle.
*/
int sqlite3_blob_write(sqlite3_blob *pBlob, string z, int n, int iOffset){
return blobReadWrite(pBlob, (void )z, n, iOffset, sqlite3BtreePutData);
}
/*
** Query a blob handle for the size of the data.
**
** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
** so no mutex is required for access.
*/
int sqlite3_blob_bytes(sqlite3_blob *pBlob){
Incrblob *p = (Incrblob )pBlob;
return p ? p->nByte : 0;
}
#endif // * #if !SQLITE_OMIT_INCRBLOB */
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using FlatRedBall;
using FlatRedBall.Input;
using FlatRedBall.Instructions;
using FlatRedBall.AI.Pathfinding;
using FlatRedBall.Debugging;
using FlatRedBall.Glue.StateInterpolation;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.Graphics.Particle;
using FlatRedBall.Gum.Animation;
using FlatRedBall.Math.Geometry;
using FlatRedBall.Math.Splines;
using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
using FlatRedBall.Localization;
using FlatRedBall.Math.Statistics;
using Microsoft.Xna.Framework;
using ShmupInvaders.Entities;
using ShmupInvaders.Factories;
using ShmupInvaders.GumRuntimes;
using StateInterpolationPlugin;
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
using FlatRedBall.Screens;
namespace ShmupInvaders.Screens
{
public partial class FRBGameScreen
{
private I1DInput _playerShipInput;
private IPressableInput _playerFireInput;
private IPressableInput _restartInput;
private Vector3 _initialShipContainerPosition;
private int _wave = 1;
private bool _gameOver;
int waveShots = 0;
int totalShots = 0;
int waveHits = 0;
int totalHits = 0;
private static readonly string[] WaveColors = { "Purple", "Orange", "Green", "Blue" };
private bool _newWave = false;
void CustomInitialize()
{
GameOverText.Visible = false;
RestartLabelText.Visible = false;
_initialShipContainerPosition = ShipContainerInstance.Position;
waveShots = totalShots = waveHits = totalHits = 0;
InitializeInput();
LineSpawnerInstance.FastSpeed(true);
MainGumScreenGlueInstance.FlyInAnimation.Play(this);
_newWave = true;
this.Call(() =>
{
CurrentWave = GlobalContent.Waves[_wave.ToString()];
LineSpawnerInstance.FastSpeed(false);
_newWave = false;
WaveScreenText.Visible = false;
}).After(4);
FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.Mars, false, true);
}
private void InitializeInput()
{
_playerShipInput = InputManager.Keyboard.Get1DInput(MoveLeftKey, MoveRightKey);
_playerFireInput = InputManager.Keyboard.GetKey(FireBulletKey);
_restartInput = InputManager.Keyboard.GetKey(Keys.R);
}
void CustomActivity(bool firstTimeCalled)
{
FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.Mars, false, true);
if (_gameOver == false && _newWave == false)
{
if (this.ShipContainerInstance.CollideAgainstBounce(this.LeftBoundary, 0, 1, 1) ||
this.ShipContainerInstance.CollideAgainstBounce(this.RightBoundary, 0, 1, 1))
{
var currentXVelocity = ShipContainerInstance.XVelocity;
ShipContainerInstance.XVelocity = 0;
// Using TweenerHolder instead of PositionedObjectTweenerExtensionMethods.Tween,
// because the latter function returns a TweenerHolder instead of a tweener, and I need the "Ended" event
new TweenerHolder()
{
Caller = ShipContainerInstance
}.Tween("Y", this.ShipContainerInstance.Y - StepDownPixels, .5f, InterpolationType.Bounce, Easing.Out).Ended += () =>
{
ShipContainerInstance.XVelocity = currentXVelocity * StepDownSpeedMultiplier;
};
//this.Call(ShakeScreen).After(.2);
}
HandleInput();
HandleCollisions();
FireEnemyBullets();
DestroyBullets();
}
else if (_gameOver && _restartInput.WasJustPressed)
{
ScreenManager.MoveToScreen(this.GetType());
}
}
private void FireEnemyBullets()
{
foreach (var ship in ShipEntityList)
{
if (ship.BulletCharged(PauseAdjustedCurrentTime))
{
ship.FireBullet(PauseAdjustedCurrentTime);
}
}
}
private void ShakeScreen()
{
var shakerX = new ShakeTweener
{
Amplitude = 20f,
Duration = .275f
};
var shakerY = new ShakeTweener
{
Amplitude = 10f,
MaxAmplitude = 10f,
Duration = .275f
};
TweenerManager.Self.Add(shakerY);
shakerY.PositionChanged += position => Camera.Main.Position.Y = position;
}
private void DisplayWaveScreen()
{
var step = TextTimeStep;
var text = $"WAVE {_wave + 1}";
WaveScreenText.Visible = true;
WaveScreenText.Text = "";
for (var it = 1; it <= text.Length; ++it)
{
var newText = text.Substring(0, it);
this.Call(() =>
{
WaveScreenText.Text = newText;
}).After(step * it);
}
WaveHitsNumText = waveHits.ToString();
WaveShotsNumText = waveShots.ToString();
WaveAccuracyNumText = (((float)waveHits / waveShots) * 100.0f).ToString("##.##") + "%";
StatisticsComponentInstance.Visible = true;
}
private void GameOver()
{
_gameOver = true;
PlayerShipInstance.XVelocity = 0;
ShipContainerInstance.XVelocity = 0;
var text = GameOverText.Text;
GameOverText.Visible = true;
GameOverText.Text = "";
var step = TextTimeStep;
var lastTime = 1;
for(var it = 1; it <= text.Length; ++it)
{
var newText = text.Substring(0, it);
this.Call(() =>
{
GameOverText.Text = newText;
}).After(step * it);
lastTime = it;
}
text = RestartLabelText.Text;
RestartLabelText.Visible = true;
RestartLabelText.Text = "";
for(var it = 1; it <= text.Length; ++it)
{
var newText = text.Substring(0, it);
this.Call(() =>
{
RestartLabelText.Text = newText;
}).After((it + lastTime) * step);
}
GameOverHitsNumText = totalHits.ToString();
GameOverShotsNumText = totalShots.ToString();
GameOverAccuracyNumText = (((float)totalHits / totalShots) * 100.0f).ToString("##.##") + "%";
GameOverStatisticsComponentRuntime.Visible = true;
}
private void YouWin()
{
_gameOver = true;
PlayerShipInstance.XVelocity = 0;
ShipContainerInstance.XVelocity = 0;
var text = WinScreenText.Text;
WinScreenText.Visible = true;
WinScreenText.Text = "";
var step = TextTimeStep;
var lastTime = 0;
for (var it = 1; it <= text.Length; ++it)
{
var newText = text.Substring(0, it);
this.Call(() =>
{
WinScreenText.Text = newText;
}).After(step * it);
lastTime = it;
}
text = WinRestartLabelText.Text;
WinRestartLabelText.Visible = true;
WinRestartLabelText.Text = "";
for (var it = 1; it <= text.Length; ++it)
{
var newText = text.Substring(0, it);
this.Call(() =>
{
WinRestartLabelText.Text = newText;
}).After((it + lastTime) * step);
}
StatisticsComponentInstance.Visible = false;
WaveScreenText.Visible = false;
WinHitsNumText = totalHits.ToString();
WinShotsNumText = totalShots.ToString();
WinAccuracyNumText = (((float)totalHits / totalShots) * 100.0f).ToString("##.##") + "%";
WinStatisticsComponentRuntime.Visible = true;
}
private void DestroyBullets()
{
for(var pbi = PlayerBulletList.Count - 1; pbi >= 0; pbi--)
{
var playerBullet = PlayerBulletList[pbi];
if (playerBullet.Y > RightBoundary.Top)
{
playerBullet.Destroy();
}
}
}
private void HandleCollisions()
{
HandlePlayerCollision();
HandleBulletCollisions();
HandleRicochetCollisions();
}
private void HandlePlayerCollision()
{
// Stay in the screen
PlayerShipInstance.CollideAgainstMove(LeftBoundary, 0, 1);
PlayerShipInstance.CollideAgainstMove(RightBoundary, 0, 1);
if (ShipContainerInstance.CollideAgainst(PlayerShipInstance))
{
GameOver();
}
if (ShipContainerInstance.AxisAlignedRectangleInstance.Bottom < LeftBoundary.Bottom)
{
GameOver();
}
}
private void HandleBulletCollisions()
{
HandlePlayerBulletCollision();
HandleEnemyBulletCollision();
}
private void HandleEnemyBulletCollision()
{
for (var ebi = EnemyBulletList.Count - 1; ebi >= 0; ebi--)
{
var enemyBullet = EnemyBulletList[ebi];
if (enemyBullet.CollideAgainst(PlayerShipInstance))
{
// You Lose!
GameOver();
enemyBullet.Destroy();
}
else if (enemyBullet.Y < RightBoundary.Bottom)
{
enemyBullet.Destroy();
}
}
}
private void HandlePlayerBulletCollision()
{
for (var pbi = PlayerBulletList.Count - 1; pbi >= 0; pbi--)
{
var playerBullet = PlayerBulletList[pbi];
for (var sei = ShipEntityList.Count - 1; sei >= 0; sei--)
{
var shipEntity = ShipEntityList[sei];
if (HandleShipHit(shipEntity, playerBullet))
{
playerBullet.Destroy();
++waveHits;
++totalHits;
break;
}
}
for (var ebi = EnemyBulletList.Count - 1; ebi >= 0; ebi--)
{
var enemyBullet = EnemyBulletList[ebi];
if (playerBullet.CollideAgainst(enemyBullet))
{
// Spawn ricochet
enemyBullet.CurrentFlashState = EnemyBullet.Flash.Lit;
enemyBullet.Velocity = Vector3.Zero;
++waveHits;
++totalHits;
this.Call(() =>
{
enemyBullet.CurrentFlashState = EnemyBullet.Flash.Normal;
SpawnRicochet(enemyBullet);
enemyBullet.Destroy();
playerBullet.Destroy();
}).After(TimeSpan.FromMilliseconds(100).TotalSeconds);
}
}
}
if (ShipEntityList.Count == 0 && !_newWave)
{
for (var ebi = EnemyBulletList.Count - 1; ebi >= 0; ebi--)
{
EnemyBulletList[ebi].Destroy();
}
_newWave = true;
// All ships destroyed. Start new wave:
LineSpawnerInstance.FastSpeed(true);
DisplayWaveScreen();
PlayerShipInstance.Velocity = Vector3.Zero;
PlayerShipInstance.CurrentFlyState = PlayerShip.Fly.Straight;
PlayerShipInstance.Tween(nameof(PlayerShipInstance.X), 0f, 4.0f, InterpolationType.Linear, Easing.In);
if (GlobalContent.Waves.ContainsKey((_wave + 1).ToString()))
{
this.Call(() =>
{
++_wave;
CurrentWave = GlobalContent.Waves[_wave.ToString()];
LineSpawnerInstance.FastSpeed(false);
WaveScreenText.Visible = false;
StatisticsComponentInstance.Visible = false;
_newWave = false;
}).After(4.0);
}
else
{
// YOU WIN!
YouWin();
}
}
}
private void HandleRicochetCollisions()
{
for (var rbi = RicochetList.Count - 1; rbi >= 0; rbi--)
{
var ricochetBullet = RicochetList[rbi];
for (var esi = ShipEntityList.Count - 1; esi >= 0; esi--)
{
var enemyShip = ShipEntityList[esi];
if (HandleShipHit(enemyShip, ricochetBullet))
{
ricochetBullet.Destroy();
break;
}
}
for (var ebi = EnemyBulletList.Count - 1; ebi >= 0; ebi--)
{
var enemyBullet = EnemyBulletList[ebi];
if (enemyBullet.CollideAgainst(ricochetBullet))
{
SpawnRicochet(enemyBullet);
ricochetBullet.Destroy();
enemyBullet.Destroy();
break;
}
}
}
}
private bool HandleShipHit(ShipEntity shipEntity, ICollidable bullet)
{
if (bullet.CollideAgainst(shipEntity) && shipEntity.SpriteInstance.CurrentChainName != "Explosion")
{
FlashEnemyShip(shipEntity);
if (shipEntity.TotalHits++ < shipEntity.HitsToKill - 1)
{
this.Call(() => shipEntity.SpriteInstance.ColorOperation = ColorOperation.None)
.After(TimeSpan.FromMilliseconds(10).TotalSeconds);
shipEntity.DamageInstance.Play();
return true;
}
else
{
shipEntity.SpriteInstance.ColorOperation = ColorOperation.None;
}
shipEntity.SpriteInstance.CurrentChainName = "Explosion";
shipEntity.SpriteInstance.TextureScale = .6f;
shipEntity.NextBullet = PauseAdjustedCurrentTime + 1.0;
shipEntity.Detach();
shipEntity.ExplosionInstance.Play();
this.Call(() =>
{
shipEntity.Destroy();
RecalculateContainerSize();
}).After(.55);
//Score += shipEntity.PointValue;
return true;
}
return false;
}
private void SpawnRicochet(EnemyBullet enemyBullet)
{
var up = RicochetFactory.CreateNew();
var down = RicochetFactory.CreateNew();
var left = RicochetFactory.CreateNew();
var right = RicochetFactory.CreateNew();
var upleft = RicochetFactory.CreateNew();
var upright = RicochetFactory.CreateNew();
var downright = RicochetFactory.CreateNew();
var downleft = RicochetFactory.CreateNew();
up.CurrentDirectionState = Ricochet.Direction.Up;
down.CurrentDirectionState = Ricochet.Direction.Down;
left.CurrentDirectionState = Ricochet.Direction.Left;
right.CurrentDirectionState = Ricochet.Direction.Right;
upleft.CurrentDirectionState = Ricochet.Direction.UpLeft;
upright.CurrentDirectionState = Ricochet.Direction.UpRight;
downright.CurrentDirectionState = Ricochet.Direction.DownRight;
downleft.CurrentDirectionState = Ricochet.Direction.DownLeft;
up.Position = down.Position = left.Position = right.Position
= upleft.Position = upright.Position = downright.Position = downleft.Position = enemyBullet.Position;
up.YVelocity = 1 * RicochetSpeed;
down.YVelocity = -1 * RicochetSpeed;
left.XVelocity = -1 * RicochetSpeed;
right.XVelocity = 1 * RicochetSpeed;
upleft.XVelocity = left.XVelocity;
upleft.YVelocity = up.YVelocity;
upright.XVelocity = right.XVelocity;
upright.YVelocity = up.YVelocity;
downright.XVelocity = right.XVelocity;
downright.YVelocity = down.YVelocity;
downleft.XVelocity = left.XVelocity;
downleft.YVelocity = down.YVelocity;
this.Call(() => {
up.Destroy();
down.Destroy();
left.Destroy();
right.Destroy();
upleft.Destroy();
upright.Destroy();
downright.Destroy();
downleft.Destroy();
}).After(RicochetTTL);
RicochetSoundEffectInstance.Play();
}
private static void FlashEnemyShip(ShipEntity shipEntity)
{
shipEntity.SpriteInstance.ColorOperation = ColorOperation.Add;
shipEntity.SpriteInstance.Red = 255f;
shipEntity.SpriteInstance.Blue = 255f;
shipEntity.SpriteInstance.Green = 255f;
}
private void RecalculateContainerSize()
{
if (ShipEntityList.Count > 0)
{
var minX = ShipEntityList.Min(s => s.RelativeX);
var maxX = ShipEntityList.Max(s => s.RelativeX);
var minY = ShipEntityList.Min(s => s.RelativeY);
var maxY = ShipEntityList.Max(s => s.RelativeY);
var width = maxX - minX;
width += ColumnSpacing;
var height = maxY - minY;
height += RowSpacing;
ShipContainerInstance.AxisAlignedRectangleInstance.Width = width;
ShipContainerInstance.AxisAlignedRectangleInstance.Height = height;
ShipContainerInstance.AxisAlignedRectangleInstance.RelativeX = minX + width / 2f - ColumnSpacing / 2f;
ShipContainerInstance.AxisAlignedRectangleInstance.RelativeY = minY + height / 2f - RowSpacing / 2f;
}
}
private void HandleInput()
{
PlayerShipInstance.XVelocity = _playerShipInput.Value*PlayerShipSpeed;
if (PlayerShipInstance.XVelocity < 0)
{
PlayerShipInstance.CurrentFlyState = PlayerShip.Fly.Left;
}
else if (PlayerShipInstance.XVelocity > 0)
{
PlayerShipInstance.CurrentFlyState = PlayerShip.Fly.Right;
}
else
{
PlayerShipInstance.CurrentFlyState = PlayerShip.Fly.Straight;
}
if (_playerFireInput.WasJustPressed && PlayerBulletList.Count < MaxBullets)
{
var bullet = PlayerBulletFactory.CreateNew();
++totalShots;
++waveShots;
bullet.Position = PlayerShipInstance.Position;
bullet.Y += 22;
bullet.YVelocity = PlayerBulletSpeed;
PlayerShipInstance.LaserInstance.Play();
}
}
void CustomDestroy()
{
}
static void CustomLoadStaticContent(string contentManagerName)
{
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Orleans.Runtime
{
// This is the public interface to be used by the consistent ring
public interface IRingRange
{
/// <summary>
/// Check if <paramref name="n"/> is our responsibility to serve
/// </summary>
/// <returns>true if the reminder is in our responsibility range, false otherwise</returns>
bool InRange(uint n);
bool InRange(GrainReference grainReference);
}
// This is the internal interface to be used only by the different range implementations.
internal interface IRingRangeInternal : IRingRange
{
long RangeSize();
double RangePercentage();
string ToFullString();
}
public interface ISingleRange : IRingRange
{
/// <summary>
/// Exclusive
/// </summary>
uint Begin { get; }
/// <summary>
/// Inclusive
/// </summary>
uint End { get; }
}
[Serializable]
internal sealed class SingleRange : IRingRangeInternal, IEquatable<SingleRange>, ISingleRange
{
private readonly uint begin;
private readonly uint end;
/// <summary>
/// Exclusive
/// </summary>
public uint Begin { get { return begin; } }
/// <summary>
/// Inclusive
/// </summary>
public uint End { get { return end; } }
public SingleRange(uint begin, uint end)
{
this.begin = begin;
this.end = end;
}
public bool InRange(GrainReference grainReference)
{
return InRange(grainReference.GetUniformHashCode());
}
/// <summary>
/// checks if n is element of (Begin, End], while remembering that the ranges are on a ring
/// </summary>
/// <param name="n"></param>
/// <returns>true if n is in (Begin, End], false otherwise</returns>
public bool InRange(uint n)
{
uint num = n;
if (begin < end)
{
return num > begin && num <= end;
}
// Begin > End
return num > begin || num <= end;
}
public long RangeSize()
{
if (begin < end)
{
return end - begin;
}
return RangeFactory.RING_SIZE - (begin - end);
}
public double RangePercentage() => RangeSize() * (100.0 / RangeFactory.RING_SIZE);
public bool Equals(SingleRange other)
{
return other != null && begin == other.begin && end == other.end;
}
public override bool Equals(object obj)
{
return Equals(obj as SingleRange);
}
public override int GetHashCode()
{
return (int)(begin ^ end);
}
public override string ToString()
{
if (begin == 0 && end == 0)
{
return "<(0 0], Size=x100000000, %Ring=100%>";
}
return String.Format("<(x{0,8:X8} x{1,8:X8}], Size=x{2,8:X8}, %Ring={3:0.000}%>", begin, end, RangeSize(), RangePercentage());
}
public string ToFullString()
{
return ToString();
}
internal bool Overlaps(SingleRange other) => Equals(other) || InRange(other.begin) || other.InRange(begin);
internal SingleRange Merge(SingleRange other)
{
if ((begin | end) == 0 || (other.begin | other.end) == 0)
{
return RangeFactory.FullRange;
}
if (Equals(other))
{
return this;
}
if (InRange(other.begin))
{
return MergeEnds(other);
}
if (other.InRange(begin))
{
return other.MergeEnds(this);
}
throw new InvalidOperationException("Ranges don't overlap");
}
// other range begins inside this range, merge it based on where it ends
private SingleRange MergeEnds(SingleRange other)
{
if (begin == other.end)
{
return RangeFactory.FullRange;
}
if (!InRange(other.end))
{
return new SingleRange(begin, other.end);
}
if (other.InRange(begin))
{
return RangeFactory.FullRange;
}
return this;
}
}
public static class RangeFactory
{
public const long RING_SIZE = ((long)uint.MaxValue) + 1;
private static readonly GeneralMultiRange EmptyRange = new(new());
internal static readonly SingleRange FullRange = new(0, 0);
public static IRingRange CreateFullRange() => FullRange;
public static IRingRange CreateRange(uint begin, uint end) => new SingleRange(begin, end);
public static IRingRange CreateRange(List<IRingRange> inRanges) => inRanges.Count switch
{
0 => EmptyRange,
1 => inRanges[0],
_ => GeneralMultiRange.Create(inRanges)
};
internal static IRingRange GetEquallyDividedSubRange(IRingRange range, int numSubRanges, int mySubRangeIndex)
=> EquallyDividedMultiRange.GetEquallyDividedSubRange(range, numSubRanges, mySubRangeIndex);
public static IEnumerable<ISingleRange> GetSubRanges(IRingRange range) => range switch
{
ISingleRange single => new[] { single },
GeneralMultiRange m => m.Ranges,
_ => throw new NotSupportedException(),
};
}
[Serializable]
internal sealed class GeneralMultiRange : IRingRangeInternal
{
private readonly List<SingleRange> ranges;
private readonly long rangeSize;
internal List<SingleRange> Ranges => ranges;
internal GeneralMultiRange(List<SingleRange> ranges)
{
this.ranges = ranges;
foreach (var r in ranges)
rangeSize += r.RangeSize();
}
internal static IRingRange Create(List<IRingRange> inRanges)
{
var ranges = inRanges.ConvertAll(r => (SingleRange)r);
return HasOverlaps() ? Compact() : new GeneralMultiRange(ranges);
bool HasOverlaps()
{
var last = ranges[0];
for (var i = 1; i < ranges.Count; i++)
{
if (last.Overlaps(last = ranges[i])) return true;
}
return false;
}
IRingRange Compact()
{
var lastIdx = 0;
var last = ranges[0];
for (var i = 1; i < ranges.Count; i++)
{
var r = ranges[i];
if (last.Overlaps(r)) ranges[lastIdx] = last = last.Merge(r);
else ranges[++lastIdx] = last = r;
}
if (lastIdx == 0) return last;
ranges.RemoveRange(++lastIdx, ranges.Count - lastIdx);
return new GeneralMultiRange(ranges);
}
}
public bool InRange(uint n)
{
foreach (var s in ranges)
{
if (s.InRange(n)) return true;
}
return false;
}
public bool InRange(GrainReference grainReference)
{
return InRange(grainReference.GetUniformHashCode());
}
public long RangeSize() => rangeSize;
public double RangePercentage() => RangeSize() * (100.0 / RangeFactory.RING_SIZE);
public override string ToString()
{
if (ranges.Count == 0) return "Empty MultiRange";
if (ranges.Count == 1) return ranges[0].ToString();
return String.Format("<MultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%>", RangeSize(), RangePercentage());
}
public string ToFullString()
{
if (ranges.Count == 0) return "Empty MultiRange";
if (ranges.Count == 1) return ranges[0].ToString();
return String.Format("<MultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%, {2} Ranges: {3}>", RangeSize(), RangePercentage(), ranges.Count, Utils.EnumerableToString(ranges, r => r.ToFullString()));
}
}
internal static class EquallyDividedMultiRange
{
private static SingleRange GetEquallyDividedSubRange(SingleRange singleRange, int numSubRanges, int mySubRangeIndex)
{
var rangeSize = singleRange.RangeSize();
uint portion = (uint)(rangeSize / numSubRanges);
uint remainder = (uint)(rangeSize - portion * numSubRanges);
uint start = singleRange.Begin;
for (int i = 0; i < numSubRanges; i++)
{
// (Begin, End]
uint end = (unchecked(start + portion));
// I want it to overflow on purpose. It will do the right thing.
if (remainder > 0)
{
end++;
remainder--;
}
if (i == mySubRangeIndex)
return new SingleRange(start, end);
start = end; // nextStart
}
throw new ArgumentException(nameof(mySubRangeIndex));
}
// Takes a range and devides it into numSubRanges equal ranges and returns the subrange at mySubRangeIndex.
public static IRingRange GetEquallyDividedSubRange(IRingRange range, int numSubRanges, int mySubRangeIndex)
{
if (numSubRanges <= 0) throw new ArgumentException(nameof(numSubRanges));
if ((uint)mySubRangeIndex >= (uint)numSubRanges) throw new ArgumentException(nameof(mySubRangeIndex));
if (numSubRanges == 1) return range;
switch (range)
{
case SingleRange singleRange:
return GetEquallyDividedSubRange(singleRange, numSubRanges, mySubRangeIndex);
case GeneralMultiRange multiRange:
switch (multiRange.Ranges.Count)
{
case 0: return multiRange;
case 1: return GetEquallyDividedSubRange(multiRange.Ranges[0], numSubRanges, mySubRangeIndex);
default:
// Take each of the single ranges in the multi range and divide each into equal sub ranges.
var singlesForThisIndex = new List<SingleRange>(multiRange.Ranges.Count);
foreach (var singleRange in multiRange.Ranges)
singlesForThisIndex.Add(GetEquallyDividedSubRange(singleRange, numSubRanges, mySubRangeIndex));
return new GeneralMultiRange(singlesForThisIndex);
}
default: throw new ArgumentException(nameof(range));
}
}
}
}
| |
// Copyright (c) Lex Li. 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.Net;
using System.Runtime.InteropServices;
using Microsoft.Web.Administration;
using Xunit;
namespace Tests
{
public static class TestCases
{
public static void TestIisExpress(ServerManager server)
{
Assert.Equal(5, server.ApplicationPools.Count);
Assert.True(server.ApplicationPools.AllowsAdd);
Assert.False(server.ApplicationPools.AllowsClear);
Assert.False(server.ApplicationPools.AllowsRemove);
Assert.Equal(
new[] { '\\', '/', '"', '|', '<', '>', ':', '*', '?', ']', '[', '+', '=', ';', ',', '@', '&' },
ApplicationPoolCollection.InvalidApplicationPoolNameCharacters());
Assert.Equal(12, server.Sites.Count);
Assert.True(server.Sites.AllowsAdd);
Assert.False(server.Sites.AllowsClear);
Assert.False(server.Sites.AllowsRemove);
Assert.Equal(
new[] { '\\', '/', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>' },
SiteCollection.InvalidSiteNameCharacters());
var siteDefaults = server.SiteDefaults;
//Assert.Equal("[http] :8080:localhost", server.Sites[0].Bindings[0].ToString());
Assert.Equal("localhost on *:8080 (http)", server.Sites[0].Bindings[0].ToShortString());
Assert.Equal("%IIS_USER_HOME%\\Logs", siteDefaults.LogFile.Directory);
Assert.Equal(LogFormat.W3c, siteDefaults.LogFile.LogFormat);
Assert.Equal("%IIS_USER_HOME%\\TraceLogFiles", siteDefaults.TraceFailedRequestsLogging.Directory);
Assert.True(siteDefaults.TraceFailedRequestsLogging.Enabled);
Assert.True(siteDefaults.LogFile.Enabled);
Assert.Equal("Clr4IntegratedAppPool", server.ApplicationDefaults.ApplicationPoolName);
var pool = server.ApplicationPools[0];
var model = pool.GetChildElement("processModel");
var item = model["maxProcesses"];
Assert.Equal("Clr4IntegratedAppPool", pool.Name);
Assert.Equal("v4.0", pool.ManagedRuntimeVersion);
Assert.Equal(1, pool.ProcessModel.MaxProcesses);
Assert.Equal(string.Empty, pool.ProcessModel.UserName);
#if IIS
Assert.Equal(1L, item);
#else
Assert.Equal(1U, item);
#endif
// TODO: why it should be int.
#if IIS
Assert.Equal(0, pool.GetAttributeValue("managedPipelineMode"));
pool.SetAttributeValue("managedPipelineMode", 1);
Assert.Equal(1, pool.GetAttributeValue("managedPipelineMode"));
pool.SetAttributeValue("managedPipelineMode", "Integrated");
Assert.Equal(0, pool.GetAttributeValue("managedPipelineMode"));
#else
Assert.Equal(0L, pool.GetAttributeValue("managedPipelineMode"));
pool.SetAttributeValue("managedPipelineMode", 1);
Assert.Equal(1L, pool.GetAttributeValue("managedPipelineMode"));
pool.SetAttributeValue("managedPipelineMode", "Integrated");
Assert.Equal(0L, pool.GetAttributeValue("managedPipelineMode"));
Assert.Equal(14, pool.ApplicationCount);
#endif
var name = Assert.Throws<COMException>(() => pool.SetAttributeValue("name", ""));
Assert.Equal("Invalid application pool name\r\n", name.Message);
var time = Assert.Throws<COMException>(() => pool.ProcessModel.IdleTimeout = TimeSpan.MaxValue);
Assert.Equal("Timespan value must be between 00:00:00 and 30.00:00:00 seconds inclusive, with a granularity of 60 seconds\r\n", time.Message);
var site = server.Sites[0];
Assert.Equal("WebSite1", site.Name);
Assert.Equal(14, site.Bindings.Count);
var binding = site.Bindings[0];
Assert.Equal(IPAddress.Any, binding.EndPoint.Address);
Assert.Equal(8080, binding.EndPoint.Port);
Assert.Equal("localhost", binding.Host);
Assert.Equal("*:8080:localhost", binding.ToString());
Assert.Equal(":8080:localhost", binding.BindingInformation);
Assert.True(site.Bindings.AllowsAdd);
Assert.True(site.Bindings.AllowsClear);
Assert.False(site.Bindings.AllowsRemove);
Assert.Equal("%IIS_USER_HOME%\\Logs", site.LogFile.Directory);
var sslSite = server.Sites[1];
var sslBinding = sslSite.Bindings[1];
var certificateHash = sslBinding.CertificateHash;
var certificateStoreName = sslBinding.CertificateStoreName;
Assert.Equal(SslFlags.Sni, sslBinding.SslFlags);
sslSite.Bindings.RemoveAt(1);
sslSite.Bindings.Add(":443:localhost", "https");
sslBinding = sslSite.Bindings[1];
Assert.Equal(SslFlags.None, sslBinding.SslFlags);
sslSite.Bindings.RemoveAt(1);
sslSite.Bindings.Add(":443:localhost", certificateHash, certificateStoreName, SslFlags.Sni);
sslBinding = sslSite.Bindings[1];
Assert.Equal(SslFlags.Sni, sslBinding.SslFlags);
sslSite.Bindings.RemoveAt(1);
sslSite.Bindings.Add(":443:localhost", certificateHash, certificateStoreName);
sslBinding = sslSite.Bindings[1];
Assert.Equal(SslFlags.None, sslBinding.SslFlags);
{
sslBinding = sslSite.Bindings.CreateElement();
var exception = Assert.Throws<FileNotFoundException>(() => sslSite.Bindings.Add(sslBinding));
Assert.Equal("Filename: \r\nError: Element is missing required attributes protocol,bindingInformation\r\n\r\n", exception.Message);
}
var app = site.Applications[0];
Assert.True(site.Applications.AllowsAdd);
Assert.False(site.Applications.AllowsClear);
Assert.False(site.Applications.AllowsRemove);
Assert.Equal(
new[] { '\\', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>', '*' },
ApplicationCollection.InvalidApplicationPathCharacters());
Assert.Equal("Clr4IntegratedAppPool", app.ApplicationPoolName);
Assert.Equal("/", app.Path);
var vDir = app.VirtualDirectories[0];
Assert.True(app.VirtualDirectories.AllowsAdd);
Assert.False(app.VirtualDirectories.AllowsClear);
Assert.False(app.VirtualDirectories.AllowsRemove);
Assert.Equal(
new[] { '\\', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>', '*' },
VirtualDirectoryCollection.InvalidVirtualDirectoryPathCharacters());
Assert.Equal(Helper.IsRunningOnMono() ? "%JEXUS_TEST_HOME%/WebSite1" : "%JEXUS_TEST_HOME%\\WebSite1", vDir.PhysicalPath);
{
var config = server.GetApplicationHostConfiguration();
var section = config.GetSection("system.applicationHost/log");
var mode = section.Attributes["centralLogFileMode"];
#if IIS
Assert.Equal(0, mode.Value);
#else
Assert.Equal(0L, mode.Value);
#endif
var encoding = section.Attributes["logInUTF8"];
Assert.Equal(true, encoding.Value);
ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging");
Assert.Equal(false, httpLoggingSection["dontLog"]);
ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
Assert.Equal(true, defaultDocumentSection["enabled"]);
ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
Assert.Equal(6, filesCollection.Count);
var errorsSection = config.GetSection("system.webServer/httpErrors");
var errorsCollection = errorsSection.GetCollection();
Assert.Equal(9, errorsCollection.Count);
var anonymousSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication");
var anonymousEnabled = (bool)anonymousSection["enabled"];
Assert.True(anonymousEnabled);
var value = anonymousSection["password"];
Assert.Equal(string.Empty, value);
var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
var windowsEnabled = (bool)windowsSection["enabled"];
Assert.False(windowsEnabled);
windowsSection["enabled"] = true;
server.CommitChanges();
}
{
var config = server.GetApplicationHostConfiguration();
var locations = config.GetLocationPaths();
Assert.Equal(3, locations.Length);
var exception =
Assert.Throws<FileNotFoundException>(
() =>
config.GetSection(
"system.webServer/security/authentication/anonymousAuthentication",
"Default Web Site"));
Assert.Equal(
"Filename: \r\nError: Unrecognized configuration path 'MACHINE/WEBROOT/APPHOST/Default Web Site'\r\n\r\n",
exception.Message);
Assert.Equal(null, exception.FileName);
var anonymousSection = config.GetSection(
"system.webServer/security/authentication/anonymousAuthentication",
"WebSite2");
var anonymousEnabled = (bool)anonymousSection["enabled"];
Assert.True(anonymousEnabled);
Assert.Equal("test", anonymousSection["userName"]);
// Assert.Equal("123456", anonymousSection["password"]);
}
{
// server config "Website1"
var config = server.GetApplicationHostConfiguration();
// enable Windows authentication
var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite1");
Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
Assert.Equal(false, windowsSection.IsLocked);
Assert.Equal(true, windowsSection.IsLocallyStored);
var windowsEnabled = (bool)windowsSection["enabled"];
Assert.True(windowsEnabled);
windowsSection["enabled"] = false;
Assert.Equal(false, windowsSection["enabled"]);
{
// disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", "WebSite1");
Assert.Equal(false, httpLoggingSection["dontLog"]);
httpLoggingSection["dontLog"] = true;
}
{
ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", "WebSite1/test");
// TODO:
// Assert.Equal(true, httpLoggingSection["dontLog"]);
httpLoggingSection["dontLog"] = false;
}
}
var siteName = Assert.Throws<COMException>(() => server.Sites[0].Name = "");
Assert.Equal("Invalid site name\r\n", siteName.Message);
var limit = Assert.Throws<COMException>(() => server.Sites[0].Limits.MaxBandwidth = 12);
Assert.Equal("Integer value must not be between 0 and 1023 inclusive\r\n", limit.Message);
var appPath = Assert.Throws<COMException>(() => server.Sites[0].Applications[0].Path = "");
Assert.Equal("Invalid application path\r\n", appPath.Message);
var vDirPath =
Assert.Throws<COMException>(() => server.Sites[0].Applications[0].VirtualDirectories[0].Path = "");
Assert.Equal("Invalid virtual directory path\r\n", vDirPath.Message);
{
// site config "Website1"
var config = server.Sites[0].Applications[0].GetWebConfiguration();
// enable Windows authentication
var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
Assert.Equal(true, windowsSection.IsLocked);
Assert.Equal(false, windowsSection.IsLocallyStored);
var windowsEnabled = (bool)windowsSection["enabled"];
Assert.True(windowsEnabled);
var exception = Assert.Throws<FileLoadException>(() => windowsSection["enabled"] = false);
Assert.Equal(
"This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=\"Deny\"), or set explicitly by a location tag with overrideMode=\"Deny\" or the legacy allowOverride=\"false\".\r\n",
exception.Message);
Assert.Equal(null, exception.FileName);
var compression = config.GetSection("system.webServer/urlCompression");
Assert.Equal(OverrideMode.Inherit, compression.OverrideMode);
Assert.Equal(OverrideMode.Allow, compression.OverrideModeEffective);
Assert.Equal(false, compression.IsLocked);
Assert.Equal(false, compression.IsLocallyStored);
Assert.Equal(true, compression["doDynamicCompression"]);
compression["doDynamicCompression"] = false;
{
// disable default document. Saved to web.config as this section can be overridden anywhere.
ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
Assert.Equal(true, defaultDocumentSection["enabled"]);
defaultDocumentSection["enabled"] = false;
ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
Assert.Equal(7, filesCollection.Count);
{
var first = filesCollection[0];
Assert.Equal("home1.html", first["value"]);
Assert.True(first.IsLocallyStored);
}
var second = filesCollection[1];
Assert.Equal("Default.htm", second["value"]);
Assert.False(second.IsLocallyStored);
var third = filesCollection[2];
Assert.Equal("Default.asp", third["value"]);
Assert.False(third.IsLocallyStored);
ConfigurationElement addElement = filesCollection.CreateElement();
addElement["value"] = @"home.html";
filesCollection.AddAt(0, addElement);
Assert.Equal(8, filesCollection.Count);
{
var first = filesCollection[0];
Assert.Equal("home.html", first["value"]);
// TODO: why?
// Assert.False(first.IsLocallyStored);
}
filesCollection.RemoveAt(4);
Assert.Equal(7, filesCollection.Count);
ConfigurationElement lastElement = filesCollection.CreateElement();
lastElement["value"] = @"home1.html";
lastElement["value"] = @"home2.html";
filesCollection.Add(lastElement);
Assert.Equal(8, filesCollection.Count);
}
//{
// var last = filesCollection[8];
// Assert.Equal("home2.html", last["value"]);
// // TODO: why?
// Assert.False(last.IsLocallyStored);
//}
{
// disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging");
Assert.Equal(false, httpLoggingSection["dontLog"]);
Assert.Throws<FileLoadException>(() => httpLoggingSection["dontLog"] = true);
}
{
ConfigurationSection httpLoggingSection = config.GetSection(
"system.webServer/httpLogging",
"WebSite1/test");
// TODO:
//Assert.Equal(true, httpLoggingSection["dontLog"]);
Assert.Throws<FileLoadException>(() => httpLoggingSection["dontLog"] = false);
}
var errorsSection = config.GetSection("system.webServer/httpErrors");
Assert.Equal(OverrideMode.Inherit, errorsSection.OverrideMode);
Assert.Equal(OverrideMode.Allow, errorsSection.OverrideModeEffective);
Assert.Equal(false, errorsSection.IsLocked);
Assert.Equal(false, errorsSection.IsLocallyStored);
var errorsCollection = errorsSection.GetCollection();
Assert.Equal(9, errorsCollection.Count);
var error = errorsCollection.CreateElement();
var cast = Assert.Throws<InvalidCastException>(() => error.SetAttributeValue("statusCode", "500"));
Assert.Equal(Helper.IsRunningOnMono() ? "Cannot cast from source type to destination type." : "Specified cast is not valid.", cast.Message);
var ex2 = Assert.Throws<COMException>(() => error["statusCode"] = 90000);
Assert.Equal("Integer value must be between 400 and 999 inclusive\r\n", ex2.Message);
error["statusCode"] = 500;
error["subStatusCode"] = 55;
error["prefixLanguageFilePath"] = string.Empty;
error["responseMode"] = "File";
var ex1 = Assert.Throws<FileNotFoundException>(() => errorsCollection.Add(error));
Assert.Equal("Filename: \r\nError: Element is missing required attributes path\r\n\r\n", ex1.Message);
Assert.Equal(null, ex1.FileName);
var ex = Assert.Throws<COMException>(() => error["path"] = "");
Assert.Equal("String must not be empty\r\n", ex.Message);
error["path"] = "test.htm";
errorsCollection.Add(error);
var staticContent = config.GetSection("system.webServer/staticContent").GetChildElement("clientCache");
staticContent["cacheControlMode"] = "DisableCache";
ConfigurationSection requestFilteringSection =
config.GetSection("system.webServer/security/requestFiltering");
ConfigurationElement hiddenSegmentsElement = requestFilteringSection.GetChildElement("hiddenSegments");
ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();
Assert.Equal(8, hiddenSegmentsCollection.Count);
var test = hiddenSegmentsCollection.CreateElement();
test["segment"] = "test";
hiddenSegmentsCollection.Add(test);
var old = hiddenSegmentsCollection[0];
hiddenSegmentsCollection.Remove(old);
var section = config.GetSection("system.webServer/rewrite/rules");
ConfigurationElementCollection collection = section.GetCollection();
//collection.Clear();
////collection.Delete();
//collection = section.GetCollection();
//Assert.Equal(0, collection.Count);
var newElement = collection.CreateElement();
newElement["name"] = "test";
collection.Add(newElement);
Assert.Equal(2, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
newElement = collection.CreateElement();
newElement["name"] = "test";
collection.Add(newElement);
Assert.Equal(1, collection.Count);
}
{
// server config "Website1"
var config = server.GetApplicationHostConfiguration();
// enable Windows authentication
var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite1");
Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
Assert.Equal(false, windowsSection.IsLocked);
Assert.Equal(true, windowsSection.IsLocallyStored);
var windowsEnabled = (bool)windowsSection["enabled"];
Assert.False(windowsEnabled);
}
{
Configuration config = server.GetApplicationHostConfiguration();
var anonymousSection = config.GetSection(
"system.webServer/security/authentication/anonymousAuthentication",
"WebSite2");
// anonymousSection["userName"] = "test1";
// anonymousSection["password"] = "654321";
ConfigurationSection windowsAuthenticationSection =
config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite2");
windowsAuthenticationSection["enabled"] = true;
ConfigurationElement extendedProtectionElement =
windowsAuthenticationSection.GetChildElement("extendedProtection");
extendedProtectionElement["tokenChecking"] = @"Allow";
extendedProtectionElement["flags"] = @"None";
var exception = Assert.Throws<COMException>(() => extendedProtectionElement["tokenChecking"] = @"NotExist");
Assert.Equal("Enum must be one of None, Allow, Require\r\n", exception.Message);
exception = Assert.Throws<COMException>(() => extendedProtectionElement["flags"] = @"NotExist");
Assert.Equal("Flags must be some combination of None, Proxy, NoServiceNameCheck, AllowDotlessSpn, ProxyCohosting\r\n", exception.Message);
ConfigurationElementCollection extendedProtectionCollection = extendedProtectionElement.GetCollection();
ConfigurationElement spnElement = extendedProtectionCollection.CreateElement("spn");
spnElement["name"] = @"HTTP/www.contoso.com";
extendedProtectionCollection.Add(spnElement);
ConfigurationElement spnElement1 = extendedProtectionCollection.CreateElement("spn");
spnElement1["name"] = @"HTTP/contoso.com";
extendedProtectionCollection.Add(spnElement1);
server.CommitChanges();
ConfigurationSection rulesSection = config.GetSection("system.webServer/rewrite/rules");
ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();
Assert.Equal(1, rulesCollection.Count);
ConfigurationElement ruleElement = rulesCollection[0];
Assert.Equal("lextudio2", ruleElement["name"]);
#if IIS
Assert.Equal(0, ruleElement["patternSyntax"]);
#else
Assert.Equal(0L, ruleElement["patternSyntax"]);
#endif
Assert.Equal(true, ruleElement["stopProcessing"]);
ConfigurationElement matchElement = ruleElement.GetChildElement("match");
Assert.Equal(@"(.*)", matchElement["url"]);
ConfigurationElement actionElement = ruleElement.GetChildElement("action");
#if IIS
Assert.Equal(1, actionElement["type"]);
#else
Assert.Equal(1L, actionElement["type"]);
#endif
Assert.Equal("/www/{R:0}", actionElement["url"]);
}
// remove application pool
Assert.False(server.ApplicationPools.AllowsRemove);
Assert.Equal(5, server.ApplicationPools.Count);
server.ApplicationPools.RemoveAt(4);
Assert.Equal(4, server.ApplicationPools.Count);
// remove binding
server.Sites[1].Bindings.RemoveAt(1);
// remove site
server.Sites.RemoveAt(4);
// remove application
var site1 = server.Sites[9];
site1.Applications.RemoveAt(1);
// remove virtual directory
var application = server.Sites[2].Applications[0];
application.VirtualDirectories.RemoveAt(1);
server.CommitChanges();
}
public static void TestIisExpressMissingWebsiteConfig(ServerManager server)
{
Assert.Equal(5, server.ApplicationPools.Count);
Assert.True(server.ApplicationPools.AllowsAdd);
Assert.False(server.ApplicationPools.AllowsClear);
Assert.False(server.ApplicationPools.AllowsRemove);
Assert.Equal(
new[] { '\\', '/', '"', '|', '<', '>', ':', '*', '?', ']', '[', '+', '=', ';', ',', '@', '&' },
ApplicationPoolCollection.InvalidApplicationPoolNameCharacters());
Assert.Equal(12, server.Sites.Count);
Assert.True(server.Sites.AllowsAdd);
Assert.False(server.Sites.AllowsClear);
Assert.False(server.Sites.AllowsRemove);
Assert.Equal(
new[] { '\\', '/', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>' },
SiteCollection.InvalidSiteNameCharacters());
var siteDefaults = server.SiteDefaults;
//Assert.Equal("localhost on *:8080 (http)", server.Sites[0].Bindings[0].ToShortString());
Assert.Equal("%IIS_USER_HOME%\\Logs", siteDefaults.LogFile.Directory);
Assert.Equal(LogFormat.W3c, siteDefaults.LogFile.LogFormat);
Assert.Equal("%IIS_USER_HOME%\\TraceLogFiles", siteDefaults.TraceFailedRequestsLogging.Directory);
Assert.True(siteDefaults.TraceFailedRequestsLogging.Enabled);
Assert.True(siteDefaults.LogFile.Enabled);
Assert.Equal("Clr4IntegratedAppPool", server.ApplicationDefaults.ApplicationPoolName);
var pool = server.ApplicationPools[0];
var model = pool.GetChildElement("processModel");
var item = model["maxProcesses"];
Assert.Equal("Clr4IntegratedAppPool", pool.Name);
Assert.Equal("v4.0", pool.ManagedRuntimeVersion);
Assert.Equal(1, pool.ProcessModel.MaxProcesses);
Assert.Equal(string.Empty, pool.ProcessModel.UserName);
#if IIS
Assert.Equal(1L, item);
#else
Assert.Equal(1U, item);
#endif
var name = Assert.Throws<COMException>(() => pool.SetAttributeValue("name", ""));
Assert.Equal("Invalid application pool name\r\n", name.Message);
var time = Assert.Throws<COMException>(() => pool.ProcessModel.IdleTimeout = TimeSpan.MaxValue);
Assert.Equal("Timespan value must be between 00:00:00 and 30.00:00:00 seconds inclusive, with a granularity of 60 seconds\r\n", time.Message);
var site = server.Sites[0];
Assert.Equal("WebSite1", site.Name);
Assert.Equal(14, site.Bindings.Count);
Assert.Equal("localhost on *:8080 (http)", site.Bindings[0].ToShortString());
Assert.Equal("0.0.0.0:8080", site.Bindings[0].EndPoint.ToString());
Assert.Equal("localhost", site.Bindings[0].Host);
Assert.Null(site.Bindings[1].EndPoint);
Assert.Equal(string.Empty, site.Bindings[1].Host);
Assert.False(site.Bindings[1].IsIPPortHostBinding);
Assert.False(site.Bindings[1].UseDsMapper);
Assert.Null(site.Bindings[1].CertificateHash);
Assert.Null(site.Bindings[1].CertificateStoreName);
Assert.Equal("808:* (net.tcp)", site.Bindings[1].ToShortString());
Assert.Null(site.Bindings[2].EndPoint);
Assert.Equal(string.Empty, site.Bindings[2].Host);
Assert.False(site.Bindings[2].IsIPPortHostBinding);
Assert.False(site.Bindings[2].UseDsMapper);
Assert.Null(site.Bindings[2].CertificateHash);
Assert.Null(site.Bindings[2].CertificateStoreName);
Assert.Equal("localhost (net.msmq)", site.Bindings[2].ToShortString());
Assert.Null(site.Bindings[3].EndPoint);
Assert.Equal(string.Empty, site.Bindings[3].Host);
Assert.False(site.Bindings[3].IsIPPortHostBinding);
Assert.False(site.Bindings[3].UseDsMapper);
Assert.Null(site.Bindings[3].CertificateHash);
Assert.Null(site.Bindings[3].CertificateStoreName);
Assert.Equal("localhost (msmq.formatname)", site.Bindings[3].ToShortString());
Assert.Null(site.Bindings[4].EndPoint);
Assert.Equal(string.Empty, site.Bindings[4].Host);
Assert.False(site.Bindings[4].IsIPPortHostBinding);
Assert.False(site.Bindings[4].UseDsMapper);
Assert.Null(site.Bindings[4].CertificateHash);
Assert.Null(site.Bindings[4].CertificateStoreName);
Assert.Equal("* (net.pipe)", site.Bindings[4].ToShortString());
Assert.Null(site.Bindings[5].EndPoint);
Assert.Equal(string.Empty, site.Bindings[5].Host);
Assert.False(site.Bindings[5].IsIPPortHostBinding);
Assert.False(site.Bindings[5].UseDsMapper);
Assert.Null(site.Bindings[5].CertificateHash);
Assert.Null(site.Bindings[5].CertificateStoreName);
Assert.Equal("*:21: (ftp)", site.Bindings[5].ToShortString());
Assert.Equal("* on *:8080 (http)", site.Bindings[6].ToShortString());
Assert.Equal("0.0.0.0:8080", site.Bindings[6].EndPoint.ToString());
Assert.Equal("*", site.Bindings[6].Host);
Assert.Equal("localhost on *:443 (https)", site.Bindings[7].ToShortString());
Assert.Equal("0.0.0.0:443", site.Bindings[7].EndPoint.ToString());
Assert.Equal("localhost", site.Bindings[7].Host);
Assert.Equal("* on *:44300 (https)", site.Bindings[8].ToShortString());
Assert.Equal("0.0.0.0:44300", site.Bindings[8].EndPoint.ToString());
Assert.Equal("*", site.Bindings[8].Host);
Assert.Null(site.Bindings[9].EndPoint);
Assert.Equal(string.Empty, site.Bindings[9].Host);
Assert.False(site.Bindings[9].IsIPPortHostBinding);
Assert.False(site.Bindings[9].UseDsMapper);
Assert.Null(site.Bindings[9].CertificateHash);
Assert.Null(site.Bindings[9].CertificateStoreName);
Assert.Equal("*:210:localhost (ftp)", site.Bindings[9].ToShortString());
{
var binding = site.Bindings[10];
Assert.Null(binding.EndPoint);
Assert.Equal(string.Empty, binding.Host);
Assert.False(binding.IsIPPortHostBinding);
Assert.False(binding.UseDsMapper);
Assert.Null(binding.CertificateHash);
Assert.Null(binding.CertificateStoreName);
Assert.Equal("* (net.tcp)", binding.ToShortString());
}
{
var binding = site.Bindings[11];
Assert.Null(binding.EndPoint);
Assert.Equal(string.Empty, binding.Host);
Assert.False(binding.IsIPPortHostBinding);
Assert.False(binding.UseDsMapper);
Assert.Null(binding.CertificateHash);
Assert.Null(binding.CertificateStoreName);
Assert.Equal("* (net.msmq)", binding.ToShortString());
}
{
var siteBinding = site.Bindings[12];
Assert.Null(siteBinding.EndPoint);
Assert.Equal(string.Empty, siteBinding.Host);
Assert.False(siteBinding.IsIPPortHostBinding);
Assert.False(siteBinding.UseDsMapper);
Assert.Null(siteBinding.CertificateHash);
Assert.Null(siteBinding.CertificateStoreName);
Assert.Equal("* (msmq.formatname)", siteBinding.ToShortString());
}
{
var binding = site.Bindings[13];
Assert.Null(binding.EndPoint);
Assert.Equal(string.Empty, binding.Host);
Assert.False(binding.IsIPPortHostBinding);
Assert.False(binding.UseDsMapper);
Assert.Null(binding.CertificateHash);
Assert.Null(binding.CertificateStoreName);
Assert.Equal("localhost (net.pipe)", binding.ToShortString());
}
Assert.True(site.Bindings.AllowsAdd);
Assert.True(site.Bindings.AllowsClear);
Assert.False(site.Bindings.AllowsRemove);
var app = site.Applications[0];
Assert.True(site.Applications.AllowsAdd);
Assert.False(site.Applications.AllowsClear);
Assert.False(site.Applications.AllowsRemove);
Assert.Equal(
new[] { '\\', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>', '*' },
ApplicationCollection.InvalidApplicationPathCharacters());
Assert.Equal("/", app.Path);
var vDir = app.VirtualDirectories[0];
Assert.True(app.VirtualDirectories.AllowsAdd);
Assert.False(app.VirtualDirectories.AllowsClear);
Assert.False(app.VirtualDirectories.AllowsRemove);
Assert.Equal(
new[] { '\\', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>', '*' },
VirtualDirectoryCollection.InvalidVirtualDirectoryPathCharacters());
Assert.Equal(Helper.IsRunningOnMono() ? "%JEXUS_TEST_HOME%/WebSite1" : "%JEXUS_TEST_HOME%\\WebSite1", vDir.PhysicalPath);
{
var config = server.GetApplicationHostConfiguration();
var section = config.GetSection("system.applicationHost/log");
var encoding = section.Attributes["logInUTF8"];
Assert.Equal(true, encoding.Value);
ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging");
Assert.Equal(false, httpLoggingSection["dontLog"]);
ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
Assert.Equal(true, defaultDocumentSection["enabled"]);
ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
Assert.Equal(6, filesCollection.Count);
var errorsSection = config.GetSection("system.webServer/httpErrors");
var errorsCollection = errorsSection.GetCollection();
Assert.Equal(9, errorsCollection.Count);
var anonymousSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication");
var anonymousEnabled = (bool)anonymousSection["enabled"];
Assert.True(anonymousEnabled);
var value = anonymousSection["password"];
Assert.Equal(string.Empty, value);
var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
var windowsEnabled = (bool)windowsSection["enabled"];
Assert.False(windowsEnabled);
windowsSection["enabled"] = true;
server.CommitChanges();
}
{
var config = server.GetApplicationHostConfiguration();
var locations = config.GetLocationPaths();
Assert.Equal(3, locations.Length);
var exception =
Assert.Throws<FileNotFoundException>(
() =>
config.GetSection(
"system.webServer/security/authentication/anonymousAuthentication",
"Default Web Site"));
Assert.Equal(
"Filename: \r\nError: Unrecognized configuration path 'MACHINE/WEBROOT/APPHOST/Default Web Site'\r\n\r\n",
exception.Message);
Assert.Equal(null, exception.FileName);
var anonymousSection = config.GetSection(
"system.webServer/security/authentication/anonymousAuthentication",
"WebSite2");
var anonymousEnabled = (bool)anonymousSection["enabled"];
Assert.True(anonymousEnabled);
Assert.Equal("test", anonymousSection["userName"]);
// Assert.Equal("123456", anonymousSection["password"]);
}
{
// server config "Website1"
var config = server.GetApplicationHostConfiguration();
// enable Windows authentication
var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite1");
Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
Assert.Equal(false, windowsSection.IsLocked);
Assert.Equal(true, windowsSection.IsLocallyStored);
var windowsEnabled = (bool)windowsSection["enabled"];
Assert.True(windowsEnabled);
windowsSection["enabled"] = false;
Assert.Equal(false, windowsSection["enabled"]);
{
// disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", "WebSite1");
Assert.Equal(false, httpLoggingSection["dontLog"]);
httpLoggingSection["dontLog"] = true;
}
{
ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", "WebSite1/test");
// TODO:
// Assert.Equal(true, httpLoggingSection["dontLog"]);
httpLoggingSection["dontLog"] = false;
}
}
var siteName = Assert.Throws<COMException>(() => server.Sites[0].Name = "");
Assert.Equal("Invalid site name\r\n", siteName.Message);
var limit = Assert.Throws<COMException>(() => server.Sites[0].Limits.MaxBandwidth = 12);
Assert.Equal("Integer value must not be between 0 and 1023 inclusive\r\n", limit.Message);
var appPath = Assert.Throws<COMException>(() => server.Sites[0].Applications[0].Path = "");
Assert.Equal("Invalid application path\r\n", appPath.Message);
var vDirPath =
Assert.Throws<COMException>(() => server.Sites[0].Applications[0].VirtualDirectories[0].Path = "");
Assert.Equal("Invalid virtual directory path\r\n", vDirPath.Message);
{
// site config "Website1"
var config = server.Sites[0].Applications[0].GetWebConfiguration();
// enable Windows authentication
var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
Assert.Equal(true, windowsSection.IsLocked);
Assert.Equal(false, windowsSection.IsLocallyStored);
var windowsEnabled = (bool)windowsSection["enabled"];
Assert.True(windowsEnabled);
var exception = Assert.Throws<FileLoadException>(() => windowsSection["enabled"] = false);
Assert.Equal(
"This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=\"Deny\"), or set explicitly by a location tag with overrideMode=\"Deny\" or the legacy allowOverride=\"false\".\r\n",
exception.Message);
Assert.Equal(null, exception.FileName);
var compression = config.GetSection("system.webServer/urlCompression");
Assert.Equal(OverrideMode.Inherit, compression.OverrideMode);
Assert.Equal(OverrideMode.Allow, compression.OverrideModeEffective);
Assert.Equal(false, compression.IsLocked);
Assert.Equal(false, compression.IsLocallyStored);
Assert.Equal(true, compression["doDynamicCompression"]);
compression["doDynamicCompression"] = false;
{
// disable default document. Saved to web.config as this section can be overridden anywhere.
ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
Assert.Equal(true, defaultDocumentSection["enabled"]);
defaultDocumentSection["enabled"] = false;
ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
Assert.Equal(6, filesCollection.Count);
{
var first = filesCollection[0];
Assert.Equal("Default.htm", first["value"]);
Assert.False(first.IsLocallyStored);
}
var second = filesCollection[1];
Assert.Equal("Default.asp", second["value"]);
Assert.False(second.IsLocallyStored);
var third = filesCollection[2];
Assert.Equal("index.htm", third["value"]);
Assert.False(third.IsLocallyStored);
ConfigurationElement addElement = filesCollection.CreateElement();
addElement["value"] = @"home.html";
filesCollection.AddAt(0, addElement);
Assert.Equal(7, filesCollection.Count);
{
var first = filesCollection[0];
Assert.Equal("home.html", first["value"]);
// TODO: why?
// Assert.False(first.IsLocallyStored);
}
filesCollection.RemoveAt(4);
Assert.Equal(6, filesCollection.Count);
ConfigurationElement lastElement = filesCollection.CreateElement();
lastElement["value"] = @"home.html";
var dup = Assert.Throws<COMException>(() => filesCollection.Add(lastElement));
#if IIS
Assert.Equal(
"Filename: \r\nError: Cannot add duplicate collection entry of type 'add' with unique key attribute 'value' set to 'home.html'\r\n\r\n",
dup.Message);
#else
Assert.Equal(
$"Filename: \\\\?\\{config.FileContext.FileName}\r\nLine number: 0\r\nError: Cannot add duplicate collection entry of type 'add' with unique key attribute 'value' set to 'home.html'\r\n\r\n",
dup.Message);
#endif
lastElement["value"] = @"home2.html";
filesCollection.Add(lastElement);
Assert.Equal(7, filesCollection.Count);
}
//{
// var last = filesCollection[8];
// Assert.Equal("home2.html", last["value"]);
// // TODO: why?
// Assert.False(last.IsLocallyStored);
//}
{
// disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging");
Assert.Equal(false, httpLoggingSection["dontLog"]);
Assert.Throws<FileLoadException>(() => httpLoggingSection["dontLog"] = true);
}
{
ConfigurationSection httpLoggingSection = config.GetSection(
"system.webServer/httpLogging",
"WebSite1/test");
// TODO:
//Assert.Equal(true, httpLoggingSection["dontLog"]);
Assert.Throws<FileLoadException>(() => httpLoggingSection["dontLog"] = false);
}
var errorsSection = config.GetSection("system.webServer/httpErrors");
Assert.Equal(OverrideMode.Inherit, errorsSection.OverrideMode);
Assert.Equal(OverrideMode.Allow, errorsSection.OverrideModeEffective);
Assert.Equal(false, errorsSection.IsLocked);
Assert.Equal(false, errorsSection.IsLocallyStored);
var errorsCollection = errorsSection.GetCollection();
Assert.Equal(9, errorsCollection.Count);
var error = errorsCollection.CreateElement();
var cast = Assert.Throws<InvalidCastException>(() => error.SetAttributeValue("statusCode", "500"));
Assert.Equal(Helper.IsRunningOnMono() ? "Cannot cast from source type to destination type." : "Specified cast is not valid.", cast.Message);
var ex2 = Assert.Throws<COMException>(() => error["statusCode"] = 90000);
Assert.Equal("Integer value must be between 400 and 999 inclusive\r\n", ex2.Message);
error["statusCode"] = 500;
error["subStatusCode"] = 55;
error["prefixLanguageFilePath"] = string.Empty;
error["responseMode"] = 0;
error["responseMode"] = ResponseMode.Test;
#if IIS
Assert.Equal(1, error["responseMode"]);
#else
Assert.Equal(1L, error["responseMode"]);
#endif
error["responseMode"] = "File";
var ex1 = Assert.Throws<FileNotFoundException>(() => errorsCollection.Add(error));
Assert.Equal("Filename: \r\nError: Element is missing required attributes path\r\n\r\n", ex1.Message);
Assert.Equal(null, ex1.FileName);
var ex = Assert.Throws<COMException>(() => error["path"] = "");
Assert.Equal("String must not be empty\r\n", ex.Message);
error["path"] = "test.htm";
errorsCollection.Add(error);
var staticContent = config.GetSection("system.webServer/staticContent").GetChildElement("clientCache");
staticContent["cacheControlMode"] = "DisableCache";
ConfigurationSection requestFilteringSection =
config.GetSection("system.webServer/security/requestFiltering");
ConfigurationElement hiddenSegmentsElement = requestFilteringSection.GetChildElement("hiddenSegments");
ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();
Assert.Equal(8, hiddenSegmentsCollection.Count);
var test = hiddenSegmentsCollection.CreateElement();
test["segment"] = "test";
hiddenSegmentsCollection.Add(test);
var old = hiddenSegmentsCollection[0];
hiddenSegmentsCollection.Remove(old);
var section = config.GetSection("system.webServer/rewrite/rules");
ConfigurationElementCollection collection = section.GetCollection();
//collection.Clear();
////collection.Delete();
//collection = section.GetCollection();
//Assert.Equal(0, collection.Count);
var newElement = collection.CreateElement();
newElement["name"] = "test";
collection.Add(newElement);
Assert.Equal(2, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
newElement = collection.CreateElement();
newElement["name"] = "test";
collection.Add(newElement);
Assert.Equal(1, collection.Count);
}
{
// server config "Website1"
var config = server.GetApplicationHostConfiguration();
// enable Windows authentication
var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite1");
Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
Assert.Equal(false, windowsSection.IsLocked);
Assert.Equal(true, windowsSection.IsLocallyStored);
var windowsEnabled = (bool)windowsSection["enabled"];
Assert.False(windowsEnabled);
}
{
Configuration config = server.GetApplicationHostConfiguration();
var anonymousSection = config.GetSection(
"system.webServer/security/authentication/anonymousAuthentication",
"WebSite2");
// anonymousSection["userName"] = "test1";
// anonymousSection["password"] = "654321";
ConfigurationSection windowsAuthenticationSection =
config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite2");
windowsAuthenticationSection["enabled"] = true;
ConfigurationElement extendedProtectionElement =
windowsAuthenticationSection.GetChildElement("extendedProtection");
extendedProtectionElement["tokenChecking"] = @"Allow";
extendedProtectionElement["flags"] = @"None";
var exception = Assert.Throws<COMException>(() => extendedProtectionElement["tokenChecking"] = @"NotExist");
Assert.Equal("Enum must be one of None, Allow, Require\r\n", exception.Message);
exception = Assert.Throws<COMException>(() => extendedProtectionElement["flags"] = @"NotExist");
Assert.Equal("Flags must be some combination of None, Proxy, NoServiceNameCheck, AllowDotlessSpn, ProxyCohosting\r\n", exception.Message);
ConfigurationElementCollection extendedProtectionCollection = extendedProtectionElement.GetCollection();
ConfigurationElement spnElement = extendedProtectionCollection.CreateElement("spn");
spnElement["name"] = @"HTTP/www.contoso.com";
extendedProtectionCollection.Add(spnElement);
ConfigurationElement spnElement1 = extendedProtectionCollection.CreateElement("spn");
spnElement1["name"] = @"HTTP/contoso.com";
extendedProtectionCollection.Add(spnElement1);
server.CommitChanges();
ConfigurationSection rulesSection = config.GetSection("system.webServer/rewrite/rules");
ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();
Assert.Equal(1, rulesCollection.Count);
ConfigurationElement ruleElement = rulesCollection[0];
Assert.Equal("lextudio2", ruleElement["name"]);
#if IIS
Assert.Equal(0, ruleElement["patternSyntax"]);
#else
Assert.Equal(0L, ruleElement["patternSyntax"]);
#endif
Assert.Equal(true, ruleElement["stopProcessing"]);
ConfigurationElement matchElement = ruleElement.GetChildElement("match");
Assert.Equal(@"(.*)", matchElement["url"]);
ConfigurationElement actionElement = ruleElement.GetChildElement("action");
#if IIS
Assert.Equal(1, actionElement["type"]);
#else
Assert.Equal(1L, actionElement["type"]);
#endif
Assert.Equal("/www/{R:0}", actionElement["url"]);
}
// remove application pool
Assert.False(server.ApplicationPools.AllowsRemove);
Assert.Equal(5, server.ApplicationPools.Count);
server.ApplicationPools.RemoveAt(4);
Assert.Equal(4, server.ApplicationPools.Count);
// remove binding
server.Sites[1].Bindings.RemoveAt(1);
// remove site
server.Sites.RemoveAt(4);
// remove application
var site1 = server.Sites[9];
site1.Applications.RemoveAt(1);
// remove virtual directory
var application = server.Sites[2].Applications[0];
application.VirtualDirectories.RemoveAt(1);
server.CommitChanges();
}
private enum ResponseMode
{
File = 0,
Test = 1
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// please define BEHAVIAC_NOT_USE_UNITY in your project file if you are not using unity
#if !BEHAVIAC_NOT_USE_UNITY
// if you have compiling errors complaining the following using 'UnityEngine',
//usually, you need to define BEHAVIAC_NOT_USE_UNITY in your project file
using UnityEngine;
#endif//!BEHAVIAC_NOT_USE_UNITY
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
#if BEHAVIAC_USE_SYSTEM_XML
using System.Xml;
#else
using System.Security;
using MiniXml;
#endif
namespace behaviac
{
public class BehaviorLoader
{
public virtual bool Load()
{
return false;
}
public virtual bool UnLoad()
{
return false;
}
}
public class AgentMeta
{
private Dictionary<uint, IProperty> _memberProperties = new Dictionary<uint, IProperty>();
private Dictionary<uint, ICustomizedProperty> _customizedProperties = new Dictionary<uint, ICustomizedProperty>();
private Dictionary<uint, ICustomizedProperty> _customizedStaticProperties = new Dictionary<uint, ICustomizedProperty>();
private Dictionary<uint, IInstantiatedVariable> _customizedStaticVars = null;
private Dictionary<uint, IMethod> _methods = new Dictionary<uint, IMethod>();
private static Dictionary<uint, AgentMeta> _agentMetas = new Dictionary<uint, AgentMeta>();
private static Dictionary<string, TypeCreator> _Creators = new Dictionary<string, TypeCreator>();
private static Dictionary<string, Type> _typesRegistered = new Dictionary<string, Type>();
private static uint _totalSignature = 0;
public static uint TotalSignature
{
set
{
_totalSignature = value;
}
get
{
return _totalSignature;
}
}
private uint _signature = 0;
public uint Signature
{
get
{
return _signature;
}
}
public static Dictionary<uint, AgentMeta> _AgentMetas_
{
get
{
return _agentMetas;
}
}
private static BehaviorLoader _behaviorLoader;
public static BehaviorLoader _BehaviorLoader_
{
set
{
_behaviorLoader = value;
}
}
public AgentMeta(uint signature = 0)
{
_signature = signature;
}
public static void Register()
{
RegisterBasicTypes();
const string kLoaderClass = "behaviac.BehaviorLoaderImplement";
Type loaderType = Type.GetType(kLoaderClass);
if (loaderType == null)
{
System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (System.Reflection.Assembly assembly in assemblies)
{
loaderType = assembly.GetType(kLoaderClass);
if (loaderType != null)
{
break;
}
}
}
if (loaderType != null)
{
_behaviorLoader = (BehaviorLoader)Activator.CreateInstance(loaderType);
_behaviorLoader.Load();
}
LoadAllMetaFiles();
}
public static void UnRegister()
{
UnRegisterBasicTypes();
if (_behaviorLoader != null)
{
_behaviorLoader.UnLoad();
}
_agentMetas.Clear();
_Creators.Clear();
}
public static Type GetTypeFromName(string typeName)
{
if (_typesRegistered.ContainsKey(typeName))
{
return _typesRegistered[typeName];
}
return null;
}
public static AgentMeta GetMeta(uint classId)
{
if (_agentMetas.ContainsKey(classId))
{
return _agentMetas[classId];
}
return null;
}
public Dictionary<uint, IInstantiatedVariable> InstantiateCustomizedProperties()
{
Dictionary<uint, IInstantiatedVariable> vars = new Dictionary<uint, IInstantiatedVariable>();
//instance customzied properties
{
var e = this._customizedProperties.Keys.GetEnumerator();
while (e.MoveNext())
{
uint id = e.Current;
ICustomizedProperty pCustomProperty = this._customizedProperties[id];
vars[id] = pCustomProperty.Instantiate();
}
}
if (_customizedStaticVars == null)
{
_customizedStaticVars = new Dictionary<uint, IInstantiatedVariable>();
var e = this._customizedStaticProperties.Keys.GetEnumerator();
while (e.MoveNext())
{
uint id = e.Current;
ICustomizedProperty pCustomProperty = this._customizedStaticProperties[id];
this._customizedStaticVars[id] = pCustomProperty.Instantiate();
}
}
//static customzied properties
{
var e = this._customizedStaticVars.Keys.GetEnumerator();
while (e.MoveNext())
{
uint id = e.Current;
IInstantiatedVariable pVar = this._customizedStaticVars[id];
vars[id] = pVar;
}
}
return vars;
}
public void RegisterMemberProperty(uint propId, IProperty property)
{
_memberProperties[propId] = property;
}
public void RegisterCustomizedProperty(uint propId, ICustomizedProperty property)
{
_customizedProperties[propId] = property;
}
public void RegisterStaticCustomizedProperty(uint propId, ICustomizedProperty property)
{
_customizedStaticProperties[propId] = property;
}
public void RegisterMethod(uint methodId, IMethod method)
{
_methods[methodId] = method;
}
public IProperty GetProperty(uint propId)
{
if (_customizedStaticProperties.ContainsKey(propId))
{
return _customizedStaticProperties[propId];
}
if (_customizedProperties.ContainsKey(propId))
{
return _customizedProperties[propId];
}
if (_memberProperties.ContainsKey(propId))
{
return _memberProperties[propId];
}
return null;
}
public IProperty GetMemberProperty(uint propId)
{
if (_memberProperties.ContainsKey(propId))
{
return _memberProperties[propId];
}
return null;
}
public Dictionary<uint, IProperty> GetMemberProperties()
{
return _memberProperties;
}
public IMethod GetMethod(uint methodId)
{
if (_methods.ContainsKey(methodId))
{
return _methods[methodId];
}
return null;
}
class TypeCreator
{
public delegate ICustomizedProperty PropertyCreator(uint propId, string propName, string valueStr);
public delegate ICustomizedProperty ArrayItemPropertyCreator(uint parentId, string parentName);
public delegate IInstanceMember InstancePropertyCreator(string instance, IInstanceMember indexMember, uint id);
public delegate IInstanceMember InstanceConstCreator(string typeName, string valueStr);
public delegate ICustomizedProperty CustomizedPropertyCreator(uint id, string name, string valueStr);
public delegate ICustomizedProperty CustomizedArrayItemPropertyCreator(uint id, string name);
PropertyCreator _propertyCreator;
ArrayItemPropertyCreator _arrayItemPropertyCreator;
InstancePropertyCreator _instancePropertyCreator;
InstanceConstCreator _instanceConstCreator;
CustomizedPropertyCreator _customizedPropertyCreator;
CustomizedArrayItemPropertyCreator _customizedArrayItemPropertyCreator;
public TypeCreator(PropertyCreator propCreator, ArrayItemPropertyCreator arrayItemPropCreator, InstancePropertyCreator instancePropertyCreator,
InstanceConstCreator instanceConstCreator, CustomizedPropertyCreator customizedPropertyCreator, CustomizedArrayItemPropertyCreator customizedArrayItemPropertyCreator)
{
_propertyCreator = propCreator;
_arrayItemPropertyCreator = arrayItemPropCreator;
_instancePropertyCreator = instancePropertyCreator;
_instanceConstCreator = instanceConstCreator;
_customizedPropertyCreator = customizedPropertyCreator;
_customizedArrayItemPropertyCreator = customizedArrayItemPropertyCreator;
}
public ICustomizedProperty CreateProperty(uint propId, string propName, string valueStr)
{
return _propertyCreator(propId, propName, valueStr);
}
public ICustomizedProperty CreateArrayItemProperty(uint parentId, string parentName)
{
return _arrayItemPropertyCreator(parentId, parentName);
}
public IInstanceMember CreateInstanceProperty(string instance, IInstanceMember indexMember, uint id)
{
return _instancePropertyCreator(instance, indexMember, id);
}
public IInstanceMember CreateInstanceConst(string typeName, string valueStr)
{
return _instanceConstCreator(typeName, valueStr);
}
public ICustomizedProperty CreateCustomizedProperty(uint id, string name, string valueStr)
{
return _customizedPropertyCreator(id, name, valueStr);
}
public ICustomizedProperty CreateCustomizedArrayItemProperty(uint id, string name)
{
return _customizedArrayItemPropertyCreator(id, name);
}
}
public static string GetTypeName(string typeName)
{
typeName = typeName.Replace("*", "");
return typeName;
}
public static ICustomizedProperty CreateProperty(string typeName, uint propId, string propName, string valueStr)
{
typeName = GetTypeName(typeName);
if (_Creators.ContainsKey(typeName))
{
TypeCreator creator = _Creators[typeName];
return creator.CreateProperty(propId, propName, valueStr);
}
Debug.Check(false);
return null;
}
public static ICustomizedProperty CreateArrayItemProperty(string typeName, uint parentId, string parentName)
{
typeName = GetTypeName(typeName);
if (_Creators.ContainsKey(typeName))
{
TypeCreator creator = _Creators[typeName];
return creator.CreateArrayItemProperty(parentId, parentName);
}
Debug.Check(false);
return null;
}
public static IInstanceMember CreateInstanceProperty(string typeName, string instance, IInstanceMember indexMember, uint varId)
{
typeName = GetTypeName(typeName);
if (_Creators.ContainsKey(typeName))
{
TypeCreator creator = _Creators[typeName];
return creator.CreateInstanceProperty(instance, indexMember, varId);
}
Debug.Check(false);
return null;
}
public static IInstanceMember CreateInstanceConst(string typeName, string valueStr)
{
typeName = GetTypeName(typeName);
if (_Creators.ContainsKey(typeName))
{
TypeCreator creator = _Creators[typeName];
return creator.CreateInstanceConst(typeName, valueStr);
}
Debug.Check(false);
return null;
}
public static ICustomizedProperty CreateCustomizedProperty(string typeName, uint id, string name, string valueStr)
{
typeName = GetTypeName(typeName);
if (_Creators.ContainsKey(typeName))
{
TypeCreator creator = _Creators[typeName];
return creator.CreateCustomizedProperty(id, name, valueStr);
}
Debug.Check(false);
return null;
}
public static ICustomizedProperty CreateCustomizedArrayItemProperty(string typeName, uint id, string name)
{
typeName = GetTypeName(typeName);
if (_Creators.ContainsKey(typeName))
{
TypeCreator creator = _Creators[typeName];
return creator.CreateCustomizedArrayItemProperty(id, name);
}
Debug.Check(false);
return null;
}
public static object ParseTypeValue(string typeName, string valueStr)
{
bool bArrayType = false;
Type type = Utils.GetTypeFromName(typeName, ref bArrayType);
Debug.Check(type != null);
if (bArrayType || !Utils.IsRefNullType(type))
{
if (!string.IsNullOrEmpty(valueStr))
{
return StringUtils.FromString(type, valueStr, bArrayType);
}
else if (type == typeof(string))
{
return string.Empty;
}
}
return null;
}
public static string ParseInstanceNameProperty(string fullName, ref string instanceName, ref string agentType)
{
//Self.AgentActionTest::Action2(0)
int pClassBegin = fullName.IndexOf('.');
if (pClassBegin != -1)
{
instanceName = fullName.Substring(0, pClassBegin).Replace("::", ".");
string propertyName = fullName.Substring(pClassBegin + 1);
int variableEnd = propertyName.LastIndexOf(':');
Debug.Check(variableEnd != -1);
agentType = propertyName.Substring(0, variableEnd - 1).Replace("::", ".");
string variableName = propertyName.Substring(variableEnd + 1);
return variableName;
}
return fullName;
}
public static ICustomizedProperty CreatorProperty<T>(uint propId, string propName, string valueStr)
{
return new CCustomizedProperty<T>(propId, propName, valueStr);
}
public static ICustomizedProperty CreatorArrayItemProperty<T>(uint parentId, string parentName)
{
return new CCustomizedArrayItemProperty<T>(parentId, parentName);
}
public static IInstanceMember CreatorInstanceProperty<T>(string instance, IInstanceMember indexMember, uint varId)
{
return new CInstanceCustomizedProperty<T>(instance, indexMember, varId);
}
public static IInstanceMember CreatorInstanceConst<T>(string typeName, string valueStr)
{
return new CInstanceConst<T>(typeName, valueStr);
}
public static ICustomizedProperty CreateCustomizedProperty<T>(uint id, string name, string valueStr)
{
return new CCustomizedProperty<T>(id, name, valueStr);
}
public static ICustomizedProperty CreateCustomizedArrayItemProperty<T>(uint id, string name)
{
return new CCustomizedArrayItemProperty<T>(id, name);
}
public static bool Register<T>(string typeName)
{
typeName = typeName.Replace("::", ".");
TypeCreator tc = new TypeCreator(CreatorProperty<T>, CreatorArrayItemProperty<T>, CreatorInstanceProperty<T>,
CreatorInstanceConst<T>, CreateCustomizedProperty<T>, CreateCustomizedArrayItemProperty<T>);
_Creators[typeName] = tc;
string vectorTypeName = string.Format("vector<{0}>", typeName);
TypeCreator tcl = new TypeCreator(CreatorProperty<List<T>>, CreatorArrayItemProperty<List<T>>, CreatorInstanceProperty<List<T>>,
CreatorInstanceConst<List<T>>, CreateCustomizedProperty<List<T>>, CreateCustomizedArrayItemProperty<List<T>>);
_Creators[vectorTypeName] = tcl;
_typesRegistered[typeName] = typeof(T);
_typesRegistered[vectorTypeName] = typeof(List<T>);
return true;
}
public static void UnRegister<T>(string typeName)
{
typeName = typeName.Replace("::", ".");
string vectorTypeName = string.Format("vector<{0}>", typeName);
_typesRegistered.Remove(typeName);
_typesRegistered.Remove(vectorTypeName);
_Creators.Remove(typeName);
_Creators.Remove(vectorTypeName);
}
private static void RegisterBasicTypes()
{
Register<bool>("bool");
Register<Boolean>("Boolean");
Register<byte>("byte");
Register<byte>("ubyte");
Register<Byte>("Byte");
Register<char>("char");
Register<Char>("Char");
Register<decimal>("decimal");
Register<Decimal>("Decimal");
Register<double>("double");
Register<Double>("Double");
Register<float>("float");
Register<int>("int");
Register<Int16>("Int16");
Register<Int32>("Int32");
Register<Int64>("Int64");
Register<long>("long");
Register<long>("llong");
Register<sbyte>("sbyte");
Register<SByte>("SByte");
Register<short>("short");
Register<ushort>("ushort");
Register<uint>("uint");
Register<UInt16>("UInt16");
Register<UInt32>("UInt32");
Register<UInt64>("UInt64");
Register<ulong>("ulong");
Register<ulong>("ullong");
Register<Single>("Single");
Register<string>("string");
Register<String>("String");
Register<object>("object");
#if !BEHAVIAC_NOT_USE_UNITY
Register<UnityEngine.GameObject>("UnityEngine.GameObject");
Register<UnityEngine.Vector2>("UnityEngine.Vector2");
Register<UnityEngine.Vector3>("UnityEngine.Vector3");
Register<UnityEngine.Vector4>("UnityEngine.Vector4");
#endif
Register<behaviac.Agent>("behaviac.Agent");
Register<behaviac.EBTStatus>("behaviac.EBTStatus");
}
private static void UnRegisterBasicTypes()
{
UnRegister<bool>("bool");
UnRegister<Boolean>("Boolean");
UnRegister<byte>("byte");
UnRegister<byte>("ubyte");
UnRegister<Byte>("Byte");
UnRegister<char>("char");
UnRegister<Char>("Char");
UnRegister<decimal>("decimal");
UnRegister<Decimal>("Decimal");
UnRegister<double>("double");
UnRegister<Double>("Double");
UnRegister<float>("float");
UnRegister<Single>("Single");
UnRegister<int>("int");
UnRegister<Int16>("Int16");
UnRegister<Int32>("Int32");
UnRegister<Int64>("Int64");
UnRegister<long>("long");
UnRegister<long>("llong");
UnRegister<sbyte>("sbyte");
UnRegister<SByte>("SByte");
UnRegister<short>("short");
UnRegister<ushort>("ushort");
UnRegister<uint>("uint");
UnRegister<UInt16>("UInt16");
UnRegister<UInt32>("UInt32");
UnRegister<UInt64>("UInt64");
UnRegister<ulong>("ulong");
UnRegister<ulong>("ullong");
UnRegister<string>("string");
UnRegister<String>("String");
UnRegister<object>("object");
#if !BEHAVIAC_NOT_USE_UNITY
UnRegister<UnityEngine.GameObject>("UnityEngine.GameObject");
UnRegister<UnityEngine.Vector2>("UnityEngine.Vector2");
UnRegister<UnityEngine.Vector3>("UnityEngine.Vector3");
UnRegister<UnityEngine.Vector4>("UnityEngine.Vector4");
#endif
UnRegister<behaviac.Agent>("behaviac.Agent");
UnRegister<behaviac.EBTStatus>("behaviac.EBTStatus");
}
public static IInstanceMember ParseProperty<T>(string value)
{
try
{
if (string.IsNullOrEmpty(value))
{
return null;
}
List<string> tokens = StringUtils.SplitTokens(ref value);
// const
if (tokens.Count == 1)
{
string typeName = Utils.GetNativeTypeName(typeof(T));
return AgentMeta.CreateInstanceConst(typeName, tokens[0]);
}
return ParseProperty(value);
}
catch (System.Exception e)
{
Debug.Check(false, e.Message);
}
return null;
}
public static IInstanceMember ParseProperty(string value, List<string> tokens = null)
{
try
{
if (string.IsNullOrEmpty(value))
{
return null;
}
if (tokens == null)
{
tokens = StringUtils.SplitTokens(ref value);
}
string typeName = "";
if (tokens[0] == "const")
{
// const Int32 0
Debug.Check(tokens.Count == 3);
const int kConstLength = 5;
string strRemaining = value.Substring(kConstLength + 1);
int p = StringUtils.FirstToken(strRemaining, ' ', ref typeName);
typeName = typeName.Replace("::", ".");
string strVale = strRemaining.Substring(p + 1);
// const
return AgentMeta.CreateInstanceConst(typeName, strVale);
}
else
{
string propStr = "";
string indexPropStr = "";
if (tokens[0] == "static")
{
// static float Self.AgentNodeTest::s_float_type_0
// static float Self.AgentNodeTest::s_float_type_0[int Self.AgentNodeTest::par_int_type_2]
Debug.Check(tokens.Count == 3 || tokens.Count == 4);
typeName = tokens[1];
propStr = tokens[2];
if (tokens.Count == 4) // array index
{
indexPropStr = tokens[3];
}
}
else
{
// float Self.AgentNodeTest::par_float_type_1
// float Self.AgentNodeTest::par_float_type_1[int Self.AgentNodeTest::par_int_type_2]
Debug.Check(tokens.Count == 2 || tokens.Count == 3);
typeName = tokens[0];
propStr = tokens[1];
if (tokens.Count == 3) // array index
{
indexPropStr = tokens[2];
}
}
string arrayItem = "";
IInstanceMember indexMember = null;
if (!string.IsNullOrEmpty(indexPropStr))
{
arrayItem = "[]";
indexMember = ParseProperty<int>(indexPropStr);
}
typeName = typeName.Replace("::", ".");
propStr = propStr.Replace("::", ".");
string[] props = propStr.Split('.');
Debug.Check(props.Length >= 3);
string instantceName = props[0];
string propName = props[props.Length - 1];
string className = props[1];
for (int i = 2; i < props.Length - 1; ++i)
{
className += "." + props[i];
}
uint classId = Utils.MakeVariableId(className);
AgentMeta meta = AgentMeta.GetMeta(classId);
Debug.Check(meta != null, "please add the exported 'AgentProperties.cs' and 'customizedtypes.cs' into the project!");
uint propId = Utils.MakeVariableId(propName + arrayItem);
// property
if (meta != null)
{
IProperty p = meta.GetProperty(propId);
if (p != null)
{
return p.CreateInstance(instantceName, indexMember);
}
}
// local var
return AgentMeta.CreateInstanceProperty(typeName, instantceName, indexMember, propId);
}
}
catch (System.Exception e)
{
Debug.Check(false, e.Message);
}
return null;
}
public static IMethod ParseMethod(string valueStr, ref string methodName)
{
//Self.test_ns::AgentActionTest::Action2(0)
if (string.IsNullOrEmpty(valueStr) || (valueStr[0] == '\"' && valueStr[1] == '\"'))
{
return null;
}
string agentIntanceName = null;
string agentClassName = null;
int pBeginP = ParseMethodNames(valueStr, ref agentIntanceName, ref agentClassName, ref methodName);
uint agentClassId = Utils.MakeVariableId(agentClassName);
uint methodId = Utils.MakeVariableId(methodName);
AgentMeta meta = AgentMeta.GetMeta(agentClassId);
Debug.Check(meta != null);
if (meta != null)
{
IMethod method = meta.GetMethod(methodId);
if (method == null)
{
Debug.Check(false, string.Format("Method of {0}::{1} is not registered!\n", agentClassName, methodName));
}
else
{
method = (IMethod)(method.Clone());
string paramsStr = valueStr.Substring(pBeginP);
Debug.Check(paramsStr[0] == '(');
List<string> paramsTokens = new List<string>();
int len = paramsStr.Length;
Debug.Check(paramsStr[len - 1] == ')');
string text = paramsStr.Substring(1, len - 2);
paramsTokens = ParseForParams(text);
method.Load(agentIntanceName, paramsTokens.ToArray());
}
return method;
}
return null;
}
public static IMethod ParseMethod(string valueStr)
{
string methodName = "";
return ParseMethod(valueStr, ref methodName);
}
private static int ParseMethodNames(string fullName, ref string agentIntanceName, ref string agentClassName, ref string methodName)
{
//Self.test_ns::AgentActionTest::Action2(0)
int pClassBegin = fullName.IndexOf('.');
Debug.Check(pClassBegin != -1);
agentIntanceName = fullName.Substring(0, pClassBegin);
int pBeginAgentClass = pClassBegin + 1;
int pBeginP = fullName.IndexOf('(', pBeginAgentClass);
Debug.Check(pBeginP != -1);
//test_ns::AgentActionTest::Action2(0)
int pBeginMethod = fullName.LastIndexOf(':', pBeginP);
Debug.Check(pBeginMethod != -1);
//skip '::'
Debug.Check(fullName[pBeginMethod] == ':' && fullName[pBeginMethod - 1] == ':');
pBeginMethod += 1;
int pos1 = pBeginP - pBeginMethod;
methodName = fullName.Substring(pBeginMethod, pos1);
int pos = pBeginMethod - 2 - pBeginAgentClass;
agentClassName = fullName.Substring(pBeginAgentClass, pos).Replace("::", ".");
return pBeginP;
}
//suppose params are seprated by ','
private static List<string> ParseForParams(string tsrc)
{
tsrc = StringUtils.RemoveQuot(tsrc);
int tsrcLen = tsrc.Length;
int startIndex = 0;
int index = 0;
int quoteDepth = 0;
List<string> params_ = new List<string>();
for (; index < tsrcLen; ++index)
{
if (tsrc[index] == '"')
{
quoteDepth++;
if ((quoteDepth & 0x1) == 0)
{
//closing quote
quoteDepth -= 2;
Debug.Check(quoteDepth >= 0);
}
}
else if (quoteDepth == 0 && tsrc[index] == ',')
{
//skip ',' inside quotes, like "count, count"
int lengthTemp = index - startIndex;
string strTemp = tsrc.Substring(startIndex, lengthTemp);
params_.Add(strTemp);
startIndex = index + 1;
}
}//end for
// the last param
int lengthTemp0 = index - startIndex;
if (lengthTemp0 > 0)
{
string strTemp = tsrc.Substring(startIndex, lengthTemp0);
params_.Add(strTemp);
}
return params_;
}
private static void LoadAllMetaFiles()
{
string metaFolder = "";
List<byte[]> fileBuffers = null;
try
{
string ext = (Workspace.Instance.FileFormat == Workspace.EFileFormat.EFF_bson) ? ".bson" : ".xml";
metaFolder = Path.Combine(Workspace.Instance.FilePath, "meta");
metaFolder = metaFolder.Replace('\\', '/');
if (!string.IsNullOrEmpty(Workspace.Instance.MetaFile))
{
string metaFile = Path.Combine(metaFolder, Workspace.Instance.MetaFile);
metaFile = Path.ChangeExtension(metaFile, ".meta");
byte[] fileBuffer = FileManager.Instance.FileOpen(metaFile, ext);
if (Workspace.Instance.FileFormat == Workspace.EFileFormat.EFF_bson)
{
load_bson(fileBuffer);
}
else// if (Workspace.Instance.FileFormat == Workspace.EFileFormat.EFF_xml)
{
load_xml(fileBuffer);
}
}
else
{
fileBuffers = FileManager.Instance.DirOpen(metaFolder, ext);
foreach (byte[] fileBuffer in fileBuffers)
{
if (Workspace.Instance.FileFormat == Workspace.EFileFormat.EFF_bson)
{
load_bson(fileBuffer);
}
else// if (Workspace.Instance.FileFormat == Workspace.EFileFormat.EFF_xml)
{
load_xml(fileBuffer);
}
}
}
}
catch (Exception ex)
{
int count = (fileBuffers != null) ? fileBuffers.Count : 0;
string errorInfo = string.Format("Load Meta Error: there are {0} meta fiels in {1}", count, metaFolder);
Debug.LogWarning(errorInfo + ex.Message + ex.StackTrace);
}
}
private static void registerCustomizedProperty(AgentMeta meta, string propName, string typeName, string valueStr, bool isStatic)
{
typeName = typeName.Replace("::", ".");
uint nameId = Utils.MakeVariableId(propName);
IProperty prop = meta.GetProperty(nameId);
ICustomizedProperty newProp = AgentMeta.CreateCustomizedProperty(typeName, nameId, propName, valueStr);
if (prop != null && newProp != null)
{
object newValue = newProp.GetValueObject(null);
object value = prop.GetValueObject(null);
if (newValue != null && value != null && newValue.GetType() == value.GetType())
{
return;
}
string errorInfo = string.Format("The type of '{0}' has been modified to {1}, which would bring the unpredictable consequences.", propName, typeName);
Debug.LogWarning(errorInfo);
Debug.Check(false, errorInfo);
}
if (isStatic)
{
meta.RegisterStaticCustomizedProperty(nameId, newProp);
}
else
{
meta.RegisterCustomizedProperty(nameId, newProp);
}
Type type = AgentMeta.GetTypeFromName(typeName);
if (Utils.IsArrayType(type))
{
// Get item type, i.e. vector<int>
int kStartIndex = "vector<".Length;
typeName = typeName.Substring(kStartIndex, typeName.Length - kStartIndex - 1); // item type
ICustomizedProperty arrayItemProp = AgentMeta.CreateCustomizedArrayItemProperty(typeName, nameId, propName);
nameId = Utils.MakeVariableId(propName + "[]");
if (isStatic)
{
meta.RegisterStaticCustomizedProperty(nameId, arrayItemProp);
}
else
{
meta.RegisterCustomizedProperty(nameId, arrayItemProp);
}
}
}
private static bool checkSignature(string signatureStr)
{
if (signatureStr != AgentMeta.TotalSignature.ToString())
{
string errorInfo = "[meta] The types/AgentProperties.cs should be exported from the behaviac designer, and then integrated into your project!\n";
Debug.LogWarning(errorInfo);
Debug.Check(false, errorInfo);
return false;
}
return true;
}
private static bool load_xml(byte[] pBuffer)
{
try
{
Debug.Check(pBuffer != null);
string xml = System.Text.Encoding.UTF8.GetString(pBuffer);
SecurityParser xmlDoc = new SecurityParser();
xmlDoc.LoadXml(xml);
SecurityElement rootNode = xmlDoc.ToXml();
if (rootNode.Children == null || rootNode.Tag != "agents" && rootNode.Children.Count != 1)
{
return false;
}
string versionStr = rootNode.Attribute("version");
Debug.Check(!string.IsNullOrEmpty(versionStr));
string signatureStr = rootNode.Attribute("signature");
checkSignature(signatureStr);
foreach (SecurityElement bbNode in rootNode.Children)
{
if (bbNode.Tag == "agent" && bbNode.Children != null)
{
string agentType = bbNode.Attribute("type").Replace("::", ".");
uint classId = Utils.MakeVariableId(agentType);
AgentMeta meta = AgentMeta.GetMeta(classId);
if (meta == null)
{
meta = new AgentMeta();
_agentMetas[classId] = meta;
}
string agentSignature = bbNode.Attribute("signature");
if (agentSignature == meta.Signature.ToString())
{
continue;
}
foreach (SecurityElement propertiesNode in bbNode.Children)
{
if (propertiesNode.Tag == "properties" && propertiesNode.Children != null)
{
foreach (SecurityElement propertyNode in propertiesNode.Children)
{
if (propertyNode.Tag == "property")
{
string memberStr = propertyNode.Attribute("member");
bool bIsMember = (!string.IsNullOrEmpty(memberStr) && memberStr == "true");
if (!bIsMember)
{
string propName = propertyNode.Attribute("name");
string propType = propertyNode.Attribute("type").Replace("::", ".");
string valueStr = propertyNode.Attribute("defaultvalue");
string isStatic = propertyNode.Attribute("static");
bool bIsStatic = (!string.IsNullOrEmpty(isStatic) && isStatic == "true");
registerCustomizedProperty(meta, propName, propType, valueStr, bIsStatic);
}
}
}
}
}//end of for propertiesNode
}
}//end of for bbNode
return true;
}
catch (Exception e)
{
Debug.Check(false, e.Message + e.StackTrace);
}
Debug.Check(false);
return false;
}
private static bool load_bson(byte[] pBuffer)
{
try
{
BsonDeserizer d = new BsonDeserizer();
if (d.Init(pBuffer))
{
BsonDeserizer.BsonTypes type = d.ReadType();
if (type == BsonDeserizer.BsonTypes.BT_AgentsElement)
{
bool bOk = d.OpenDocument();
Debug.Check(bOk);
string verStr = d.ReadString();
int version = int.Parse(verStr);
string signatureStr = d.ReadString(); // signature;
checkSignature(signatureStr);
{
type = d.ReadType();
while (type != BsonDeserizer.BsonTypes.BT_None)
{
if (type == BsonDeserizer.BsonTypes.BT_AgentElement)
{
load_agent(version, d);
}
type = d.ReadType();
}
Debug.Check(type == BsonDeserizer.BsonTypes.BT_None);
}
d.CloseDocument(false);
return true;
}
}
}
catch (Exception e)
{
Debug.Check(false, e.Message);
}
Debug.Check(false);
return false;
}
private static bool load_agent(int version, BsonDeserizer d)
{
try
{
d.OpenDocument();
string agentType = d.ReadString().Replace("::", ".");
string pBaseName = d.ReadString();
Debug.Check(!string.IsNullOrEmpty(pBaseName));
uint classId = Utils.MakeVariableId(agentType);
AgentMeta meta = AgentMeta.GetMeta(classId);
if (meta == null)
{
meta = new AgentMeta();
_agentMetas[classId] = meta;
}
bool signatrueChanged = false;
string agentSignature = d.ReadString();
if (agentSignature != meta.Signature.ToString())
{
signatrueChanged = true;
}
BsonDeserizer.BsonTypes type = d.ReadType();
while (type != BsonDeserizer.BsonTypes.BT_None)
{
if (type == BsonDeserizer.BsonTypes.BT_PropertiesElement)
{
d.OpenDocument();
type = d.ReadType();
while (type != BsonDeserizer.BsonTypes.BT_None)
{
if (type == BsonDeserizer.BsonTypes.BT_PropertyElement)
{
d.OpenDocument();
string propName = d.ReadString();
string propType = d.ReadString();
string memberStr = d.ReadString();
bool bIsMember = (!string.IsNullOrEmpty(memberStr) && memberStr == "true");
string isStatic = d.ReadString();
bool bIsStatic = (!string.IsNullOrEmpty(isStatic) && isStatic == "true");
if (!bIsMember)
{
string valueStr = d.ReadString();
if (signatrueChanged)
{
registerCustomizedProperty(meta, propName, propType, valueStr, bIsStatic);
}
}
else
{
d.ReadString(); // agentTypeMember
}
d.CloseDocument(true);
}
else
{
Debug.Check(false);
}
type = d.ReadType();
}//end of while
d.CloseDocument(false);
}
else if (type == BsonDeserizer.BsonTypes.BT_MethodsElement)
{
load_methods(d, agentType, type);
}
else
{
Debug.Check(type == BsonDeserizer.BsonTypes.BT_None);
}
type = d.ReadType();
}
d.CloseDocument(false);
return true;
}
catch (Exception ex)
{
Debug.Check(false, ex.Message);
}
return false;
}
private static void load_methods(BsonDeserizer d, string agentType, BsonDeserizer.BsonTypes type)
{
d.OpenDocument();
type = d.ReadType();
while (type == BsonDeserizer.BsonTypes.BT_MethodElement)
{
d.OpenDocument();
/*string methodName = */
d.ReadString();
string agentStr = d.ReadString();
Debug.Check(!string.IsNullOrEmpty(agentStr));
type = d.ReadType();
while (type == BsonDeserizer.BsonTypes.BT_ParameterElement)
{
d.OpenDocument();
string paramName = d.ReadString();
Debug.Check(!string.IsNullOrEmpty(paramName));
/*string paramType = */
d.ReadString();
d.CloseDocument(true);
type = d.ReadType();
}
d.CloseDocument(false);
type = d.ReadType();
}
d.CloseDocument(false);
}
}
}//namespace behaviac
| |
// 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.
////////////////////////////////////////////////////////////////////////////////
// JitHelpers
// Low-level Jit Helpers
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Threading;
using System.Runtime;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Runtime.CompilerServices {
// Wrapper for address of a string variable on stack
internal struct StringHandleOnStack
{
private IntPtr m_ptr;
internal StringHandleOnStack(IntPtr pString)
{
m_ptr = pString;
}
}
// Wrapper for address of a object variable on stack
internal struct ObjectHandleOnStack
{
private IntPtr m_ptr;
internal ObjectHandleOnStack(IntPtr pObject)
{
m_ptr = pObject;
}
}
// Wrapper for StackCrawlMark
internal struct StackCrawlMarkHandle
{
private IntPtr m_ptr;
internal StackCrawlMarkHandle(IntPtr stackMark)
{
m_ptr = stackMark;
}
}
// Helper class to assist with unsafe pinning of arbitrary objects. The typical usage pattern is:
// fixed (byte * pData = &JitHelpers.GetPinningHelper(value).m_data)
// {
// ... pData is what Object::GetData() returns in VM ...
// }
internal class PinningHelper
{
public byte m_data;
}
[FriendAccessAllowed]
internal static class JitHelpers
{
// The special dll name to be used for DllImport of QCalls
internal const string QCall = "QCall";
// Wraps object variable into a handle. Used to return managed strings from QCalls.
// s has to be a local variable on the stack.
[SecurityCritical]
static internal StringHandleOnStack GetStringHandleOnStack(ref string s)
{
return new StringHandleOnStack(UnsafeCastToStackPointer(ref s));
}
// Wraps object variable into a handle. Used to pass managed object references in and out of QCalls.
// o has to be a local variable on the stack.
[SecurityCritical]
static internal ObjectHandleOnStack GetObjectHandleOnStack<T>(ref T o) where T : class
{
return new ObjectHandleOnStack(UnsafeCastToStackPointer(ref o));
}
// Wraps StackCrawlMark into a handle. Used to pass StackCrawlMark to QCalls.
// stackMark has to be a local variable on the stack.
[SecurityCritical]
static internal StackCrawlMarkHandle GetStackCrawlMarkHandle(ref StackCrawlMark stackMark)
{
return new StackCrawlMarkHandle(UnsafeCastToStackPointer(ref stackMark));
}
#if _DEBUG
[SecurityCritical]
[FriendAccessAllowed]
static internal T UnsafeCast<T>(Object o) where T : class
{
T ret = UnsafeCastInternal<T>(o);
Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
return ret;
}
// The IL body of this method is not critical, but its body will be replaced with unsafe code, so
// this method is effectively critical
[SecurityCritical]
static private T UnsafeCastInternal<T>(Object o) where T : class
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
Contract.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(int)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(uint)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(short)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ushort)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(byte)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(sbyte)),
"Error, T must be an 4 byte (or less) enum JitHelpers.UnsafeEnumCast!");
return UnsafeEnumCastInternal<T>(val);
}
static private int UnsafeEnumCastInternal<T>(T val) where T : struct // Actually T must be 4 (or less) byte enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
Contract.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(long)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)),
"Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!");
return UnsafeEnumCastLongInternal<T>(val);
}
static private long UnsafeEnumCastLongInternal<T>(T val) where T : struct // Actually T must be 8 byte enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
// Internal method for getting a raw pointer for handles in JitHelpers.
// The reference has to point into a local stack variable in order so it can not be moved by the GC.
[SecurityCritical]
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
IntPtr p = UnsafeCastToStackPointerInternal<T>(ref val);
Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!");
return p;
}
[SecurityCritical]
static private IntPtr UnsafeCastToStackPointerInternal<T>(ref T val)
{
// The body of this function will be replaced by the EE with unsafe code that just returns val!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
#else // _DEBUG
// The IL body of this method is not critical, but its body will be replaced with unsafe code, so
// this method is effectively critical
[SecurityCritical]
[FriendAccessAllowed]
static internal T UnsafeCast<T>(Object o) where T : class
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
// should be return (long) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
[SecurityCritical]
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
#endif // _DEBUG
// Set the given element in the array without any type or range checks
[SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static internal void UnsafeSetArrayElement(Object[] target, int index, Object element);
// Used for unsafe pinning of arbitrary objects.
[System.Security.SecurityCritical] // auto-generated
static internal PinningHelper GetPinningHelper(Object o)
{
// This cast is really unsafe - call the private version that does not assert in debug
#if _DEBUG
return UnsafeCastInternal<PinningHelper>(o);
#else
return UnsafeCast<PinningHelper>(o);
#endif
}
#if _DEBUG
[SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static bool IsAddressInStack(IntPtr ptr);
#endif
}
}
| |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
using Pomelo.EntityFrameworkCore.MySql.Query.Expressions.Internal;
namespace Pomelo.EntityFrameworkCore.MySql.Query.ExpressionVisitors.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class MySqlQuerySqlGenerator : QuerySqlGenerator
{
// The order in which the types are specified matters, because types get matched by using StartsWith.
private static readonly Dictionary<string, string[]> _castMappings = new Dictionary<string, string[]>
{
{ "signed", new []{ "tinyint", "smallint", "mediumint", "int", "bigint", "bit" }},
{ "decimal(65,30)", new []{ "decimal" } },
{ "double", new []{ "double" } },
{ "float", new []{ "float" } },
{ "binary", new []{ "binary", "varbinary", "tinyblob", "blob", "mediumblob", "longblob" } },
{ "datetime(6)", new []{ "datetime(6)" } },
{ "datetime", new []{ "datetime" } },
{ "date", new []{ "date" } },
{ "timestamp(6)", new []{ "timestamp(6)" } },
{ "timestamp", new []{ "timestamp" } },
{ "time(6)", new []{ "time(6)" } },
{ "time", new []{ "time" } },
{ "json", new []{ "json" } },
{ "char", new []{ "char", "varchar", "text", "tinytext", "mediumtext", "longtext" } },
{ "nchar", new []{ "nchar", "nvarchar" } },
};
private const ulong LimitUpperBound = 18446744073709551610;
private readonly IMySqlOptions _options;
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public MySqlQuerySqlGenerator(
[NotNull] QuerySqlGeneratorDependencies dependencies,
[CanBeNull] IMySqlOptions options)
: base(dependencies)
{
_options = options;
}
protected override Expression VisitExtension(Expression extensionExpression)
=> extensionExpression switch
{
MySqlJsonTraversalExpression jsonTraversalExpression => VisitJsonPathTraversal(jsonTraversalExpression),
MySqlColumnAliasReferenceExpression columnAliasReferenceExpression => VisitColumnAliasReference(columnAliasReferenceExpression),
_ => base.VisitExtension(extensionExpression)
};
private Expression VisitColumnAliasReference(MySqlColumnAliasReferenceExpression columnAliasReferenceExpression)
{
Sql.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(columnAliasReferenceExpression.Alias));
return columnAliasReferenceExpression;
}
protected virtual Expression VisitJsonPathTraversal(MySqlJsonTraversalExpression expression)
{
// If the path contains parameters, then the -> and ->> aliases are not supported by MySQL, because
// we need to concatenate the path and the parameters.
// We will use JSON_EXTRACT (and JSON_UNQUOTE if needed) only in this case, because the aliases
// are much more readable.
var isSimplePath = expression.Path.All(
l => l is SqlConstantExpression ||
l is MySqlJsonArrayIndexExpression e && e.Expression is SqlConstantExpression);
if (expression.ReturnsText)
{
Sql.Append("JSON_UNQUOTE(");
}
if (expression.Path.Count > 0)
{
Sql.Append("JSON_EXTRACT(");
}
Visit(expression.Expression);
if (expression.Path.Count > 0)
{
Sql.Append(", ");
if (!isSimplePath)
{
Sql.Append("CONCAT(");
}
Sql.Append("'$");
foreach (var location in expression.Path)
{
if (location is MySqlJsonArrayIndexExpression arrayIndexExpression)
{
var isConstantExpression = arrayIndexExpression.Expression is SqlConstantExpression;
Sql.Append("[");
if (!isConstantExpression)
{
Sql.Append("', ");
}
Visit(arrayIndexExpression.Expression);
if (!isConstantExpression)
{
Sql.Append(", '");
}
Sql.Append("]");
}
else
{
Sql.Append(".");
Visit(location);
}
}
Sql.Append("'");
if (!isSimplePath)
{
Sql.Append(")");
}
Sql.Append(")");
}
if (expression.ReturnsText)
{
Sql.Append(")");
}
return expression;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override void GenerateLimitOffset(SelectExpression selectExpression)
{
Check.NotNull(selectExpression, nameof(selectExpression));
if (selectExpression.Limit != null)
{
Sql.AppendLine().Append("LIMIT ");
Visit(selectExpression.Limit);
}
if (selectExpression.Offset != null)
{
if (selectExpression.Limit == null)
{
// if we want to use Skip() without Take() we have to define the upper limit of LIMIT
Sql.AppendLine().Append($"LIMIT {LimitUpperBound}");
}
Sql.Append(" OFFSET ");
Visit(selectExpression.Offset);
}
}
protected override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
{
if (sqlFunctionExpression.Name.StartsWith("@@", StringComparison.Ordinal))
{
Sql.Append(sqlFunctionExpression.Name);
return sqlFunctionExpression;
}
return base.VisitSqlFunction(sqlFunctionExpression);
}
protected override Expression VisitCrossApply(CrossApplyExpression crossApplyExpression)
{
Sql.Append("JOIN ");
if (crossApplyExpression.Table is not TableExpression)
{
Sql.Append("LATERAL ");
}
Visit(crossApplyExpression.Table);
Sql.Append(" ON TRUE");
return crossApplyExpression;
}
protected override Expression VisitOuterApply(OuterApplyExpression outerApplyExpression)
{
Sql.Append("LEFT JOIN ");
if (outerApplyExpression.Table is not TableExpression)
{
Sql.Append("LATERAL ");
}
Visit(outerApplyExpression.Table);
Sql.Append(" ON TRUE");
return outerApplyExpression;
}
protected override Expression VisitSqlBinary(SqlBinaryExpression sqlBinaryExpression)
{
Check.NotNull(sqlBinaryExpression, nameof(sqlBinaryExpression));
if (sqlBinaryExpression.OperatorType == ExpressionType.Add &&
sqlBinaryExpression.Type == typeof(string) &&
sqlBinaryExpression.Left.TypeMapping?.ClrType == typeof(string) &&
sqlBinaryExpression.Right.TypeMapping?.ClrType == typeof(string))
{
Sql.Append("CONCAT(");
Visit(sqlBinaryExpression.Left);
Sql.Append(", ");
Visit(sqlBinaryExpression.Right);
Sql.Append(")");
return sqlBinaryExpression;
}
var requiresBrackets = RequiresBrackets(sqlBinaryExpression.Left);
if (requiresBrackets)
{
Sql.Append("(");
}
Visit(sqlBinaryExpression.Left);
if (requiresBrackets)
{
Sql.Append(")");
}
Sql.Append(GetOperator(sqlBinaryExpression));
// EF uses unary Equal and NotEqual to represent is-null checking.
// These need to be surrounded with parenthesis in various cases (e.g. where TRUE = x IS NOT NULL).
// See https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/issues/1309
requiresBrackets = RequiresBrackets(sqlBinaryExpression.Right) ||
!requiresBrackets &&
sqlBinaryExpression.Right is SqlUnaryExpression sqlUnaryExpression &&
(sqlUnaryExpression.OperatorType == ExpressionType.Equal || sqlUnaryExpression.OperatorType == ExpressionType.NotEqual);
if (requiresBrackets)
{
Sql.Append("(");
}
Visit(sqlBinaryExpression.Right);
if (requiresBrackets)
{
Sql.Append(")");
}
return sqlBinaryExpression;
}
private static bool RequiresBrackets(SqlExpression expression)
=> expression is SqlBinaryExpression
|| expression is LikeExpression
|| (expression is SqlUnaryExpression unary
&& unary.Operand.Type == typeof(bool)
&& (unary.OperatorType == ExpressionType.Equal
|| unary.OperatorType == ExpressionType.NotEqual));
public virtual Expression VisitMySqlRegexp(MySqlRegexpExpression mySqlRegexpExpression)
{
Check.NotNull(mySqlRegexpExpression, nameof(mySqlRegexpExpression));
Visit(mySqlRegexpExpression.Match);
Sql.Append(" REGEXP ");
Visit(mySqlRegexpExpression.Pattern);
return mySqlRegexpExpression;
}
public virtual Expression VisitMySqlMatch(MySqlMatchExpression mySqlMatchExpression)
{
Check.NotNull(mySqlMatchExpression, nameof(mySqlMatchExpression));
Sql.Append("MATCH ");
Sql.Append("(");
Visit(mySqlMatchExpression.Match);
Sql.Append(")");
Sql.Append(" AGAINST ");
Sql.Append("(");
Visit(mySqlMatchExpression.Against);
switch (mySqlMatchExpression.SearchMode)
{
case MySqlMatchSearchMode.NaturalLanguage:
break;
case MySqlMatchSearchMode.NaturalLanguageWithQueryExpansion:
Sql.Append(" WITH QUERY EXPANSION");
break;
case MySqlMatchSearchMode.Boolean:
Sql.Append(" IN BOOLEAN MODE");
break;
}
Sql.Append(")");
return mySqlMatchExpression;
}
protected override Expression VisitSqlUnary(SqlUnaryExpression sqlUnaryExpression)
=> sqlUnaryExpression.OperatorType == ExpressionType.Convert
? VisitConvert(sqlUnaryExpression)
: base.VisitSqlUnary(sqlUnaryExpression);
private SqlUnaryExpression VisitConvert(SqlUnaryExpression sqlUnaryExpression)
{
var castMapping = GetCastStoreType(sqlUnaryExpression.TypeMapping);
if (castMapping == "binary")
{
Sql.Append("UNHEX(HEX(");
Visit(sqlUnaryExpression.Operand);
Sql.Append("))");
return sqlUnaryExpression;
}
// There needs to be no CAST() applied between the exact same store type. This could happen, e.g. if
// `System.DateTime` and `System.DateTimeOffset` are used in conjunction, because both use different type
// mappings, but map to the same store type (e.g. `datetime(6)`).
//
// There also is no need for a double CAST() to the same type. Due to only rudimentary CAST() support in
// MySQL, the final store type of a CAST() operation might be different than the store type of the type
// mapping of the expression (e.g. "float" will be cast to "double"). So we optimize these cases too.
//
// An exception is the JSON data type, when used in conjunction with a parameter (like `JsonDocument`).
// JSON parameters like that will be serialized to string and supplied as a string parameter to MySQL
// (at least this seems to be the case currently with MySqlConnector). To make assignments and comparisons
// between JSON columns and JSON parameters (supplied as string) work, the string needs to be explicitly
// converted to JSON.
var sameInnerCastStoreType = sqlUnaryExpression.Operand is SqlUnaryExpression operandUnary &&
operandUnary.OperatorType == ExpressionType.Convert &&
castMapping.Equals(GetCastStoreType(operandUnary.TypeMapping), StringComparison.OrdinalIgnoreCase);
if (castMapping == "json" && !_options.ServerVersion.Supports.JsonDataTypeEmulation ||
!castMapping.Equals(sqlUnaryExpression.Operand.TypeMapping.StoreType, StringComparison.OrdinalIgnoreCase) &&
!sameInnerCastStoreType)
{
var useDecimalToDoubleWorkaround = false;
if (castMapping.StartsWith("double") &&
!_options.ServerVersion.Supports.DoubleCast)
{
useDecimalToDoubleWorkaround = true;
castMapping = "decimal(65,30)";
}
if (useDecimalToDoubleWorkaround)
{
Sql.Append("(");
}
Sql.Append("CAST(");
Visit(sqlUnaryExpression.Operand);
Sql.Append(" AS ");
Sql.Append(castMapping);
Sql.Append(")");
// FLOAT and DOUBLE are supported by CAST() as of MySQL 8.0.17.
// For server versions before that, a workaround is applied, that casts to a DECIMAL,
// that is then added to 0e0, which results in a DOUBLE.
// REF: https://dev.mysql.com/doc/refman/8.0/en/number-literals.html
if (useDecimalToDoubleWorkaround)
{
Sql.Append(" + 0e0)");
}
}
else
{
Visit(sqlUnaryExpression.Operand);
}
return sqlUnaryExpression;
}
private string GetCastStoreType(RelationalTypeMapping typeMapping)
{
var storeTypeLower = typeMapping.StoreType.ToLower();
string castMapping = null;
foreach (var kvp in _castMappings)
{
foreach (var storeType in kvp.Value)
{
if (storeTypeLower.StartsWith(storeType))
{
castMapping = kvp.Key;
break;
}
}
if (castMapping != null)
{
break;
}
}
if (castMapping == null)
{
throw new InvalidOperationException($"Cannot cast from type '{typeMapping.StoreType}'");
}
if (castMapping == "signed" && storeTypeLower.Contains("unsigned"))
{
castMapping = "unsigned";
}
// As of MySQL 8.0.18, a FLOAT cast might unnecessarily drop decimal places and round,
// so we just keep casting to double instead. MySqlConnector ensures, that a System.Single
// will be returned if expected, even if we return a DOUBLE.
if (castMapping.StartsWith("float") &&
!_options.ServerVersion.Supports.FloatCast)
{
castMapping = "double";
}
return castMapping;
}
public virtual Expression VisitMySqlComplexFunctionArgumentExpression(MySqlComplexFunctionArgumentExpression mySqlComplexFunctionArgumentExpression)
{
Check.NotNull(mySqlComplexFunctionArgumentExpression, nameof(mySqlComplexFunctionArgumentExpression));
var first = true;
foreach (var argument in mySqlComplexFunctionArgumentExpression.ArgumentParts)
{
if (first)
{
first = false;
}
else
{
Sql.Append(mySqlComplexFunctionArgumentExpression.Delimiter);
}
Visit(argument);
}
return mySqlComplexFunctionArgumentExpression;
}
public virtual Expression VisitMySqlCollateExpression(MySqlCollateExpression mySqlCollateExpression)
{
Check.NotNull(mySqlCollateExpression, nameof(mySqlCollateExpression));
Sql.Append("CONVERT(");
Visit(mySqlCollateExpression.ValueExpression);
Sql.Append($" USING {mySqlCollateExpression.Charset}) COLLATE {mySqlCollateExpression.Collation}");
return mySqlCollateExpression;
}
public virtual Expression VisitMySqlBinaryExpression(MySqlBinaryExpression mySqlBinaryExpression)
{
if (mySqlBinaryExpression.OperatorType == MySqlBinaryExpressionOperatorType.NonOptimizedEqual)
{
var equalExpression = new SqlBinaryExpression(
ExpressionType.Equal,
mySqlBinaryExpression.Left,
mySqlBinaryExpression.Right,
mySqlBinaryExpression.Type,
mySqlBinaryExpression.TypeMapping);
Visit(equalExpression);
}
else
{
Sql.Append("(");
Visit(mySqlBinaryExpression.Left);
Sql.Append(")");
switch (mySqlBinaryExpression.OperatorType)
{
case MySqlBinaryExpressionOperatorType.IntegerDivision:
Sql.Append(" DIV ");
break;
default:
throw new ArgumentOutOfRangeException();
}
Sql.Append("(");
Visit(mySqlBinaryExpression.Right);
Sql.Append(")");
}
return mySqlBinaryExpression;
}
/// <inheritdoc />
protected override void CheckComposableSql(string sql)
{
// MySQL supports CTE (WITH) expressions within subqueries, as well as others,
// so we allow any raw SQL to be composed over.
}
}
}
| |
using MagicOnion.Utils;
using MessagePack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace MagicOnion.Server.Hubs
{
#if ENABLE_SAVE_ASSEMBLY
public
#else
internal
#endif
static class AssemblyHolder
{
public const string ModuleName = "MagicOnion.Server.Hubs.DynamicBroadcaster";
readonly static DynamicAssembly assembly;
internal static DynamicAssembly Assembly { get { return assembly; } }
static AssemblyHolder()
{
assembly = new DynamicAssembly(ModuleName);
}
#if ENABLE_SAVE_ASSEMBLY
public static AssemblyBuilder Save()
{
return assembly.Save();
}
#endif
}
#if ENABLE_SAVE_ASSEMBLY
public
#else
internal
#endif
static class DynamicBroadcasterBuilder<T>
{
public static readonly Type BroadcasterType;
public static readonly Type BroadcasterType_ExceptOne;
public static readonly Type BroadcasterType_ExceptMany;
// TODO:impl Type
public static readonly Type BroadcasterType_ToOne;
public static readonly Type BroadcasterType_ToMany;
static readonly MethodInfo groupWriteAllMethodInfo = typeof(IGroup).GetMethod(nameof(IGroup.WriteAllAsync))!;
static readonly MethodInfo groupWriteExceptOneMethodInfo = typeof(IGroup).GetMethods().First(x => x.Name == nameof(IGroup.WriteExceptAsync) && !x.GetParameters()[2].ParameterType.IsArray);
static readonly MethodInfo groupWriteExceptManyMethodInfo = typeof(IGroup).GetMethods().First(x => x.Name == nameof(IGroup.WriteExceptAsync) && x.GetParameters()[2].ParameterType.IsArray);
static readonly MethodInfo groupWriteToOneMethodInfo = typeof(IGroup).GetMethods().First(x => x.Name == nameof(IGroup.WriteToAsync) && !x.GetParameters()[2].ParameterType.IsArray);
static readonly MethodInfo groupWriteToManyMethodInfo = typeof(IGroup).GetMethods().First(x => x.Name == nameof(IGroup.WriteToAsync) && x.GetParameters()[2].ParameterType.IsArray);
static readonly MethodInfo fireAndForget = typeof(DynamicBroadcasterBuilder<T>).GetMethod(nameof(FireAndForget), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)!;
static DynamicBroadcasterBuilder()
{
var t = typeof(T);
var ti = t.GetTypeInfo();
if (!ti.IsInterface) throw new Exception("Broadcaster Proxy only allows interface. Type:" + ti.Name);
var asm = AssemblyHolder.Assembly;
var methodDefinitions = BroadcasterHelper.SearchDefinitions(t);
BroadcasterHelper.VerifyMethodDefinitions(methodDefinitions);
{
var typeBuilder = asm.DefineType($"{AssemblyHolder.ModuleName}.{ti.FullName}Broadcaster_{Guid.NewGuid().ToString()}", TypeAttributes.Public, typeof(object), new Type[] { t })!;
var (group, ctor) = DefineConstructor(typeBuilder);
DefineMethods(typeBuilder, t, group, methodDefinitions, groupWriteAllMethodInfo, null);
BroadcasterType = typeBuilder.CreateTypeInfo()!.AsType();
}
{
var typeBuilder = asm.DefineType($"{AssemblyHolder.ModuleName}.{ti.FullName}BroadcasterExceptOne_{Guid.NewGuid().ToString()}", TypeAttributes.Public, typeof(object), new Type[] { t });
var (group, except, ctor) = DefineConstructor2(typeBuilder);
DefineMethods(typeBuilder, t, group, methodDefinitions, groupWriteExceptOneMethodInfo, except);
BroadcasterType_ExceptOne = typeBuilder.CreateTypeInfo()!.AsType();
}
{
var typeBuilder = asm.DefineType($"{AssemblyHolder.ModuleName}.{ti.FullName}BroadcasterExceptMany_{Guid.NewGuid().ToString()}", TypeAttributes.Public, typeof(object), new Type[] { t });
var (group, except, ctor) = DefineConstructor3(typeBuilder);
DefineMethods(typeBuilder, t, group, methodDefinitions, groupWriteExceptManyMethodInfo, except);
BroadcasterType_ExceptMany = typeBuilder.CreateTypeInfo()!.AsType();
}
{
var typeBuilder = asm.DefineType($"{AssemblyHolder.ModuleName}.{ti.FullName}BroadcasterToOne_{Guid.NewGuid().ToString()}", TypeAttributes.Public, typeof(object), new Type[] { t });
var (group, to, ctor) = DefineConstructor2(typeBuilder);
DefineMethods(typeBuilder, t, group, methodDefinitions, groupWriteToOneMethodInfo, to);
BroadcasterType_ToOne = typeBuilder.CreateTypeInfo()!.AsType();
}
{
var typeBuilder = asm.DefineType($"{AssemblyHolder.ModuleName}.{ti.FullName}BroadcasterToMany_{Guid.NewGuid().ToString()}", TypeAttributes.Public, typeof(object), new Type[] { t });
var (group, to, ctor) = DefineConstructor3(typeBuilder);
DefineMethods(typeBuilder, t, group, methodDefinitions, groupWriteToManyMethodInfo, to);
BroadcasterType_ToMany = typeBuilder.CreateTypeInfo()!.AsType();
}
}
static (FieldInfo, ConstructorInfo) DefineConstructor(TypeBuilder typeBuilder)
{
// .ctor(IGroup group)
var groupField = typeBuilder.DefineField("group", typeof(IGroup), FieldAttributes.Private | FieldAttributes.InitOnly);
var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGroup) });
var il = ctor.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(object).GetConstructors().First());
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, groupField);
il.Emit(OpCodes.Ret);
return (groupField, ctor);
}
static (FieldInfo groupField, FieldInfo exceptField, ConstructorInfo) DefineConstructor2(TypeBuilder typeBuilder)
{
// .ctor(IGroup group, Guid except)
var groupField = typeBuilder.DefineField("group", typeof(IGroup), FieldAttributes.Private | FieldAttributes.InitOnly);
var connectionIdField = typeBuilder.DefineField("connectionId", typeof(Guid), FieldAttributes.Private | FieldAttributes.InitOnly);
var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGroup), typeof(Guid) });
var il = ctor.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(object).GetConstructors().First());
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, groupField);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Stfld, connectionIdField);
il.Emit(OpCodes.Ret);
return (groupField, connectionIdField, ctor);
}
static (FieldInfo groupField, FieldInfo exceptField, ConstructorInfo) DefineConstructor3(TypeBuilder typeBuilder)
{
// .ctor(IGroup group, Guid[] except)
var groupField = typeBuilder.DefineField("group", typeof(IGroup), FieldAttributes.Private | FieldAttributes.InitOnly);
var connectionIdsField = typeBuilder.DefineField("connectionIds", typeof(Guid[]), FieldAttributes.Private | FieldAttributes.InitOnly);
var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGroup), typeof(Guid[]) });
var il = ctor.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(object).GetConstructors().First());
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, groupField);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Stfld, connectionIdsField);
il.Emit(OpCodes.Ret);
return (groupField, connectionIdsField, ctor);
}
static void DefineMethods(TypeBuilder typeBuilder, Type interfaceType, FieldInfo groupField, BroadcasterHelper.MethodDefinition[] definitions, MethodInfo writeMethod, FieldInfo? exceptField)
{
// Proxy Methods
for (int i = 0; i < definitions.Length; i++)
{
var def = definitions[i];
var parameters = def.MethodInfo.GetParameters().Select(x => x.ParameterType).ToArray();
var method = typeBuilder.DefineMethod(def.MethodInfo.Name, MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
def.MethodInfo.ReturnType,
parameters);
var il = method.GetILGenerator();
// like this.
// return group.WriteAllAsync(9013131, new DynamicArgumentTuple<int, string>(senderId, message));
// BroadcasterHelper.FireAndForget(...)
// load group field
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, groupField);
// arg1
il.EmitLdc_I4(def.MethodId);
// create request for arg2
for (int j = 0; j < parameters.Length; j++)
{
il.Emit(OpCodes.Ldarg, j + 1);
}
Type? callType = null;
if (parameters.Length == 0)
{
// use Nil.
callType = typeof(Nil);
il.Emit(OpCodes.Ldsfld, typeof(Nil).GetField("Default")!);
}
else if (parameters.Length == 1)
{
// already loaded parameter.
callType = parameters[0];
}
else
{
// call new DynamicArgumentTuple<T>
callType = BroadcasterHelper.dynamicArgumentTupleTypes[parameters.Length - 2].MakeGenericType(parameters);
il.Emit(OpCodes.Newobj, callType.GetConstructors().First());
}
if (writeMethod != groupWriteAllMethodInfo)
{
if (exceptField == null) throw new InvalidOperationException("Non group-wide write method requires except field.");
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, exceptField);
}
if (def.MethodInfo.ReturnType == typeof(void))
{
il.Emit(OpCodes.Ldc_I4_1); // fireAndForget = true
}
else
{
il.Emit(OpCodes.Ldc_I4_0); // fireAndForget = false
}
il.Emit(OpCodes.Callvirt, writeMethod.MakeGenericMethod(callType));
if (def.MethodInfo.ReturnType == typeof(void))
{
il.Emit(OpCodes.Call, fireAndForget);
}
il.Emit(OpCodes.Ret);
}
}
static async void FireAndForget(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (Exception ex)
{
MagicOnionServerInternalLogger.Current.LogError(ex, "exception occured in client broadcast.");
}
}
}
}
| |
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 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;
}
}
}
| |
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System.Collections.Generic;
using System.Text;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
using Antlr4.Runtime.Tree;
namespace Antlr4.Runtime
{
/// <summary>A rule context is a record of a single rule invocation.</summary>
/// <remarks>
/// A rule context is a record of a single rule invocation. It knows
/// which context invoked it, if any. If there is no parent context, then
/// naturally the invoking state is not valid. The parent link
/// provides a chain upwards from the current rule invocation to the root
/// of the invocation tree, forming a stack. We actually carry no
/// information about the rule associated with this context (except
/// when parsing). We keep only the state number of the invoking state from
/// the ATN submachine that invoked this. Contrast this with the s
/// pointer inside ParserRuleContext that tracks the current state
/// being "executed" for the current rule.
/// The parent contexts are useful for computing lookahead sets and
/// getting error information.
/// These objects are used during parsing and prediction.
/// For the special case of parsers, we use the subclass
/// ParserRuleContext.
/// </remarks>
/// <seealso cref="ParserRuleContext"/>
public class RuleContext : IRuleNode
{
/// <summary>What context invoked this rule?</summary>
private Antlr4.Runtime.RuleContext _parent;
/// <summary>
/// What state invoked the rule associated with this context?
/// The "return address" is the followState of invokingState
/// If parent is null, this should be -1.
/// </summary>
/// <remarks>
/// What state invoked the rule associated with this context?
/// The "return address" is the followState of invokingState
/// If parent is null, this should be -1.
/// </remarks>
public int invokingState = -1;
public RuleContext()
{
}
public RuleContext(Antlr4.Runtime.RuleContext parent, int invokingState)
{
this._parent = parent;
//if ( parent!=null ) System.out.println("invoke "+stateNumber+" from "+parent);
this.invokingState = invokingState;
}
public static Antlr4.Runtime.RuleContext GetChildContext(Antlr4.Runtime.RuleContext parent, int invokingState)
{
return new Antlr4.Runtime.RuleContext(parent, invokingState);
}
public virtual int Depth()
{
int n = 0;
Antlr4.Runtime.RuleContext p = this;
while (p != null)
{
p = p._parent;
n++;
}
return n;
}
/// <summary>
/// A context is empty if there is no invoking state; meaning nobody call
/// current context.
/// </summary>
/// <remarks>
/// A context is empty if there is no invoking state; meaning nobody call
/// current context.
/// </remarks>
public virtual bool IsEmpty
{
get
{
return invokingState == -1;
}
}
public virtual Interval SourceInterval
{
get
{
// satisfy the ParseTree / SyntaxTree interface
return Interval.Invalid;
}
}
RuleContext IRuleNode.RuleContext
{
get
{
return this;
}
}
public virtual Antlr4.Runtime.RuleContext Parent
{
get
{
return _parent;
}
set
{
_parent = value;
}
}
IRuleNode IRuleNode.Parent
{
get
{
return Parent;
}
}
IParseTree IParseTree.Parent
{
get
{
return Parent;
}
}
ITree ITree.Parent
{
get
{
return Parent;
}
}
public virtual Antlr4.Runtime.RuleContext Payload
{
get
{
return this;
}
}
object ITree.Payload
{
get
{
return Payload;
}
}
/// <summary>Return the combined text of all child nodes.</summary>
/// <remarks>
/// Return the combined text of all child nodes. This method only considers
/// tokens which have been added to the parse tree.
/// <p/>
/// Since tokens on hidden channels (e.g. whitespace or comments) are not
/// added to the parse trees, they will not appear in the output of this
/// method.
/// </remarks>
public virtual string GetText()
{
if (ChildCount == 0)
{
return string.Empty;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < ChildCount; i++)
{
builder.Append(GetChild(i).GetText());
}
return builder.ToString();
}
public virtual int RuleIndex
{
get
{
return -1;
}
}
/* For rule associated with this parse tree internal node, return
* the outer alternative number used to match the input. Default
* implementation does not compute nor store this alt num. Create
* a subclass of ParserRuleContext with backing field and set
* option contextSuperClass.
* to set it.
*/
public virtual int getAltNumber() { return Atn.ATN.INVALID_ALT_NUMBER; }
/* Set the outer alternative number for this context node. Default
* implementation does nothing to avoid backing field overhead for
* trees that don't need it. Create
* a subclass of ParserRuleContext with backing field and set
* option contextSuperClass.
*/
public virtual void setAltNumber(int altNumber) { }
public virtual IParseTree GetChild(int i)
{
return null;
}
ITree ITree.GetChild(int i)
{
return GetChild(i);
}
public virtual int ChildCount
{
get
{
return 0;
}
}
public virtual T Accept<T>(IParseTreeVisitor<T> visitor)
{
return visitor.VisitChildren(this);
}
/// <summary>
/// Print out a whole tree, not just a node, in LISP format
/// (root child1 ..
/// </summary>
/// <remarks>
/// Print out a whole tree, not just a node, in LISP format
/// (root child1 .. childN). Print just a node if this is a leaf.
/// We have to know the recognizer so we can get rule names.
/// </remarks>
public virtual string ToStringTree(Parser recog)
{
return Trees.ToStringTree(this, recog);
}
/// <summary>
/// Print out a whole tree, not just a node, in LISP format
/// (root child1 ..
/// </summary>
/// <remarks>
/// Print out a whole tree, not just a node, in LISP format
/// (root child1 .. childN). Print just a node if this is a leaf.
/// </remarks>
public virtual string ToStringTree(IList<string> ruleNames)
{
return Trees.ToStringTree(this, ruleNames);
}
public virtual string ToStringTree()
{
return ToStringTree((IList<string>)null);
}
public override string ToString()
{
return ToString((IList<string>)null, (Antlr4.Runtime.RuleContext)null);
}
public string ToString(IRecognizer recog)
{
return ToString(recog, ParserRuleContext.EmptyContext);
}
public string ToString(IList<string> ruleNames)
{
return ToString(ruleNames, null);
}
// recog null unless ParserRuleContext, in which case we use subclass toString(...)
public virtual string ToString(IRecognizer recog, Antlr4.Runtime.RuleContext stop)
{
string[] ruleNames = recog != null ? recog.RuleNames : null;
IList<string> ruleNamesList = ruleNames != null ? Arrays.AsList(ruleNames) : null;
return ToString(ruleNamesList, stop);
}
public virtual string ToString(IList<string> ruleNames, Antlr4.Runtime.RuleContext stop)
{
StringBuilder buf = new StringBuilder();
Antlr4.Runtime.RuleContext p = this;
buf.Append("[");
while (p != null && p != stop)
{
if (ruleNames == null)
{
if (!p.IsEmpty)
{
buf.Append(p.invokingState);
}
}
else
{
int ruleIndex = p.RuleIndex;
string ruleName = ruleIndex >= 0 && ruleIndex < ruleNames.Count ? ruleNames[ruleIndex] : ruleIndex.ToString();
buf.Append(ruleName);
}
if (p.Parent != null && (ruleNames != null || !p.Parent.IsEmpty))
{
buf.Append(" ");
}
p = p.Parent;
}
buf.Append("]");
return buf.ToString();
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.Build.Construction;
using Microsoft.DotNet.Tools;
using Microsoft.DotNet.Tools.Test.Utilities;
using Msbuild.Tests.Utilities;
using System;
using System.IO;
using Xunit;
namespace Microsoft.DotNet.Cli.Remove.Reference.Tests
{
public class GivenDotnetRemoveReference : TestBase
{
private const string HelpText = @"Usage: dotnet remove <PROJECT> reference [options] <args>
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
<args> Project to project references to remove
Options:
-h, --help Show help information.
-f, --framework <FRAMEWORK> Remove reference only when targeting a specific framework
";
private const string RemoveCommandHelpText = @"Usage: dotnet remove [options] <PROJECT> [command]
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
Options:
-h, --help Show help information.
Commands:
package <PACKAGE_NAME> .NET Remove Package reference Command.
reference <args> .NET Remove Project to Project reference Command
";
const string FrameworkNet451Arg = "-f net451";
const string ConditionFrameworkNet451 = "== 'net451'";
const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0";
const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'";
static readonly string[] DefaultFrameworks = new string[] { "netcoreapp1.0", "net451" };
private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "")
{
return new TestSetup(
TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName)
.CreateInstance(callingMethod: callingMethod, identifier: identifier)
.WithSourceFiles()
.Root
.FullName);
}
private ProjDir NewDir([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
return new ProjDir(TestAssets.CreateTestDirectory(callingMethod: callingMethod, identifier: identifier).FullName);
}
private ProjDir NewLib(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var projDir = dir == null ? NewDir(callingMethod: callingMethod, identifier: identifier) : new ProjDir(dir);
try
{
string newArgs = $"classlib -o \"{projDir.Path}\" --no-restore";
new NewCommandShim()
.WithWorkingDirectory(projDir.Path)
.ExecuteWithCapturedOutput(newArgs)
.Should().Pass();
}
catch (System.ComponentModel.Win32Exception e)
{
throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{projDir.Path}`\nException:\n{e}");
}
return projDir;
}
private static void SetTargetFrameworks(ProjDir proj, string[] frameworks)
{
var csproj = proj.CsProj();
csproj.AddProperty("TargetFrameworks", string.Join(";", frameworks));
csproj.Save();
}
private ProjDir NewLibWithFrameworks(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var ret = NewLib(dir, callingMethod: callingMethod, identifier: identifier);
SetTargetFrameworks(ret, DefaultFrameworks);
return ret;
}
private ProjDir GetLibRef(TestSetup setup)
{
return new ProjDir(setup.LibDir);
}
private ProjDir AddLibRef(TestSetup setup, ProjDir proj, string additionalArgs = "")
{
var ret = GetLibRef(setup);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"{additionalArgs} \"{ret.CsProjPath}\"")
.Should().Pass();
return ret;
}
private ProjDir AddValidRef(TestSetup setup, ProjDir proj, string frameworkArg = "")
{
var ret = new ProjDir(setup.ValidRefDir);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"{frameworkArg} \"{ret.CsProjPath}\"")
.Should().Pass();
return ret;
}
[Theory]
[InlineData("--help")]
[InlineData("-h")]
public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg)
{
var cmd = new RemoveReferenceCommand().Execute(helpArg);
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Theory]
[InlineData("")]
[InlineData("unknownCommandName")]
public void WhenNoCommandIsPassedItPrintsError(string commandName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"remove {commandName}");
cmd.Should().Fail();
cmd.StdErr.Should().Be(CommonLocalizableStrings.RequiredCommandNotPassed);
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(RemoveCommandHelpText);
}
[Fact]
public void WhenTooManyArgumentsArePassedItPrintsError()
{
var cmd = new AddReferenceCommand()
.WithProject("one two three")
.Execute("proj.csproj");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().BeVisuallyEquivalentTo($@"{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "two")}
{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "three")}");
}
[Theory]
[InlineData("idontexist.csproj")]
[InlineData("ihave?inv@lid/char\\acters")]
public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName)
{
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindProjectOrDirectory, projName));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage()
{
string projName = "Broken/Broken.csproj";
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.ProjectIsInvalid, "Broken/Broken.csproj"));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne");
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(workingDir)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.MoreThanOneProjectInDirectory, workingDir + Path.DirectorySeparatorChar));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindAnyProjectInDirectory, setup.TestRoot + Path.DirectorySeparatorChar));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void ItRemovesRefWithoutCondAndPrintsStatus()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void ItRemovesRefWithCondAndPrintsStatus()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib, FrameworkNet451Arg);
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(libref.Name, ConditionFrameworkNet451).Should().Be(0);
}
[Fact]
public void WhenTwoDifferentRefsArePresentItDoesNotRemoveBoth()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
var validref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenRefWithoutCondIsNotThereItPrintsMessage()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
string csprojContetntBefore = lib.CsProjContent();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, libref.CsProjPath));
lib.CsProjContent().Should().BeEquivalentTo(csprojContetntBefore);
}
[Fact]
public void WhenRefWithCondIsNotThereItPrintsMessage()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
string csprojContetntBefore = lib.CsProjContent();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, libref.CsProjPath));
lib.CsProjContent().Should().BeEquivalentTo(csprojContetntBefore);
}
[Fact]
public void WhenRefWithAndWithoutCondArePresentAndRemovingNoCondItDoesNotRemoveOther()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCond = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefNoCond = AddLibRef(setup, lib);
var csprojBefore = lib.CsProj();
int noCondBefore = csprojBefore.NumberOfItemGroupsWithoutCondition();
int condBefore = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{librefNoCond.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(librefNoCond.Name).Should().Be(0);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCond.Name, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithAndWithoutCondArePresentAndRemovingCondItDoesNotRemoveOther()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCond = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefNoCond = AddLibRef(setup, lib);
var csprojBefore = lib.CsProj();
int noCondBefore = csprojBefore.NumberOfItemGroupsWithoutCondition();
int condBefore = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{librefCond.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(librefNoCond.Name).Should().Be(1);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCond.Name, ConditionFrameworkNet451).Should().Be(0);
}
[Fact]
public void WhenRefWithDifferentCondIsPresentItDoesNotRemoveIt()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCondNet451 = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefCondNetCoreApp10 = AddLibRef(setup, lib, FrameworkNetCoreApp10Arg);
var csprojBefore = lib.CsProj();
int condNet451Before = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
int condNetCoreApp10Before = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNetCoreApp10);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{librefCondNet451.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condNet451Before - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCondNet451.Name, ConditionFrameworkNet451).Should().Be(0);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNetCoreApp10).Should().Be(condNetCoreApp10Before);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCondNetCoreApp10.Name, ConditionFrameworkNetCoreApp10).Should().Be(1);
}
[Fact]
public void WhenDuplicateReferencesArePresentItRemovesThemAll()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithDoubledRef"));
var libref = GetLibRef(setup);
string removedText = $@"{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.LibCsprojRelPath)}
{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.LibCsprojRelPath)}";
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(removedText);
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithRelPathItRemovesRefWithAbsolutePath()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.ValidRefCsprojRelToOtherProjPath));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithRelPathToProjectItRemovesRefWithPathRelToProject()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.ValidRefCsprojRelToOtherProjPath));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithAbsolutePathItRemovesRefWithRelPath()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.ValidRefCsprojRelToOtherProjPath));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingMultipleReferencesItRemovesThemAll()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
var validref = AddValidRef(setup, lib);
string outputText = $@"{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName))}
{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine(setup.ValidRefCsprojRelPath))}";
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\" \"{validref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
csproj.NumberOfProjectReferencesWithIncludeContaining(validref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingMultipleReferencesAndOneOfThemDoesNotExistItRemovesOne()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
var validref = AddValidRef(setup, lib);
string outputText = $@"{string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, setup.LibCsprojPath)}
{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine(setup.ValidRefCsprojRelPath))}";
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\" \"{validref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(validref.Name).Should().Be(0);
}
[Fact]
public void WhenDirectoryContainingProjectIsGivenReferenceIsRemoved()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
var libref = AddLibRef(setup, lib);
var result = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
result.Should().Pass();
result.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
result.StdErr.Should().BeEmpty();
}
[Fact]
public void WhenDirectoryContainsNoProjectsItCancelsWholeOperation()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
var reference = "Empty";
var result = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute(reference);
result.Should().Fail();
result.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
result.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindAnyProjectInDirectory, Path.Combine(setup.TestRoot, reference)));
}
[Fact]
public void WhenDirectoryContainsMultipleProjectsItCancelsWholeOperation()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
var reference = "MoreThanOne";
var result = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute(reference);
result.Should().Fail();
result.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
result.StdErr.Should().Be(string.Format(CommonLocalizableStrings.MoreThanOneProjectInDirectory, Path.Combine(setup.TestRoot, reference)));
}
}
}
| |
/****************************************************************************/
/* */
/* The Mondo Libraries */
/* */
/* Namespace: Mondo.Common */
/* File: KeyedDictionary.cs */
/* Class(es): KeyedDictionary */
/* Purpose: A collection of keyed objects */
/* */
/* Original Author: Jim Lightfoot */
/* Creation Date: 12 Sep 2001 */
/* */
/* Copyright (c) 2001-2011 - Jim Lightfoot, All rights reserved */
/* */
/* Licensed under the MIT license: */
/* http://www.opensource.org/licenses/mit-license.php */
/* */
/****************************************************************************/
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Data;
namespace Mondo.Common
{
/****************************************************************************/
/****************************************************************************/
public interface IDictionaryEntry<K>
{
/****************************************************************************/
K Key(int i);
}
/****************************************************************************/
/****************************************************************************/
public class KeyedDictionary<K, V> : IList where V : IDictionaryEntry<K>
{
private Mondo.Common.OrderedDictionary<K, V> m_ObjectDict;
private int m_iKeyIndex = 0;
protected bool m_bReadOnly = false;
/****************************************************************************/
public KeyedDictionary(int iInitialSize)
{
m_ObjectDict = new Mondo.Common.OrderedDictionary<K, V>(iInitialSize);
}
/****************************************************************************/
public int Count
{
get
{
return(m_ObjectDict.Count);
}
}
/****************************************************************************/
public int KeyIndex
{
get{return(m_iKeyIndex);}
set{m_iKeyIndex = value;}
}
/****************************************************************************/
public void Sort()
{
m_ObjectDict.Sort();
}
/****************************************************************************/
public void Sort(IComparer<V> objComparer)
{
m_ObjectDict.Sort(objComparer);
}
/****************************************************************************/
public bool ContainsKey(K objKey)
{
return(m_ObjectDict.ContainsKey(objKey));
}
/****************************************************************************/
public int IndexOfKey(K objKey)
{
int i = 0;
foreach(IDictionaryEntry<K> objItem in this.m_ObjectDict)
{
if(objItem.Key(KeyIndex).Equals(objKey))
return(i);
++i;
}
throw new ArgumentOutOfRangeException();
}
/****************************************************************************/
public int IndexOf(V objValue)
{
return(m_ObjectDict.IndexOf(objValue));
}
/****************************************************************************/
public V LastItem
{
get
{
return(m_ObjectDict.GetValueAt(m_ObjectDict.Count-1));
}
}
/****************************************************************************/
public V ItemBefore(V objItem)
{
return(m_ObjectDict.ItemBefore(objItem));
}
/****************************************************************************/
public V ItemAfter(V objItem)
{
return(m_ObjectDict.ItemAfter(objItem));
}
/****************************************************************************/
public void Switch(V objFirst, V objSecond)
{
if(m_bReadOnly)
throw new NotSupportedException();
m_ObjectDict.Switch(objFirst, objSecond);
return;
}
/****************************************************************************/
public virtual void Add(V objAdd)
{
if(m_bReadOnly)
throw new NotSupportedException();
m_ObjectDict.Add(objAdd.Key(this.KeyIndex), objAdd);
}
/****************************************************************************/
public virtual void Remove(K Key)
{
if(m_bReadOnly)
throw new NotSupportedException();
m_ObjectDict.Remove(Key);
}
/****************************************************************************/
public virtual void RemoveObject(V obj)
{
Remove(obj.Key(this.KeyIndex));
}
/****************************************************************************/
public virtual void RemoveAt(int iIndex)
{
if(m_bReadOnly)
throw new NotSupportedException();
V objRemove = GetValueAt(iIndex);
if(objRemove != null)
Remove(objRemove.Key(this.KeyIndex));
}
/****************************************************************************/
public virtual void ReplaceAt(int iIndex, V objAdd)
{
if(m_bReadOnly)
throw new NotSupportedException();
RemoveAt(iIndex);
Insert(iIndex, objAdd);
}
/****************************************************************************/
public virtual void Insert(int iIndex, V objAdd)
{
if(m_bReadOnly)
throw new NotSupportedException();
m_ObjectDict.Insert(iIndex, objAdd.Key(m_iKeyIndex), objAdd);
}
/****************************************************************************/
public V GetValueAt(int iIndex)
{
return(m_ObjectDict.GetValueAt(iIndex));
}
/****************************************************************************/
public virtual void Clear()
{
if(m_bReadOnly)
throw new NotSupportedException();
m_ObjectDict.Clear();
}
/****************************************************************************/
public V this [K Key]
{
get
{
return(m_ObjectDict[Key]);
}
}
/****************************************************************************/
public virtual IEnumerator GetEnumerator()
{
return(m_ObjectDict.GetEnumerator());
}
/****************************************************************************/
public IDictionaryEnumerator GetDictionaryEnumerator()
{
return(m_ObjectDict.GetDictionaryEnumerator());
}
/****************************************************************************/
public IEnumerator GetArrayEnumerator()
{
return(this.m_ObjectDict.GetArrayEnumerator());
}
/****************************************************************************/
public IEnumerator GetKeysEnumerator()
{
return(m_ObjectDict.GetKeysEnumerator());
}
#region ICollection Members
/****************************************************************************/
public void CopyTo(Array array, int index)
{
// do nothing
}
/****************************************************************************/
public bool IsSynchronized
{
get { return(false); }
}
/****************************************************************************/
public object SyncRoot
{
get { return(null); }
}
#endregion
#region IList Members
/****************************************************************************/
public int Add(object value)
{
if(value is V)
Add((V)value);
return(-1);
}
/****************************************************************************/
public bool Contains(object value)
{
if(value is V)
return(m_ObjectDict.Contains(value));
return(false);
}
/****************************************************************************/
public int IndexOf(object value)
{
if(value is V)
return(m_ObjectDict.IndexOf((V)value));
return(-1);
}
/****************************************************************************/
public void Insert(int index, object value)
{
throw new NotSupportedException();
}
/****************************************************************************/
public bool IsFixedSize
{
get { return(m_ObjectDict.IsFixedSize); }
}
/****************************************************************************/
public bool IsReadOnly
{
get { return(m_ObjectDict.IsReadOnly); }
}
/****************************************************************************/
public void Remove(object value)
{
if(value is V)
RemoveObject((V)value);
if(value is K)
Remove((K)value);
else
throw new ArgumentException();
}
/****************************************************************************/
public object this[int index]
{
get
{
return(m_ObjectDict.GetValueAt(index));
}
set
{
throw new NotSupportedException();
}
}
#endregion
}
/****************************************************************************/
/****************************************************************************/
public interface IIdentifiable : IDictionaryEntry<Guid>
{
Guid Id {get;}
}
/****************************************************************************/
/****************************************************************************/
public class IdDictionary<V> : KeyedDictionary<Guid, V> where V : IIdentifiable
{
/****************************************************************************/
public IdDictionary(int iInitialSize) : base(iInitialSize)
{
}
/****************************************************************************/
public new V this [int iIndex]
{
get
{
return(GetValueAt(iIndex));
}
}
}
/****************************************************************************/
/****************************************************************************/
public abstract class ObjectDictionary<K, V> : KeyedDictionary<K, V> where V : IDictionaryEntry<K>
{
/****************************************************************************/
public ObjectDictionary(DataSourceList aObjects) : base(127)
{
Load(aObjects);
}
/****************************************************************************/
public ObjectDictionary() : base(127)
{
}
/****************************************************************************/
public void Load(DataSourceList aObjects)
{
foreach(IDataObjectSource objRow in aObjects)
this.Add(CreateObject(objRow));
}
/****************************************************************************/
public abstract V CreateObject(IDataObjectSource objRow);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class MaxTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.Max(), q.Max());
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
Assert.Equal(q.Max(), q.Max());
}
[Fact]
public void MaxInt32()
{
var ten = Enumerable.Range(1, 10).ToArray();
var minusTen = new[] { -100, -15, -50, -10 };
var thousand = new[] { -16, 0, 50, 100, 1000 };
Assert.Equal(10, ten.Max());
Assert.Equal(-10, minusTen.Max());
Assert.Equal(1000, thousand.Max());
Assert.Equal(int.MaxValue, thousand.Concat(Enumerable.Repeat(int.MaxValue, 1)).Max());
}
[Fact]
public void NullInt32Source()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Max());
}
[Fact]
public void EmptyInt32()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().Max());
}
[Fact]
public void SolitaryInt32()
{
Assert.Equal(20, Enumerable.Repeat(20, 1).Max());
}
[Fact]
public void RepeatedInt32()
{
Assert.Equal(-2, Enumerable.Repeat(-2, 5).Max());
}
[Fact]
public void Int32FirstMax()
{
int[] source = { 16, 9, 10, 7, 8 };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void Int32LastMax()
{
int[] source = { 6, 9, 10, 0, 50 };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void Int32MaxRepeated()
{
int[] source = { -6, 0, -9, 0, -10, 0 };
Assert.Equal(0, source.Max());
}
[Fact]
public void MaxInt64()
{
var ten = Enumerable.Range(1, 10).Select(i => (long)i).ToArray();
var minusTen = new[] { -100L, -15, -50, -10 };
var thousand = new[] { -16L, 0, 50, 100, 1000 };
Assert.Equal(42, Enumerable.Repeat(42L, 1).Max());
Assert.Equal(10, ten.Max());
Assert.Equal(-10, minusTen.Max());
Assert.Equal(1000, thousand.Max());
Assert.Equal(long.MaxValue, thousand.Concat(Enumerable.Repeat(long.MaxValue, 1)).Max());
}
[Fact]
public void NullInt64Source()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Max());
}
[Fact]
public void EmptyInt64()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().Max());
}
[Fact]
public void SolitaryInt64()
{
Assert.Equal(Int32.MaxValue + 10L, Enumerable.Repeat(Int32.MaxValue + 10L, 1).Max());
}
[Fact]
public void Int64AllEqual()
{
Assert.Equal(500L, Enumerable.Repeat(500L, 5).Max());
}
[Fact]
public void Int64MaximumFirst()
{
long[] source = { 250, 49, 130, 47, 28 };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void Int64MaximumLast()
{
long[] source = { 6, 9, 10, 0, Int32.MaxValue + 50L };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void Int64MaxRepeated()
{
long[] source = { 6, 50, 9, 50, 10, 50 };
Assert.Equal(50, source.Max());
}
[Fact]
public void MaxSingle()
{
var ten = Enumerable.Range(1, 10).Select(i => (float)i).ToArray();
var minusTen = new[] { -100F, -15, -50, -10 };
var thousand = new[] { -16F, 0, 50, 100, 1000 };
Assert.Equal(10F, ten.Max());
Assert.Equal(-10F, minusTen.Max());
Assert.Equal(1000F, thousand.Max());
Assert.Equal(float.MaxValue, thousand.Concat(Enumerable.Repeat(float.MaxValue, 1)).Max());
}
[Fact]
public void EmptySingle()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().Max());
}
[Fact]
public void SolitarySingle()
{
Assert.Equal(5.5f, Enumerable.Repeat(5.5f, 1).Max());
}
[Fact]
public void Single_MaximumFirst()
{
float[] source = { 112.5f, 4.9f, 30f, 4.7f, 28f };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void Single_MaximumLast()
{
float[] source = { 6.8f, 9.4f, -10f, 0f, float.NaN, 53.6f };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void Single_MaxRepeated()
{
float[] source = { -5.5f, float.PositiveInfinity, 9.9f, float.PositiveInfinity };
Assert.True(float.IsPositiveInfinity(source.Max()));
}
[Fact]
public void SeveralNaNSingle()
{
Assert.True(float.IsNaN(Enumerable.Repeat(float.NaN, 5).Max()));
}
[Fact]
public void SeveralNaNSingleWithSelector()
{
Assert.True(float.IsNaN(Enumerable.Repeat(float.NaN, 5).Max(i => i)));
}
[Fact]
public void SeveralNaNOrNullSingleWithSelector()
{
float?[] source = new float?[] { float.NaN, null, float.NaN, null };
Assert.True(float.IsNaN(source.Max(i => i).Value));
}
[Fact]
public void NullSingleSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Max());
}
[Fact]
public void SingleNaNFirst()
{
float[] source = { float.NaN, 6.8f, 9.4f, 10f, 0, -5.6f };
Assert.Equal(10f, source.Max());
}
[Fact]
public void SingleNaNFirstWithSelector()
{
float[] source = { float.NaN, 6.8f, 9.4f, 10f, 0, -5.6f };
Assert.Equal(10f, source.Max(i => i));
}
[Fact]
public void SingleNaNLast()
{
float[] source = { 6.8f, 9.4f, 10f, 0, -5.6f, float.NaN };
Assert.Equal(10f, source.Max());
}
[Fact]
public void SingleNaNThenNegativeInfinity()
{
float[] source = { float.NaN, float.NegativeInfinity };
Assert.True(float.IsNegativeInfinity(source.Max()));
}
[Fact]
public void SingleNegativeInfinityThenNaN()
{
float[] source = { float.NegativeInfinity, float.NaN };
Assert.True(float.IsNegativeInfinity(source.Max()));
}
[Fact]
public void MaxDouble()
{
var ten = Enumerable.Range(1, 10).Select(i => (double)i).ToArray();
var minusTen = new[] { -100D, -15, -50, -10 };
var thousand = new[] { -16D, 0, 50, 100, 1000 };
Assert.Equal(10D, ten.Max());
Assert.Equal(-10D, minusTen.Max());
Assert.Equal(1000D, thousand.Max());
Assert.Equal(double.MaxValue, thousand.Concat(Enumerable.Repeat(double.MaxValue, 1)).Max());
}
[Fact]
public void NullDoubleSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Max());
}
[Fact]
public void EmptyDouble()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().Max());
}
[Fact]
public void SolitaryDouble()
{
Assert.Equal(5.5, Enumerable.Repeat(5.5, 1).Max());
}
[Fact]
public void DoubleAllEqual()
{
Assert.True(double.IsNaN(Enumerable.Repeat(double.NaN, 5).Max()));
}
[Fact]
public void DoubleAllNaNWithSelector()
{
Assert.True(double.IsNaN(Enumerable.Repeat(double.NaN, 5).Max(i => i)));
}
[Fact]
public void SeveralNaNOrNullDoubleWithSelector()
{
double?[] source = new double?[] { double.NaN, null, double.NaN, null };
Assert.True(double.IsNaN(source.Max(i => i).Value));
}
[Fact]
public void DoubleMaximumFirst()
{
double[] source = { 112.5, 4.9, 30, 4.7, 28 };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void DoubleMaximumLast()
{
double[] source = { 6.8, 9.4, -10, 0, double.NaN, 53.6 };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void DoubleMaximumRepeated()
{
double[] source = { -5.5, double.PositiveInfinity, 9.9, double.PositiveInfinity };
Assert.True(double.IsPositiveInfinity(source.Max()));
}
[Fact]
public void DoubleFirstNaN()
{
double[] source = { double.NaN, 6.8, 9.4, 10.5, 0, -5.6 };
Assert.Equal(10.5, source.Max());
}
[Fact]
public void DoubleLastNaN()
{
double[] source = { 6.8, 9.4, 10.5, 0, -5.6, double.NaN };
Assert.Equal(10.5, source.Max());
}
[Fact]
public void DoubleNaNThenNegativeInfinity()
{
double[] source = { double.NaN, double.NegativeInfinity };
Assert.True(double.IsNegativeInfinity(source.Max()));
}
[Fact]
public void DoubleNaNThenNegativeInfinityWithSelector()
{
double[] source = { double.NaN, double.NegativeInfinity };
Assert.True(double.IsNegativeInfinity(source.Max(i => i)));
}
[Fact]
public void DoubleNegativeInfinityThenNaN()
{
double[] source = { double.NegativeInfinity, double.NaN, };
Assert.True(double.IsNegativeInfinity(source.Max()));
}
[Fact]
public void MaxDecimal()
{
var ten = Enumerable.Range(1, 10).Select(i => (decimal)i).ToArray();
var minusTen = new[] { -100M, -15, -50, -10 };
var thousand = new[] { -16M, 0, 50, 100, 1000 };
Assert.Equal(10M, ten.Max());
Assert.Equal(-10M, minusTen.Max());
Assert.Equal(1000M, thousand.Max());
Assert.Equal(decimal.MaxValue, thousand.Concat(Enumerable.Repeat(decimal.MaxValue, 1)).Max());
}
[Fact]
public void NullDecimalSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Max());
}
[Fact]
public void EmptyDecimal()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().Max());
}
[Fact]
public void SolitaryDecimal()
{
Assert.Equal(5.5m, Enumerable.Repeat(5.5m, 1).Max());
}
[Fact]
public void DecimalAllEqual()
{
Assert.Equal(-3.4m, Enumerable.Repeat(-3.4m, 5).Max());
}
[Fact]
public void DecimalMaximumFirst()
{
decimal[] source = { 122.5m, 4.9m, 10m, 4.7m, 28m };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void DecimalMaximumLast()
{
decimal[] source = { 6.8m, 9.4m, 10m, 0m, 0m, Decimal.MaxValue };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void DecimalMaximumRepeated()
{
decimal[] source = { -5.5m, 0m, 9.9m, -5.5m, 9.9m };
Assert.Equal(9.9m, source.Max());
}
[Fact]
public void MaxNullableInt32()
{
var ten = Enumerable.Range(1, 10).Select(i => (int?)i).ToArray();
var minusTen = new[] { default(int?), -100, -15, -50, -10 };
var thousand = new[] { default(int?), -16, 0, 50, 100, 1000 };
Assert.Equal(10, ten.Max());
Assert.Equal(-10, minusTen.Max());
Assert.Equal(1000, thousand.Max());
Assert.Equal(int.MaxValue, thousand.Concat(Enumerable.Repeat((int?)int.MaxValue, 1)).Max());
Assert.Null(Enumerable.Repeat(default(int?), 100).Max());
}
[Fact]
public void NullNullableInt32Source()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Max());
}
[Fact]
public void EmptyNullableInt32()
{
Assert.Null(Enumerable.Empty<int?>().Max());
}
[Fact]
public void SolitaryNullableInt32()
{
Assert.Equal(-20, Enumerable.Repeat((int?)-20, 1).Max());
}
[Fact]
public void NullableInt32FirstMax()
{
int?[] source = { -6, null, -9, -10, null, -17, -18 };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void NullableInt32LastMax()
{
int?[] source = { null, null, null, null, null, -5 };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void NullableInt32MaxRepeated()
{
int?[] source = { 6, null, null, 100, 9, 100, 10, 100 };
Assert.Equal(100, source.Max());
}
[Fact]
public void NullableInt32AllNull()
{
Assert.Null(Enumerable.Repeat(default(int?), 5).Max());
}
[Fact]
public void MaxNullableInt64()
{
var ten = Enumerable.Range(1, 10).Select(i => (long?)i).ToArray();
var minusTen = new[] { default(long?), -100L, -15, -50, -10 };
var thousand = new[] { default(long?), -16L, 0, 50, 100, 1000 };
Assert.Equal(10, ten.Max());
Assert.Equal(-10, minusTen.Max());
Assert.Equal(1000, thousand.Max());
Assert.Equal(long.MaxValue, thousand.Concat(Enumerable.Repeat((long?)long.MaxValue, 1)).Max());
Assert.Null(Enumerable.Repeat(default(long?), 100).Max());
}
[Fact]
public void NullNullableInt64Source()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Max());
}
[Fact]
public void EmptyNullableInt64()
{
Assert.Null(Enumerable.Empty<long?>().Max(x => x));
}
[Fact]
public void SolitaryNullableInt64()
{
Assert.Equal(long.MaxValue, Enumerable.Repeat(long.MaxValue, 1).Max());
}
[Fact]
public void NullableInt64AllNull()
{
Assert.Null(Enumerable.Repeat(default(long?), 5).Max());
}
[Fact]
public void NullableInt64MaximumFirst()
{
long?[] source = { Int64.MaxValue, null, 9, 10, null, 7, 8 };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void NullableInt64MaximumLast()
{
long?[] source = { null, null, null, null, null, -Int32.MaxValue };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void NullableInt64MaximumRepeated()
{
long?[] source = { -6, null, null, 0, -9, 0, -10, -30 };
Assert.Equal(0, source.Max());
}
[Fact]
public void MaxNullableSingle()
{
var ten = Enumerable.Range(1, 10).Select(i => (float?)i).ToArray();
var minusTen = new[] { default(float?), -100F, -15, -50, -10 };
var thousand = new[] { default(float?), -16F, 0, 50, 100, 1000 };
Assert.Equal(10F, ten.Max());
Assert.Equal(-10F, minusTen.Max());
Assert.Equal(1000F, thousand.Max());
Assert.Equal(float.MaxValue, thousand.Concat(Enumerable.Repeat((float?)float.MaxValue, 1)).Max());
}
[Fact]
public void EmptyNullableSingle()
{
Assert.Null(Enumerable.Empty<float?>().Max());
}
[Fact]
public void SolitaryNullableSingle()
{
Assert.Equal(float.MinValue, Enumerable.Repeat((float?)float.MinValue, 1).Max());
}
[Fact]
public void NullableSingleAllNull()
{
Assert.Null(Enumerable.Repeat(default(float?), 5).Max());
}
[Fact]
public void NullableSingleMaxFirst()
{
float?[] source = { 14.50f, null, float.NaN, 10.98f, null, 7.5f, 8.6f };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void NullableSingleMaxLast()
{
float?[] source = { null, null, null, null, null, 0f };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void NullableSingleMaxRepeated()
{
float?[] source = { -6.4f, null, null, -0.5f, -9.4f, -0.5f, -10.9f, -0.5f };
Assert.Equal(-0.5f, source.Max());
}
[Fact]
public void NullNullableSingleSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Max());
}
[Fact]
public void NullableSingleNaNFirstAndContainsNull()
{
float?[] source = { float.NaN, 6.8f, 9.4f, 10f, 0, null, -5.6f };
Assert.Equal(10f, source.Max());
}
[Fact]
public void NullableSingleNaNLastAndContainsNull()
{
float?[] source = { 6.8f, 9.4f, 10f, 0, null, -5.6f, float.NaN };
Assert.Equal(10f, source.Max());
}
[Fact]
public void NullableSingleNaNThenNegativeInfinity()
{
float?[] source = { float.NaN, float.NegativeInfinity };
Assert.True(float.IsNegativeInfinity(source.Max().Value));
}
[Fact]
public void NullableSingleNegativeInfinityThenNaN()
{
float?[] source = { float.NegativeInfinity, float.NaN };
Assert.True(float.IsNegativeInfinity(source.Max().Value));
}
[Fact]
public void NullableSingleAllNaN()
{
Assert.True(float.IsNaN(Enumerable.Repeat((float?)float.NaN, 3).Max().Value));
}
[Fact]
public void NaNFirstRestJustNulls()
{
float?[] source = { float.NaN, null, null, null };
Assert.True(float.IsNaN(source.Max().Value));
}
[Fact]
public void NaNLastRestJustNulls()
{
float?[] source = { null, null, null, float.NaN };
Assert.True(float.IsNaN(source.Max().Value));
}
[Fact]
public void MaxNullableDouble()
{
var ten = Enumerable.Range(1, 10).Select(i => (double?)i).ToArray();
var minusTen = new[] { default(double?), -100D, -15, -50, -10 };
var thousand = new[] { default(double?), -16D, 0, 50, 100, 1000 };
Assert.Equal(10D, ten.Max());
Assert.Equal(-10D, minusTen.Max());
Assert.Equal(1000D, thousand.Max());
Assert.Equal(double.MaxValue, thousand.Concat(Enumerable.Repeat((double?)double.MaxValue, 1)).Max());
}
[Fact]
public void NullNullableDoubleSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Max());
}
[Fact]
public void EmptyNullableDouble()
{
Assert.Null(Enumerable.Empty<double?>().Max());
}
[Fact]
public void SolitaryNullableDouble()
{
Assert.Equal(double.MinValue, Enumerable.Repeat(double.MinValue, 1).Max());
}
[Fact]
public void NullableDoubleAllNull()
{
Assert.Null(Enumerable.Repeat(default(double?), 5).Max());
}
[Fact]
public void NullableDoubleMaximumFirst()
{
double?[] source = { 14.50, null, Double.NaN, 10.98, null, 7.5, 8.6 };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void NullableDoubleMaximumLast()
{
double?[] source = { null, null, null, null, null, 0 };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void NullableDoubleMaximumRepeated()
{
double?[] source = { -6.4, null, null, -0.5, -9.4, -0.5, -10.9, -0.5 };
Assert.Equal(-0.5, source.Max());
}
[Fact]
public void NullableDoubleNaNFirstAndContainsNulls()
{
double?[] source = { double.NaN, 6.8, 9.4, 10.5, 0, null, -5.6 };
Assert.Equal(10.5, source.Max());
}
[Fact]
public void NullableDoubleNaNLastAndContainsNulls()
{
double?[] source = { 6.8, 9.4, 10.8, 0, null, -5.6, double.NaN };
Assert.Equal(10.8, source.Max());
}
[Fact]
public void NullableDoubleNaNThenNegativeInfinity()
{
double?[] source = { double.NaN, double.NegativeInfinity };
Assert.True(double.IsNegativeInfinity(source.Max().Value));
}
[Fact]
public void NullableDoubleNegativeInfinityThenNaN()
{
double?[] source = { double.NegativeInfinity, double.NaN };
Assert.True(double.IsNegativeInfinity(source.Max().Value));
}
[Fact]
public void NullableDoubleOnlyNaN()
{
Assert.True(double.IsNaN(Enumerable.Repeat((double?)double.NaN, 3).Max().Value));
}
[Fact]
public void NullableDoubleNaNThenNulls()
{
double?[] source = { double.NaN, null, null, null };
Assert.True(double.IsNaN(source.Max().Value));
}
[Fact]
public void NullableDoubleNullsThenNaN()
{
double?[] source = { null, null, null, double.NaN };
Assert.True(double.IsNaN(source.Max().Value));
}
[Fact]
public void MaxNullableDecimal()
{
var ten = Enumerable.Range(1, 10).Select(i => (decimal?)i).ToArray();
var minusTen = new[] { default(decimal?), -100M, -15, -50, -10 };
var thousand = new[] { default(decimal?), -16M, 0, 50, 100, 1000 };
Assert.Equal(42M, Enumerable.Repeat((decimal?)42, 1).Max());
Assert.Equal(10M, ten.Max());
Assert.Equal(-10M, minusTen.Max());
Assert.Equal(1000M, thousand.Max());
Assert.Equal(decimal.MaxValue, thousand.Concat(Enumerable.Repeat((decimal?)decimal.MaxValue, 1)).Max());
}
[Fact]
public void NullNullableDecimalSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Max());
}
[Fact]
public void EmptyNullableDecimal()
{
Assert.Null(Enumerable.Empty<decimal?>().Max());
}
[Fact]
public void SolitaryNullableDecimal()
{
Assert.Equal(decimal.MaxValue, Enumerable.Repeat((decimal?)decimal.MaxValue, 1).Max());
}
[Fact]
public void NullableDecimalAllNulls()
{
Assert.Null(Enumerable.Repeat(default(decimal?), 5).Max());
}
[Fact]
public void NullableDecimalMaximumFirst()
{
decimal?[] source = { 14.50m, null, null, 10.98m, null, 7.5m, 8.6m };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void NullableDecimalMaximumLast()
{
decimal?[] source = { null, null, null, null, null, 0m };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void NullableDecimalMaximumRepeated()
{
decimal?[] source = { 6.4m, null, null, decimal.MaxValue, 9.4m, decimal.MaxValue, 10.9m, decimal.MaxValue };
Assert.Equal(decimal.MaxValue, source.Max());
}
// Normally NaN < anything is false, as is anything < NaN
// However, this leads to some irksome outcomes in Min and Max.
// If we use those semantics then Min(NaN, 5.0) is NaN, but
// Min(5.0, NaN) is 5.0! To fix this, we impose a total
// ordering where NaN is smaller than every value, including
// negative infinity.
// This behaviour must be confirmed as happening.
// Note that further to this, null is taken as not being in a sequence at all
// (Null will be returned if the only element in a sequence, but this will also
// happen with an empty sequence).
[Fact]
public void NaNFirstSingle()
{
var nanThenOne = Enumerable.Range(1, 10).Select(i => (float)i).Concat(Enumerable.Repeat(float.NaN, 1)).ToArray();
var nanThenMinusTen = new[] { -1F, -10, float.NaN, 10, 200, 1000 };
var nanThenMinValue = new[] { float.MinValue, 3000F, 100, 200, float.NaN, 1000 };
Assert.False(float.IsNaN(nanThenOne.Max()));
Assert.False(float.IsNaN(nanThenMinusTen.Max()));
Assert.False(float.IsNaN(nanThenMinValue.Max()));
var nanWithNull = new[] { default(float?), float.NaN, default(float?) };
Assert.True(float.IsNaN(nanWithNull.Max().Value));
}
[Fact]
public void NaNFirstDouble()
{
var nanThenOne = Enumerable.Range(1, 10).Select(i => (double)i).Concat(Enumerable.Repeat(double.NaN, 1)).ToArray();
var nanThenMinusTen = new[] { -1F, -10, double.NaN, 10, 200, 1000 };
var nanThenMinValue = new[] { double.MinValue, 3000F, 100, 200, double.NaN, 1000 };
Assert.False(double.IsNaN(nanThenOne.Max()));
Assert.False(double.IsNaN(nanThenMinusTen.Max()));
Assert.False(double.IsNaN(nanThenMinValue.Max()));
var nanWithNull = new[] { default(double?), double.NaN, default(double?) };
Assert.True(double.IsNaN(nanWithNull.Max().Value));
}
[Fact]
public void MaxDateTime()
{
var ten = Enumerable.Range(1, 10).Select(i => new DateTime(2000, 1, i)).ToArray();
var newYearsEve = new[]
{
new DateTime(2000, 12, 1),
new DateTime(2000, 12, 31),
new DateTime(2000, 1, 12)
};
var threeThousand = new[]
{
new DateTime(3000, 1, 1),
new DateTime(100, 1, 1),
new DateTime(200, 1, 1),
new DateTime(1000, 1, 1)
};
Assert.Equal(new DateTime(2000, 1, 10), ten.Max());
Assert.Equal(new DateTime(2000, 12, 31), newYearsEve.Max());
Assert.Equal(new DateTime(3000, 1, 1), threeThousand.Max());
Assert.Equal(DateTime.MaxValue, threeThousand.Concat(Enumerable.Repeat(DateTime.MaxValue, 1)).Max());
}
[Fact]
public void EmptyDateTime()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().Max());
}
[Fact]
public void NullDateTimeSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<DateTime>)null).Max());
}
[Fact]
public void MaxString()
{
var nine = Enumerable.Range(1, 10).Select(i => i.ToString()).ToArray();
var agents = new[] { "Alice", "Bob", "Charlie", "Eve", "Mallory", "Victor", "Trent" };
var confusedAgents = new[] { null, "Charlie", null, "Victor", "Trent", null, "Eve", "Alice", "Mallory", "Bob" };
Assert.Equal("9", nine.Max());
Assert.Equal("Victor", agents.Max());
Assert.Equal("Victor", confusedAgents.Max());
}
[Fact]
public void NullStringSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<string>)null).Max());
}
[Fact]
public void EmptyString()
{
Assert.Null(Enumerable.Empty<string>().Max());
}
[Fact]
public void SolitaryString()
{
Assert.Equal("Hello", Enumerable.Repeat("Hello", 1).Max());
}
[Fact]
public void StringAllSame()
{
Assert.Equal("hi", Enumerable.Repeat("hi", 5).Max());
}
[Fact]
public void StringMaximumFirst()
{
string[] source = { "zzz", "aaa", "abcd", "bark", "temp", "cat" };
Assert.Equal(source.First(), source.Max());
}
[Fact]
public void StringMaximumLast()
{
string[] source = { null, null, null, null, "aAa" };
Assert.Equal(source.Last(), source.Max());
}
[Fact]
public void StringMaximumRepeated()
{
string[] source = { "ooo", "ccc", "ccc", "ooo", "ooo", "nnn" };
Assert.Equal("ooo", source.Max());
}
[Fact]
public void StringAllNull()
{
Assert.Null(Enumerable.Repeat(default(string), 5).Max());
}
[Fact]
public void MaxInt32WithSelector()
{
var ten = Enumerable.Range(1, 10).ToArray();
var minusTen = new[] { -100, -15, -50, -10 };
var thousand = new[] { -16, 0, 50, 100, 1000 };
Assert.Equal(42, Enumerable.Repeat(42, 1).Max(x => x));
Assert.Equal(10, ten.Max(x => x));
Assert.Equal(-10, minusTen.Max(x => x));
Assert.Equal(1000, thousand.Max(x => x));
Assert.Equal(int.MaxValue, thousand.Concat(Enumerable.Repeat(int.MaxValue, 1)).Max(x => x));
}
[Fact]
public void EmptyInt32WithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().Max(x => x));
}
[Fact]
public void NullInt32SourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Max(i => i));
}
[Fact]
public void Int32SourceWithNullSelector()
{
Func<int, int> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().Max(selector));
}
[Fact]
public void MaxInt32WithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=10 },
new { name="John", num=-105 },
new { name="Bob", num=30 }
};
Assert.Equal(30, source.Max(e => e.num));
}
[Fact]
public void MaxInt64WithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (long)i).ToArray();
var minusTen = new[] { -100L, -15, -50, -10 };
var thousand = new[] { -16L, 0, 50, 100, 1000 };
Assert.Equal(42, Enumerable.Repeat(42L, 1).Max(x => x));
Assert.Equal(10, ten.Max(x => x));
Assert.Equal(-10, minusTen.Max(x => x));
Assert.Equal(1000, thousand.Max(x => x));
Assert.Equal(long.MaxValue, thousand.Concat(Enumerable.Repeat(long.MaxValue, 1)).Max(x => x));
}
[Fact]
public void EmptyInt64WithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().Max(x => x));
}
[Fact]
public void NullInt64SourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Max(i => i));
}
[Fact]
public void Int64SourceWithNullSelector()
{
Func<long, long> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().Max(selector));
}
[Fact]
public void MaxInt64WithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=10L },
new { name="John", num=-105L },
new { name="Bob", num=long.MaxValue }
};
Assert.Equal(long.MaxValue, source.Max(e => e.num));
}
[Fact]
public void MaxSingleWithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (float)i).ToArray();
var minusTen = new[] { -100F, -15, -50, -10 };
var thousand = new[] { -16F, 0, 50, 100, 1000 };
Assert.Equal(42F, Enumerable.Repeat(42F, 1).Max(x => x));
Assert.Equal(10F, ten.Max(x => x));
Assert.Equal(-10F, minusTen.Max(x => x));
Assert.Equal(1000F, thousand.Max(x => x));
Assert.Equal(float.MaxValue, thousand.Concat(Enumerable.Repeat(float.MaxValue, 1)).Max(x => x));
}
[Fact]
public void MaxSingleWithSelectorAccessingProperty()
{
var source = new []
{
new { name = "Tim", num = 40.5f },
new { name = "John", num = -10.25f },
new { name = "Bob", num = 100.45f }
};
Assert.Equal(100.45f, source.Select(e => e.num).Max());
}
[Fact]
public void NullSingleSourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Max(i => i));
}
[Fact]
public void SingleSourceWithNullSelector()
{
Func<float, float> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float>().Max(selector));
}
[Fact]
public void EmptySingleWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().Max(x => x));
}
[Fact]
public void MaxDoubleWithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (double)i).ToArray();
var minusTen = new[] { -100D, -15, -50, -10 };
var thousand = new[] { -16D, 0, 50, 100, 1000 };
Assert.Equal(42D, Enumerable.Repeat(42D, 1).Max(x => x));
Assert.Equal(10D, ten.Max(x => x));
Assert.Equal(-10D, minusTen.Max(x => x));
Assert.Equal(1000D, thousand.Max(x => x));
Assert.Equal(double.MaxValue, thousand.Concat(Enumerable.Repeat(double.MaxValue, 1)).Max(x => x));
}
[Fact]
public void EmptyDoubleWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().Max(x => x));
}
[Fact]
public void NullDoubleSourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Max(i => i));
}
[Fact]
public void DoubleSourceWithNullSelector()
{
Func<double, double> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().Max(selector));
}
[Fact]
public void MaxDoubleWithSelectorAccessingField()
{
var source = new[]{
new { name="Tim", num=40.5 },
new { name="John", num=-10.25 },
new { name="Bob", num=100.45 }
};
Assert.Equal(100.45, source.Max(e => e.num));
}
[Fact]
public void MaxDecimalWithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (decimal)i).ToArray();
var minusTen = new[] { -100M, -15, -50, -10 };
var thousand = new[] { -16M, 0, 50, 100, 1000 };
Assert.Equal(42M, Enumerable.Repeat(42M, 1).Max(x => x));
Assert.Equal(10M, ten.Max(x => x));
Assert.Equal(-10M, minusTen.Max(x => x));
Assert.Equal(1000M, thousand.Max(x => x));
Assert.Equal(decimal.MaxValue, thousand.Concat(Enumerable.Repeat(decimal.MaxValue, 1)).Max(x => x));
}
[Fact]
public void EmptyDecimalWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().Max(x => x));
}
[Fact]
public void NullDecimalSourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Max(i => i));
}
[Fact]
public void DecimalSourceWithNullSelector()
{
Func<decimal, decimal> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().Max(selector));
}
[Fact]
public void MaxDecimalWithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=420.5m },
new { name="John", num=900.25m },
new { name="Bob", num=10.45m }
};
Assert.Equal(900.25m, source.Max(e => e.num));
}
[Fact]
public void MaxNullableInt32WithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (int?)i).ToArray();
var minusTen = new[] { default(int?), -100, -15, -50, -10 };
var thousand = new[] { default(int?), -16, 0, 50, 100, 1000 };
Assert.Equal(42, Enumerable.Repeat((int?)42, 1).Max(x => x));
Assert.Equal(10, ten.Max(x => x));
Assert.Equal(-10, minusTen.Max(x => x));
Assert.Equal(1000, thousand.Max(x => x));
Assert.Equal(int.MaxValue, thousand.Concat(Enumerable.Repeat((int?)int.MaxValue, 1)).Max(x => x));
Assert.Null(Enumerable.Repeat(default(int?), 100).Max(x => x));
}
[Fact]
public void EmptyNullableInt32WithSelector()
{
Assert.Null(Enumerable.Empty<int?>().Max(x => x));
}
[Fact]
public void NullNullableInt32SourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Max(i => i));
}
[Fact]
public void NullableInt32SourceWithNullSelector()
{
Func<int?, int?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().Max(selector));
}
[Fact]
public void MaxNullableInt32WithSelectorAccessingField()
{
var source = new[]{
new { name="Tim", num=(int?)10 },
new { name="John", num=(int?)-105 },
new { name="Bob", num=(int?)null }
};
Assert.Equal(10, source.Max(e => e.num));
}
[Fact]
public void MaxNullableInt64WithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (long?)i).ToArray();
var minusTen = new[] { default(long?), -100L, -15, -50, -10 };
var thousand = new[] { default(long?), -16L, 0, 50, 100, 1000 };
Assert.Equal(42, Enumerable.Repeat((long?)42, 1).Max(x => x));
Assert.Equal(10, ten.Max(x => x));
Assert.Equal(10, ten.Concat(new[] { default(long?) }).Max(x => x));
Assert.Equal(-10, minusTen.Max(x => x));
Assert.Equal(1000, thousand.Max(x => x));
Assert.Equal(long.MaxValue, thousand.Concat(Enumerable.Repeat((long?)long.MaxValue, 1)).Max(x => x));
Assert.Null(Enumerable.Repeat(default(long?), 100).Max(x => x));
}
[Fact]
public void EmptyNullableInt64WithSelector()
{
Assert.Null(Enumerable.Empty<long?>().Max(x => x));
}
[Fact]
public void NullNullableInt64SourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Max(i => i));
}
[Fact]
public void NullableInt64SourceWithNullSelector()
{
Func<long?, long?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().Max(selector));
}
[Fact]
public void MaxNullableInt64WithSelectorAccessingField()
{
var source = new[]{
new {name="Tim", num=default(long?) },
new {name="John", num=(long?)-105L },
new {name="Bob", num=(long?)long.MaxValue }
};
Assert.Equal(long.MaxValue, source.Max(e => e.num));
}
[Fact]
public void MaxNullableSingleWithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (float?)i).ToArray();
var minusTen = new[] { default(float?), -100F, -15, -50, -10 };
var thousand = new[] { default(float?), -16F, 0, 50, 100, 1000 };
Assert.Equal(42F, Enumerable.Repeat((float?)42, 1).Max(x => x));
Assert.Equal(10F, ten.Max(x => x));
Assert.Equal(-10F, minusTen.Max(x => x));
Assert.Equal(1000F, thousand.Max(x => x));
Assert.Equal(float.MaxValue, thousand.Concat(Enumerable.Repeat((float?)float.MaxValue, 1)).Max(x => x));
Assert.Null(Enumerable.Repeat(default(float?), 100).Max(x => x));
}
[Fact]
public void EmptyNullableSingleWithSelector()
{
Assert.Null(Enumerable.Empty<float?>().Max(x => x));
}
[Fact]
public void NullNullableSingleSourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Max(i => i));
}
[Fact]
public void NullableSingleSourceWithNullSelector()
{
Func<float?, float?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().Max(selector));
}
[Fact]
public void MaxNullableSingleWithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=(float?)40.5f },
new { name="John", num=(float?)null },
new { name="Bob", num=(float?)100.45f }
};
Assert.Equal(100.45f, source.Max(e => e.num));
}
[Fact]
public void MaxNullableDoubleWithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (double?)i).ToArray();
var minusTen = new[] { default(double?), -100D, -15, -50, -10 };
var thousand = new[] { default(double?), -16D, 0, 50, 100, 1000 };
Assert.Equal(42D, Enumerable.Repeat((double?)42, 1).Max(x => x));
Assert.Equal(10D, ten.Max(x => x));
Assert.Equal(-10D, minusTen.Max(x => x));
Assert.Equal(1000D, thousand.Max(x => x));
Assert.Equal(double.MaxValue, thousand.Concat(Enumerable.Repeat((double?)double.MaxValue, 1)).Max(x => x));
Assert.Null(Enumerable.Repeat(default(double?), 100).Max(x => x));
}
[Fact]
public void EmptyNullableDoubleWithSelector()
{
Assert.Null(Enumerable.Empty<double?>().Max(x => x));
}
[Fact]
public void NullNullableDoubleSourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Max(i => i));
}
[Fact]
public void NullableDoubleSourceWithNullSelector()
{
Func<double?, double?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().Max(selector));
}
[Fact]
public void MaxNullableDoubleWithSelectorAccessingProperty()
{
var source = new []{
new { name = "Tim", num = (double?)40.5},
new { name = "John", num = default(double?)},
new { name = "Bob", num = (double?)100.45}
};
Assert.Equal(100.45, source.Max(e => e.num));
}
[Fact]
public void MaxNullableDecimalWithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => (decimal?)i).ToArray();
var minusTen = new[] { default(decimal?), -100M, -15, -50, -10 };
var thousand = new[] { default(decimal?), -16M, 0, 50, 100, 1000 };
Assert.Equal(42M, Enumerable.Repeat((decimal?)42, 1).Max(x => x));
Assert.Equal(10M, ten.Max(x => x));
Assert.Equal(-10M, minusTen.Max(x => x));
Assert.Equal(1000M, thousand.Max(x => x));
Assert.Equal(decimal.MaxValue, thousand.Concat(Enumerable.Repeat((decimal?)decimal.MaxValue, 1)).Max(x => x));
Assert.Null(Enumerable.Repeat(default(decimal?), 100).Max(x => x));
}
[Fact]
public void EmptyNullableDecimalWithSelector()
{
Assert.Null(Enumerable.Empty<decimal?>().Max(x => x));
}
[Fact]
public void NullNullableDecimalSourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Max(i => i));
}
[Fact]
public void NullableDecimalSourceWithNullSelector()
{
Func<decimal?, decimal?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().Max(selector));
}
[Fact]
public void MaxNullableDecimalWithSelectorAccessingProperty()
{
var source = new[] {
new { name="Tim", num=(decimal?)420.5m },
new { name="John", num=default(decimal?) },
new { name="Bob", num=(decimal?)10.45m }
};
Assert.Equal(420.5m, source.Max(e => e.num));
}
// Normally NaN < anything is false, as is anything < NaN
// However, this leads to some irksome outcomes in Min and Max.
// If we use those semantics then Min(NaN, 5.0) is NaN, but
// Min(5.0, NaN) is 5.0! To fix this, we impose a total
// ordering where NaN is smaller than every value, including
// negative infinity.
// This behaviour must be confirmed as happening.
// Note that further to this, null is taken as not being in a sequence at all
// (Null will be returned if the only element in a sequence, but this will also
// happen with an empty sequence).
[Fact]
public void NaNFirstSingleWithSelector()
{
var nanThenOne = Enumerable.Range(1, 10).Select(i => (float)i).Concat(Enumerable.Repeat(float.NaN, 1)).ToArray();
var nanThenMinusTen = new[] { -1F, -10, float.NaN, 10, 200, 1000 };
var nanThenMinValue = new[] { float.MinValue, 3000F, 100, 200, float.NaN, 1000 };
Assert.False(float.IsNaN(nanThenOne.Max(x => x)));
Assert.False(float.IsNaN(nanThenMinusTen.Max(x => x)));
Assert.False(float.IsNaN(nanThenMinValue.Max(x => x)));
var nanWithNull = new[] { default(float?), float.NaN, default(float?) };
Assert.True(float.IsNaN(nanWithNull.Max(x => x).Value));
}
[Fact]
public void NaNFirstDoubleWithSelector()
{
var nanThenOne = Enumerable.Range(1, 10).Select(i => (double)i).Concat(Enumerable.Repeat(double.NaN, 1)).ToArray();
var nanThenMinusTen = new[] { -1F, -10, double.NaN, 10, 200, 1000 };
var nanThenMinValue = new[] { double.MinValue, 3000F, 100, 200, double.NaN, 1000 };
Assert.False(double.IsNaN(nanThenOne.Max(x => x)));
Assert.False(double.IsNaN(nanThenMinusTen.Max(x => x)));
Assert.False(double.IsNaN(nanThenMinValue.Max(x => x)));
var nanWithNull = new[] { default(double?), double.NaN, default(double?) };
Assert.True(double.IsNaN(nanWithNull.Max(x => x).Value));
}
[Fact]
public void MaxDateTimeWithSelector()
{
var ten = Enumerable.Range(1, 10).Select(i => new DateTime(2000, 1, i)).ToArray();
var newYearsEve = new[]
{
new DateTime(2000, 12, 1),
new DateTime(2000, 12, 31),
new DateTime(2000, 1, 12)
};
var threeThousand = new[]
{
new DateTime(3000, 1, 1),
new DateTime(100, 1, 1),
new DateTime(200, 1, 1),
new DateTime(1000, 1, 1)
};
Assert.Equal(new DateTime(2000, 1, 10), ten.Max(x => x));
Assert.Equal(new DateTime(2000, 12, 31), newYearsEve.Max(x => x));
Assert.Equal(new DateTime(3000, 1, 1), threeThousand.Max(x => x));
Assert.Equal(DateTime.MaxValue, threeThousand.Concat(Enumerable.Repeat(DateTime.MaxValue, 1)).Max(x => x));
}
[Fact]
public void EmptyMaxDateTimeWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().Max(i => i));
}
[Fact]
public void EmptyNullableDateTimeWithSelector()
{
Assert.Null(Enumerable.Empty<DateTime?>().Max(x => x));
}
[Fact]
public void NullNullableDateTimeSourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<DateTime?>)null).Max(i => i));
}
[Fact]
public void NullableDateTimeSourceWithNullSelector()
{
Func<DateTime?, DateTime?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<DateTime?>().Max(selector));
}
[Fact]
public void MaxStringWithSelector()
{
var nine = Enumerable.Range(1, 10).Select(i => i.ToString()).ToArray();
var agents = new[] { "Alice", "Bob", "Charlie", "Eve", "Mallory", "Victor", "Trent" };
var confusedAgents = new[] { null, "Charlie", null, "Victor", "Trent", null, "Eve", "Alice", "Mallory", "Bob" };
Assert.Equal("9", nine.Max(x => x));
Assert.Equal("Victor", agents.Max(x => x));
Assert.Equal("Victor", confusedAgents.Max(x => x));
}
public void EmptyStringSourceWithSelector()
{
Assert.Null(Enumerable.Empty<string>().Max(x => x));
}
[Fact]
public void NullStringSourceWithSelector()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<string>)null).Max(i => i));
}
[Fact]
public void StringSourceWithNullSelector()
{
Func<string, string> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<string>().Max(selector));
}
[Fact]
public void MaxStringWithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=420.5m },
new { name="John", num=900.25m },
new { name="Bob", num=10.45m }
};
Assert.Equal("Tim", source.Max(e => e.name));
}
[Fact]
public void EmptyBoolean()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<bool>().Max());
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/rpc/code.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Rpc {
/// <summary>Holder for reflection information generated from google/rpc/code.proto</summary>
public static partial class CodeReflection {
#region Descriptor
/// <summary>File descriptor for google/rpc/code.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CodeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChVnb29nbGUvcnBjL2NvZGUucHJvdG8SCmdvb2dsZS5ycGMqtwIKBENvZGUS",
"BgoCT0sQABINCglDQU5DRUxMRUQQARILCgdVTktOT1dOEAISFAoQSU5WQUxJ",
"RF9BUkdVTUVOVBADEhUKEURFQURMSU5FX0VYQ0VFREVEEAQSDQoJTk9UX0ZP",
"VU5EEAUSEgoOQUxSRUFEWV9FWElTVFMQBhIVChFQRVJNSVNTSU9OX0RFTklF",
"RBAHEhMKD1VOQVVUSEVOVElDQVRFRBAQEhYKElJFU09VUkNFX0VYSEFVU1RF",
"RBAIEhcKE0ZBSUxFRF9QUkVDT05ESVRJT04QCRILCgdBQk9SVEVEEAoSEAoM",
"T1VUX09GX1JBTkdFEAsSEQoNVU5JTVBMRU1FTlRFRBAMEgwKCElOVEVSTkFM",
"EA0SDwoLVU5BVkFJTEFCTEUQDhINCglEQVRBX0xPU1MQD0JYCg5jb20uZ29v",
"Z2xlLnJwY0IJQ29kZVByb3RvUAFaM2dvb2dsZS5nb2xhbmcub3JnL2dlbnBy",
"b3RvL2dvb2dsZWFwaXMvcnBjL2NvZGU7Y29kZaICA1JQQ2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Rpc.Code), }, null, null));
}
#endregion
}
#region Enums
/// <summary>
/// The canonical error codes for gRPC APIs.
///
/// Sometimes multiple error codes may apply. Services should return
/// the most specific error code that applies. For example, prefer
/// `OUT_OF_RANGE` over `FAILED_PRECONDITION` if both codes apply.
/// Similarly prefer `NOT_FOUND` or `ALREADY_EXISTS` over `FAILED_PRECONDITION`.
/// </summary>
public enum Code {
/// <summary>
/// Not an error; returned on success
///
/// HTTP Mapping: 200 OK
/// </summary>
[pbr::OriginalName("OK")] Ok = 0,
/// <summary>
/// The operation was cancelled, typically by the caller.
///
/// HTTP Mapping: 499 Client Closed Request
/// </summary>
[pbr::OriginalName("CANCELLED")] Cancelled = 1,
/// <summary>
/// Unknown error. For example, this error may be returned when
/// a `Status` value received from another address space belongs to
/// an error space that is not known in this address space. Also
/// errors raised by APIs that do not return enough error information
/// may be converted to this error.
///
/// HTTP Mapping: 500 Internal Server Error
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 2,
/// <summary>
/// The client specified an invalid argument. Note that this differs
/// from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments
/// that are problematic regardless of the state of the system
/// (e.g., a malformed file name).
///
/// HTTP Mapping: 400 Bad Request
/// </summary>
[pbr::OriginalName("INVALID_ARGUMENT")] InvalidArgument = 3,
/// <summary>
/// The deadline expired before the operation could complete. For operations
/// that change the state of the system, this error may be returned
/// even if the operation has completed successfully. For example, a
/// successful response from a server could have been delayed long
/// enough for the deadline to expire.
///
/// HTTP Mapping: 504 Gateway Timeout
/// </summary>
[pbr::OriginalName("DEADLINE_EXCEEDED")] DeadlineExceeded = 4,
/// <summary>
/// Some requested entity (e.g., file or directory) was not found.
///
/// Note to server developers: if a request is denied for an entire class
/// of users, such as gradual feature rollout or undocumented whitelist,
/// `NOT_FOUND` may be used. If a request is denied for some users within
/// a class of users, such as user-based access control, `PERMISSION_DENIED`
/// must be used.
///
/// HTTP Mapping: 404 Not Found
/// </summary>
[pbr::OriginalName("NOT_FOUND")] NotFound = 5,
/// <summary>
/// The entity that a client attempted to create (e.g., file or directory)
/// already exists.
///
/// HTTP Mapping: 409 Conflict
/// </summary>
[pbr::OriginalName("ALREADY_EXISTS")] AlreadyExists = 6,
/// <summary>
/// The caller does not have permission to execute the specified
/// operation. `PERMISSION_DENIED` must not be used for rejections
/// caused by exhausting some resource (use `RESOURCE_EXHAUSTED`
/// instead for those errors). `PERMISSION_DENIED` must not be
/// used if the caller can not be identified (use `UNAUTHENTICATED`
/// instead for those errors). This error code does not imply the
/// request is valid or the requested entity exists or satisfies
/// other pre-conditions.
///
/// HTTP Mapping: 403 Forbidden
/// </summary>
[pbr::OriginalName("PERMISSION_DENIED")] PermissionDenied = 7,
/// <summary>
/// The request does not have valid authentication credentials for the
/// operation.
///
/// HTTP Mapping: 401 Unauthorized
/// </summary>
[pbr::OriginalName("UNAUTHENTICATED")] Unauthenticated = 16,
/// <summary>
/// Some resource has been exhausted, perhaps a per-user quota, or
/// perhaps the entire file system is out of space.
///
/// HTTP Mapping: 429 Too Many Requests
/// </summary>
[pbr::OriginalName("RESOURCE_EXHAUSTED")] ResourceExhausted = 8,
/// <summary>
/// The operation was rejected because the system is not in a state
/// required for the operation's execution. For example, the directory
/// to be deleted is non-empty, an rmdir operation is applied to
/// a non-directory, etc.
///
/// Service implementors can use the following guidelines to decide
/// between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`:
/// (a) Use `UNAVAILABLE` if the client can retry just the failing call.
/// (b) Use `ABORTED` if the client should retry at a higher level
/// (e.g., when a client-specified test-and-set fails, indicating the
/// client should restart a read-modify-write sequence).
/// (c) Use `FAILED_PRECONDITION` if the client should not retry until
/// the system state has been explicitly fixed. E.g., if an "rmdir"
/// fails because the directory is non-empty, `FAILED_PRECONDITION`
/// should be returned since the client should not retry unless
/// the files are deleted from the directory.
///
/// HTTP Mapping: 400 Bad Request
/// </summary>
[pbr::OriginalName("FAILED_PRECONDITION")] FailedPrecondition = 9,
/// <summary>
/// The operation was aborted, typically due to a concurrency issue such as
/// a sequencer check failure or transaction abort.
///
/// See the guidelines above for deciding between `FAILED_PRECONDITION`,
/// `ABORTED`, and `UNAVAILABLE`.
///
/// HTTP Mapping: 409 Conflict
/// </summary>
[pbr::OriginalName("ABORTED")] Aborted = 10,
/// <summary>
/// The operation was attempted past the valid range. E.g., seeking or
/// reading past end-of-file.
///
/// Unlike `INVALID_ARGUMENT`, this error indicates a problem that may
/// be fixed if the system state changes. For example, a 32-bit file
/// system will generate `INVALID_ARGUMENT` if asked to read at an
/// offset that is not in the range [0,2^32-1], but it will generate
/// `OUT_OF_RANGE` if asked to read from an offset past the current
/// file size.
///
/// There is a fair bit of overlap between `FAILED_PRECONDITION` and
/// `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific
/// error) when it applies so that callers who are iterating through
/// a space can easily look for an `OUT_OF_RANGE` error to detect when
/// they are done.
///
/// HTTP Mapping: 400 Bad Request
/// </summary>
[pbr::OriginalName("OUT_OF_RANGE")] OutOfRange = 11,
/// <summary>
/// The operation is not implemented or is not supported/enabled in this
/// service.
///
/// HTTP Mapping: 501 Not Implemented
/// </summary>
[pbr::OriginalName("UNIMPLEMENTED")] Unimplemented = 12,
/// <summary>
/// Internal errors. This means that some invariants expected by the
/// underlying system have been broken. This error code is reserved
/// for serious errors.
///
/// HTTP Mapping: 500 Internal Server Error
/// </summary>
[pbr::OriginalName("INTERNAL")] Internal = 13,
/// <summary>
/// The service is currently unavailable. This is most likely a
/// transient condition, which can be corrected by retrying with
/// a backoff. Note that it is not always safe to retry
/// non-idempotent operations.
///
/// See the guidelines above for deciding between `FAILED_PRECONDITION`,
/// `ABORTED`, and `UNAVAILABLE`.
///
/// HTTP Mapping: 503 Service Unavailable
/// </summary>
[pbr::OriginalName("UNAVAILABLE")] Unavailable = 14,
/// <summary>
/// Unrecoverable data loss or corruption.
///
/// HTTP Mapping: 500 Internal Server Error
/// </summary>
[pbr::OriginalName("DATA_LOSS")] DataLoss = 15,
}
#endregion
}
#endregion Designer generated code
| |
/*
* 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.IO;
using System.Reflection;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Collections.Generic;
using System.Xml;
namespace OpenSim.Region.Framework.Scenes
{
public partial class SceneObjectGroup : EntityBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Force all task inventories of prims in the scene object to persist
/// </summary>
public void ForceInventoryPersistence()
{
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
parts[i].Inventory.ForceInventoryPersistence();
}
/// <summary>
/// Start the scripts contained in all the prims in this group.
/// </summary>
/// <param name="startParam"></param>
/// <param name="postOnRez"></param>
/// <param name="engine"></param>
/// <param name="stateSource"></param>
/// <returns>
/// Number of scripts that were valid for starting. This does not guarantee that all these scripts
/// were actually started, but just that the start could be attempt (e.g. the asset data for the script could be found)
/// </returns>
public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource)
{
int scriptsStarted = 0;
// Don't start scripts if they're turned off in the region!
if (!m_scene.RegionInfo.RegionSettings.DisableScripts)
{
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
scriptsStarted
+= parts[i].Inventory.CreateScriptInstances(startParam, postOnRez, engine, stateSource);
}
return scriptsStarted;
}
/// <summary>
/// Stop and remove the scripts contained in all the prims in this group
/// </summary>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if these scripts are being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
{
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
parts[i].Inventory.RemoveScriptInstances(sceneObjectBeingDeleted);
}
/// <summary>
/// Stop the scripts contained in all the prims in this group
/// </summary>
public void StopScriptInstances()
{
Array.ForEach<SceneObjectPart>(m_parts.GetArray(), p => p.Inventory.StopScriptInstances());
}
/// <summary>
/// Add an inventory item from a user's inventory to a prim in this scene object.
/// </summary>
/// <param name="agentID">The agent adding the item.</param>
/// <param name="localID">The local ID of the part receiving the add.</param>
/// <param name="item">The user inventory item being added.</param>
/// <param name="copyItemID">The item UUID that should be used by the new item.</param>
/// <returns></returns>
public bool AddInventoryItem(UUID agentID, uint localID, InventoryItemBase item, UUID copyItemID)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Adding inventory item {0} from {1} to part with local ID {2}",
// item.Name, remoteClient.Name, localID);
UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID;
SceneObjectPart part = GetPart(localID);
if (part != null)
{
TaskInventoryItem taskItem = new TaskInventoryItem();
taskItem.ItemID = newItemId;
taskItem.AssetID = item.AssetID;
taskItem.Name = item.Name;
taskItem.Description = item.Description;
taskItem.OwnerID = part.OwnerID; // Transfer ownership
taskItem.CreatorID = item.CreatorIdAsUuid;
taskItem.Type = item.AssetType;
taskItem.InvType = item.InvType;
if (agentID != part.OwnerID && m_scene.Permissions.PropagatePermissions())
{
taskItem.BasePermissions = item.BasePermissions &
item.NextPermissions;
taskItem.CurrentPermissions = item.CurrentPermissions &
item.NextPermissions;
taskItem.EveryonePermissions = item.EveryOnePermissions &
item.NextPermissions;
taskItem.GroupPermissions = item.GroupPermissions &
item.NextPermissions;
taskItem.NextPermissions = item.NextPermissions;
// We're adding this to a prim we don't own. Force
// owner change
taskItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
}
else
{
taskItem.BasePermissions = item.BasePermissions;
taskItem.CurrentPermissions = item.CurrentPermissions;
taskItem.EveryonePermissions = item.EveryOnePermissions;
taskItem.GroupPermissions = item.GroupPermissions;
taskItem.NextPermissions = item.NextPermissions;
}
taskItem.Flags = item.Flags;
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Flags are 0x{0:X} for item {1} added to part {2} by {3}",
// taskItem.Flags, taskItem.Name, localID, remoteClient.Name);
// TODO: These are pending addition of those fields to TaskInventoryItem
// taskItem.SalePrice = item.SalePrice;
// taskItem.SaleType = item.SaleType;
taskItem.CreationDate = (uint)item.CreationDate;
bool addFromAllowedDrop = agentID != part.OwnerID;
part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}",
localID, Name, UUID, newItemId);
}
return false;
}
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="primID"></param>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
public TaskInventoryItem GetInventoryItem(uint primID, UUID itemID)
{
SceneObjectPart part = GetPart(primID);
if (part != null)
{
return part.Inventory.GetInventoryItem(itemID);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in prim {1}, {2} to get inventory item ID {3}",
primID, part.Name, part.UUID, itemID);
}
return null;
}
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in this prim's inventory</param>
/// <returns>false if the item did not exist, true if the update occurred succesfully</returns>
public bool UpdateInventoryItem(TaskInventoryItem item)
{
SceneObjectPart part = GetPart(item.ParentPartID);
if (part != null)
{
part.Inventory.UpdateInventoryItem(item);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim ID {0} to update item {1}, {2}",
item.ParentPartID, item.Name, item.ItemID);
}
return false;
}
public int RemoveInventoryItem(uint localID, UUID itemID)
{
SceneObjectPart part = GetPart(localID);
if (part != null)
{
int type = part.Inventory.RemoveInventoryItem(itemID);
return type;
}
return -1;
}
public uint GetEffectivePermissions()
{
uint perms=(uint)(PermissionMask.Modify |
PermissionMask.Copy |
PermissionMask.Move |
PermissionMask.Transfer) | 7;
uint ownerMask = 0x7fffffff;
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
ownerMask &= part.OwnerMask;
perms &= part.Inventory.MaskEffectivePermissions();
}
if ((ownerMask & (uint)PermissionMask.Modify) == 0)
perms &= ~(uint)PermissionMask.Modify;
if ((ownerMask & (uint)PermissionMask.Copy) == 0)
perms &= ~(uint)PermissionMask.Copy;
if ((ownerMask & (uint)PermissionMask.Transfer) == 0)
perms &= ~(uint)PermissionMask.Transfer;
// If root prim permissions are applied here, this would screw
// with in-inventory manipulation of the next owner perms
// in a major way. So, let's move this to the give itself.
// Yes. I know. Evil.
// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Modify) == 0)
// perms &= ~((uint)PermissionMask.Modify >> 13);
// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Copy) == 0)
// perms &= ~((uint)PermissionMask.Copy >> 13);
// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Transfer) == 0)
// perms &= ~((uint)PermissionMask.Transfer >> 13);
return perms;
}
public void ApplyNextOwnerPermissions()
{
// m_log.DebugFormat("[PRIM INVENTORY]: Applying next owner permissions to {0} {1}", Name, UUID);
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
parts[i].ApplyNextOwnerPermissions();
}
public string GetStateSnapshot()
{
Dictionary<UUID, string> states = new Dictionary<UUID, string>();
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
foreach (KeyValuePair<UUID, string> s in part.Inventory.GetScriptStates())
states[s.Key] = s.Value;
}
if (states.Count < 1)
return String.Empty;
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
String.Empty, String.Empty);
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ScriptData",
String.Empty);
xmldoc.AppendChild(rootElement);
XmlElement wrapper = xmldoc.CreateElement("", "ScriptStates",
String.Empty);
rootElement.AppendChild(wrapper);
foreach (KeyValuePair<UUID, string> state in states)
{
XmlDocument sdoc = new XmlDocument();
sdoc.LoadXml(state.Value);
XmlNodeList rootL = sdoc.GetElementsByTagName("State");
XmlNode rootNode = rootL[0];
XmlNode newNode = xmldoc.ImportNode(rootNode, true);
wrapper.AppendChild(newNode);
}
return xmldoc.InnerXml;
}
public void SetState(string objXMLData, IScene ins)
{
if (!(ins is Scene))
return;
Scene s = (Scene)ins;
if (objXMLData == String.Empty)
return;
IScriptModule scriptModule = null;
foreach (IScriptModule sm in s.RequestModuleInterfaces<IScriptModule>())
{
if (sm.ScriptEngineName == s.DefaultScriptEngine)
scriptModule = sm;
else if (scriptModule == null)
scriptModule = sm;
}
if (scriptModule == null)
return;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(objXMLData);
}
catch (Exception) // (System.Xml.XmlException)
{
// We will get here if the XML is invalid or in unit
// tests. Really should determine which it is and either
// fail silently or log it
// Fail silently, for now.
// TODO: Fix this
//
return;
}
XmlNodeList rootL = doc.GetElementsByTagName("ScriptData");
if (rootL.Count != 1)
return;
XmlElement rootE = (XmlElement)rootL[0];
XmlNodeList dataL = rootE.GetElementsByTagName("ScriptStates");
if (dataL.Count != 1)
return;
XmlElement dataE = (XmlElement)dataL[0];
foreach (XmlNode n in dataE.ChildNodes)
{
XmlElement stateE = (XmlElement)n;
UUID itemID = new UUID(stateE.GetAttribute("UUID"));
scriptModule.SetXMLState(itemID, n.OuterXml);
}
}
public void ResumeScripts()
{
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
parts[i].Inventory.ResumeScripts();
}
/// <summary>
/// Returns true if any part in the scene object contains scripts, false otherwise.
/// </summary>
/// <returns></returns>
public bool ContainsScripts()
{
foreach (SceneObjectPart part in Parts)
if (part.Inventory.ContainsScripts())
return true;
return false;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Orleans.Messaging;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Messaging
{
internal class Gateway
{
private readonly MessageCenter messageCenter;
private readonly GatewayAcceptor acceptor;
private readonly Lazy<GatewaySender>[] senders;
private readonly GatewayClientCleanupAgent dropper;
// clients is the main authorative collection of all connected clients.
// Any client currently in the system appears in this collection.
// In addition, we use clientSockets collection for fast retrival of ClientState.
// Anything that appears in those 2 collections should also appear in the main clients collection.
private readonly ConcurrentDictionary<GrainId, ClientState> clients;
private readonly ConcurrentDictionary<Socket, ClientState> clientSockets;
private readonly SiloAddress gatewayAddress;
private int nextGatewaySenderToUseForRoundRobin;
private readonly ClientsReplyRoutingCache clientsReplyRoutingCache;
private ClientObserverRegistrar clientRegistrar;
private readonly object lockable;
private static readonly Logger logger = LogManager.GetLogger("Orleans.Messaging.Gateway");
private IMessagingConfiguration MessagingConfiguration { get { return messageCenter.MessagingConfiguration; } }
internal Gateway(MessageCenter msgCtr, IPEndPoint gatewayAddress)
{
messageCenter = msgCtr;
acceptor = new GatewayAcceptor(msgCtr, this, gatewayAddress);
senders = new Lazy<GatewaySender>[messageCenter.MessagingConfiguration.GatewaySenderQueues];
nextGatewaySenderToUseForRoundRobin = 0;
dropper = new GatewayClientCleanupAgent(this);
clients = new ConcurrentDictionary<GrainId, ClientState>();
clientSockets = new ConcurrentDictionary<Socket, ClientState>();
clientsReplyRoutingCache = new ClientsReplyRoutingCache(messageCenter.MessagingConfiguration);
this.gatewayAddress = SiloAddress.New(gatewayAddress, 0);
lockable = new object();
}
internal void Start(ClientObserverRegistrar clientRegistrar)
{
this.clientRegistrar = clientRegistrar;
this.clientRegistrar.SetGateway(this);
acceptor.Start();
for (int i = 0; i < senders.Length; i++)
{
int capture = i;
senders[capture] = new Lazy<GatewaySender>(() =>
{
var sender = new GatewaySender("GatewaySiloSender_" + capture, this);
sender.Start();
return sender;
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
dropper.Start();
}
internal void Stop()
{
dropper.Stop();
foreach (var sender in senders)
{
if (sender != null && sender.IsValueCreated)
sender.Value.Stop();
}
acceptor.Stop();
}
internal ICollection<GrainId> GetConnectedClients()
{
return clients.Keys;
}
internal void RecordOpenedSocket(Socket sock, GrainId clientId)
{
lock (lockable)
{
logger.Info(ErrorCode.GatewayClientOpenedSocket, "Recorded opened socket from endpoint {0}, client ID {1}.", sock.RemoteEndPoint, clientId);
ClientState clientState;
if (clients.TryGetValue(clientId, out clientState))
{
var oldSocket = clientState.Socket;
if (oldSocket != null)
{
// The old socket will be closed by itself later.
ClientState ignore;
clientSockets.TryRemove(oldSocket, out ignore);
}
QueueRequest(clientState, null);
}
else
{
int gatewayToUse = nextGatewaySenderToUseForRoundRobin % senders.Length;
nextGatewaySenderToUseForRoundRobin++; // under Gateway lock
clientState = new ClientState(clientId, gatewayToUse, MessagingConfiguration.ClientDropTimeout);
clients[clientId] = clientState;
MessagingStatisticsGroup.ConnectedClientCount.Increment();
}
clientState.RecordConnection(sock);
clientSockets[sock] = clientState;
clientRegistrar.ClientAdded(clientId);
NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket();
}
}
internal void RecordClosedSocket(Socket sock)
{
if (sock == null) return;
lock (lockable)
{
ClientState cs = null;
if (!clientSockets.TryGetValue(sock, out cs)) return;
EndPoint endPoint = null;
try
{
endPoint = sock.RemoteEndPoint;
}
catch (Exception) { } // guard against ObjectDisposedExceptions
logger.Info(ErrorCode.GatewayClientClosedSocket, "Recorded closed socket from endpoint {0}, client ID {1}.", endPoint != null ? endPoint.ToString() : "null", cs.Id);
ClientState ignore;
clientSockets.TryRemove(sock, out ignore);
cs.RecordDisconnection();
}
}
internal SiloAddress TryToReroute(Message msg)
{
// for responses from ClientAddressableObject to ClientGrain try to use clientsReplyRoutingCache for sending replies directly back.
if (!msg.SendingGrain.IsClient || !msg.TargetGrain.IsClient) return null;
if (msg.Direction != Message.Directions.Response) return null;
SiloAddress gateway;
return clientsReplyRoutingCache.TryFindClientRoute(msg.TargetGrain, out gateway) ? gateway : null;
}
internal void DropDisconnectedClients()
{
lock (lockable)
{
List<ClientState> clientsToDrop = clients.Values.Where(cs => cs.ReadyToDrop()).ToList();
foreach (ClientState client in clientsToDrop)
DropClient(client);
}
}
internal void DropExpiredRoutingCachedEntries()
{
lock (lockable)
{
clientsReplyRoutingCache.DropExpiredEntries();
}
}
// This function is run under global lock
// There is NO need to acquire individual ClientState lock, since we only access client Id (immutable) and close an older socket.
private void DropClient(ClientState client)
{
logger.Info(ErrorCode.GatewayDroppingClient, "Dropping client {0}, {1} after disconnect with no reconnect",
client.Id, DateTime.UtcNow.Subtract(client.DisconnectedSince));
ClientState ignore;
clients.TryRemove(client.Id, out ignore);
clientRegistrar.ClientDropped(client.Id);
Socket oldSocket = client.Socket;
if (oldSocket != null)
{
// this will not happen, since we drop only already disconnected clients, for socket is already null. But leave this code just to be sure.
client.RecordDisconnection();
clientSockets.TryRemove(oldSocket, out ignore);
SocketManager.CloseSocket(oldSocket);
}
MessagingStatisticsGroup.ConnectedClientCount.DecrementBy(1);
}
/// <summary>
/// See if this message is intended for a grain we're proxying, and queue it for delivery if so.
/// </summary>
/// <param name="msg"></param>
/// <returns>true if the message should be delivered to a proxied grain, false if not.</returns>
internal bool TryDeliverToProxy(Message msg)
{
// See if it's a grain we're proxying.
ClientState client;
// not taking global lock on the crytical path!
if (!clients.TryGetValue(msg.TargetGrain, out client))
return false;
// when this Gateway receives a message from client X to client addressale object Y
// it needs to record the original Gateway address through which this message came from (the address of the Gateway that X is connected to)
// it will use this Gateway to re-route the REPLY from Y back to X.
if (msg.SendingGrain.IsClient && msg.TargetGrain.IsClient)
{
clientsReplyRoutingCache.RecordClientRoute(msg.SendingGrain, msg.SendingSilo);
}
msg.TargetSilo = null;
msg.SendingSilo = gatewayAddress; // This makes sure we don't expose wrong silo addresses to the client. Client will only see silo address of the Gateway it is connected to.
QueueRequest(client, msg);
return true;
}
private void QueueRequest(ClientState clientState, Message msg)
{
//int index = senders.Length == 1 ? 0 : Math.Abs(clientId.GetHashCode()) % senders.Length;
int index = clientState.GatewaySenderNumber;
senders[index].Value.QueueRequest(new OutgoingClientMessage(clientState.Id, msg));
}
internal void SendMessage(Message msg)
{
messageCenter.SendMessage(msg);
}
private class ClientState
{
private readonly TimeSpan clientDropTimeout;
internal Queue<Message> PendingToSend { get; private set; }
internal Queue<List<Message>> PendingBatchesToSend { get; private set; }
internal Socket Socket { get; private set; }
internal DateTime DisconnectedSince { get; private set; }
internal GrainId Id { get; private set; }
internal int GatewaySenderNumber { get; private set; }
internal bool IsConnected { get { return Socket != null; } }
internal ClientState(GrainId id, int gatewaySenderNumber, TimeSpan clientDropTimeout)
{
Id = id;
GatewaySenderNumber = gatewaySenderNumber;
this.clientDropTimeout = clientDropTimeout;
PendingToSend = new Queue<Message>();
PendingBatchesToSend = new Queue<List<Message>>();
}
internal void RecordDisconnection()
{
if (Socket == null) return;
DisconnectedSince = DateTime.UtcNow;
Socket = null;
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
internal void RecordConnection(Socket sock)
{
Socket = sock;
DisconnectedSince = DateTime.MaxValue;
}
internal bool ReadyToDrop()
{
return !IsConnected &&
(DateTime.UtcNow.Subtract(DisconnectedSince) >= clientDropTimeout);
}
}
private class GatewayClientCleanupAgent : AsynchAgent
{
private readonly Gateway gateway;
internal GatewayClientCleanupAgent(Gateway gateway)
{
this.gateway = gateway;
}
#region Overrides of AsynchAgent
protected override void Run()
{
while (!Cts.IsCancellationRequested)
{
gateway.DropDisconnectedClients();
gateway.DropExpiredRoutingCachedEntries();
Thread.Sleep(gateway.MessagingConfiguration.ClientDropTimeout);
}
}
#endregion
}
// this cache is used to record the addresses of Gateways from which clients connected to.
// it is used to route replies to clients from client addressable objects
// without this cache this Gateway will not know how to route the reply back to the client
// (since clients are not registered in the directory and this Gateway may not be proxying for the client for whom the reply is destined).
private class ClientsReplyRoutingCache
{
// for every client: the Gateway to use to route repies back to it plus the last time that client connected via this Gateway.
private readonly ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>> clientRoutes;
private readonly TimeSpan TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
internal ClientsReplyRoutingCache(IMessagingConfiguration messagingConfiguration)
{
clientRoutes = new ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>>();
TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES = messagingConfiguration.ResponseTimeout.Multiply(5);
}
internal void RecordClientRoute(GrainId client, SiloAddress gateway)
{
var now = DateTime.UtcNow;
clientRoutes.AddOrUpdate(client, new Tuple<SiloAddress, DateTime>(gateway, now), (k, v) => new Tuple<SiloAddress, DateTime>(gateway, now));
}
internal bool TryFindClientRoute(GrainId client, out SiloAddress gateway)
{
gateway = null;
Tuple<SiloAddress, DateTime> tuple;
bool ret = clientRoutes.TryGetValue(client, out tuple);
if (ret)
gateway = tuple.Item1;
return ret;
}
internal void DropExpiredEntries()
{
List<GrainId> clientsToDrop = clientRoutes.Where(route => Expired(route.Value.Item2)).Select(kv => kv.Key).ToList();
foreach (GrainId client in clientsToDrop)
{
Tuple<SiloAddress, DateTime> tuple;
clientRoutes.TryRemove(client, out tuple);
}
}
private bool Expired(DateTime lastUsed)
{
return DateTime.UtcNow.Subtract(lastUsed) >= TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
}
}
private class GatewaySender : AsynchQueueAgent<OutgoingClientMessage>
{
private readonly Gateway gateway;
private readonly CounterStatistic gatewaySends;
internal GatewaySender(string name, Gateway gateway)
: base(name, gateway.MessagingConfiguration)
{
this.gateway = gateway;
gatewaySends = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT);
OnFault = FaultBehavior.RestartOnFault;
}
protected override void Process(OutgoingClientMessage request)
{
if (Cts.IsCancellationRequested) return;
var client = request.Item1;
var msg = request.Item2;
// Find the client state
ClientState clientState;
bool found;
// TODO: Why do we need this lock here if clients is a ConcurrentDictionary?
//lock (gateway.lockable)
{
found = gateway.clients.TryGetValue(client, out clientState);
}
// This should never happen -- but make sure to handle it reasonably, just in case
if (!found || (clientState == null))
{
if (msg == null) return;
Log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), client);
MessagingStatisticsGroup.OnFailedSentMessage(msg);
// Message for unrecognized client -- reject it
if (msg.Direction == Message.Directions.Request)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, "Unknown client " + client);
gateway.SendMessage(error);
}
else
{
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
return;
}
// if disconnected - queue for later.
if (!clientState.IsConnected)
{
if (msg == null) return;
if (Log.IsVerbose3) Log.Verbose3("Queued message {0} for client {1}", msg, client);
clientState.PendingToSend.Enqueue(msg);
return;
}
// if the queue is non empty - drain it first.
if (clientState.PendingToSend.Count > 0)
{
if (msg != null)
clientState.PendingToSend.Enqueue(msg);
// For now, drain in-line, although in the future this should happen in yet another asynch agent
Drain(clientState);
return;
}
// the queue was empty AND we are connected.
// If the request includes a message to send, send it (or enqueue it for later)
if (msg == null) return;
if (!Send(msg, clientState.Socket))
{
if (Log.IsVerbose3) Log.Verbose3("Queued message {0} for client {1}", msg, client);
clientState.PendingToSend.Enqueue(msg);
}
else
{
if (Log.IsVerbose3) Log.Verbose3("Sent message {0} to client {1}", msg, client);
}
}
private void Drain(ClientState clientState)
{
// For now, drain in-line, although in the future this should happen in yet another asynch agent
while (clientState.PendingToSend.Count > 0)
{
var m = clientState.PendingToSend.Peek();
if (Send(m, clientState.Socket))
{
if (Log.IsVerbose3) Log.Verbose3("Sent queued message {0} to client {1}", m, clientState.Id);
clientState.PendingToSend.Dequeue();
}
else
{
return;
}
}
}
private bool Send(Message msg, Socket sock)
{
if (Cts.IsCancellationRequested) return false;
if (sock == null) return false;
// Send the message
List<ArraySegment<byte>> data;
int headerLength;
try
{
data = msg.Serialize(out headerLength);
}
catch (Exception exc)
{
OnMessageSerializationFailure(msg, exc);
return true;
}
int length = data.Sum(x => x.Count);
int bytesSent = 0;
bool exceptionSending = false;
bool countMismatchSending = false;
string sendErrorStr;
try
{
bytesSent = sock.Send(data);
if (bytesSent != length)
{
// The complete message wasn't sent, even though no error was reported; treat this as an error
countMismatchSending = true;
sendErrorStr = String.Format("Byte count mismatch on send: sent {0}, expected {1}", bytesSent, length);
Log.Warn(ErrorCode.GatewayByteCountMismatch, sendErrorStr);
}
}
catch (Exception exc)
{
exceptionSending = true;
string remoteEndpoint = "";
if (!(exc is ObjectDisposedException))
{
try
{
remoteEndpoint = sock.RemoteEndPoint.ToString();
}
catch (Exception){}
}
sendErrorStr = String.Format("Exception sending to client at {0}: {1}", remoteEndpoint, exc);
Log.Warn(ErrorCode.GatewayExceptionSendingToClient, sendErrorStr, exc);
}
MessagingStatisticsGroup.OnMessageSend(msg.TargetSilo, msg.Direction, bytesSent, headerLength, SocketDirection.GatewayToClient);
bool sendError = exceptionSending || countMismatchSending;
if (sendError)
{
gateway.RecordClosedSocket(sock);
SocketManager.CloseSocket(sock);
}
gatewaySends.Increment();
msg.ReleaseBodyAndHeaderBuffers();
return !sendError;
}
private void OnMessageSerializationFailure(Message msg, Exception exc)
{
// we only get here if we failed to serialize the msg (or any other catastrophic failure).
// Request msg fails to serialize on the sending silo, so we just enqueue a rejection msg.
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
Log.Warn(ErrorCode.Messaging_Gateway_SerializationError, String.Format("Unexpected error serializing message {0} on the gateway", msg.ToString()), exc);
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
}
}
| |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using Hotcakes.Commerce.Catalog;
using Hotcakes.Commerce.Storage;
using Hotcakes.Web;
using Encoder = System.Drawing.Imaging.Encoder;
namespace Hotcakes.Commerce.Utilities
{
/// <summary>
/// This class helps generate HTML, paths, and other information for images used in the application
/// </summary>
[Serializable]
public static class ImageHelper
{
public static string SafeImage(string imagePath)
{
var result = string.Empty;
if (imagePath.ToLower().StartsWith("http:"))
{
result = imagePath;
}
else
{
if (HttpContext.Current != null)
{
if (File.Exists(HttpContext.Current.Server.MapPath(imagePath)))
{
result = imagePath;
}
}
}
return result;
}
public static string GetValidImage(string fileName, bool useAppRoot)
{
var result = "DesktopModules/Hotcakes/Core/Admin/Images/NoImageAvailable.gif";
if (fileName.Length != 0)
{
// Allow direct URLs as file names
if ((fileName.ToLower().StartsWith("http://") == false) &
(fileName.ToLower().StartsWith("https://") == false))
{
var fileNameReplaced = fileName.Replace("/", "\\");
if (fileNameReplaced.StartsWith("\\"))
{
fileNameReplaced = fileNameReplaced.Remove(0, 1);
}
if (File.Exists(Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, fileNameReplaced)))
{
result = fileName.Replace("\\", "/");
}
if (useAppRoot)
{
if (result.StartsWith("/"))
{
result = "~" + result;
}
else
{
result = "~/" + result;
}
}
}
else
{
result = fileName.Replace("\\", "/");
}
}
else
{
if (useAppRoot)
{
result = "~/" + result;
}
}
return result;
}
public static ImageInfo GetImageInformation(string fileName)
{
var result = new ImageInfo();
result.Width = 0;
result.Height = 0;
result.FormattedDimensions = "unknown";
result.FormattedSize = "unknown";
result.SizeInBytes = 0;
var fullName = string.Empty;
if (fileName != null)
{
fullName = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, fileName.Replace("/", "\\"));
}
if (File.Exists(fullName))
{
var f = new FileInfo(Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, fileName));
if (f != null)
{
result.SizeInBytes = f.Length;
if (result.SizeInBytes < 1024)
{
result.FormattedSize = result.SizeInBytes + " bytes";
}
else
{
if (result.SizeInBytes < 1048576)
{
result.FormattedSize = Math.Round(result.SizeInBytes/1024, 1) + " KB";
}
else
{
result.FormattedSize = Math.Round(result.SizeInBytes/1048576, 1) + " MB";
}
}
}
f = null;
if (File.Exists(fullName))
{
Image WorkingImage;
WorkingImage = Image.FromFile(fullName);
if (WorkingImage != null)
{
result.Width = WorkingImage.Width;
result.Height = WorkingImage.Height;
result.FormattedDimensions = result.Width.ToString(CultureInfo.InvariantCulture) + " x " +
result.Height.ToString(CultureInfo.InvariantCulture);
}
WorkingImage.Dispose();
WorkingImage = null;
}
}
return result;
}
public static ImageInfo GetProportionalImageDimensionsForImage(ImageInfo oldInfo, int maxWidth, int maxHeight)
{
var result = new ImageInfo();
if (oldInfo != null)
{
var s = Images.GetNewDimensions(maxWidth, maxHeight, oldInfo.Width, oldInfo.Height);
result.Height = s.Height;
result.Width = s.Width;
}
return result;
}
public static bool CompressJpeg(string filePath, long quality)
{
var result = true;
var fullFile = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, filePath);
if (File.Exists(fullFile))
{
if (quality < 1L)
{
quality = 1L;
}
else
{
if (quality > 100L)
{
quality = 100L;
}
}
Image WorkingImage;
WorkingImage = Image.FromFile(filePath);
Image FinalImage;
FinalImage = new Bitmap(WorkingImage.Width, WorkingImage.Height, PixelFormat.Format24bppRgb);
var G = Graphics.FromImage(FinalImage);
G.InterpolationMode = InterpolationMode.HighQualityBicubic;
G.PixelOffsetMode = PixelOffsetMode.HighQuality;
G.CompositingQuality = CompositingQuality.HighQuality;
G.SmoothingMode = SmoothingMode.HighQuality;
G.DrawImage(WorkingImage, 0, 0, WorkingImage.Width, WorkingImage.Height);
// Dispose working Image so we can save with the same name
WorkingImage.Dispose();
WorkingImage = null;
// Compression Code
var myCodec = GetEncoderInfo("image/jpeg");
var myEncoder = Encoder.Quality;
var myEncoderParams = new EncoderParameters(1);
var myParam = new EncoderParameter(myEncoder, quality);
myEncoderParams.Param[0] = myParam;
// End Compression Code
File.Delete(fullFile);
FinalImage.Save(fullFile, myCodec, myEncoderParams);
FinalImage.Dispose();
FinalImage = null;
}
else
{
result = false;
}
return result;
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j <= encoders.Length; j++)
{
if (encoders[j].MimeType == mimeType)
{
return encoders[j];
}
}
return null;
}
public static bool ResizeImage(string currentImagePath, string newImagePath, int newHeight, int newWidth)
{
try
{
Images.ShrinkImageFileOnDisk(currentImagePath, newImagePath, newHeight, newWidth);
return true;
}
catch (Exception Ex)
{
throw new ArgumentException("Image Resize Error: " + Ex.Message);
}
}
/// <summary>
/// This method will iterate through the specified swatches and emit the requisite HTML for each
/// </summary>
/// <param name="p">Product - an instance of the product to find swatches for</param>
/// <param name="app">HotcakesApplicateion - an instance of the current store application object</param>
/// <returns>String - the HTML to be used for rendering the swatches</returns>
/// <remarks>
/// If the swatch doesn't match an available swatch file, it will not be included in the HTML. Also, all swatch
/// images must be PNG or GIF.
/// </remarks>
public static string GenerateSwatchHtmlForProduct(Product p, HotcakesApplication app)
{
var result = string.Empty;
if (app.CurrentStore.Settings.ProductEnableSwatches == false) return result;
if (p.Options.Count > 0)
{
var found = false;
var swatchBase = DiskStorage.GetStoreDataUrl(app, app.IsCurrentRequestSecure());
swatchBase += "swatches";
if (p.SwatchPath.Length > 0) swatchBase += "/" + p.SwatchPath;
var swatchPhysicalBase = DiskStorage.GetStoreDataPhysicalPath(app.CurrentStore.Id);
swatchPhysicalBase += "swatches\\";
if (p.SwatchPath.Length > 0) swatchPhysicalBase += p.SwatchPath + "\\";
var sb = new StringBuilder();
sb.Append("<div class=\"productswatches\">");
foreach (var opt in p.Options)
{
if (opt.IsColorSwatch)
{
found = true;
foreach (var oi in opt.Items)
{
if (oi.IsLabel) continue;
var prefix = CleanSwatchName(oi.Name);
if (File.Exists(swatchPhysicalBase + prefix + ".png"))
{
sb.Append("<img width=\"18\" height=\"18\" src=\"" + swatchBase + "/" + prefix +
".png\" border=\"0\" alt=\"" + prefix + "\" />");
}
else
{
sb.Append("<img width=\"18\" height=\"18\" src=\"" + swatchBase + "/" + prefix +
".gif\" border=\"0\" alt=\"" + prefix + "\" />");
}
}
}
}
sb.Append("</div>");
if (found)
{
result = sb.ToString();
}
}
return result;
}
private static string CleanSwatchName(string source)
{
var result = source.Replace(" ", "_");
result = result.Replace("/", string.Empty);
result = result.Replace("\"", string.Empty);
result = result.Replace("//", string.Empty);
result = result.Replace(":", string.Empty);
result = result.Replace(";", string.Empty);
result = result.Replace("'", string.Empty);
result = result.Replace("!", string.Empty);
result = result.Replace("~", string.Empty);
result = result.Replace("@", string.Empty);
result = result.Replace("#", string.Empty);
result = result.Replace("$", string.Empty);
result = result.Replace("%", string.Empty);
result = result.Replace("^", string.Empty);
result = result.Replace("&", string.Empty);
result = result.Replace("*", string.Empty);
result = result.Replace("(", string.Empty);
result = result.Replace(")", string.Empty);
result = result.Replace("[", string.Empty);
result = result.Replace("]", string.Empty);
result = result.Replace("{", string.Empty);
result = result.Replace("}", string.Empty);
result = result.Replace("|", string.Empty);
result = result.Replace("-", string.Empty);
result = result.Replace("+", string.Empty);
result = result.Replace("<", string.Empty);
result = result.Replace(">", string.Empty);
result = result.Replace(".", string.Empty);
result = result.Replace(",", string.Empty);
result = result.Replace("?", string.Empty);
result = result.Replace("=", string.Empty);
result = result.Replace("`", string.Empty);
return result;
}
}
}
| |
// 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.Compute
{
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>
/// VirtualMachinesOperations operations.
/// </summary>
public partial interface IVirtualMachinesOperations
{
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs
/// a template that can be used to create similar VMs.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualMachineCaptureResult>> CaptureWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualMachine>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachine parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> DeleteWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieves information about the model view or the instance view of
/// a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values
/// include: 'instanceView'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualMachine>> GetWithHttpMessagesAsync(string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks.
/// Virtual machine must be stop-deallocated before invoking this
/// operation.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> ConvertToManagedDisksWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Shuts down the virtual machine and releases the compute resources.
/// You are not billed for the compute resources that this virtual
/// machine uses.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> DeallocateWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets the state of the virtual machine to generalized.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> GeneralizeWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the virtual machines in the specified resource group.
/// Use the nextLink property in the response to get the next page of
/// virtual machines.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualMachine>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the virtual machines in the specified subscription.
/// Use the nextLink property in the response to get the next page of
/// virtual machines.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualMachine>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all available virtual machine sizes to which the specified
/// virtual machine can be resized.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<VirtualMachineSize>>> ListAvailableSizesWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual
/// machine can be restarted with the same provisioned resources. You
/// are still charged for this virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> PowerOffWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> RestartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> StartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> RedeployWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to perform maintenance on a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> PerformMaintenanceWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Run command on the VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Run command operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RunCommandResult>> RunCommandWithHttpMessagesAsync(string resourceGroupName, string vmName, RunCommandInput parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs
/// a template that can be used to create similar VMs.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualMachineCaptureResult>> BeginCaptureWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualMachine>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachine parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks.
/// Virtual machine must be stop-deallocated before invoking this
/// operation.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginConvertToManagedDisksWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Shuts down the virtual machine and releases the compute resources.
/// You are not billed for the compute resources that this virtual
/// machine uses.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginDeallocateWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual
/// machine can be restarted with the same provisioned resources. You
/// are still charged for this virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginPowerOffWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginRestartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginStartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginRedeployWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The operation to perform maintenance on a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginPerformMaintenanceWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Run command on the VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Run command operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RunCommandResult>> BeginRunCommandWithHttpMessagesAsync(string resourceGroupName, string vmName, RunCommandInput parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the virtual machines in the specified resource group.
/// Use the nextLink property in the response to get the next page of
/// virtual machines.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualMachine>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the virtual machines in the specified subscription.
/// Use the nextLink property in the response to get the next page of
/// virtual machines.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualMachine>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays;
using osu.Game.Overlays.BeatmapListing;
using osu.Game.Scoring;
using osuTK.Input;
using APIUser = osu.Game.Online.API.Requests.Responses.APIUser;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneBeatmapListingOverlay : OsuManualInputManagerTestScene
{
private readonly List<APIBeatmapSet> setsForResponse = new List<APIBeatmapSet>();
private BeatmapListingOverlay overlay;
private BeatmapListingSearchControl searchControl => overlay.ChildrenOfType<BeatmapListingSearchControl>().Single();
[SetUpSteps]
public void SetUpSteps()
{
AddStep("setup overlay", () =>
{
Child = overlay = new BeatmapListingOverlay { State = { Value = Visibility.Visible } };
setsForResponse.Clear();
});
AddStep("initialize dummy", () =>
{
var api = (DummyAPIAccess)API;
api.HandleRequest = req =>
{
if (!(req is SearchBeatmapSetsRequest searchBeatmapSetsRequest)) return false;
searchBeatmapSetsRequest.TriggerSuccess(new SearchBeatmapSetsResponse
{
BeatmapSets = setsForResponse,
});
return true;
};
// non-supporter user
api.LocalUser.Value = new APIUser
{
Username = "TestBot",
Id = API.LocalUser.Value.Id + 1,
};
});
}
[Test]
public void TestHideViaBack()
{
AddAssert("is visible", () => overlay.State.Value == Visibility.Visible);
AddStep("hide", () => InputManager.Key(Key.Escape));
AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden);
}
[Test]
public void TestHideViaBackWithSearch()
{
AddAssert("is visible", () => overlay.State.Value == Visibility.Visible);
AddStep("search something", () => overlay.ChildrenOfType<SearchTextBox>().First().Text = "search");
AddStep("kill search", () => InputManager.Key(Key.Escape));
AddAssert("search textbox empty", () => string.IsNullOrEmpty(overlay.ChildrenOfType<SearchTextBox>().First().Text));
AddAssert("is visible", () => overlay.State.Value == Visibility.Visible);
AddStep("hide", () => InputManager.Key(Key.Escape));
AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden);
}
[Test]
public void TestHideViaBackWithScrolledSearch()
{
AddAssert("is visible", () => overlay.State.Value == Visibility.Visible);
AddStep("show many results", () => fetchFor(Enumerable.Repeat(CreateAPIBeatmapSet(Ruleset.Value), 100).ToArray()));
AddUntilStep("placeholder hidden", () => !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent));
AddStep("scroll to bottom", () => overlay.ChildrenOfType<OverlayScrollContainer>().First().ScrollToEnd());
AddStep("kill search", () => InputManager.Key(Key.Escape));
AddUntilStep("search textbox empty", () => string.IsNullOrEmpty(overlay.ChildrenOfType<SearchTextBox>().First().Text));
AddUntilStep("is scrolled to top", () => overlay.ChildrenOfType<OverlayScrollContainer>().First().Current == 0);
AddAssert("is visible", () => overlay.State.Value == Visibility.Visible);
AddStep("hide", () => InputManager.Key(Key.Escape));
AddUntilStep("is hidden", () => overlay.State.Value == Visibility.Hidden);
}
[Test]
public void TestNoBeatmapsPlaceholder()
{
AddStep("fetch for 0 beatmaps", () => fetchFor());
AddUntilStep("placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true);
AddStep("fetch for 1 beatmap", () => fetchFor(CreateAPIBeatmapSet(Ruleset.Value)));
AddUntilStep("placeholder hidden", () => !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent));
AddStep("fetch for 0 beatmaps", () => fetchFor());
AddUntilStep("placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true);
// fetch once more to ensure nothing happens in displaying placeholder again when it already is present.
AddStep("fetch for 0 beatmaps again", () => fetchFor());
AddUntilStep("placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true);
}
[Test]
public void TestUserWithoutSupporterUsesSupporterOnlyFiltersWithoutResults()
{
AddStep("fetch for 0 beatmaps", () => fetchFor());
AddStep("set dummy as non-supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = false);
// only Rank Achieved filter
setRankAchievedFilter(new[] { ScoreRank.XH });
supporterRequiredPlaceholderShown();
setRankAchievedFilter(Array.Empty<ScoreRank>());
notFoundPlaceholderShown();
// only Played filter
setPlayedFilter(SearchPlayed.Played);
supporterRequiredPlaceholderShown();
setPlayedFilter(SearchPlayed.Any);
notFoundPlaceholderShown();
// both RankAchieved and Played filters
setRankAchievedFilter(new[] { ScoreRank.XH });
setPlayedFilter(SearchPlayed.Played);
supporterRequiredPlaceholderShown();
setRankAchievedFilter(Array.Empty<ScoreRank>());
setPlayedFilter(SearchPlayed.Any);
notFoundPlaceholderShown();
}
[Test]
public void TestUserWithSupporterUsesSupporterOnlyFiltersWithoutResults()
{
AddStep("fetch for 0 beatmaps", () => fetchFor());
AddStep("set dummy as supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = true);
// only Rank Achieved filter
setRankAchievedFilter(new[] { ScoreRank.XH });
notFoundPlaceholderShown();
setRankAchievedFilter(Array.Empty<ScoreRank>());
notFoundPlaceholderShown();
// only Played filter
setPlayedFilter(SearchPlayed.Played);
notFoundPlaceholderShown();
setPlayedFilter(SearchPlayed.Any);
notFoundPlaceholderShown();
// both Rank Achieved and Played filters
setRankAchievedFilter(new[] { ScoreRank.XH });
setPlayedFilter(SearchPlayed.Played);
notFoundPlaceholderShown();
setRankAchievedFilter(Array.Empty<ScoreRank>());
setPlayedFilter(SearchPlayed.Any);
notFoundPlaceholderShown();
}
[Test]
public void TestUserWithoutSupporterUsesSupporterOnlyFiltersWithResults()
{
AddStep("fetch for 1 beatmap", () => fetchFor(CreateAPIBeatmapSet(Ruleset.Value)));
AddStep("set dummy as non-supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = false);
// only Rank Achieved filter
setRankAchievedFilter(new[] { ScoreRank.XH });
supporterRequiredPlaceholderShown();
setRankAchievedFilter(Array.Empty<ScoreRank>());
noPlaceholderShown();
// only Played filter
setPlayedFilter(SearchPlayed.Played);
supporterRequiredPlaceholderShown();
setPlayedFilter(SearchPlayed.Any);
noPlaceholderShown();
// both Rank Achieved and Played filters
setRankAchievedFilter(new[] { ScoreRank.XH });
setPlayedFilter(SearchPlayed.Played);
supporterRequiredPlaceholderShown();
setRankAchievedFilter(Array.Empty<ScoreRank>());
setPlayedFilter(SearchPlayed.Any);
noPlaceholderShown();
}
[Test]
public void TestUserWithSupporterUsesSupporterOnlyFiltersWithResults()
{
AddStep("fetch for 1 beatmap", () => fetchFor(CreateAPIBeatmapSet(Ruleset.Value)));
AddStep("set dummy as supporter", () => ((DummyAPIAccess)API).LocalUser.Value.IsSupporter = true);
// only Rank Achieved filter
setRankAchievedFilter(new[] { ScoreRank.XH });
noPlaceholderShown();
setRankAchievedFilter(Array.Empty<ScoreRank>());
noPlaceholderShown();
// only Played filter
setPlayedFilter(SearchPlayed.Played);
noPlaceholderShown();
setPlayedFilter(SearchPlayed.Any);
noPlaceholderShown();
// both Rank Achieved and Played filters
setRankAchievedFilter(new[] { ScoreRank.XH });
setPlayedFilter(SearchPlayed.Played);
noPlaceholderShown();
setRankAchievedFilter(Array.Empty<ScoreRank>());
setPlayedFilter(SearchPlayed.Any);
noPlaceholderShown();
}
private static int searchCount;
private void fetchFor(params APIBeatmapSet[] beatmaps)
{
setsForResponse.Clear();
setsForResponse.AddRange(beatmaps);
// trigger arbitrary change for fetching.
searchControl.Query.Value = $"search {searchCount++}";
}
private void setRankAchievedFilter(ScoreRank[] ranks)
{
AddStep($"set Rank Achieved filter to [{string.Join(',', ranks)}]", () =>
{
searchControl.Ranks.Clear();
searchControl.Ranks.AddRange(ranks);
});
}
private void setPlayedFilter(SearchPlayed played)
{
AddStep($"set Played filter to {played}", () => searchControl.Played.Value = played);
}
private void supporterRequiredPlaceholderShown()
{
AddUntilStep("\"supporter required\" placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.SupporterRequiredDrawable>().SingleOrDefault()?.IsPresent == true);
}
private void notFoundPlaceholderShown()
{
AddUntilStep("\"no maps found\" placeholder shown", () => overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().SingleOrDefault()?.IsPresent == true);
}
private void noPlaceholderShown()
{
AddUntilStep("no placeholder shown", () =>
!overlay.ChildrenOfType<BeatmapListingOverlay.SupporterRequiredDrawable>().Any(d => d.IsPresent)
&& !overlay.ChildrenOfType<BeatmapListingOverlay.NotFoundDrawable>().Any(d => d.IsPresent));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System.Collections.Generic;
using System.Security;
namespace System.Runtime.InteropServices
{
public static class MarshalTests
{
public static readonly object[][] StringData =
{
new object[] { "pizza" },
new object[] { "pepperoni" },
new object[] { "password" },
new object[] { "P4ssw0rdAa1!" },
};
private static SecureString ToSecureString(string data)
{
var str = new SecureString();
foreach (char c in data)
{
str.AppendChar(c);
}
str.MakeReadOnly();
return str;
}
[Theory]
[MemberData(nameof(StringData))]
[PlatformSpecific(TestPlatforms.Windows)] // SecureStringToBSTR not supported on Unix
public static void SecureStringToBSTR(string data)
{
using (SecureString str = ToSecureString(data))
{
IntPtr bstr = Marshal.SecureStringToBSTR(str);
try
{
string actual = Marshal.PtrToStringBSTR(bstr);
Assert.Equal(data, actual);
}
finally
{
Marshal.ZeroFreeBSTR(bstr);
}
}
}
[Theory]
[MemberData(nameof(StringData))]
public static void SecureStringToCoTaskMemAnsi(string data)
{
using (var str = ToSecureString(data))
{
IntPtr ptr = Marshal.SecureStringToCoTaskMemAnsi(str);
try
{
string actual = Marshal.PtrToStringAnsi(ptr);
Assert.Equal(data, actual);
}
finally
{
Marshal.ZeroFreeCoTaskMemAnsi(ptr);
}
}
}
[Theory]
[MemberData(nameof(StringData))]
public static void SecureStringToCoTaskMemUnicode(string data)
{
using (var str = ToSecureString(data))
{
IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(str);
try
{
string actual = Marshal.PtrToStringUni(ptr);
Assert.Equal(data, actual);
}
finally
{
Marshal.ZeroFreeCoTaskMemUnicode(ptr);
}
}
}
[Theory]
[MemberData(nameof(StringData))]
public static void SecureStringToGlobalAllocAnsi(string data)
{
using (var str = ToSecureString(data))
{
IntPtr ptr = Marshal.SecureStringToGlobalAllocAnsi(str);
try
{
string actual = Marshal.PtrToStringAnsi(ptr);
Assert.Equal(data, actual);
}
finally
{
Marshal.ZeroFreeGlobalAllocAnsi(ptr);
}
}
}
[Theory]
[MemberData(nameof(StringData))]
public static void SecureStringToGlobalAllocUnicode(string data)
{
using (var str = ToSecureString(data))
{
IntPtr ptr = Marshal.SecureStringToGlobalAllocUnicode(str);
try
{
string actual = Marshal.PtrToStringUni(ptr);
Assert.Equal(data, actual);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(ptr);
}
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public static void AllocHGlobal_Int32_ReadableWritable(int size)
{
IntPtr p = Marshal.AllocHGlobal(size);
Assert.NotEqual(IntPtr.Zero, p);
try
{
WriteBytes(p, size);
VerifyBytes(p, size);
}
finally
{
Marshal.FreeHGlobal(p);
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public static void AllocHGlobal_IntPtr_ReadableWritable(int size)
{
IntPtr p = Marshal.AllocHGlobal((IntPtr)size);
Assert.NotEqual(IntPtr.Zero, p);
try
{
WriteBytes(p, size);
VerifyBytes(p, size);
}
finally
{
Marshal.FreeHGlobal(p);
}
}
[Fact]
public static void ReAllocHGlobal_DataCopied()
{
const int Size = 3;
IntPtr p1 = Marshal.AllocHGlobal((IntPtr)Size);
IntPtr p2 = p1;
try
{
WriteBytes(p1, Size);
int add = 1;
do
{
p2 = Marshal.ReAllocHGlobal(p2, (IntPtr)(Size + add));
VerifyBytes(p2, Size);
add++;
}
while (p2 == p1); // stop once we've validated moved case
}
finally
{
Marshal.FreeHGlobal(p2);
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public static void AllocCoTaskMem_Int32_ReadableWritable(int size)
{
IntPtr p = Marshal.AllocCoTaskMem(size);
Assert.NotEqual(IntPtr.Zero, p);
try
{
WriteBytes(p, size);
VerifyBytes(p, size);
}
finally
{
Marshal.FreeCoTaskMem(p);
}
}
[Fact]
public static void ReAllocCoTaskMem_DataCopied()
{
const int Size = 3;
IntPtr p1 = Marshal.AllocCoTaskMem(Size);
IntPtr p2 = p1;
try
{
WriteBytes(p1, Size);
int add = 1;
do
{
p2 = Marshal.ReAllocCoTaskMem(p2, Size + add);
VerifyBytes(p2, Size);
add++;
}
while (p2 == p1); // stop once we've validated moved case
}
finally
{
Marshal.FreeCoTaskMem(p2);
}
}
private static void WriteBytes(IntPtr p, int length)
{
for (int i = 0; i < length; i++)
{
Marshal.WriteByte(p + i, (byte)i);
}
}
private static void VerifyBytes(IntPtr p, int length)
{
for (int i = 0; i < length; i++)
{
Assert.Equal((byte)i, Marshal.ReadByte(p + i));
}
}
[Fact]
public static void GetHRForException()
{
Exception e = new Exception();
try
{
Assert.Equal(0, Marshal.GetHRForException(null));
Assert.InRange(Marshal.GetHRForException(e), int.MinValue, -1);
Assert.Equal(e.HResult, Marshal.GetHRForException(e));
}
finally
{
// This GetExceptionForHR call is needed to 'eat' the IErrorInfo put to TLS by
// Marshal.GetHRForException call above. Otherwise other Marshal.GetExceptionForHR
// calls would randomly return previous exception objects passed to
// Marshal.GetHRForException.
// The correct way is to use Marshal.GetHRForException at interop boundary only, but for the
// time being we'll keep this code as-is.
Marshal.GetExceptionForHR(e.HResult);
}
}
#if netcoreapp
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public static void GenerateGuidForType()
{
Assert.Equal(typeof(int).GUID, Marshal.GenerateGuidForType(typeof(int)));
Assert.Equal(typeof(string).GUID, Marshal.GenerateGuidForType(typeof(string)));
}
[ProgId("TestProgID")]
public class ClassWithProgID
{
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public static void GenerateProgIdForType()
{
Assert.Throws<ArgumentNullException>(() => Marshal.GenerateProgIdForType(null));
Assert.Equal("TestProgID", Marshal.GenerateProgIdForType(typeof(ClassWithProgID)));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public static void GetComObjectData()
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetComObjectData(null, null));
}
[Fact]
public static void GetHINSTANCE()
{
Assert.Throws<ArgumentNullException>(() => Marshal.GetHINSTANCE(null));
IntPtr ptr = Marshal.GetHINSTANCE(typeof(int).Module);
IntPtr ptr2 = Marshal.GetHINSTANCE(typeof(string).Module);
Assert.Equal(ptr, ptr2);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public static void GetIDispatchForObject()
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetIDispatchForObject(null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public static void GetTypedObjectForIUnknown()
{
if(PlatformDetection.IsWindows)
{
Assert.Throws<ArgumentNullException>(() => Marshal.GetTypedObjectForIUnknown(IntPtr.Zero, typeof(int)));
}
else
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetTypedObjectForIUnknown(IntPtr.Zero, typeof(int)));
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public static void SetComObjectData()
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.SetComObjectData(null, null, null));
}
#endif // netcoreapp
[Fact]
public static void Prelink()
{
Assert.Throws<ArgumentNullException>(() => Marshal.Prelink(null));
}
[Fact]
public static void PrelinkAll()
{
Assert.Throws<ArgumentNullException>(() => Marshal.PrelinkAll(null));
}
[Fact]
public static void PtrToStringAuto()
{
Assert.Null(Marshal.PtrToStringAuto(IntPtr.Zero));
}
[Fact]
public static void PtrToStringAutoWithLength()
{
Assert.Throws<ArgumentNullException>(() => Marshal.PtrToStringAuto(IntPtr.Zero, 0));
String s = "Hello World";
int len = 5;
IntPtr ptr = Marshal.StringToCoTaskMemAuto(s);
String s2 = Marshal.PtrToStringAuto(ptr, len);
Assert.Equal(s.Substring(0, len), s2);
Marshal.FreeCoTaskMem(ptr);
}
[Fact]
public static void StringToCoTaskMemAuto()
{
String s = null;
// passing null string should return 0
Assert.Equal(0, (long)Marshal.StringToCoTaskMemAuto(s));
s = "Hello World";
IntPtr ptr = Marshal.StringToCoTaskMemAuto(s);
// make sure the native memory is correctly laid out
for (int i=0; i < s.Length; i++)
{
char c = (char)Marshal.ReadInt16(IntPtr.Add(ptr, i<<1));
Assert.Equal(s[i], c);
}
// make sure if we convert back to string we get the same value
String s2 = Marshal.PtrToStringAuto(ptr);
Assert.Equal(s, s2);
// free the native memory
Marshal.FreeCoTaskMem(ptr);
}
[Fact]
public static void StringToHGlobalAuto()
{
String s = null;
// passing null string should return 0
Assert.Equal(0, (long)Marshal.StringToHGlobalAuto(s));
s = "Hello World";
IntPtr ptr = Marshal.StringToHGlobalAuto(s);
// make sure the native memory is correctly laid out
for (int i=0; i < s.Length; i++)
{
char c = (char)Marshal.ReadInt16(IntPtr.Add(ptr, i<<1));
Assert.Equal(s[i], c);
}
// make sure if we convert back to string we get the same value
String s2 = Marshal.PtrToStringAuto(ptr);
Assert.Equal(s, s2);
// free the native memory
Marshal.FreeCoTaskMem(ptr);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public static void BindToMoniker()
{
String monikerName = null;
if(PlatformDetection.IsWindows)
{
if (PlatformDetection.IsNotWindowsNanoServer)
{
Assert.Throws<ArgumentException>(() => Marshal.BindToMoniker(monikerName));
}
}
else
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.BindToMoniker(monikerName));
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Net46)]
public static void ChangeWrapperHandleStrength()
{
if(PlatformDetection.IsWindows)
{
Assert.Throws<ArgumentNullException>(() => Marshal.ChangeWrapperHandleStrength(null, true));
}
else
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.ChangeWrapperHandleStrength(null, true));
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Apache.Geode.Client.FwkLib
{
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
//using Region = Apache.Geode.Client.IRegion<Object, Object>;
//using IntRegion = Apache.Geode.Client.IRegion<int, byte[]>;
//using StringRegion = Apache.Geode.Client.IRegion<string, byte[]>;
public class PerfTests<TKey, TVal> : FwkTest<TKey, TVal>
{
#region Protected members
protected TKey[] m_keysA;
protected int m_maxKeys;
protected int m_keyIndexBegin;
protected TVal[] m_cValues;
protected int m_maxValues;
public char m_keyType = 'i';
#endregion
#region Protected constants
protected const string ClientCount = "clientCount";
protected const string TimedInterval = "timedInterval";
protected const string DistinctKeys = "distinctKeys";
protected const string NumThreads = "numThreads";
protected const string ValueSizes = "valueSizes";
protected const string OpsSecond = "opsSecond";
protected const string KeyType = "keyType";
protected const string KeySize = "keySize";
protected const string KeyIndexBegin = "keyIndexBegin";
protected const string RegisterKeys = "registerKeys";
protected const string RegisterRegex = "registerRegex";
protected const string UnregisterRegex = "unregisterRegex";
protected const string ExpectedCount = "expectedCount";
protected const string InterestPercent = "interestPercent";
protected const string KeyStart = "keyStart";
protected const string KeyEnd = "keyEnd";
#endregion
#region Protected utility methods
protected void ClearKeys()
{
if (m_keysA != null)
{
for (int i = 0; i < m_keysA.Length; i++)
{
if (m_keysA[i] != null)
{
//m_keysA[i];
m_keysA[i] = default(TKey);
}
}
m_keysA = null;
m_maxKeys = 0;
}
}
protected int InitKeys(bool useDefault)
{
string typ = GetStringValue(KeyType); // int is only value to use
char newType = (typ == null || typ.Length == 0) ? 's' : typ[0];
int low = GetUIntValue(KeyIndexBegin);
low = (low > 0) ? low : 0;
//ResetKey(DistinctKeys);
int numKeys = GetUIntValue(DistinctKeys); // check distinct keys first
if (numKeys <= 0)
{
if (useDefault)
{
numKeys = 5000;
}
else
{
//FwkSevere("Failed to initialize keys with numKeys: {0}", numKeys);
return numKeys;
}
}
int high = numKeys + low;
FwkInfo("InitKeys:: numKeys: {0}; low: {1}", numKeys, low);
if ((newType == m_keyType) && (numKeys == m_maxKeys) &&
(m_keyIndexBegin == low))
{
return numKeys;
}
ClearKeys();
m_maxKeys = numKeys;
m_keyIndexBegin = low;
m_keyType = newType;
if (m_keyType == 'i')
{
InitIntKeys(low, high);
}
else
{
int keySize = GetUIntValue(KeySize);
keySize = (keySize > 0) ? keySize : 10;
string keyBase = new string('A', keySize);
InitStrKeys(low, high, keyBase);
}
for (int j = 0; j < numKeys; j++)
{
int randIndx = Util.Rand(numKeys);
if (randIndx != j)
{
TKey tmp = m_keysA[j];
m_keysA[j] = m_keysA[randIndx];
m_keysA[randIndx] = tmp;
}
}
return m_maxKeys;
}
protected int InitKeys()
{
return InitKeys(true);
}
protected void InitStrKeys(int low, int high, string keyBase)
{
m_keysA = (TKey[])(object) new String[m_maxKeys];
FwkInfo("m_maxKeys: {0}; low: {1}; high: {2}",
m_maxKeys, low, high);
for (int i = low; i < high; i++)
{
m_keysA[i - low] = (TKey)(object)(keyBase.ToString() + i.ToString("D10"));
}
}
protected void InitIntKeys(int low, int high)
{
m_keysA = (TKey[])(object) new Int32[m_maxKeys];
FwkInfo("m_maxKeys: {0}; low: {1}; high: {2}",
m_maxKeys, low, high);
for (int i = low; i < high; i++)
{
m_keysA[i - low] = (TKey)(object)i;
}
}
protected int InitValues(int numKeys)
{
return InitValues(numKeys, 0);
}
protected int InitValues(int numKeys, int size)
{
if (size <= 0)
{
size = GetUIntValue(ValueSizes);
}
if (size <= 0)
{
//FwkSevere("Failed to initialize values with valueSize: {0}", size);
return size;
}
if (numKeys <= 0)
{
numKeys = 500;
}
m_maxValues = numKeys;
if (m_cValues != null)
{
for (int i = 0; i < m_cValues.Length; i++)
{
if (m_cValues[i] != null)
{
//m_cValues[i].Dispose();
m_cValues[i] = default(TVal);
}
}
m_cValues = null;
}
m_cValues = new TVal[m_maxValues];
FwkInfo("InitValues() payload size: {0}", size);
//byte[] createPrefix = Encoding.ASCII.GetBytes("Create ");
//byte[] buffer = new byte[size];
for (int i = 0; i < m_maxValues; i++)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int j = 0; j < size; j++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
//FwkInfo("rjk: InitValues() value {0}", builder.ToString());
//Util.RandBytes(buffer);
//createPrefix.CopyTo(buffer, 0);
//string tmp = buffer;
if (typeof(TVal) == typeof(string))
{
m_cValues[i] = (TVal)(object)builder.ToString();
//FwkInfo("rjk: InitValues() value {0} size is {1}", m_cValues[i].ToString(), m_cValues[i].ToString().Length);
}
else if (typeof(TVal) == typeof(byte[]))
{
//Encoding.ASCII.GetBytes(buffer);
//Util.RandBytes(buffer);
//createPrefix.CopyTo(buffer, 0);
m_cValues[i] = (TVal)(object)(Encoding.ASCII.GetBytes(builder.ToString()));
//FwkInfo("rjk: InitValues() type is byte[] value {0} size is {1}", m_cValues[i].ToString(), ((byte[])(object)m_cValues[i]).Length);
}
/*
Util.RandBytes(buffer);
createPrefix.CopyTo(buffer, 0);
if (typeof(TVal) == typeof(string))
{
String MyString;
//Encoding ASCIIEncod = new Encoding();
MyString = Encoding.ASCII.GetString(buffer);
m_cValues[i] = (TVal)(MyString as object);
FwkInfo("rjk: InitValues() value {0} size is {1}", MyString.ToString(), m_cValues[i].ToString().Length);
}
else if (typeof(TVal) == typeof(byte[]))
{
Util.RandBytes(buffer);
createPrefix.CopyTo(buffer, 0);
m_cValues[i] = (TVal)(buffer as object);
}
* */
//for (int ii = 0; ii < buffer.Length; ++ii)
//{
// FwkInfo("rjk: InitValues() index is {0} value is {1} buffer = {2}", i, m_cValues[ii], buffer[ii]);
//}
}
return size;
}
protected IRegion<TKey, TVal> GetRegion()
{
return GetRegion(null);
}
protected IRegion<TKey, TVal> GetRegion(string regionName)
{
IRegion<TKey, TVal> region;
if (regionName == null)
{
regionName = GetStringValue("regionName");
}
if (regionName == null)
{
region = GetRootRegion();
if (region == null)
{
IRegion<TKey, TVal>[] rootRegions = CacheHelper<TKey, TVal>.DCache.RootRegions<TKey, TVal>();
if (rootRegions != null && rootRegions.Length > 0)
{
region = rootRegions[Util.Rand(rootRegions.Length)];
}
}
}
else
{
region = CacheHelper<TKey, TVal>.GetRegion(regionName);
}
return region;
}
#endregion
#region Public methods
public static ICacheListener<TKey, TVal> CreatePerfTestCacheListener()
{
return new PerfTestCacheListener<TKey, TVal>();
}
public static ICacheListener<TKey, TVal> CreateConflationTestCacheListener()
{
return new ConflationTestCacheListener<TKey, TVal>();
}
public static ICacheListener<TKey, TVal> CreateLatencyListenerP()
{
return new LatencyListener<TKey, TVal>();
}
public static ICacheListener<TKey, TVal> CreateDupChecker()
{
return new DupChecker<TKey, TVal>();
}
public virtual void DoCreateRegion()
{
FwkInfo("In DoCreateRegion()");
try
{
IRegion<TKey,TVal> region = null;
FwkInfo("Tkey = {0} , Val = {1}", typeof(TKey).Name, typeof(TVal));
region = CreateRootRegion();
if (region == null)
{
FwkException("DoCreateRegion() could not create region.");
}
FwkInfo("DoCreateRegion() Created region '{0}'", region.Name);
}
catch (Exception ex)
{
FwkException("DoCreateRegion() Caught Exception: {0}", ex);
}
FwkInfo("DoCreateRegion() complete.");
}
public void DoCloseCache()
{
FwkInfo("DoCloseCache() Closing cache and disconnecting from" +
" distributed system.");
CacheHelper<TKey,TVal>.Close();
}
public void DoPuts()
{
FwkInfo("In DoPuts()");
try
{
IRegion<TKey, TVal> region = GetRegion();
int numClients = GetUIntValue(ClientCount);
string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes);
int timedInterval = GetTimeValue(TimedInterval) * 1000;
if (timedInterval <= 0)
{
timedInterval = 5000;
}
int maxTime = 10 * timedInterval;
// Loop over key set sizes
ResetKey(DistinctKeys);
int numKeys;
while ((numKeys = InitKeys(false)) > 0)
{ // keys loop
// Loop over value sizes
ResetKey(ValueSizes);
int valSize;
while ((valSize = InitValues(numKeys)) > 0)
{ // value loop
// Loop over threads
ResetKey(NumThreads);
int numThreads;
while ((numThreads = GetUIntValue(NumThreads)) > 0)
{
try
{
//if (m_keyType == 's')
//{
//StringRegion sregion = region as StringRegion;
PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues);
FwkInfo("Running warmup task for {0} iterations.", numKeys);
RunTask(puts, 1, numKeys, -1, -1, null);
// Running the warmup task
Thread.Sleep(3000);
// And we do the real work now
FwkInfo("Running timed task for {0} secs and {1} threads; numKeys[{2}]",
timedInterval / 1000, numThreads, numKeys);
SetTaskRunInfo(label, "Puts", m_maxKeys, numClients,
valSize, numThreads);
RunTask(puts, numThreads, -1, timedInterval, maxTime, null);
AddTaskRunRecord(puts.Iterations, puts.ElapsedTime);
}
catch (ClientTimeoutException)
{
FwkException("In DoPuts() Timed run timed out.");
}
Thread.Sleep(3000); // Put a marker of inactivity in the stats
}
Thread.Sleep(3000); // Put a marker of inactivity in the stats
} // value loop
Thread.Sleep(3000); // Put a marker of inactivity in the stats
} // keys loop
}
catch (Exception ex)
{
FwkException("DoPuts() Caught Exception: {0}", ex);
}
Thread.Sleep(3000); // Put a marker of inactivity in the stats
FwkInfo("DoPuts() complete.");
}
public void DoPopulateRegion()
{
FwkInfo("In DoPopulateRegion()");
try
{
IRegion<TKey,TVal> region = GetRegion();
ResetKey(DistinctKeys);
int numKeys = InitKeys();
InitValues(numKeys);
PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues);
FwkInfo("Populating region.");
RunTask(puts, 1, m_maxKeys, -1, -1, null);
}
catch (Exception ex)
{
FwkException("DoPopulateRegion() Caught Exception: {0}", ex);
}
FwkInfo("DoPopulateRegion() complete.");
}
public void DoSerialPuts()
{
FwkInfo("In DoSerialPuts()");
try
{
IRegion<int, int> region = (IRegion<int, int>)GetRegion();
int keyStart = GetUIntValue(KeyStart);
int keyEnd = GetUIntValue(KeyEnd);
for (Int32 keys = keyStart; keys <= keyEnd; keys++)
{
if (keys % 50 == 1)
{
FwkInfo("DoSerialPuts() putting 1000 values for key " + keys);
}
Int32 key = keys;
for (Int32 values = 1; values <= 1000; values++)
{
Int32 value = values;
region[key] = value;
}
}
}
catch (Exception ex)
{
FwkException("DoSerialPuts() Caught Exception: {0}", ex);
}
Thread.Sleep(3000); // Put a marker of inactivity in the stats
FwkInfo("DoSerialPuts() complete.");
}
public void DoPutBursts()
{
FwkInfo("In DoPutBursts()");
try
{
IRegion<TKey,TVal> region = GetRegion();
int numClients = GetUIntValue(ClientCount);
string label = CacheHelper<TKey,TVal>.RegionTag(region.Attributes);
int timedInterval = GetTimeValue(TimedInterval) * 1000;
if (timedInterval <= 0)
{
timedInterval = 5000;
}
int burstMillis = GetUIntValue("burstMillis");
if (burstMillis <= 0)
{
burstMillis = 500;
}
int burstPause = GetTimeValue("burstPause") * 1000;
if (burstPause <= 0)
{
burstPause = 1000;
}
int opsSec = GetUIntValue(OpsSecond);
if (opsSec <= 0)
{
opsSec = 100;
}
// Loop over key set sizes
ResetKey(DistinctKeys);
int numKeys;
while ((numKeys = InitKeys(false)) > 0)
{ // keys loop
// Loop over value sizes
ResetKey(ValueSizes);
int valSize;
while ((valSize = InitValues(numKeys)) > 0)
{ // value loop
// Loop over threads
ResetKey(NumThreads);
int numThreads;
while ((numThreads = GetUIntValue(NumThreads)) > 0)
{ // thread loop
// And we do the real work now
MeteredPutsTask<TKey, TVal> mputs = new MeteredPutsTask<TKey, TVal>(region, m_keysA,
m_cValues, opsSec);
FwkInfo("Running warmup metered task for {0} iterations.", m_maxKeys);
RunTask(mputs, 1, m_maxKeys, -1, -1, null);
Thread.Sleep(10000);
PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues);
int loopIters = (timedInterval / burstMillis) + 1;
FwkInfo("Running timed task for {0} secs and {1} threads.",
timedInterval/1000, numThreads);
SetTaskRunInfo(label, "PutBursts", numKeys, numClients,
valSize, numThreads);
int totIters = 0;
TimeSpan totTime = TimeSpan.Zero;
for (int i = loopIters; i > 0; i--)
{
try
{
RunTask(puts, numThreads, -1, burstMillis, 30000, null);
}
catch (ClientTimeoutException)
{
FwkException("In DoPutBursts() Timed run timed out.");
}
totIters += puts.Iterations;
totTime += puts.ElapsedTime;
double psec = (totIters * 1000.0) / totTime.TotalMilliseconds;
FwkInfo("PerfSuite interim: {0} {1} {2}", psec, totIters, totTime);
Thread.Sleep(burstPause);
}
AddTaskRunRecord(totIters, totTime);
// real work complete for this pass thru the loop
Thread.Sleep(3000); // Put a marker of inactivity in the stats
} // thread loop
Thread.Sleep(3000); // Put a marker of inactivity in the stats
} // value loop
Thread.Sleep(3000); // Put a marker of inactivity in the stats
} // keys loop
}
catch (Exception ex)
{
FwkException("DoPutBursts() Caught Exception: {0}", ex);
}
Thread.Sleep(3000); // Put a marker of inactivity in the stats
FwkInfo("DoPutBursts() complete.");
}
public void DoLatencyPuts()
{
FwkInfo("In DoLatencyPuts()");
try
{
IRegion<TKey,TVal> region = GetRegion();
int numClients = GetUIntValue(ClientCount);
string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes);
int timedInterval = GetTimeValue(TimedInterval) * 1000;
if (timedInterval <= 0)
{
timedInterval = 5000;
}
int maxTime = 10 * timedInterval;
int opsSec = GetUIntValue(OpsSecond);
if (opsSec < 0)
{
opsSec = 100;
}
// Loop over key set sizes
ResetKey(DistinctKeys);
int numKeys;
while ((numKeys = InitKeys(false)) > 0)
{ // keys loop
// Loop over value sizes
ResetKey(ValueSizes);
int valSize;
while ((valSize = InitValues(numKeys)) > 0)
{ // value loop
// Loop over threads
ResetKey(NumThreads);
int numThreads;
while ((numThreads = GetUIntValue(NumThreads)) > 0)
{
LatencyPutsTask<TKey, TVal> puts = new LatencyPutsTask<TKey, TVal>(region, m_keysA,
m_cValues, opsSec);
// Running the warmup task
FwkInfo("Running warmup task for {0} iterations.", numKeys);
RunTask(puts, 1, numKeys, -1, -1, null);
Thread.Sleep(3000);
// And we do the real work now
FwkInfo("Running timed task for {0} secs and {1} threads.",
timedInterval/1000, numThreads);
SetTaskRunInfo(label, "LatencyPuts", numKeys, numClients, valSize, numThreads);
Util.BBSet("LatencyBB", "LatencyTag", TaskData);
try
{
RunTask(puts, numThreads, -1, timedInterval, maxTime, null);
}
catch (ClientTimeoutException)
{
FwkException("In DoLatencyPuts() Timed run timed out.");
}
AddTaskRunRecord(puts.Iterations, puts.ElapsedTime);
// real work complete for this pass thru the loop
Thread.Sleep(3000); // Put a marker of inactivity in the stats
} // thread loop
Thread.Sleep(3000); // Put a marker of inactivity in the stats
} // value loop
Thread.Sleep(3000); // Put a marker of inactivity in the stats
} // keys loop
}
catch (Exception ex)
{
FwkException("DoLatencyPuts() Caught Exception: {0}", ex);
}
Thread.Sleep(3000); // Put a marker of inactivity in the stats
FwkInfo("DoLatencyPuts() complete.");
}
public void DoGets()
{
FwkInfo("In DoGets()");
try
{
IRegion<TKey,TVal> region = GetRegion();
FwkInfo("rjk:DoGets region name is {0} ", region.Name);
int numClients = GetUIntValue(ClientCount);
string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes);
int timedInterval = GetTimeValue(TimedInterval) * 1000;
if (timedInterval <= 0)
{
timedInterval = 5000;
}
int maxTime = 10 * timedInterval;
ResetKey(DistinctKeys);
InitKeys();
int valSize = GetUIntValue(ValueSizes);
FwkInfo("rjk:DoGets number of keys in region is {0} .", region.Keys.Count);
// Loop over threads
ResetKey(NumThreads);
int numThreads;
while ((numThreads = GetUIntValue(NumThreads)) > 0)
{ // thread loop
// And we do the real work now
GetsTask<TKey, TVal> gets = new GetsTask<TKey, TVal>(region, m_keysA);
FwkInfo("Running warmup task for {0} iterations.", m_maxKeys);
RunTask(gets, 1, m_maxKeys, -1, -1, null);
region.GetLocalView().InvalidateRegion();
Thread.Sleep(3000);
FwkInfo("Running timed task for {0} secs and {1} threads.",
timedInterval/1000, numThreads);
SetTaskRunInfo(label, "Gets", m_maxKeys, numClients, valSize, numThreads);
try
{
RunTask(gets, numThreads, -1, timedInterval, maxTime, null);
}
catch (ClientTimeoutException)
{
FwkException("In DoGets() Timed run timed out.");
}
AddTaskRunRecord(gets.Iterations, gets.ElapsedTime);
// real work complete for this pass thru the loop
Thread.Sleep(3000);
} // thread loop
}
catch (Exception ex)
{
FwkException("DoGets() Caught Exception: {0}", ex);
}
Thread.Sleep(3000);
FwkInfo("DoGets() complete.");
}
public void DoPopServers()
{
FwkInfo("In DoPopServers()");
try
{
IRegion<TKey,TVal> region = GetRegion();
ResetKey(DistinctKeys);
int numKeys = InitKeys();
ResetKey(ValueSizes);
InitValues(numKeys);
int opsSec = GetUIntValue(OpsSecond);
MeteredPutsTask<TKey, TVal> mputs = new MeteredPutsTask<TKey, TVal>(region, m_keysA,
m_cValues, opsSec);
RunTask(mputs, 1, m_maxKeys, -1, -1, null);
}
catch (Exception ex)
{
FwkException("DoPopServers() Caught Exception: {0}", ex);
}
FwkInfo("DoPopServers() complete.");
}
public void DoPopClient()
{
FwkInfo("In DoPopClient()");
try
{
IRegion<TKey,TVal> region = GetRegion();
ResetKey(DistinctKeys);
InitKeys();
GetsTask<TKey, TVal> gets = new GetsTask<TKey, TVal>(region, m_keysA);
RunTask(gets, 1, m_maxKeys, -1, -1, null);
}
catch (Exception ex)
{
FwkException("DoPopClient() Caught Exception: {0}", ex);
}
FwkInfo("DopopClient() complete.");
}
public void DoPopClientMS()
{
FwkInfo("In DoPopClientMS()");
try
{
IRegion<TKey,TVal> region = GetRegion();
ResetKey(DistinctKeys);
int numKeys = GetUIntValue(DistinctKeys);
int clientCount = GetUIntValue(ClientCount);
int interestPercent = GetUIntValue(InterestPercent);
if (interestPercent <= 0)
{
if (clientCount <= 0)
{
interestPercent = 100;
}
else
{
interestPercent = (100 / clientCount);
}
}
int myNumKeys = (numKeys * interestPercent) / 100;
int myNum = Util.ClientNum;
int myStart = myNum * myNumKeys;
int myValSize = 10;
m_maxKeys = numKeys;
InitIntKeys(myStart, myStart + myNumKeys);
InitValues(myNumKeys, myValSize);
FwkInfo("DoPopClientMS() Client number: {0}, Client count: {1}, " +
"MaxKeys: {2}", myNum, clientCount, m_maxKeys);
PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues);
RunTask(puts, 1, m_maxKeys, -1, -1, null);
}
catch (Exception ex)
{
FwkException("DoPopClientMS() Caught Exception: {0}", ex);
}
FwkInfo("DoPopClientMS() complete.");
}
public void DoDestroys()
{
FwkInfo("In DoDestroys()");
try
{
IRegion<TKey,TVal> region = GetRegion();
int numClients = GetUIntValue(ClientCount);
FwkInfo("DoDestroys() numclients set to {0}", numClients);
string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes);
int timedInterval = GetTimeValue(TimedInterval) * 1000;
if (timedInterval <= 0)
{
timedInterval = 5000;
}
int maxTime = 10 * timedInterval;
// always use only one thread for destroys.
int numKeys;
// Loop over distinctKeys
while ((numKeys = InitKeys(false)) > 0)
{ // thread loop
int valSize = InitValues(numKeys);
// And we do the real work now
//populate the region
PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues);
FwkInfo("DoDestroys() Populating region.");
RunTask(puts, 1, m_maxKeys, -1, -1, null);
DestroyTask<TKey, TVal> destroys = new DestroyTask<TKey, TVal>(region, m_keysA);
FwkInfo("Running timed task for {0} iterations and {1} threads.",
numKeys, 1);
SetTaskRunInfo(label, "Destroys", numKeys, numClients, valSize, 1);
try
{
RunTask(destroys, 1, numKeys, -1, maxTime, null);
}
catch (ClientTimeoutException)
{
FwkException("In DoDestroys() Timed run timed out.");
}
AddTaskRunRecord(destroys.Iterations, destroys.ElapsedTime);
// real work complete for this pass thru the loop
Thread.Sleep(3000);
} // distinctKeys loop
}
catch (Exception ex)
{
FwkException("DoDestroys() Caught Exception: {0}", ex);
}
Thread.Sleep(3000);
FwkInfo("DoDestroys() complete.");
}
public void DoCheckValues()
{
FwkInfo("In DoCheckValues()");
try
{
IRegion<TKey,TVal> region = GetRegion();
ICollection<TVal> vals = region.Values;
int creates = 0;
int updates = 0;
int unknowns = 0;
if (vals != null)
{
byte[] createPrefix = Encoding.ASCII.GetBytes("Create ");
byte[] updatePrefix = Encoding.ASCII.GetBytes("Update ");
foreach (object val in vals)
{
byte[] valBytes = val as byte[];
if (Util.CompareArraysPrefix(valBytes, createPrefix))
{
creates++;
}
else if (Util.CompareArraysPrefix(valBytes, updatePrefix))
{
updates++;
}
else
{
unknowns++;
}
}
FwkInfo("DoCheckValues() Found {0} values from creates, " +
"{1} values from updates, and {2} unknown values.",
creates, updates, unknowns);
}
}
catch (Exception ex)
{
FwkException("DoCheckValues() Caught Exception: {0}", ex);
}
}
public void DoLocalDestroyEntries()
{
FwkInfo("In DoLocalDestroyEntries()");
try
{
IRegion<TKey,TVal> region = GetRegion();
ICollection<TKey> keys = region.GetLocalView().Keys;
if (keys != null)
{
foreach (TKey key in keys)
{
region.GetLocalView().Remove(key);
}
}
}
catch (Exception ex)
{
FwkException("DoLocalDestroyEntries() Caught Exception: {0}", ex);
}
}
public void DoDestroyRegion()
{
FwkInfo("In DoDestroyRegion");
try
{
IRegion<TKey,TVal> region = GetRegion();
region.DestroyRegion();
}
catch (Exception ex)
{
FwkException("DoDestroyRegion() caught exception: {0}" , ex);
}
}
public void DoLocalDestroyRegion()
{
FwkInfo("In DoLocalDestroyRegion()");
try
{
IRegion<TKey,TVal> region = GetRegion();
region.GetLocalView().DestroyRegion();
}
catch (Exception ex)
{
FwkException("DoLocalDestroyRegion() Caught Exception: {0}", ex);
}
}
public void DoPutAll()
{
FwkInfo("In DoPutAll()");
try
{
IRegion<TKey,TVal> region = GetRegion();
ResetKey(DistinctKeys);
int numKeys = InitKeys();
ResetKey(ValueSizes);
InitValues(numKeys);
IDictionary<TKey, TVal> map = new Dictionary<TKey, TVal>();
map.Clear();
Int32 i = 0;
while (i < numKeys)
{
map.Add(m_keysA[i], m_cValues[i]);
i++;
}
DateTime startTime;
DateTime endTime;
TimeSpan elapsedTime;
startTime = DateTime.Now;
region.PutAll(map, TimeSpan.FromSeconds(60));
endTime = DateTime.Now;
elapsedTime = endTime - startTime;
FwkInfo("PerfTests.DoPutAll: Time Taken to execute" +
" the putAll for {0}: is {1}ms", numKeys,
elapsedTime.TotalMilliseconds);
}
catch (Exception ex)
{
FwkException("DoPutAll() Caught Exception: {0}", ex);
}
FwkInfo("DoPutAll() complete.");
}
public void DoGetAllAndVerification()
{
FwkInfo("In DoGetAllAndVerification()");
try
{
IRegion<TKey,TVal> region = GetRegion();
ResetKey(DistinctKeys);
ResetKey(ValueSizes);
ResetKey("addToLocalCache");
ResetKey("inValidateRegion");
int numKeys = InitKeys(false);
Int32 i = 0;
bool isInvalidateRegion = GetBoolValue("isInvalidateRegion");
if (isInvalidateRegion)
{
region.GetLocalView().InvalidateRegion();
}
List<TKey> keys = new List<TKey>();
keys.Clear();
while (i < numKeys)
{
keys.Add(m_keysA[i]);
i++;
}
bool isAddToLocalCache = GetBoolValue("addToLocalCache");
Dictionary<TKey, TVal> values = new Dictionary<TKey, TVal>();
values.Clear();
DateTime startTime;
DateTime endTime;
TimeSpan elapsedTime;
startTime = DateTime.Now;
region.GetAll(keys.ToArray(), values, null, isAddToLocalCache);
endTime = DateTime.Now;
elapsedTime = endTime - startTime;
FwkInfo("PerfTests.DoGetAllAndVerification: Time Taken to execute" +
" the getAll for {0}: is {1}ms", numKeys,
elapsedTime.TotalMilliseconds);
int payload = GetUIntValue("valueSizes");
FwkInfo("PerfTests.DoGetAllAndVerification: keyCount = {0}" + " valueCount = {1} ",
keys.Count, values.Count);
if (values.Count == keys.Count)
{
foreach (KeyValuePair<TKey, TVal> entry in values)
{
TVal item = entry.Value;
//if (item != payload) // rjk Need to check how to verify
//{
// FwkException("PerfTests.DoGetAllAndVerification: value size {0} is not equal to " +
// "expected payload size {1} for key : {2}", item.Length, payload, entry.Key);
//}
}
}
if (isAddToLocalCache)
{
if (keys.Count != region.Count)
{
FwkException("PerfTests.DoGetAllAndVerification: number of keys in region do not" +
" match expected number");
}
}
else
{
if (region.Count != 0)
{
FwkException("PerfTests.DoGetAllAndVerification: expected zero keys in region");
}
}
}
catch (Exception ex)
{
FwkException("DoGetAllAndVerification() Caught Exception: {0}", ex);
}
FwkInfo("DoGetAllAndVerification() complete.");
}
public void DoResetListener()
{
try
{
IRegion<TKey,TVal> region = GetRegion();
int sleepTime = GetUIntValue("sleepTime");
PerfTestCacheListener<TKey,TVal> listener =
region.Attributes.CacheListener as PerfTestCacheListener<TKey, TVal>;
if (listener != null)
{
listener.Reset(sleepTime);
}
}
catch (Exception ex)
{
FwkSevere("DoResetListener() Caught Exception: {0}", ex);
}
Thread.Sleep(3000);
FwkInfo("DoResetListener() complete.");
}
public void DoRegisterInterestList()
{
FwkInfo("In DoRegisterInterestList()");
try
{
ResetKey(DistinctKeys);
ResetKey(KeyIndexBegin);
ResetKey(RegisterKeys);
string typ = GetStringValue(KeyType); // int is only value to use
char newType = (typ == null || typ.Length == 0) ? 's' : typ[0];
IRegion<TKey,TVal> region = GetRegion();
int numKeys = GetUIntValue(DistinctKeys); // check distince keys first
if (numKeys <= 0)
{
FwkSevere("DoRegisterInterestList() Failed to initialize keys " +
"with numKeys: {0}", numKeys);
return;
}
int low = GetUIntValue(KeyIndexBegin);
low = (low > 0) ? low : 0;
int numOfRegisterKeys = GetUIntValue(RegisterKeys);
int high = numOfRegisterKeys + low;
ClearKeys();
m_maxKeys = numOfRegisterKeys;
m_keyIndexBegin = low;
m_keyType = newType;
if (m_keyType == 'i')
{
InitIntKeys(low, high);
}
else
{
int keySize = GetUIntValue(KeySize);
keySize = (keySize > 0) ? keySize : 10;
string keyBase = new string('A', keySize);
InitStrKeys(low, high, keyBase);
}
FwkInfo("DoRegisterInterestList() registering interest for {0} to {1}",
low, high);
TKey[] registerKeyList = new TKey[high - low];
for (int j = low; j < high; j++)
{
if (m_keysA[j - low] != null)
{
registerKeyList[j - low] = m_keysA[j - low];
}
else
{
FwkInfo("DoRegisterInterestList() key[{0}] is null.", (j - low));
}
}
bool isDurable = GetBoolValue("isDurableReg");
ResetKey("getInitialValues");
bool isGetInitialValues = GetBoolValue("getInitialValues");
bool isReceiveValues = true;
bool checkReceiveVal = GetBoolValue("checkReceiveVal");
if (checkReceiveVal)
{
ResetKey("receiveValue");
isReceiveValues = GetBoolValue("receiveValue");
}
region.GetSubscriptionService().RegisterKeys(registerKeyList, isDurable, isGetInitialValues, isReceiveValues);
String durableClientId = CacheHelper<TKey, TVal>.DCache.DistributedSystem.SystemProperties.DurableClientId;
if (durableClientId.Length > 0)
{
CacheHelper<TKey, TVal>.DCache.ReadyForEvents();
}
}
catch (Exception ex)
{
FwkException("DoRegisterInterestList() Caught Exception: {0}", ex);
}
FwkInfo("DoRegisterInterestList() complete.");
}
public void DoRegisterAllKeys()
{
FwkInfo("In DoRegisterAllKeys()");
try
{
IRegion<TKey,TVal> region = GetRegion();
FwkInfo("DoRegisterAllKeys() region name is {0}", region.Name);
bool isDurable = GetBoolValue("isDurableReg");
ResetKey("getInitialValues");
bool isGetInitialValues = GetBoolValue("getInitialValues");
bool checkReceiveVal = GetBoolValue("checkReceiveVal");
bool isReceiveValues = true;
if (checkReceiveVal)
{
ResetKey("receiveValue");
isReceiveValues = GetBoolValue("receiveValue");
}
region.GetSubscriptionService().RegisterAllKeys(isDurable, isGetInitialValues,isReceiveValues);
String durableClientId = CacheHelper<TKey, TVal>.DCache.DistributedSystem.SystemProperties.DurableClientId;
if (durableClientId.Length > 0)
{
CacheHelper<TKey, TVal>.DCache.ReadyForEvents();
}
}
catch (Exception ex)
{
FwkException("DoRegisterAllKeys() Caught Exception: {0}", ex);
}
FwkInfo("DoRegisterAllKeys() complete.");
}
public void DoVerifyInterestList()
{
FwkInfo("In DoVerifyInterestList()");
try
{
int countUpdate = 0;
IRegion<TKey,TVal> region = GetRegion();
InitKeys();
ResetKey(RegisterKeys);
int numOfRegisterKeys = GetUIntValue(RegisterKeys);
int payload = GetUIntValue(ValueSizes);
ICollection<TKey> keys = region.GetLocalView().Keys;
byte[] value;
int valueSize;
if (keys != null)
{
foreach (TKey key in keys)
{
bool containsValue = region.ContainsValueForKey(key);
RegionEntry<TKey,TVal> entry = region.GetEntry(key);
if(!containsValue)
{
FwkInfo("Skipping check for key {0}",key);
}
else
{
if (entry == null)
{
FwkException("Failed to find entry for key [{0}] in local cache", key);
}
value = entry.Value as byte[];
if (value == null)
{
FwkException("Failed to find value for key [{0}] in local cache", key);
}
valueSize = (value == null ? -1 : value.Length);
if (valueSize == payload)
{
++countUpdate;
}
}
GC.KeepAlive(entry);
}
}
if (countUpdate != numOfRegisterKeys)
{
FwkException("DoVerifyInterestList() update interest list " +
"count {0} is not equal to number of register keys {1}",
countUpdate, numOfRegisterKeys);
}
}
catch (Exception ex)
{
FwkException("DoVerifyInterestList() Caught Exception: {0} : {1}",ex.GetType().Name, ex);
}
FwkInfo("DoVerifyInterestList() complete.");
}
public void DoRegisterRegexList()
{
FwkInfo("In DoRegisterRegexList()");
try
{
IRegion<TKey,TVal> region = GetRegion();
string regex = GetStringValue(RegisterRegex);
FwkInfo("DoRegisterRegexList() region name is {0}; regex is {1}",
region.Name, regex);
bool isDurable = GetBoolValue("isDurableReg");
ResetKey("getInitialValues");
bool isGetInitialValues = GetBoolValue("getInitialValues");
bool isReceiveValues = true;
bool checkReceiveVal = GetBoolValue("checkReceiveVal");
if (checkReceiveVal)
{
ResetKey("receiveValue");
isReceiveValues = GetBoolValue("receiveValue");
}
region.GetSubscriptionService().RegisterRegex(regex, isDurable, isGetInitialValues, isReceiveValues);
String durableClientId = CacheHelper<TKey, TVal>.DCache.DistributedSystem.SystemProperties.DurableClientId;
if (durableClientId.Length > 0)
{
CacheHelper<TKey, TVal>.DCache.ReadyForEvents();
}
}
catch (Exception ex)
{
FwkException("DoRegisterRegexList() Caught Exception: {0}", ex);
}
FwkInfo("DoRegisterRegexList() complete.");
}
public void DoUnRegisterRegexList()
{
FwkInfo("In DoUnRegisterRegexList()");
try
{
IRegion<TKey,TVal> region = GetRegion();
string regex = GetStringValue(UnregisterRegex);
FwkInfo("DoUnRegisterRegexList() region name is {0}; regex is {1}",
region.Name, regex);
region.GetSubscriptionService().UnregisterRegex(regex);
}
catch (Exception ex)
{
FwkException("DoUnRegisterRegexList() Caught Exception: {0}", ex);
}
FwkInfo("DoUnRegisterRegexList() complete.");
}
public void DoDestroysKeys()
{
FwkInfo("In PerfTest::DoDestroyKeys()");
try
{
IRegion<TKey,TVal> region=GetRegion();
ResetKey("distinctKeys");
InitValues(InitKeys());
DestroyTask<TKey, TVal> destroys = new DestroyTask<TKey, TVal>(region, m_keysA);
RunTask(destroys,1,m_maxKeys,-1,-1,null);
}
catch(Exception e)
{
FwkException("PerfTest caught exception: {0}", e);
}
FwkInfo("In PerfTest::DoDestroyKeys()complete");
}
public void DoServerKeys()
{
FwkInfo("In DoServerKeys()");
try
{
IRegion<TKey,TVal> region = GetRegion();
FwkAssert(region != null,
"DoServerKeys() No region to perform operations on.");
FwkInfo("DoServerKeys() region name is {0}", region.Name);
int expectedKeys = GetUIntValue(ExpectedCount);
ICollection<TKey> serverKeys = region.Keys;
int foundKeys = (serverKeys == null ? 0 : serverKeys.Count);
FwkAssert(expectedKeys == foundKeys,
"DoServerKeys() expected {0} keys but found {1} keys.",
expectedKeys, foundKeys);
}
catch (Exception ex)
{
FwkException("DoServerKeys() Caught Exception: {0}", ex);
}
FwkInfo("DoServerKeys() complete.");
}
public void DoIterateInt32Keys()
{
FwkInfo("DoIterateInt32Keys() called.");
try
{
IRegion<TKey,TVal> region = GetRegion();
FwkAssert(region != null,
"DoIterateInt32Keys() No region to perform operations on.");
FwkInfo("DoIterateInt32Keys() region name is {0}", region.Name);
ICollection<TKey> serverKeys = region.Keys;
FwkInfo("DoIterateInt32Keys() GetServerKeys() returned {0} keys.",
(serverKeys != null ? serverKeys.Count : 0));
if (serverKeys != null)
{
foreach (TKey intKey in serverKeys)
{
FwkInfo("ServerKeys: {0}", intKey);
}
}
}
catch (Exception ex)
{
FwkException("DoIterateInt32Keys() Caught Exception: {0}", ex);
}
FwkInfo("DoIterateInt32Keys() complete.");
}
public void DoValidateQConflation()
{
FwkInfo("DoValidateQConflation() called.");
try
{
IRegion<TKey,TVal> region = GetRegion();
region.GetLocalView().DestroyRegion();
int expectedAfterCreateEvent = GetUIntValue("expectedAfterCreateCount");
int expectedAfterUpdateEvent = GetUIntValue("expectedAfterUpdateCount");
bool isServerConflateTrue = GetBoolValue("isServerConflateTrue");
Int32 eventAfterCreate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_CREATE_COUNT_" + Util.ClientId + "_" + region.Name);
Int32 eventAfterUpdate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_UPDATE_COUNT_" + Util.ClientId + "_" + region.Name);
FwkInfo("DoValidateQConflation() -- eventAfterCreate {0} and eventAfterUpdate {1}", eventAfterCreate, eventAfterUpdate);
String conflateEvent = CacheHelper<TKey, TVal>.DCache.DistributedSystem.SystemProperties.ConflateEvents;
String durableClientId = CacheHelper<TKey, TVal>.DCache.DistributedSystem.SystemProperties.DurableClientId;
Int32 totalCount = 3500;
if(durableClientId.Length > 0) {
FwkInfo("DoValidateQConflation() Validation for Durable client .");
if (conflateEvent.Equals("true") && ((eventAfterCreate + eventAfterUpdate) < totalCount +10))
{
FwkInfo("DoValidateQConflation() Conflate Events is true complete.");
}
else if (conflateEvent.Equals("false") && ((eventAfterCreate + eventAfterUpdate) == totalCount +10))
{
FwkInfo("DoValidateQConflation() Conflate Events is false complete.");
}
else if (conflateEvent.Equals("server") && isServerConflateTrue && ((eventAfterCreate + eventAfterUpdate) <= totalCount + 10))
{
FwkInfo("DoValidateQConflation() Conflate Events is server=true complete.");
}
else if (conflateEvent.Equals("server") && !isServerConflateTrue && ((eventAfterCreate + eventAfterUpdate) == totalCount + 10))
{
FwkInfo("DoValidateQConflation() Conflate Events is server=false complete.");
}
else
{
FwkException("DoValidateQConflation() ConflateEvent setting is {0} and Expected AfterCreateCount to have {1} keys and " +
" found {2} . Expected AfterUpdateCount to have {3} keys, found {4} keys", conflateEvent, expectedAfterCreateEvent
, eventAfterCreate, expectedAfterUpdateEvent, eventAfterUpdate);
}
}
else {
if (conflateEvent.Equals("true") && ((eventAfterCreate == expectedAfterCreateEvent) &&
(((eventAfterUpdate >= expectedAfterUpdateEvent)) && eventAfterUpdate < totalCount)))
{
FwkInfo("DoValidateQConflation() Conflate Events is true complete.");
}
else if (conflateEvent.Equals("false") && ((eventAfterCreate == expectedAfterCreateEvent) &&
(eventAfterUpdate == expectedAfterUpdateEvent)))
{
FwkInfo("DoValidateQConflation() Conflate Events is false complete.");
}
else if (conflateEvent.Equals("server") && isServerConflateTrue && ((eventAfterCreate == expectedAfterCreateEvent) &&
(((eventAfterUpdate >= expectedAfterUpdateEvent)) && eventAfterUpdate < totalCount)))
{
FwkInfo("DoValidateQConflation() Conflate Events is server=true complete.");
}
else if (conflateEvent.Equals("server") && !isServerConflateTrue && ((eventAfterCreate == expectedAfterCreateEvent) &&
(eventAfterUpdate == expectedAfterUpdateEvent)))
{
FwkInfo("DoValidateQConflation() Conflate Events is server=false complete.");
}
else
{
FwkException("DoValidateQConflation() ConflateEvent setting is {0} and Expected AfterCreateCount to have {1} keys and " +
" found {2} . Expected AfterUpdateCount to have {3} keys, found {4} keys" , conflateEvent,expectedAfterCreateEvent
, eventAfterCreate,expectedAfterUpdateEvent, eventAfterUpdate);
}
}
}
catch (Exception ex)
{
FwkException("DoValidateQConflation() Caught Exception: {0}", ex);
}
FwkInfo("DoValidateQConflation() complete.");
}
public void DoCreateUpdateDestroy()
{
FwkInfo("DoCreateUpdateDestroy() called.");
try
{
DoPopulateRegion();
DoPopulateRegion();
DoDestroysKeys();
}
catch (Exception ex)
{
FwkException("DoCreateUpdateDestroy() Caught Exception: {0}", ex);
}
FwkInfo("DoCreateUpdateDestroy() complete.");
}
public void DoValidateBankTest()
{
FwkInfo("DoValidateBankTest() called.");
try
{
IRegion<TKey,TVal> region = GetRegion();
region.GetLocalView().DestroyRegion();
int expectedAfterCreateEvent = GetUIntValue("expectedAfterCreateCount");
int expectedAfterUpdateEvent = GetUIntValue("expectedAfterUpdateCount");
int expectedAfterInvalidateEvent = GetUIntValue("expectedAfterInvalidateCount");
int expectedAfterDestroyEvent = GetUIntValue("expectedAfterDestroyCount");
Int32 eventAfterCreate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_CREATE_COUNT_" + Util.ClientId + "_" + region.Name);
Int32 eventAfterUpdate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_UPDATE_COUNT_" + Util.ClientId + "_" + region.Name);
Int32 eventAfterInvalidate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_INVALIDATE_COUNT_" + Util.ClientId + "_" + region.Name);
Int32 eventAfterDestroy = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_DESTROY_COUNT_" + Util.ClientId + "_" + region.Name);
FwkInfo("DoValidateBankTest() -- eventAfterCreate {0} ,eventAfterUpdate {1} ," +
"eventAfterInvalidate {2} , eventAfterDestroy {3}", eventAfterCreate, eventAfterUpdate,eventAfterInvalidate,eventAfterDestroy);
if (expectedAfterCreateEvent == eventAfterCreate && expectedAfterUpdateEvent == eventAfterUpdate &&
expectedAfterInvalidateEvent == eventAfterInvalidate && expectedAfterDestroyEvent == eventAfterDestroy)
{
FwkInfo("DoValidateBankTest() Validation success.");
}
else
{
FwkException("Validation Failed() Region: {0} eventAfterCreate {1}, eventAfterUpdate {2} " +
"eventAfterInvalidate {3}, eventAfterDestroy {4} ",region.Name, eventAfterCreate, eventAfterUpdate
, eventAfterInvalidate, eventAfterDestroy);
}
}
catch (Exception ex)
{
FwkException("DoValidateBankTest() Caught Exception: {0}", ex);
}
FwkInfo("DoValidateBankTest() complete.");
}
#endregion
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Autodesk.Revit;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.DoorSwing.CS
{
/// <summary>
/// The DoorGeometry object is used to transform Revit geometry data
/// to appropriate format for GDI.
/// </summary>
public class DoorGeometry
{
#region "Members"
// User preferences for parsing of geometry.
Options m_options;
// boundingBox of the geometry.
BoundingBoxXYZ m_bbox;
// curves can represent the wireFrame of the door's geometry.
List<List<XYZ>> m_curve3Ds = new List<List<XYZ>>();
#endregion
#region "Properties"
/// <summary>
/// BoundingBox of the 2D geometry.
/// </summary>
public System.Drawing.RectangleF BBOX2D
{
get
{
return new System.Drawing.RectangleF((float)m_bbox.Min.X, (float)m_bbox.Min.Y,
(float)(m_bbox.Max.X - m_bbox.Min.X), (float)(m_bbox.Max.Y - m_bbox.Min.Y));
}
}
#endregion
#region "Methods"
/// <summary>
/// construct function.
/// </summary>
/// <param name="door">of which geometry data is wanted.</param>
public DoorGeometry(Autodesk.Revit.DB.Element door)
{
m_options = new Options();
m_options.View = GetPlanform2DView(door);
m_options.ComputeReferences = false;
Autodesk.Revit.DB.GeometryElement geoEle = door.get_Geometry(m_options);
AddGeometryElement(geoEle);
m_bbox = door.get_BoundingBox(m_options.View);
}
/// <summary>
/// Draw the line contains in m_curve3Ds in 2d Preview.Drawn as top view.
/// </summary>
/// <param name="graphics">Graphics to draw</param>
/// <param name="drawPen">The pen to draw curves.</param>
public void DrawGraphics(System.Drawing.Graphics graphics, System.Drawing.Pen drawPen)
{
for (int i = 0; i < m_curve3Ds.Count; i++)
{
List<XYZ> points = m_curve3Ds[i];
for (int j = 0; j < (points.Count - 1); j++)
{
// ignore xyz.Z value, drawn as top view.
System.Drawing.PointF startPoint = new System.Drawing.PointF((float)points[j].X, (float)points[j].Y);
System.Drawing.PointF endPoint = new System.Drawing.PointF((float)points[j + 1].X, (float)points[j + 1].Y);
graphics.DrawLine(drawPen, startPoint, endPoint);
}
}
}
/// <summary>
/// Retrieve the ViewPlan corresponding to the door's level.
/// </summary>
/// <param name="door">
/// one door whose level is corresponding to the retrieved ViewPlan.
/// </param>
/// <returns>One ViewPlan</returns>
static private ViewPlan GetPlanform2DView(Autodesk.Revit.DB.Element door)
{
IEnumerable<ViewPlan> viewPlans = from elem in
new FilteredElementCollector(door.Document).OfClass(typeof(ViewPlan)).ToElements()
let viewPlan = elem as ViewPlan
where viewPlan != null && !viewPlan.IsTemplate && viewPlan.GenLevel.Id.IntegerValue == door.Level.Id.IntegerValue
select viewPlan;
if (viewPlans.Count() > 0)
{
return viewPlans.First();
}
else
return null;
}
/// <summary>
/// iterate GeometryObject in GeometryObjectArray and generate data accordingly.
/// </summary>
/// <param name="geoEle">a geometry object of element</param>
private void AddGeometryElement(Autodesk.Revit.DB.GeometryElement geoEle)
{
// get all geometric primitives contained in the Geometry Element
GeometryObjectArray geoObjArray = geoEle.Objects;
// iterate each Geometry Object and generate data accordingly.
foreach (GeometryObject geoObj in geoObjArray)
{
if (geoObj is Curve)
{
AddCurve(geoObj);
}
else if (geoObj is Edge)
{
AddEdge(geoObj);
}
else if (geoObj is Autodesk.Revit.DB.GeometryElement)
{
AddElement(geoObj);
}
else if (geoObj is Face)
{
AddFace(geoObj);
}
else if (geoObj is Autodesk.Revit.DB.GeometryInstance)
{
AddInstance(geoObj);
}
else if (geoObj is Mesh)
{
AddMesh(geoObj);
}
else if (geoObj is Profile)
{
AddProfile(geoObj);
}
else if (geoObj is Solid)
{
AddSolid(geoObj);
}
}
}
/// <summary>
/// generate data of a Curve.
/// </summary>
/// <param name="obj">a geometry object of element.</param>
private void AddCurve(GeometryObject obj)
{
Curve curve = obj as Curve;
if (!curve.IsBound)
{
return;
}
// get a polyline approximation to the curve.
List<XYZ> points = curve.Tessellate() as List<XYZ>;
m_curve3Ds.Add(points);
}
/// <summary>
/// generate data of an Edge.
/// </summary>
/// <param name="obj">a geometry object of element.</param>
private void AddEdge(GeometryObject obj)
{
Edge edge = obj as Edge;
// get a polyline approximation to the edge.
List<XYZ> points = edge.Tessellate() as List<XYZ>;
m_curve3Ds.Add(points);
}
/// <summary>
/// generate data of a Geometry Element.
/// </summary>
/// <param name="obj">a geometry object of element.</param>
private void AddElement(GeometryObject obj)
{
Autodesk.Revit.DB.GeometryElement geoEle = obj as Autodesk.Revit.DB.GeometryElement;
AddGeometryElement(geoEle);
}
/// <summary>
/// generate data of a Face.
/// </summary>
/// <param name="obj">a geometry object of element.</param>
private void AddFace(GeometryObject obj)
{
Face face = obj as Face;
// get a triangular mesh approximation to the face.
Mesh mesh = face.Triangulate();
if (null != mesh)
{
AddMesh(mesh);
}
}
/// <summary>
/// generate data of a Geometry Instance.
/// </summary>
/// <param name="obj">a geometry object of element.</param>
private void AddInstance(GeometryObject obj)
{
Autodesk.Revit.DB.GeometryInstance instance = obj as Autodesk.Revit.DB.GeometryInstance;
Autodesk.Revit.DB.GeometryElement geoElement = instance.SymbolGeometry;
AddGeometryElement(geoElement);
}
/// <summary>
/// generate data of a Mesh.
/// </summary>
/// <param name="obj">a geometry object of element.</param>
private void AddMesh(GeometryObject obj)
{
Mesh mesh = obj as Mesh;
List<XYZ> points = new List<XYZ>();
// get all triangles of the mesh.
for (int i = 0; i < mesh.NumTriangles; i++)
{
MeshTriangle trigangle = mesh.get_Triangle(i);
for (int j = 0; j < 3; j++)
{
// A vertex of the triangle.
Autodesk.Revit.DB.XYZ point = trigangle.get_Vertex(j);
double x = point.X;
double y = point.Y;
double z = point.Z;
points.Add(point);
}
Autodesk.Revit.DB.XYZ iniPoint = points[0];
points.Add(iniPoint);
m_curve3Ds.Add(points);
}
}
/// <summary>
/// generate data of a Profile.
/// </summary>
/// <param name="obj">a geometry object of element.</param>
private void AddProfile(GeometryObject obj)
{
Profile profile = obj as Profile;
// get the curves that make up the boundary of the profile.
CurveArray curves = profile.Curves;
foreach (Curve curve in curves)
{
AddCurve(curve);
}
}
/// <summary>
/// generate data of a Solid.
/// </summary>
/// <param name="obj">a geometry object of element.</param>
private void AddSolid(GeometryObject obj)
{
Solid solid = obj as Solid;
// get the faces that belong to the solid.
FaceArray faces = solid.Faces;
foreach (Face face in faces)
{
AddFace(face);
}
}
#endregion
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Animation;
using Avalonia.Collections;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.VisualTree;
namespace Avalonia
{
/// <summary>
/// Base class for controls that provides rendering and related visual properties.
/// </summary>
/// <remarks>
/// The <see cref="Visual"/> class acts as a node in the Avalonia scene graph and holds
/// all the information needed for an <see cref="IRenderTarget"/> to render the control.
/// To traverse the scene graph (aka Visual Tree), use the extension methods defined
/// in <see cref="VisualExtensions"/>.
/// </remarks>
public class Visual : Animatable, IVisual
{
/// <summary>
/// Defines the <see cref="Bounds"/> property.
/// </summary>
public static readonly DirectProperty<Visual, Rect> BoundsProperty =
AvaloniaProperty.RegisterDirect<Visual, Rect>(nameof(Bounds), o => o.Bounds);
/// <summary>
/// Defines the <see cref="ClipToBounds"/> property.
/// </summary>
public static readonly StyledProperty<bool> ClipToBoundsProperty =
AvaloniaProperty.Register<Visual, bool>(nameof(ClipToBounds));
/// <summary>
/// Defines the <see cref="Clip"/> property.
/// </summary>
public static readonly StyledProperty<Geometry> ClipProperty =
AvaloniaProperty.Register<Visual, Geometry>(nameof(Clip));
/// <summary>
/// Defines the <see cref="IsVisibleProperty"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsVisibleProperty =
AvaloniaProperty.Register<Visual, bool>(nameof(IsVisible), true);
/// <summary>
/// Defines the <see cref="Opacity"/> property.
/// </summary>
public static readonly StyledProperty<double> OpacityProperty =
AvaloniaProperty.Register<Visual, double>(nameof(Opacity), 1);
/// <summary>
/// Defines the <see cref="OpacityMask"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> OpacityMaskProperty =
AvaloniaProperty.Register<Visual, IBrush>(nameof(OpacityMask));
/// <summary>
/// Defines the <see cref="RenderTransform"/> property.
/// </summary>
public static readonly StyledProperty<Transform> RenderTransformProperty =
AvaloniaProperty.Register<Visual, Transform>(nameof(RenderTransform));
/// <summary>
/// Defines the <see cref="RenderTransformOrigin"/> property.
/// </summary>
public static readonly StyledProperty<RelativePoint> RenderTransformOriginProperty =
AvaloniaProperty.Register<Visual, RelativePoint>(nameof(RenderTransformOrigin), defaultValue: RelativePoint.Center);
/// <summary>
/// Defines the <see cref="IVisual.VisualParent"/> property.
/// </summary>
public static readonly DirectProperty<Visual, IVisual> VisualParentProperty =
AvaloniaProperty.RegisterDirect<Visual, IVisual>("VisualParent", o => o._visualParent);
/// <summary>
/// Defines the <see cref="ZIndex"/> property.
/// </summary>
public static readonly StyledProperty<int> ZIndexProperty =
AvaloniaProperty.Register<Visual, int>(nameof(ZIndex));
private Rect _bounds;
private IVisual _visualParent;
/// <summary>
/// Initializes static members of the <see cref="Visual"/> class.
/// </summary>
static Visual()
{
AffectsRender(BoundsProperty, IsVisibleProperty, OpacityProperty);
RenderTransformProperty.Changed.Subscribe(RenderTransformChanged);
}
/// <summary>
/// Initializes a new instance of the <see cref="Visual"/> class.
/// </summary>
public Visual()
{
var visualChildren = new AvaloniaList<IVisual>();
visualChildren.ResetBehavior = ResetBehavior.Remove;
visualChildren.Validate = ValidateVisualChild;
visualChildren.CollectionChanged += VisualChildrenChanged;
VisualChildren = visualChildren;
}
/// <summary>
/// Raised when the control is attached to a rooted visual tree.
/// </summary>
public event EventHandler<VisualTreeAttachmentEventArgs> AttachedToVisualTree;
/// <summary>
/// Raised when the control is detached from a rooted visual tree.
/// </summary>
public event EventHandler<VisualTreeAttachmentEventArgs> DetachedFromVisualTree;
/// <summary>
/// Gets the bounds of the scene graph node relative to its parent.
/// </summary>
public Rect Bounds
{
get { return _bounds; }
protected set { SetAndRaise(BoundsProperty, ref _bounds, value); }
}
/// <summary>
/// Gets a value indicating whether the scene graph node should be clipped to its bounds.
/// </summary>
public bool ClipToBounds
{
get { return GetValue(ClipToBoundsProperty); }
set { SetValue(ClipToBoundsProperty, value); }
}
/// <summary>
/// Gets or sets the geometry clip for this visual.
/// </summary>
public Geometry Clip
{
get { return GetValue(ClipProperty); }
set { SetValue(ClipProperty, value); }
}
/// <summary>
/// Gets a value indicating whether this scene graph node and all its parents are visible.
/// </summary>
public bool IsEffectivelyVisible
{
get { return this.GetSelfAndVisualAncestors().All(x => x.IsVisible); }
}
/// <summary>
/// Gets a value indicating whether this scene graph node is visible.
/// </summary>
public bool IsVisible
{
get { return GetValue(IsVisibleProperty); }
set { SetValue(IsVisibleProperty, value); }
}
/// <summary>
/// Gets the opacity of the scene graph node.
/// </summary>
public double Opacity
{
get { return GetValue(OpacityProperty); }
set { SetValue(OpacityProperty, value); }
}
/// <summary>
/// Gets the opacity mask of the scene graph node.
/// </summary>
public IBrush OpacityMask
{
get { return GetValue(OpacityMaskProperty); }
set { SetValue(OpacityMaskProperty, value); }
}
/// <summary>
/// Gets the render transform of the scene graph node.
/// </summary>
public Transform RenderTransform
{
get { return GetValue(RenderTransformProperty); }
set { SetValue(RenderTransformProperty, value); }
}
/// <summary>
/// Gets the transform origin of the scene graph node.
/// </summary>
public RelativePoint RenderTransformOrigin
{
get { return GetValue(RenderTransformOriginProperty); }
set { SetValue(RenderTransformOriginProperty, value); }
}
/// <summary>
/// Gets the Z index of the node.
/// </summary>
/// <remarks>
/// Controls with a higher <see cref="ZIndex"/> will appear in front of controls with
/// a lower ZIndex. If two controls have the same ZIndex then the control that appears
/// later in the containing element's children collection will appear on top.
/// </remarks>
public int ZIndex
{
get { return GetValue(ZIndexProperty); }
set { SetValue(ZIndexProperty, value); }
}
/// <summary>
/// Gets the control's visual children.
/// </summary>
protected IAvaloniaList<IVisual> VisualChildren
{
get;
private set;
}
/// <summary>
/// Gets the root of the visual tree, if the control is attached to a visual tree.
/// </summary>
protected IRenderRoot VisualRoot
{
get;
private set;
}
/// <summary>
/// Gets a value indicating whether this scene graph node is attached to a visual root.
/// </summary>
bool IVisual.IsAttachedToVisualTree => VisualRoot != null;
/// <summary>
/// Gets the scene graph node's child nodes.
/// </summary>
IAvaloniaReadOnlyList<IVisual> IVisual.VisualChildren => VisualChildren;
/// <summary>
/// Gets the scene graph node's parent node.
/// </summary>
IVisual IVisual.VisualParent => _visualParent;
/// <summary>
/// Gets the root of the visual tree, if the control is attached to a visual tree.
/// </summary>
IRenderRoot IVisual.VisualRoot => VisualRoot;
/// <summary>
/// Invalidates the visual and queues a repaint.
/// </summary>
public void InvalidateVisual()
{
VisualRoot?.RenderQueueManager?.InvalidateRender(this);
}
/// <summary>
/// Renders the visual to a <see cref="DrawingContext"/>.
/// </summary>
/// <param name="context">The drawing context.</param>
public virtual void Render(DrawingContext context)
{
Contract.Requires<ArgumentNullException>(context != null);
}
/// <summary>
/// Returns a transform that transforms the visual's coordinates into the coordinates
/// of the specified <paramref name="visual"/>.
/// </summary>
/// <param name="visual">The visual to translate the coordinates to.</param>
/// <returns>
/// A <see cref="Matrix"/> containing the transform or null if the visuals don't share a
/// common ancestor.
/// </returns>
public Matrix? TransformToVisual(IVisual visual)
{
var common = this.FindCommonVisualAncestor(visual);
if (common != null)
{
var thisOffset = GetOffsetFrom(common, this);
var thatOffset = GetOffsetFrom(common, visual);
return Matrix.CreateTranslation(-thatOffset) * Matrix.CreateTranslation(thisOffset);
}
return null;
}
/// <summary>
/// Indicates that a property change should cause <see cref="InvalidateVisual"/> to be
/// called.
/// </summary>
/// <param name="properties">The properties.</param>
/// <remarks>
/// This method should be called in a control's static constructor with each property
/// on the control which when changed should cause a redraw. This is similar to WPF's
/// FrameworkPropertyMetadata.AffectsRender flag.
/// </remarks>
protected static void AffectsRender(params AvaloniaProperty[] properties)
{
foreach (var property in properties)
{
property.Changed.Subscribe(AffectsRenderInvalidate);
}
}
/// <summary>
/// Calls the <see cref="OnAttachedToVisualTree(VisualTreeAttachmentEventArgs)"/> method
/// for this control and all of its visual descendents.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
Logger.Verbose(LogArea.Visual, this, "Attached to visual tree");
VisualRoot = e.Root;
if (RenderTransform != null)
{
RenderTransform.Changed += RenderTransformChanged;
}
OnAttachedToVisualTree(e);
if (VisualChildren != null)
{
foreach (Visual child in VisualChildren.OfType<Visual>())
{
child.OnAttachedToVisualTreeCore(e);
}
}
}
/// <summary>
/// Calls the <see cref="OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs)"/> method
/// for this control and all of its visual descendents.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
Logger.Verbose(LogArea.Visual, this, "Detached from visual tree");
VisualRoot = null;
if (RenderTransform != null)
{
RenderTransform.Changed -= RenderTransformChanged;
}
OnDetachedFromVisualTree(e);
if (VisualChildren != null)
{
foreach (Visual child in VisualChildren.OfType<Visual>())
{
child.OnDetachedFromVisualTreeCore(e);
}
}
}
/// <summary>
/// Called when the control is added to a visual tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
AttachedToVisualTree?.Invoke(this, e);
}
/// <summary>
/// Called when the control is removed from a visual tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
DetachedFromVisualTree?.Invoke(this, e);
}
/// <summary>
/// Called when the control's visual parent changes.
/// </summary>
/// <param name="oldParent">The old visual parent.</param>
/// <param name="newParent">The new visual parent.</param>
protected virtual void OnVisualParentChanged(IVisual oldParent, IVisual newParent)
{
RaisePropertyChanged(VisualParentProperty, oldParent, newParent, BindingPriority.LocalValue);
}
/// <summary>
/// Called when a property changes that should invalidate the visual.
/// </summary>
/// <param name="e">The event args.</param>
private static void AffectsRenderInvalidate(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as Visual)?.InvalidateVisual();
}
/// <summary>
/// Gets the visual offset from the specified ancestor.
/// </summary>
/// <param name="ancestor">The ancestor visual.</param>
/// <param name="visual">The visual.</param>
/// <returns>The visual offset.</returns>
private static Vector GetOffsetFrom(IVisual ancestor, IVisual visual)
{
var result = new Vector();
while (visual != ancestor)
{
result = new Vector(result.X + visual.Bounds.X, result.Y + visual.Bounds.Y);
visual = visual.VisualParent;
if (visual == null)
{
throw new ArgumentException("'visual' is not a descendent of 'ancestor'.");
}
}
return result;
}
/// <summary>
/// Called when a visual's <see cref="RenderTransform"/> changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void RenderTransformChanged(AvaloniaPropertyChangedEventArgs e)
{
var sender = e.Sender as Visual;
if (sender?.VisualRoot != null)
{
var oldValue = e.OldValue as Transform;
var newValue = e.NewValue as Transform;
if (oldValue != null)
{
oldValue.Changed -= sender.RenderTransformChanged;
}
if (newValue != null)
{
newValue.Changed += sender.RenderTransformChanged;
}
sender.InvalidateVisual();
}
}
/// <summary>
/// Ensures a visual child is not null and not already parented.
/// </summary>
/// <param name="c">The visual child.</param>
private static void ValidateVisualChild(IVisual c)
{
if (c == null)
{
throw new ArgumentNullException("Cannot add null to VisualChildren.");
}
if (c.VisualParent != null)
{
throw new InvalidOperationException("The control already has a visual parent.");
}
}
/// <summary>
/// Called when the <see cref="RenderTransform"/>'s <see cref="Transform.Changed"/> event
/// is fired.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void RenderTransformChanged(object sender, EventArgs e)
{
InvalidateVisual();
}
/// <summary>
/// Sets the visual parent of the Visual.
/// </summary>
/// <param name="value">The visual parent.</param>
private void SetVisualParent(Visual value)
{
if (_visualParent == value)
{
return;
}
var old = _visualParent;
_visualParent = value;
if (VisualRoot != null)
{
var e = new VisualTreeAttachmentEventArgs(VisualRoot);
OnDetachedFromVisualTreeCore(e);
}
if (_visualParent is IRenderRoot || _visualParent?.IsAttachedToVisualTree == true)
{
var root = this.GetVisualAncestors().OfType<IRenderRoot>().FirstOrDefault();
var e = new VisualTreeAttachmentEventArgs(root);
OnAttachedToVisualTreeCore(e);
}
OnVisualParentChanged(old, value);
}
/// <summary>
/// Called when the <see cref="VisualChildren"/> collection changes.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void VisualChildrenChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (Visual v in e.NewItems)
{
v.SetVisualParent(this);
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (Visual v in e.OldItems)
{
v.SetVisualParent(null);
}
break;
}
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Xml;
using Stetic.Wrapper;
namespace Stetic
{
public static class WidgetUtils
{
static Gdk.Atom steticAtom;
static int undoIdCount;
static Gdk.Pixbuf missingIcon;
static Gtk.Widget renderer;
public static Gdk.Atom ApplicationXSteticAtom {
get {
if (steticAtom == null)
steticAtom = Gdk.Atom.Intern ("application/x-stetic", false);
return steticAtom;
}
}
public static XmlElement ExportWidget (Gtk.Widget widget)
{
XmlDocument doc = new XmlDocument ();
Stetic.Wrapper.Widget wrapper = Stetic.Wrapper.Widget.Lookup (widget);
if (wrapper == null)
throw new InvalidOperationException ();
XmlElement elem = wrapper.Write (new ObjectWriter (doc, FileFormat.Native));
doc.AppendChild (elem);
return doc.DocumentElement;
}
public static Gtk.Widget ImportWidget (IProject project, XmlElement element)
{
ObjectReader reader = new ObjectReader (project, FileFormat.Native);
ObjectWrapper wrapper = Stetic.ObjectWrapper.ReadObject (reader, element);
return wrapper.Wrapped as Gtk.Widget;
}
public static XmlElement Write (ObjectWrapper wrapper, XmlDocument doc)
{
ClassDescriptor klass = wrapper.ClassDescriptor;
XmlElement elem = doc.CreateElement ("widget");
elem.SetAttribute ("class", klass.Name);
elem.SetAttribute ("id", ((Gtk.Widget)wrapper.Wrapped).Name);
GetProps (wrapper, elem);
GetSignals (wrapper, elem);
return elem;
}
public static void GetProps (ObjectWrapper wrapper, XmlElement parent_elem)
{
ClassDescriptor klass = wrapper.ClassDescriptor;
foreach (ItemGroup group in klass.ItemGroups) {
foreach (ItemDescriptor item in group) {
PropertyDescriptor prop = item as PropertyDescriptor;
if (prop == null)
continue;
if (!prop.VisibleFor (wrapper.Wrapped) || !prop.CanWrite || prop.Name == "Name") // Name is written in the id attribute
continue;
object value = prop.GetValue (wrapper.Wrapped);
// If the property has its default value, we don't need to write it
if (value == null || (prop.HasDefault && prop.IsDefaultValue (value)))
continue;
string val = prop.ValueToString (value);
if (val == null)
continue;
XmlElement prop_elem = parent_elem.OwnerDocument.CreateElement ("property");
prop_elem.SetAttribute ("name", prop.Name);
if (val.Length > 0)
prop_elem.InnerText = val;
if (prop.Translatable && prop.IsTranslated (wrapper.Wrapped)) {
prop_elem.SetAttribute ("translatable", "yes");
string tcx = prop.TranslationContext (wrapper.Wrapped);
if (tcx != null && tcx.Length > 0) {
prop_elem.SetAttribute ("context", "yes");
prop_elem.InnerText = tcx + "|" + prop_elem.InnerText;
}
string tcm = prop.TranslationComment (wrapper.Wrapped);
if (tcm != null && tcm.Length > 0)
prop_elem.SetAttribute ("comments", prop.TranslationComment (wrapper.Wrapped));
}
parent_elem.AppendChild (prop_elem);
}
}
}
public static void GetSignals (ObjectWrapper ob, XmlElement parent_elem)
{
foreach (Signal signal in ob.Signals) {
if (!signal.SignalDescriptor.VisibleFor (ob.Wrapped))
continue;
XmlElement signal_elem = parent_elem.OwnerDocument.CreateElement ("signal");
signal_elem.SetAttribute ("name", signal.SignalDescriptor.Name);
signal_elem.SetAttribute ("handler", signal.Handler);
if (signal.After)
signal_elem.SetAttribute ("after", "yes");
parent_elem.AppendChild (signal_elem);
}
}
static public void Read (ObjectWrapper wrapper, XmlElement elem)
{
string className = elem.GetAttribute ("class");
if (className == null)
throw new GladeException ("<widget> node with no class name");
ClassDescriptor klass = Registry.LookupClassByName (className);
if (klass == null)
throw new GladeException ("No stetic ClassDescriptor for " + className);
Gtk.Widget widget = (Gtk.Widget) wrapper.Wrapped;
if (widget == null) {
widget = (Gtk.Widget) klass.CreateInstance (wrapper.Project);
ObjectWrapper.Bind (wrapper.Project, klass, wrapper, widget, true);
}
widget.Name = elem.GetAttribute ("id");
ReadMembers (klass, wrapper, widget, elem);
if (!(widget is Gtk.Window))
widget.ShowAll ();
}
public static void ReadMembers (ClassDescriptor klass, ObjectWrapper wrapper, object wrapped, XmlElement elem)
{
foreach (XmlNode node in elem.ChildNodes) {
XmlElement child = node as XmlElement;
if (child == null)
continue;
if (child.LocalName == "signal")
ReadSignal (klass, wrapper, child);
else if (child.LocalName == "property")
ReadProperty (klass, wrapper, wrapped, child);
}
}
public static void ReadSignal (ClassDescriptor klass, ObjectWrapper ob, XmlElement elem)
{
string name = elem.GetAttribute ("name");
SignalDescriptor signal = klass.SignalGroups.GetItem (name) as SignalDescriptor;
if (signal != null) {
string handler = elem.GetAttribute ("handler");
bool after = elem.GetAttribute ("after") == "yes";
ob.Signals.Add (new Signal (signal, handler, after));
}
}
public static void ReadProperty (ClassDescriptor klass, ObjectWrapper wrapper, object wrapped, XmlElement prop_node)
{
string name = prop_node.GetAttribute ("name");
PropertyDescriptor prop = klass [name] as PropertyDescriptor;
if (prop == null || !prop.CanWrite)
return;
string strval = prop_node.InnerText;
// Skip translation context
if (prop_node.GetAttribute ("context") == "yes" && strval.IndexOf ('|') != -1)
strval = strval.Substring (strval.IndexOf ('|') + 1);
object value = prop.StringToValue (strval);
prop.SetValue (wrapped, value);
if (prop.Translatable) {
if (prop_node.GetAttribute ("translatable") != "yes") {
prop.SetTranslated (wrapped, false);
}
else {
prop.SetTranslated (wrapped, true);
if (prop_node.GetAttribute ("context") == "yes") {
strval = prop_node.InnerText;
int bar = strval.IndexOf ('|');
if (bar != -1)
prop.SetTranslationContext (wrapped, strval.Substring (0, bar));
}
if (prop_node.HasAttribute ("comments"))
prop.SetTranslationComment (wrapped, prop_node.GetAttribute ("comments"));
}
}
}
static public void SetPacking (Stetic.Wrapper.Container.ContainerChild wrapper, XmlElement child_elem)
{
XmlElement packing = child_elem["packing"];
if (packing == null)
return;
Gtk.Container.ContainerChild cc = wrapper.Wrapped as Gtk.Container.ContainerChild;
ClassDescriptor klass = wrapper.ClassDescriptor;
ReadMembers (klass, wrapper, cc, packing);
}
internal static XmlElement CreatePacking (XmlDocument doc, Stetic.Wrapper.Container.ContainerChild childwrapper)
{
XmlElement packing_elem = doc.CreateElement ("packing");
WidgetUtils.GetProps (childwrapper, packing_elem);
return packing_elem;
}
public static void Copy (Gtk.Widget widget, Gtk.SelectionData seldata, bool copyAsText)
{
XmlElement elem = ExportWidget (widget);
if (elem == null)
return;
if (copyAsText)
seldata.Text = elem.OuterXml;
else
seldata.Set (ApplicationXSteticAtom, 8, System.Text.Encoding.UTF8.GetBytes (elem.OuterXml));
}
public static Stetic.Wrapper.Widget Paste (IProject project, Gtk.SelectionData seldata)
{
if (seldata == null || seldata.Type == null || seldata.Type.Name != ApplicationXSteticAtom.Name)
return null;
string data = System.Text.Encoding.UTF8.GetString (seldata.Data);
XmlDocument doc = new XmlDocument ();
doc.PreserveWhitespace = true;
try {
doc.LoadXml (data);
} catch {
return null;
}
Gtk.Widget w = ImportWidget (project, doc.DocumentElement);
return Wrapper.Widget.Lookup (w);
}
public static IDesignArea GetDesignArea (Gtk.Widget w)
{
while (w != null && !(w is IDesignArea))
w = w.Parent;
return w as IDesignArea;
}
internal static void ParseWidgetName (string name, out string baseName, out int idx)
{
// Extract a numerical suffix from the name
// If suffix has more than 4 digits, only the last 4 digits are considered
// a numerical suffix.
int n;
for (n = name.Length - 1; n >= name.Length-4 && n >= 0 && char.IsDigit (name [n]); n--)
;
if (n < name.Length - 1) {
baseName = name.Substring (0, n + 1);
idx = int.Parse (name.Substring (n + 1));
} else {
baseName = name;
idx = 0;
}
}
internal static string GetUndoId ()
{
return (undoIdCount++).ToString ();
}
public static Gdk.Pixbuf MissingIcon {
get {
if (missingIcon == null) {
try {
missingIcon = Gtk.IconTheme.Default.LoadIcon ("gtk-missing-image", 16, 0);
} catch {}
if (missingIcon == null)
missingIcon = Gdk.Pixbuf.LoadFromResource ("missing.png");
}
return missingIcon;
}
}
public static string AbsoluteToRelativePath (string baseDirectoryPath, string absPath)
{
if (! Path.IsPathRooted (absPath))
return absPath;
absPath = Path.GetFullPath (absPath);
baseDirectoryPath = Path.GetFullPath (baseDirectoryPath);
char[] separators = { Path.DirectorySeparatorChar, Path.VolumeSeparatorChar, Path.AltDirectorySeparatorChar };
baseDirectoryPath = baseDirectoryPath.TrimEnd (separators);
string[] bPath = baseDirectoryPath.Split (separators);
string[] aPath = absPath.Split (separators);
int indx = 0;
for(; indx < Math.Min(bPath.Length, aPath.Length); ++indx){
if(!bPath[indx].Equals(aPath[indx]))
break;
}
if (indx == 0) {
return absPath;
}
string erg = "";
if(indx == bPath.Length) {
erg += "." + Path.DirectorySeparatorChar;
} else {
for (int i = indx; i < bPath.Length; ++i) {
erg += ".." + Path.DirectorySeparatorChar;
}
}
erg += String.Join(Path.DirectorySeparatorChar.ToString(), aPath, indx, aPath.Length-indx);
return erg;
}
public static int CompareVersions (string v1, string v2)
{
string[] a1 = v1.Split ('.');
string[] a2 = v2.Split ('.');
for (int n=0; n<a1.Length; n++) {
if (n >= a2.Length)
return -1;
if (a1[n].Length == 0) {
if (a2[n].Length != 0)
return 1;
continue;
}
try {
int n1 = int.Parse (a1[n]);
int n2 = int.Parse (a2[n]);
if (n1 < n2)
return 1;
else if (n1 > n2)
return -1;
} catch {
return 1;
}
}
if (a2.Length > a1.Length)
return 1;
return 0;
}
public static Gdk.Pixbuf LoadIcon (string name, Gtk.IconSize size)
{
if (renderer == null)
renderer = new Gtk.HBox ();
Gdk.Pixbuf image = renderer.RenderIcon (name, size, null);
if (image != null)
return image;
int w, h;
Gtk.Icon.SizeLookup (size, out w, out h);
try {
return Gtk.IconTheme.Default.LoadIcon (name, w, 0);
} catch {
// Icon not in theme
return MissingIcon;
}
}
}
}
| |
using System;
using System.Linq;
namespace InjectMe
{
/// <summary>
/// Provides methods to explicitly resolve services in an <see cref="InjectMe.IContainer"/>.
/// </summary>
public class ServiceLocator : IServiceLocator
{
private readonly IContainer _container;
/// <summary>
/// Initializes a new instance of the ServiceLocator class using the specified <paramref name="container"/>.
/// </summary>
/// <param name="container">
/// The container to resolve services in.
/// </param>
public ServiceLocator(IContainer container)
{
_container = container;
}
/// <summary>
/// Resolves a service of type <paramref name="serviceType"/> with the specified <paramref name="serviceName"/>.
/// </summary>
/// <param name="serviceType">
/// The type of service to resolve.
/// </param>
/// <param name="serviceName">
/// The name of the service to resolve.
/// </param>
/// <returns>
/// An activated service.
/// </returns>
/// <exception cref="ServiceNotRegisteredException">
/// No service of the requested identity has been registered in the container.
/// </exception>
/// <remarks>
/// Returns the default service if no <paramref name="serviceName"/> is specified.
/// </remarks>
public object Resolve(Type serviceType, string serviceName)
{
var instance = TryResolve(serviceType, serviceName);
if (instance == null)
throw new ServiceNotRegisteredException(serviceType, serviceName);
return instance;
}
/// <summary>
/// Resolves a service of type <typeparamref name="T"/> with the specified <paramref name="serviceName"/>.
/// </summary>
/// <typeparam name="T">
/// The type of service to resolve.
/// </typeparam>
/// <param name="serviceName">
/// The name of the service to resolve.
/// </param>
/// <returns>
/// An activated service.
/// </returns>
/// <exception cref="ServiceNotRegisteredException">
/// No service of the requested identity has been registered in the container.
/// </exception>
/// <remarks>
/// Returns the default service if no <paramref name="serviceName"/> is specified.
/// </remarks>
public T Resolve<T>(string serviceName) where T : class
{
var serviceType = typeof(T);
var instance = (T)Resolve(serviceType, serviceName);
return instance;
}
/// <summary>
/// Resolves all services of type <paramref name="serviceType"/>.
/// </summary>
/// <param name="serviceType">
/// The type of service to resolve.
/// </param>
/// <returns>
/// An array of activated services.
/// </returns>
/// <exception cref="ServiceNotRegisteredException">
/// No service of the requested identity has been registered in the container.
/// </exception>
public object[] ResolveAll(Type serviceType)
{
var instances = _container.ResolveAll(serviceType);
if (instances == null)
throw new ServiceNotRegisteredException(serviceType);
return instances.ToArray();
}
/// <summary>
/// Resolves all services of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">
/// The type of service to resolve.
/// </typeparam>
/// <returns>
/// An array of activated services.
/// </returns>
/// <exception cref="ServiceNotRegisteredException">
/// No service of the requested identity has been registered in the container.
/// </exception>
public T[] ResolveAll<T>() where T : class
{
var serviceType = typeof(T);
var instances = _container.ResolveAll(serviceType);
if (instances == null)
throw new ServiceNotRegisteredException(serviceType);
return instances.
Cast<T>().
ToArray();
}
/// <summary>
/// Resolves a service of type <paramref name="serviceType"/> with the specified <paramref name="serviceName"/>.
/// </summary>
/// <param name="serviceType">
/// The type of service to resolve.
/// </param>
/// <param name="serviceName">
/// The name of the service to resolve.
/// </param>
/// <returns>
/// An ativated service, if one has been registered for the specified identity; otherwise null.
/// </returns>
/// <remarks>
/// Returns the default service if no <paramref name="serviceName"/> is specified.
/// </remarks>
public object TryResolve(Type serviceType, string serviceName)
{
var identity = new ServiceIdentity(serviceType, serviceName);
var instance = _container.Resolve(identity);
return instance;
}
/// <summary>
/// Resolves a service of type <typeparamref name="T"/> with the specified <paramref name="serviceName"/>.
/// </summary>
/// <typeparam name="T">
/// The type of service to resolve.
/// </typeparam>
/// <param name="serviceName">
/// The name of the service to resolve.
/// </param>
/// <returns>
/// An ativated service, if one has been registered for the specified identity; otherwise null.
/// </returns>
/// <remarks>
/// Returns the default service if no <paramref name="serviceName"/> is specified.
/// </remarks>
public T TryResolve<T>(string serviceName) where T : class
{
var serviceType = typeof(T);
var instance = (T)TryResolve(serviceType, serviceName);
return instance;
}
/// <summary>
/// Resolves all services of type <paramref name="serviceType"/>.
/// </summary>
/// <param name="serviceType">
/// The type of service to resolve.
/// </param>
/// <returns>
/// An array of activated services, if any has been registered for type <paramref name="serviceType"/>; otherwise an empty array.
/// </returns>
public object[] TryResolveAll(Type serviceType)
{
var instances = _container.ResolveAll(serviceType);
if (instances == null)
return new object[0];
return instances.ToArray();
}
/// <summary>
/// Resolves all services of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">
/// The type of service to resolve.
/// </typeparam>
/// <returns>
/// An array of activated services, if any has been registered for type <typeparamref name="T"/>; otherwise an empty array.
/// </returns>
public T[] TryResolveAll<T>() where T : class
{
var serviceType = typeof(T);
var instances = _container.ResolveAll(serviceType);
if (instances == null)
return new T[0];
return instances.
Cast<T>().
ToArray();
}
}
}
| |
using Machine.Specifications;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.TestCorrelator;
using System.Collections.Generic;
using System.Linq;
using It = Machine.Specifications.It;
namespace BellRichM.Logging.Test
{
public class LoggingAdapterSpecs
{
protected static LoggerAdapter<LoggingAdapterSpecs> loggerAdapter;
protected static ILogger logger;
protected static string message = "message {int} {string} {object}";
protected static object[] parameters;
protected static IEnumerable<LogEvent> logEvents;
Establish context = () =>
{
parameters = new object[]
{
1,
"foo",
new { intProperty = 108, stringProperty = "bar" }
};
logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Verbose()
.WriteTo.TestCorrelator()
.CreateLogger();
Log.Logger = logger;
loggerAdapter = new LoggerAdapter<LoggingAdapterSpecs>();
};
}
[Behaviors]
public class LogEventBehaviors
{
protected static IEnumerable<LogEvent> logEvents;
protected static object[] parameters;
protected static string message;
private static Dictionary<string, int> contextPropertiesCount = new Dictionary<string, int>()
{
{ "\"TRACE\"", 2 },
{ "\"DEBUG\"", 2 },
{ "\"INFORMATION\"", 2 },
{ "\"WARNING\"", 2 },
{ "\"CRITICAL\"", 2 },
{ "\"ERROR\"", 2 },
{ "\"EVENT\"", 4 }
};
It should_have_correct_message = () =>
{
foreach (var logEvent in logEvents)
{
logEvent.MessageTemplate.Text.ShouldEqual(message);
}
};
It should_have_correct_number_of_properties = () =>
{
foreach (var logEvent in logEvents)
{
var count = contextPropertiesCount[logEvent.Properties["Type"].ToString()];
logEvent.Properties.Count().ShouldEqual(parameters.Length + count);
}
};
It should_have_correct_SourceContext_property = () =>
{
foreach (var logEvent in logEvents)
{
logEvent.Properties["SourceContext"].ToString().ShouldEqual<string>("\"BellRichM.Logging.Test.LoggingAdapterSpecs\"");
}
};
}
public class When_logging_trace_message : LoggingAdapterSpecs
{
Because of = () =>
{
using (var testCorrelatorContext = TestCorrelator.CreateContext())
{
loggerAdapter.LogDiagnosticTrace(message, parameters);
logEvents = TestCorrelator.GetLogEventsFromContextGuid(testCorrelatorContext.Guid);
}
};
It should_have_one_log_event = () =>
logEvents.Count().ShouldEqual(1);
It should_have_correct_property = () =>
logEvents.First()
.Properties["Type"].ToString().ShouldEqual<string>("\"TRACE\"");
Behaves_like<LogEventBehaviors> a_event_log = () => { };
}
public class When_logging_debug_message : LoggingAdapterSpecs
{
Because of = () =>
{
using (var testCorrelatorContext = TestCorrelator.CreateContext())
{
loggerAdapter.LogDiagnosticDebug(message, parameters);
logEvents = TestCorrelator.GetLogEventsFromContextGuid(testCorrelatorContext.Guid);
}
};
It should_have_one_log_event = () =>
logEvents.Count().ShouldEqual(1);
It should_have_correct_property = () =>
logEvents.First()
.Properties["Type"].ToString().ShouldEqual<string>("\"DEBUG\"");
Behaves_like<LogEventBehaviors> a_event_log = () => { };
}
public class When_logging_informational_message : LoggingAdapterSpecs
{
Because of = () =>
{
using (var testCorrelatorContext = TestCorrelator.CreateContext())
{
loggerAdapter.LogDiagnosticInformation(message, parameters);
logEvents = TestCorrelator.GetLogEventsFromContextGuid(testCorrelatorContext.Guid);
}
};
It should_have_one_log_event = () =>
logEvents.Count().ShouldEqual(1);
It should_have_correct_property = () =>
logEvents.First()
.Properties["Type"].ToString().ShouldEqual<string>("\"INFORMATION\"");
Behaves_like<LogEventBehaviors> a_event_log = () => { };
}
public class When_logging_warning_message : LoggingAdapterSpecs
{
Because of = () =>
{
using (var testCorrelatorContext = TestCorrelator.CreateContext())
{
loggerAdapter.LogDiagnosticWarning(message, parameters);
logEvents = TestCorrelator.GetLogEventsFromContextGuid(testCorrelatorContext.Guid);
}
};
It should_have_one_log_event = () =>
logEvents.Count().ShouldEqual(1);
It should_have_correct_property = () =>
logEvents.First()
.Properties["Type"].ToString().ShouldEqual<string>("\"WARNING\"");
Behaves_like<LogEventBehaviors> a_event_log = () => { };
}
public class When_logging_critical_message : LoggingAdapterSpecs
{
Because of = () =>
{
using (var testCorrelatorContext = TestCorrelator.CreateContext())
{
loggerAdapter.LogDiagnosticCritical(message, parameters);
logEvents = TestCorrelator.GetLogEventsFromContextGuid(testCorrelatorContext.Guid);
}
};
It should_have_one_log_event = () =>
logEvents.Count().ShouldEqual(1);
It should_have_correct_property = () =>
logEvents.First()
.Properties["Type"].ToString().ShouldEqual<string>("\"CRITICAL\"");
Behaves_like<LogEventBehaviors> a_event_log = () => { };
}
public class When_logging_error_message : LoggingAdapterSpecs
{
Because of = () =>
{
using (var testCorrelatorContext = TestCorrelator.CreateContext())
{
loggerAdapter.LogDiagnosticError(message, parameters);
logEvents = TestCorrelator.GetLogEventsFromContextGuid(testCorrelatorContext.Guid);
}
};
It should_have_one_log_event = () =>
logEvents.Count().ShouldEqual(1);
It should_have_correct_property = () =>
{
var logEvent = logEvents.First();
logEvent.Properties["Type"].ToString().ShouldEqual<string>("\"ERROR\"");
};
Behaves_like<LogEventBehaviors> a_event_log = () => { };
}
public class When_logging_event_message : LoggingAdapterSpecs
{
Because of = () =>
{
using (var testCorrelatorContext = TestCorrelator.CreateContext())
{
loggerAdapter.LogEvent(EventId.EndRequest, message, parameters);
logEvents = TestCorrelator.GetLogEventsFromContextGuid(testCorrelatorContext.Guid);
}
};
It should_have_two_log_event = () =>
logEvents.Count().ShouldEqual(2);
It should_have_one_event_type_property = () =>
logEvents.Where(logEvent => logEvent.Properties["Type"].ToString() == "\"EVENT\"")
.Count().ShouldEqual(1);
It should_have_correct_id = () =>
{
var id = logEvents.Where(logEvent => logEvent.Properties["Type"].ToString() == "\"EVENT\"")
.First()
.Properties["Id"]
.ToString();
id.ShouldEqual(EventId.EndRequest.ToString("D"));
};
It should_have_correct_event = () =>
{
var eventName = logEvents.Where(logEvent => logEvent.Properties["Type"].ToString() == "\"EVENT\"")
.First()
.Properties["Event"]
.ToString();
eventName.ShouldEqual(EventId.EndRequest.ToString());
};
It should_have_one_information_type_property = () =>
logEvents.Where(logEvent => logEvent.Properties["Type"].ToString() == "\"INFORMATION\"")
.Count().ShouldEqual(1);
Behaves_like<LogEventBehaviors> a_event_log = () => { };
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
namespace OpenSim.Tests.Common
{
public class MockScriptEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
{
public IConfigSource ConfigSource { get; private set; }
public IConfig Config { get; private set; }
private Scene m_scene;
/// <summary>
/// Expose posted events to tests.
/// </summary>
public Dictionary<UUID, List<EventParams>> PostedEvents { get; private set; }
/// <summary>
/// A very primitive way of hooking text cose to a posed event.
/// </summary>
/// <remarks>
/// May be replaced with something that uses more original code in the future.
/// </remarks>
public event Action<UUID, EventParams> PostEventHook;
public void Initialise(IConfigSource source)
{
ConfigSource = source;
// Can set later on if required
Config = new IniConfig("MockScriptEngine", ConfigSource);
PostedEvents = new Dictionary<UUID, List<EventParams>>();
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.StackModuleInterface<IScriptModule>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
}
public string Name { get { return "Mock Script Engine"; } }
public string ScriptEngineName { get { return Name; } }
public Type ReplaceableInterface { get { return null; } }
public event ScriptRemoved OnScriptRemoved;
public event ObjectRemoved OnObjectRemoved;
public string GetXMLState (UUID itemID)
{
throw new System.NotImplementedException ();
}
public bool SetXMLState(UUID itemID, string xml)
{
throw new System.NotImplementedException ();
}
public bool PostScriptEvent(UUID itemID, string name, object[] args)
{
// Console.WriteLine("Posting event {0} for {1}", name, itemID);
return PostScriptEvent(itemID, new EventParams(name, args, null));
}
public bool PostScriptEvent(UUID itemID, EventParams evParams)
{
List<EventParams> eventsForItem;
if (!PostedEvents.ContainsKey(itemID))
{
eventsForItem = new List<EventParams>();
PostedEvents.Add(itemID, eventsForItem);
}
else
{
eventsForItem = PostedEvents[itemID];
}
eventsForItem.Add(evParams);
if (PostEventHook != null)
PostEventHook(itemID, evParams);
return true;
}
public bool PostObjectEvent(uint localID, EventParams evParams)
{
return PostObjectEvent(m_scene.GetSceneObjectPart(localID), evParams);
}
public bool PostObjectEvent(UUID itemID, string name, object[] args)
{
return PostObjectEvent(m_scene.GetSceneObjectPart(itemID), new EventParams(name, args, null));
}
private bool PostObjectEvent(SceneObjectPart part, EventParams evParams)
{
foreach (TaskInventoryItem item in part.Inventory.GetInventoryItems(InventoryType.LSL))
PostScriptEvent(item.ItemID, evParams);
return true;
}
public void SuspendScript(UUID itemID)
{
throw new System.NotImplementedException ();
}
public void ResumeScript(UUID itemID)
{
throw new System.NotImplementedException ();
}
public ArrayList GetScriptErrors(UUID itemID)
{
throw new System.NotImplementedException ();
}
public bool HasScript(UUID itemID, out bool running)
{
throw new System.NotImplementedException ();
}
public bool GetScriptState(UUID itemID)
{
throw new System.NotImplementedException ();
}
public void SaveAllState()
{
throw new System.NotImplementedException ();
}
public void StartProcessing()
{
throw new System.NotImplementedException ();
}
public float GetScriptExecutionTime(List<UUID> itemIDs)
{
throw new System.NotImplementedException ();
}
public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
{
throw new System.NotImplementedException ();
}
public IScriptWorkItem QueueEventHandler(object parms)
{
throw new System.NotImplementedException ();
}
public DetectParams GetDetectParams(UUID item, int number)
{
throw new System.NotImplementedException ();
}
public void SetMinEventDelay(UUID itemID, double delay)
{
throw new System.NotImplementedException ();
}
public int GetStartParameter(UUID itemID)
{
throw new System.NotImplementedException ();
}
public void SetScriptState(UUID itemID, bool state)
{
throw new System.NotImplementedException ();
}
public void SetState(UUID itemID, string newState)
{
throw new System.NotImplementedException ();
}
public void ApiResetScript(UUID itemID)
{
throw new System.NotImplementedException ();
}
public void ResetScript (UUID itemID)
{
throw new System.NotImplementedException ();
}
public IScriptApi GetApi(UUID itemID, string name)
{
throw new System.NotImplementedException ();
}
public Scene World { get { return m_scene; } }
public IScriptModule ScriptModule { get { return this; } }
public string ScriptEnginePath { get { throw new System.NotImplementedException (); }}
public string ScriptClassName { get { throw new System.NotImplementedException (); } }
public string ScriptBaseClassName { get { throw new System.NotImplementedException (); } }
public string[] ScriptReferencedAssemblies { get { throw new System.NotImplementedException (); } }
public ParameterInfo[] ScriptBaseClassParameters { get { throw new System.NotImplementedException (); } }
public void ClearPostedEvents()
{
PostedEvents.Clear();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Tests
{
public class EnvironmentTests : RemoteExecutorTestBase
{
[Fact]
public void CurrentDirectory_Null_Path_Throws_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null);
}
[Fact]
public void CurrentDirectory_Empty_Path_Throws_ArgumentException()
{
Assert.Throws<ArgumentException>("value", () => Environment.CurrentDirectory = string.Empty);
}
[Fact]
public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath());
}
[Fact]
public void CurrentDirectory_SetToValidOtherDirectory()
{
RemoteInvoke(() =>
{
Environment.CurrentDirectory = TestDirectory;
Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory);
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current
// directory to a symlinked path will result in GetCurrentDirectory returning the absolute
// path that followed the symlink.
Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void CurrentManagedThreadId_Idempotent()
{
Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId);
}
[Fact]
public void CurrentManagedThreadId_DifferentForActiveThreads()
{
var ids = new HashSet<int>();
Barrier b = new Barrier(10);
Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount)
select Task.Factory.StartNew(() =>
{
b.SignalAndWait();
lock (ids) ids.Add(Environment.CurrentManagedThreadId);
b.SignalAndWait();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
Assert.Equal(b.ParticipantCount, ids.Count);
}
[Fact]
public void HasShutdownStarted_FalseWhileExecuting()
{
Assert.False(Environment.HasShutdownStarted);
}
[Fact]
public void Is64BitProcess_MatchesIntPtrSize()
{
Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess);
}
[Fact]
public void Is64BitOperatingSystem_TrueIf64BitProcess()
{
if (Environment.Is64BitProcess)
{
Assert.True(Environment.Is64BitOperatingSystem);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess()
{
Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem);
}
[Fact]
public void OSVersion_Idempotent()
{
Assert.Same(Environment.OSVersion, Environment.OSVersion);
}
[Fact]
public void OSVersion_MatchesPlatform()
{
PlatformID id = Environment.OSVersion.Platform;
Assert.Equal(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix,
id);
}
[Fact]
public void OSVersion_ValidVersion()
{
Version version = Environment.OSVersion.Version;
string versionString = Environment.OSVersion.VersionString;
Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string");
Assert.True(version.Major > 0);
Assert.Contains(version.ToString(2), versionString);
Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString);
}
[Fact]
public void SystemPageSize_Valid()
{
int pageSize = Environment.SystemPageSize;
Assert.Equal(pageSize, Environment.SystemPageSize);
Assert.True(pageSize > 0, "Expected positive page size");
Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size");
}
[Fact]
public void UserInteractive_True()
{
Assert.True(Environment.UserInteractive);
}
[Fact]
public void UserName_Valid()
{
Assert.False(string.IsNullOrWhiteSpace(Environment.UserName));
}
[Fact]
public void UserDomainName_Valid()
{
Assert.False(string.IsNullOrWhiteSpace(Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void UserDomainName_Unix_MatchesMachineName()
{
Assert.Equal(Environment.MachineName, Environment.UserDomainName);
}
[Fact]
public void Version_MatchesFixedVersion()
{
Assert.Equal(new Version(4, 0, 30319, 42000), Environment.Version);
}
[Fact]
public void WorkingSet_Valid()
{
Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value");
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process
[OuterLoop]
[Fact]
public void FailFast_ExpectFailureExitCode()
{
using (Process p = RemoteInvoke(() => { Environment.FailFast("message"); return SuccessExitCode; }).Process)
{
p.WaitForExit();
Assert.NotEqual(SuccessExitCode, p.ExitCode);
}
using (Process p = RemoteInvoke(() => { Environment.FailFast("message", new Exception("uh oh")); return SuccessExitCode; }).Process)
{
p.WaitForExit();
Assert.NotEqual(SuccessExitCode, p.ExitCode);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile()
{
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal));
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
}
[Fact]
public void GetSystemDirectory()
{
Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory);
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment
[InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.Personal, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)]
// Not set on Unix (amongst others)
//[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)]
public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
Assert.NotEmpty(Environment.GetFolderPath(folder, option));
if (option == Environment.SpecialFolderOption.None)
{
Assert.NotEmpty(Environment.GetFolderPath(folder));
}
}
[Theory]
[PlatformSpecific(TestPlatforms.OSX)] // Tests OS-specific environment
[InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)]
[InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)]
[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)]
public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
Assert.NotEmpty(Environment.GetFolderPath(folder, option));
if (option == Environment.SpecialFolderOption.None)
{
Assert.NotEmpty(Environment.GetFolderPath(folder));
}
}
// The commented out folders aren't set on all systems.
[Theory]
[InlineData(Environment.SpecialFolder.ApplicationData)]
[InlineData(Environment.SpecialFolder.CommonApplicationData)]
[InlineData(Environment.SpecialFolder.LocalApplicationData)]
[InlineData(Environment.SpecialFolder.Cookies)]
[InlineData(Environment.SpecialFolder.Desktop)]
[InlineData(Environment.SpecialFolder.Favorites)]
[InlineData(Environment.SpecialFolder.History)]
[InlineData(Environment.SpecialFolder.InternetCache)]
[InlineData(Environment.SpecialFolder.Programs)]
// [InlineData(Environment.SpecialFolder.MyComputer)]
[InlineData(Environment.SpecialFolder.MyMusic)]
[InlineData(Environment.SpecialFolder.MyPictures)]
[InlineData(Environment.SpecialFolder.MyVideos)]
[InlineData(Environment.SpecialFolder.Recent)]
[InlineData(Environment.SpecialFolder.SendTo)]
[InlineData(Environment.SpecialFolder.StartMenu)]
[InlineData(Environment.SpecialFolder.Startup)]
[InlineData(Environment.SpecialFolder.System)]
[InlineData(Environment.SpecialFolder.Templates)]
[InlineData(Environment.SpecialFolder.DesktopDirectory)]
[InlineData(Environment.SpecialFolder.Personal)]
[InlineData(Environment.SpecialFolder.ProgramFiles)]
[InlineData(Environment.SpecialFolder.CommonProgramFiles)]
[InlineData(Environment.SpecialFolder.AdminTools)]
[InlineData(Environment.SpecialFolder.CDBurning)]
[InlineData(Environment.SpecialFolder.CommonAdminTools)]
[InlineData(Environment.SpecialFolder.CommonDocuments)]
[InlineData(Environment.SpecialFolder.CommonMusic)]
// [InlineData(Environment.SpecialFolder.CommonOemLinks)]
[InlineData(Environment.SpecialFolder.CommonPictures)]
[InlineData(Environment.SpecialFolder.CommonStartMenu)]
[InlineData(Environment.SpecialFolder.CommonPrograms)]
[InlineData(Environment.SpecialFolder.CommonStartup)]
[InlineData(Environment.SpecialFolder.CommonDesktopDirectory)]
[InlineData(Environment.SpecialFolder.CommonTemplates)]
[InlineData(Environment.SpecialFolder.CommonVideos)]
[InlineData(Environment.SpecialFolder.Fonts)]
[InlineData(Environment.SpecialFolder.NetworkShortcuts)]
// [InlineData(Environment.SpecialFolder.PrinterShortcuts)]
[InlineData(Environment.SpecialFolder.UserProfile)]
[InlineData(Environment.SpecialFolder.CommonProgramFilesX86)]
[InlineData(Environment.SpecialFolder.ProgramFilesX86)]
[InlineData(Environment.SpecialFolder.Resources)]
// [InlineData(Environment.SpecialFolder.LocalizedResources)]
[InlineData(Environment.SpecialFolder.SystemX86)]
[InlineData(Environment.SpecialFolder.Windows)]
[PlatformSpecific(TestPlatforms.Windows)] // Tests OS-specific environment
public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder)
{
string knownFolder = Environment.GetFolderPath(folder);
Assert.NotEmpty(knownFolder);
// Call the older folder API to compare our results.
char* buffer = stackalloc char[260];
SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer);
string folderPath = new string(buffer);
Assert.Equal(folderPath, knownFolder);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes
public void GetLogicalDrives_Unix_AtLeastOneIsRoot()
{
string[] drives = Environment.GetLogicalDrives();
Assert.NotNull(drives);
Assert.True(drives.Length > 0, "Expected at least one drive");
Assert.All(drives, d => Assert.NotNull(d));
Assert.Contains(drives, d => d == "/");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public void GetLogicalDrives_Windows_MatchesExpectedLetters()
{
string[] drives = Environment.GetLogicalDrives();
uint mask = (uint)GetLogicalDrives();
var bits = new BitArray(new[] { (int)mask });
Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length);
for (int bit = 0, d = 0; bit < bits.Length; bit++)
{
if (bits[bit])
{
Assert.Contains((char)('A' + bit), drives[d++]);
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int GetLogicalDrives();
[DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)]
internal static extern unsafe int SHGetFolderPathW(
IntPtr hwndOwner,
int nFolder,
IntPtr hToken,
uint dwFlags,
char* pszPath);
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using System.IO;
namespace Newtonsoft.Json.Tests.Linq
{
public class JTokenTests : TestFixtureBase
{
[Test]
public void ReadFrom()
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader("{'pie':true}")));
Assert.AreEqual(true, (bool)o["pie"]);
JArray a = (JArray)JToken.ReadFrom(new JsonTextReader(new StringReader("[1,2,3]")));
Assert.AreEqual(1, (int)a[0]);
Assert.AreEqual(2, (int)a[1]);
Assert.AreEqual(3, (int)a[2]);
JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}"));
reader.Read();
reader.Read();
JProperty p = (JProperty)JToken.ReadFrom(reader);
Assert.AreEqual("pie", p.Name);
Assert.AreEqual(true, (bool)p.Value);
JConstructor c = (JConstructor)JToken.ReadFrom(new JsonTextReader(new StringReader("new Date(1)")));
Assert.AreEqual("Date", c.Name);
Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0)));
JValue v;
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""stringvalue""")));
Assert.AreEqual("stringvalue", (string)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1")));
Assert.AreEqual(1, (int)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1.1")));
Assert.AreEqual(1.1, (double)v);
}
[Test]
public void Parent()
{
JArray v = new JArray(new JConstructor("TestConstructor"), new JValue(new DateTime(2000, 12, 20)));
Assert.AreEqual(null, v.Parent);
JObject o =
new JObject(
new JProperty("Test1", v),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", "Test3Value"),
new JProperty("Test4", null)
);
Assert.AreEqual(o.Property("Test1"), v.Parent);
JProperty p = new JProperty("NewProperty", v);
// existing value should still have same parent
Assert.AreEqual(o.Property("Test1"), v.Parent);
// new value should be cloned
Assert.AreNotSame(p.Value, v);
Assert.AreEqual((DateTime)((JValue)p.Value[1]).Value, (DateTime)((JValue)v[1]).Value);
Assert.AreEqual(v, o["Test1"]);
Assert.AreEqual(null, o.Parent);
JProperty o1 = new JProperty("O1", o);
Assert.AreEqual(o, o1.Value);
Assert.AreNotEqual(null, o.Parent);
JProperty o2 = new JProperty("O2", o);
Assert.AreNotSame(o1.Value, o2.Value);
Assert.AreEqual(o1.Value.Children().Count(), o2.Value.Children().Count());
Assert.AreEqual(false, JToken.DeepEquals(o1, o2));
Assert.AreEqual(true, JToken.DeepEquals(o1.Value, o2.Value));
}
[Test]
public void Next()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
JToken next = a[0].Next;
Assert.AreEqual(6, (int)next);
next = next.Next;
Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), next));
next = next.Next;
Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), next));
next = next.Next;
Assert.IsNull(next);
}
[Test]
public void Previous()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
JToken previous = a[3].Previous;
Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), previous));
previous = previous.Previous;
Assert.AreEqual(6, (int)previous);
previous = previous.Previous;
Assert.AreEqual(5, (int)previous);
previous = previous.Previous;
Assert.IsNull(previous);
}
[Test]
public void Children()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
Assert.AreEqual(4, a.Count());
Assert.AreEqual(3, a.Children<JArray>().Count());
}
[Test]
public void BeforeAfter()
{
JArray a =
new JArray(
5,
new JArray(1, 2, 3),
new JArray(1, 2, 3),
new JArray(1, 2, 3)
);
Assert.AreEqual(5, (int)a[1].Previous);
Assert.AreEqual(2, a[2].BeforeSelf().Count());
//Assert.AreEqual(2, a[2].AfterSelf().Count());
}
[Test]
public void Casting()
{
Assert.AreEqual(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20)));
#if !PocketPC && !NET20
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.AreEqual(null, (DateTimeOffset?)new JValue((DateTimeOffset?)null));
Assert.AreEqual(null, (DateTimeOffset?)(JValue)null);
#endif
Assert.AreEqual(true, (bool)new JValue(true));
Assert.AreEqual(true, (bool?)new JValue(true));
Assert.AreEqual(null, (bool?)((JValue)null));
Assert.AreEqual(null, (bool?)new JValue((object)null));
Assert.AreEqual(10, (long)new JValue(10));
Assert.AreEqual(null, (long?)new JValue((long?)null));
Assert.AreEqual(null, (long?)(JValue)null);
Assert.AreEqual(null, (int?)new JValue((int?)null));
Assert.AreEqual(null, (int?)(JValue)null);
Assert.AreEqual(null, (DateTime?)new JValue((DateTime?)null));
Assert.AreEqual(null, (DateTime?)(JValue)null);
Assert.AreEqual(null, (short?)new JValue((short?)null));
Assert.AreEqual(null, (short?)(JValue)null);
Assert.AreEqual(null, (float?)new JValue((float?)null));
Assert.AreEqual(null, (float?)(JValue)null);
Assert.AreEqual(null, (double?)new JValue((double?)null));
Assert.AreEqual(null, (double?)(JValue)null);
Assert.AreEqual(null, (decimal?)new JValue((decimal?)null));
Assert.AreEqual(null, (decimal?)(JValue)null);
Assert.AreEqual(null, (uint?)new JValue((uint?)null));
Assert.AreEqual(null, (uint?)(JValue)null);
Assert.AreEqual(null, (sbyte?)new JValue((sbyte?)null));
Assert.AreEqual(null, (sbyte?)(JValue)null);
Assert.AreEqual(null, (ulong?)new JValue((ulong?)null));
Assert.AreEqual(null, (ulong?)(JValue)null);
Assert.AreEqual(null, (uint?)new JValue((uint?)null));
Assert.AreEqual(null, (uint?)(JValue)null);
Assert.AreEqual(11.1f, (float)new JValue(11.1));
Assert.AreEqual(float.MinValue, (float)new JValue(float.MinValue));
Assert.AreEqual(1.1, (double)new JValue(1.1));
Assert.AreEqual(uint.MaxValue, (uint)new JValue(uint.MaxValue));
Assert.AreEqual(ulong.MaxValue, (ulong)new JValue(ulong.MaxValue));
Assert.AreEqual(ulong.MaxValue, (ulong)new JProperty("Test", new JValue(ulong.MaxValue)));
Assert.AreEqual(null, (string)new JValue((string)null));
Assert.AreEqual(5m, (decimal)(new JValue(5L)));
Assert.AreEqual(5m, (decimal?)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5m)));
Assert.AreEqual(5f, (float?)(new JValue(5m)));
byte[] data = new byte[0];
Assert.AreEqual(data, (byte[])(new JValue(data)));
Assert.AreEqual(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase)));
}
[Test]
public void ImplicitCastingTo()
{
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue)new DateTime(2000, 12, 20)));
#if !PocketPC && !NET20
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue)new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null));
#endif
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)(bool?)true));
Assert.IsTrue(JToken.DeepEquals(new JValue((bool?)null), (JValue)(bool?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(10), (JValue)10));
Assert.IsTrue(JToken.DeepEquals(new JValue((long?)null), (JValue)(long?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(long.MaxValue), (JValue)long.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((int?)null), (JValue)(int?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((short?)null), (JValue)(short?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((double?)null), (JValue)(double?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((uint?)null), (JValue)(uint?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((decimal?)null), (JValue)(decimal?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((ulong?)null), (JValue)(ulong?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte?)null), (JValue)(sbyte?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((ushort?)null), (JValue)(ushort?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((string)null), (JValue)(string)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)decimal.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)(decimal?)decimal.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MinValue), (JValue)decimal.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MaxValue), (JValue)(float?)float.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((object)null), (JValue)(double?)null));
Assert.IsFalse(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null));
Assert.IsFalse(JToken.DeepEquals(new JValue((object)null), (JValue)(object)null));
byte[] emptyData = new byte[0];
Assert.IsTrue(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData));
Assert.IsFalse(JToken.DeepEquals(new JValue(emptyData), (JValue)new byte[1]));
Assert.IsTrue(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi")));
}
[Test]
public void Root()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
Assert.AreEqual(a, a.Root);
Assert.AreEqual(a, a[0].Root);
Assert.AreEqual(a, ((JArray)a[2])[0].Root);
}
[Test]
public void Remove()
{
JToken t;
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
a[0].Remove();
Assert.AreEqual(6, (int)a[0]);
a[1].Remove();
Assert.AreEqual(6, (int)a[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), a[1]));
Assert.AreEqual(2, a.Count());
t = a[1];
t.Remove();
Assert.AreEqual(6, (int)a[0]);
Assert.IsNull(t.Next);
Assert.IsNull(t.Previous);
Assert.IsNull(t.Parent);
t = a[0];
t.Remove();
Assert.AreEqual(0, a.Count());
Assert.IsNull(t.Next);
Assert.IsNull(t.Previous);
Assert.IsNull(t.Parent);
}
[Test]
public void AfterSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1];
List<JToken> afterTokens = t.AfterSelf().ToList();
Assert.AreEqual(2, afterTokens.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2), afterTokens[0]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), afterTokens[1]));
}
[Test]
public void BeforeSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[2];
List<JToken> beforeTokens = t.BeforeSelf().ToList();
Assert.AreEqual(2, beforeTokens.Count);
Assert.IsTrue(JToken.DeepEquals(new JValue(5), beforeTokens[0]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1), beforeTokens[1]));
}
[Test]
public void HasValues()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
Assert.IsTrue(a.HasValues);
}
[Test]
public void Ancestors()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1][0];
List<JToken> ancestors = t.Ancestors().ToList();
Assert.AreEqual(2, ancestors.Count());
Assert.AreEqual(a[1], ancestors[0]);
Assert.AreEqual(a, ancestors[1]);
}
[Test]
public void Descendants()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
List<JToken> descendants = a.Descendants().ToList();
Assert.AreEqual(10, descendants.Count());
Assert.AreEqual(5, (int)descendants[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 4]));
Assert.AreEqual(1, (int)descendants[descendants.Count - 3]);
Assert.AreEqual(2, (int)descendants[descendants.Count - 2]);
Assert.AreEqual(3, (int)descendants[descendants.Count - 1]);
}
[Test]
public void CreateWriter()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JsonWriter writer = a.CreateWriter();
Assert.IsNotNull(writer);
Assert.AreEqual(4, a.Count());
writer.WriteValue("String");
Assert.AreEqual(5, a.Count());
Assert.AreEqual("String", (string)a[4]);
writer.WriteStartObject();
writer.WritePropertyName("Property");
writer.WriteValue("PropertyValue");
writer.WriteEnd();
Assert.AreEqual(6, a.Count());
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5]));
}
[Test]
public void AddFirst()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a.AddFirst("First");
Assert.AreEqual("First", (string)a[0]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(5, a.Count());
a.AddFirst("NewFirst");
Assert.AreEqual("NewFirst", (string)a[0]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(6, a.Count());
Assert.AreEqual(a[0], a[0].Next.Previous);
}
[Test]
public void RemoveAll()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken first = a.First;
Assert.AreEqual(5, (int)first);
a.RemoveAll();
Assert.AreEqual(0, a.Count());
Assert.IsNull(first.Parent);
Assert.IsNull(first.Next);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.")]
public void AddPropertyToArray()
{
JArray a = new JArray();
a.Add(new JProperty("PropertyName"));
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void AddValueToObject()
{
JObject o = new JObject();
o.Add(5);
}
[Test]
public void Replace()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[0].Replace(new JValue(int.MaxValue));
Assert.AreEqual(int.MaxValue, (int)a[0]);
Assert.AreEqual(4, a.Count());
a[1][0].Replace(new JValue("Test"));
Assert.AreEqual("Test", (string)a[1][0]);
a[2].Replace(new JValue(int.MaxValue));
Assert.AreEqual(int.MaxValue, (int)a[2]);
Assert.AreEqual(4, a.Count());
Assert.IsTrue(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a));
}
[Test]
public void ToStringWithConverters()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.Indented, new IsoDateTimeConverter());
Assert.AreEqual(@"[
""2009-02-15T00:00:00Z""
]", json);
json = JsonConvert.SerializeObject(a, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json);
}
[Test]
public void ToStringWithNoIndenting()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.None, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json);
}
[Test]
public void AddAfterSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[1].AddAfterSelf("pie");
Assert.AreEqual(5, (int)a[0]);
Assert.AreEqual(1, a[1].Count());
Assert.AreEqual("pie", (string)a[2]);
Assert.AreEqual(5, a.Count());
a[4].AddAfterSelf("lastpie");
Assert.AreEqual("lastpie", (string)a[5]);
Assert.AreEqual("lastpie", (string)a.Last);
}
[Test]
public void AddBeforeSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[1].AddBeforeSelf("pie");
Assert.AreEqual(5, (int)a[0]);
Assert.AreEqual("pie", (string)a[1]);
Assert.AreEqual(a, a[1].Parent);
Assert.AreEqual(a[2], a[1].Next);
Assert.AreEqual(5, a.Count());
a[0].AddBeforeSelf("firstpie");
Assert.AreEqual("firstpie", (string)a[0]);
Assert.AreEqual(5, (int)a[1]);
Assert.AreEqual("pie", (string)a[2]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(6, a.Count());
a.Last.AddBeforeSelf("secondlastpie");
Assert.AreEqual("secondlastpie", (string)a[5]);
Assert.AreEqual(7, a.Count());
}
[Test]
public void DeepClone()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3),
new JObject(
new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
new JProperty("Second", 1),
new JProperty("Third", null),
new JProperty("Fourth", new JConstructor("Date", 12345)),
new JProperty("Fifth", double.PositiveInfinity),
new JProperty("Sixth", double.NaN)
)
);
JArray a2 = (JArray)a.DeepClone();
Console.WriteLine(a2.ToString(Formatting.Indented));
Assert.IsTrue(a.DeepEquals(a2));
}
#if !SILVERLIGHT
[Test]
public void Clone()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3),
new JObject(
new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
new JProperty("Second", 1),
new JProperty("Third", null),
new JProperty("Fourth", new JConstructor("Date", 12345)),
new JProperty("Fifth", double.PositiveInfinity),
new JProperty("Sixth", double.NaN)
)
);
ICloneable c = a;
JArray a2 = (JArray) c.Clone();
Assert.IsTrue(a.DeepEquals(a2));
}
#endif
[Test]
public void DoubleDeepEquals()
{
JArray a =
new JArray(
double.NaN,
double.PositiveInfinity,
double.NegativeInfinity
);
JArray a2 = (JArray)a.DeepClone();
Assert.IsTrue(a.DeepEquals(a2));
double d = 1 + 0.1 + 0.1 + 0.1;
JValue v1 = new JValue(d);
JValue v2 = new JValue(1.3);
Assert.IsTrue(v1.DeepEquals(v2));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel; //Component
using System.Data.Common;
using System.Diagnostics;
using System.Runtime.CompilerServices;
// todo:
// There may be two ways to improve performance:
// 1. pool statements on the connection object
// 2. Do not create a datareader object for non-datareader returning command execution.
//
// We do not want to do the effort unless we have to squeze performance.
namespace System.Data.Odbc
{
public sealed class OdbcCommand : DbCommand, ICloneable
{
private static int s_objectTypeCount; // Bid counter
internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount);
private string _commandText;
private CommandType _commandType;
private int _commandTimeout = ADP.DefaultCommandTimeout;
private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
private bool _designTimeInvisible;
private bool _isPrepared; // true if the command is prepared
private OdbcConnection _connection;
private OdbcTransaction _transaction;
private WeakReference _weakDataReaderReference;
private CMDWrapper _cmdWrapper;
private OdbcParameterCollection _parameterCollection; // Parameter collection
private ConnectionState _cmdState;
public OdbcCommand() : base()
{
GC.SuppressFinalize(this);
}
public OdbcCommand(string cmdText) : this()
{
// note: arguments are assigned to properties so we do not have to trace them.
// We still need to include them into the argument list of the definition!
CommandText = cmdText;
}
public OdbcCommand(string cmdText, OdbcConnection connection) : this()
{
CommandText = cmdText;
Connection = connection;
}
public OdbcCommand(string cmdText, OdbcConnection connection, OdbcTransaction transaction) : this()
{
CommandText = cmdText;
Connection = connection;
Transaction = transaction;
}
private void DisposeDeadDataReader()
{
if (ConnectionState.Fetching == _cmdState)
{
if (null != _weakDataReaderReference && !_weakDataReaderReference.IsAlive)
{
if (_cmdWrapper != null)
{
_cmdWrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.CLOSE);
_cmdWrapper.FreeStatementHandle(ODBC32.STMT.CLOSE);
}
CloseFromDataReader();
}
}
}
private void DisposeDataReader()
{
if (null != _weakDataReaderReference)
{
IDisposable reader = (IDisposable)_weakDataReaderReference.Target;
if ((null != reader) && _weakDataReaderReference.IsAlive)
{
((IDisposable)reader).Dispose();
}
CloseFromDataReader();
}
}
internal void DisconnectFromDataReaderAndConnection()
{
// get a reference to the datareader if it is alive
OdbcDataReader liveReader = null;
if (_weakDataReaderReference != null)
{
OdbcDataReader reader;
reader = (OdbcDataReader)_weakDataReaderReference.Target;
if (_weakDataReaderReference.IsAlive)
{
liveReader = reader;
}
}
// remove reference to this from the live datareader
if (liveReader != null)
{
liveReader.Command = null;
}
_transaction = null;
if (null != _connection)
{
_connection.RemoveWeakReference(this);
_connection = null;
}
// if the reader is dead we have to dismiss the statement
if (liveReader == null)
{
CloseCommandWrapper();
}
// else DataReader now has exclusive ownership
_cmdWrapper = null;
}
protected override void Dispose(bool disposing)
{ // MDAC 65459
if (disposing)
{
// release mananged objects
// in V1.0, V1.1 the Connection,Parameters,CommandText,Transaction where reset
this.DisconnectFromDataReaderAndConnection();
_parameterCollection = null;
CommandText = null;
}
_cmdWrapper = null; // let go of the CommandWrapper
_isPrepared = false;
base.Dispose(disposing); // notify base classes
}
internal bool Canceling
{
get
{
return _cmdWrapper.Canceling;
}
}
public override string CommandText
{
get
{
string value = _commandText;
return ((null != value) ? value : ADP.StrEmpty);
}
set
{
if (_commandText != value)
{
PropertyChanging();
_commandText = value;
}
}
}
public override int CommandTimeout
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return _commandTimeout;
}
set
{
if (value < 0)
{
throw ADP.InvalidCommandTimeout(value);
}
if (value != _commandTimeout)
{
PropertyChanging();
_commandTimeout = value;
}
}
}
public void ResetCommandTimeout()
{ // V1.2.3300
if (ADP.DefaultCommandTimeout != _commandTimeout)
{
PropertyChanging();
_commandTimeout = ADP.DefaultCommandTimeout;
}
}
private bool ShouldSerializeCommandTimeout()
{ // V1.2.3300
return (ADP.DefaultCommandTimeout != _commandTimeout);
}
[
DefaultValue(System.Data.CommandType.Text),
]
public override CommandType CommandType
{
get
{
CommandType cmdType = _commandType;
return ((0 != cmdType) ? cmdType : CommandType.Text);
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case CommandType.Text:
case CommandType.StoredProcedure:
PropertyChanging();
_commandType = value;
break;
case CommandType.TableDirect:
throw ODBC.NotSupportedCommandType(value);
default:
throw ADP.InvalidCommandType(value);
}
}
}
public new OdbcConnection Connection
{
get
{
return _connection;
}
set
{
if (value != _connection)
{
PropertyChanging();
this.DisconnectFromDataReaderAndConnection();
Debug.Assert(null == _cmdWrapper, "has CMDWrapper when setting connection");
_connection = value;
//OnSchemaChanged();
}
}
}
protected override DbConnection DbConnection
{ // V1.2.3300
get
{
return Connection;
}
set
{
Connection = (OdbcConnection)value;
}
}
protected override DbParameterCollection DbParameterCollection
{ // V1.2.3300
get
{
return Parameters;
}
}
protected override DbTransaction DbTransaction
{ // V1.2.3300
get
{
return Transaction;
}
set
{
Transaction = (OdbcTransaction)value;
}
}
// @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
// to limit the number of components that clutter the design surface,
// when the DataAdapter design wizard generates the insert/update/delete commands it will
// set the DesignTimeVisible property to false so that cmds won't appear as individual objects
[
DefaultValue(true),
DesignOnly(true),
Browsable(false),
EditorBrowsableAttribute(EditorBrowsableState.Never),
]
public override bool DesignTimeVisible
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return !_designTimeInvisible;
}
set
{
_designTimeInvisible = !value;
TypeDescriptor.Refresh(this); // VS7 208845
}
}
internal bool HasParameters
{
get
{
return (null != _parameterCollection);
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
]
public new OdbcParameterCollection Parameters
{
get
{
if (null == _parameterCollection)
{
_parameterCollection = new OdbcParameterCollection();
}
return _parameterCollection;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
]
public new OdbcTransaction Transaction
{
get
{
if ((null != _transaction) && (null == _transaction.Connection))
{
_transaction = null; // Dawn of the Dead
}
return _transaction;
}
set
{
if (_transaction != value)
{
PropertyChanging(); // fire event before value is validated
_transaction = value;
}
}
}
[
DefaultValue(System.Data.UpdateRowSource.Both),
]
public override UpdateRowSource UpdatedRowSource
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return _updatedRowSource;
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
_updatedRowSource = value;
break;
default:
throw ADP.InvalidUpdateRowSource(value);
}
}
}
internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute)
{
return _cmdWrapper.GetDescriptorHandle(attribute);
}
// GetStatementHandle
// ------------------
// Try to return a cached statement handle.
//
// Creates a CmdWrapper object if necessary
// If no handle is available a handle will be allocated.
// Bindings will be unbound if a handle is cached and the bindings are invalid.
//
internal CMDWrapper GetStatementHandle()
{
// update the command wrapper object, allocate buffer
// create reader object
//
if (_cmdWrapper == null)
{
_cmdWrapper = new CMDWrapper(_connection);
Debug.Assert(null != _connection, "GetStatementHandle without connection?");
_connection.AddWeakReference(this, OdbcReferenceCollection.CommandTag);
}
if (_cmdWrapper._dataReaderBuf == null)
{
_cmdWrapper._dataReaderBuf = new CNativeBuffer(4096);
}
// if there is already a statement handle we need to do some cleanup
//
if (null == _cmdWrapper.StatementHandle)
{
_isPrepared = false;
_cmdWrapper.CreateStatementHandle();
}
else if ((null != _parameterCollection) && _parameterCollection.RebindCollection)
{
_cmdWrapper.FreeStatementHandle(ODBC32.STMT.RESET_PARAMS);
}
return _cmdWrapper;
}
// OdbcCommand.Cancel()
//
// In ODBC3.0 ... a call to SQLCancel when no processing is done has no effect at all
// (ODBC Programmer's Reference ...)
//
public override void Cancel()
{
CMDWrapper wrapper = _cmdWrapper;
if (null != wrapper)
{
wrapper.Canceling = true;
OdbcStatementHandle stmt = wrapper.StatementHandle;
if (null != stmt)
{
lock (stmt)
{
// Cancel the statement
ODBC32.RetCode retcode = stmt.Cancel();
// copy of StatementErrorHandler, because stmt may become null
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
// don't fire info message events on cancel
break;
default:
throw wrapper.Connection.HandleErrorNoThrow(stmt, retcode);
}
}
}
}
}
object ICloneable.Clone()
{
OdbcCommand clone = new OdbcCommand();
clone.CommandText = CommandText;
clone.CommandTimeout = this.CommandTimeout;
clone.CommandType = CommandType;
clone.Connection = this.Connection;
clone.Transaction = this.Transaction;
clone.UpdatedRowSource = UpdatedRowSource;
if ((null != _parameterCollection) && (0 < Parameters.Count))
{
OdbcParameterCollection parameters = clone.Parameters;
foreach (ICloneable parameter in Parameters)
{
parameters.Add(parameter.Clone());
}
}
return clone;
}
internal bool RecoverFromConnection()
{
DisposeDeadDataReader();
return (ConnectionState.Closed == _cmdState);
}
private void CloseCommandWrapper()
{
CMDWrapper wrapper = _cmdWrapper;
if (null != wrapper)
{
try
{
wrapper.Dispose();
if (null != _connection)
{
_connection.RemoveWeakReference(this);
}
}
finally
{
_cmdWrapper = null;
}
}
}
internal void CloseFromConnection()
{
if (null != _parameterCollection)
{
_parameterCollection.RebindCollection = true;
}
DisposeDataReader();
CloseCommandWrapper();
_isPrepared = false;
_transaction = null;
}
internal void CloseFromDataReader()
{
_weakDataReaderReference = null;
_cmdState = ConnectionState.Closed;
}
public new OdbcParameter CreateParameter()
{
return new OdbcParameter();
}
protected override DbParameter CreateDbParameter()
{
return CreateParameter();
}
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
public override int ExecuteNonQuery()
{
using (OdbcDataReader reader = ExecuteReaderObject(0, ADP.ExecuteNonQuery, false))
{
reader.Close();
return reader.RecordsAffected;
}
}
public new OdbcDataReader ExecuteReader()
{
return ExecuteReader(0/*CommandBehavior*/);
}
public new OdbcDataReader ExecuteReader(CommandBehavior behavior)
{
return ExecuteReaderObject(behavior, ADP.ExecuteReader, true);
}
internal OdbcDataReader ExecuteReaderFromSQLMethod(object[] methodArguments,
ODBC32.SQL_API method)
{
return ExecuteReaderObject(CommandBehavior.Default, method.ToString(), true, methodArguments, method);
}
private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader)
{ // MDAC 68324
if ((CommandText == null) || (CommandText.Length == 0))
{
throw (ADP.CommandTextRequired(method));
}
// using all functions to tell ExecuteReaderObject that
return ExecuteReaderObject(behavior, method, needReader, null, ODBC32.SQL_API.SQLEXECDIRECT);
}
private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior,
string method,
bool needReader,
object[] methodArguments,
ODBC32.SQL_API odbcApiMethod)
{ // MDAC 68324
OdbcDataReader localReader = null;
try
{
DisposeDeadDataReader(); // this is a no-op if cmdState is not Fetching
ValidateConnectionAndTransaction(method); // cmdState will change to Executing
if (0 != (CommandBehavior.SingleRow & behavior))
{
// CommandBehavior.SingleRow implies CommandBehavior.SingleResult
behavior |= CommandBehavior.SingleResult;
}
ODBC32.RetCode retcode;
OdbcStatementHandle stmt = GetStatementHandle().StatementHandle;
_cmdWrapper.Canceling = false;
if (null != _weakDataReaderReference)
{
if (_weakDataReaderReference.IsAlive)
{
object target = _weakDataReaderReference.Target;
if (null != target && _weakDataReaderReference.IsAlive)
{
if (!((OdbcDataReader)target).IsClosed)
{
throw ADP.OpenReaderExists(); // MDAC 66411
}
}
}
}
localReader = new OdbcDataReader(this, _cmdWrapper, behavior);
//Set command properties
//Not all drivers support timeout. So fail silently if error
if (!Connection.ProviderInfo.NoQueryTimeout)
{
TrySetStatementAttribute(stmt,
ODBC32.SQL_ATTR.QUERY_TIMEOUT,
(IntPtr)this.CommandTimeout);
}
// todo: If we remember the state we can omit a lot of SQLSetStmtAttrW calls ...
// if we do not create a reader we do not even need to do that
if (needReader)
{
if (Connection.IsV3Driver)
{
if (!Connection.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns)
{
// Need to get the metadata information
//SQLServer actually requires browse info turned on ahead of time...
//Note: We ignore any failures, since this is SQLServer specific
//We won't specialcase for SQL Server but at least for non-V3 drivers
if (localReader.IsBehavior(CommandBehavior.KeyInfo))
{
if (!_cmdWrapper._ssKeyInfoModeOn)
{
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.ON);
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.ON);
_cmdWrapper._ssKeyInfoModeOff = false;
_cmdWrapper._ssKeyInfoModeOn = true;
}
}
else
{
if (!_cmdWrapper._ssKeyInfoModeOff)
{
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.OFF);
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.OFF);
_cmdWrapper._ssKeyInfoModeOff = true;
_cmdWrapper._ssKeyInfoModeOn = false;
}
}
}
}
}
if (localReader.IsBehavior(CommandBehavior.KeyInfo) ||
localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
retcode = stmt.Prepare(CommandText);
if (ODBC32.RetCode.SUCCESS != retcode)
{
_connection.HandleError(stmt, retcode);
}
}
bool mustRelease = false;
CNativeBuffer parameterBuffer = _cmdWrapper._nativeParameterBuffer;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
//Handle Parameters
//Note: We use the internal variable as to not instante a new object collection,
//for the common case of using no parameters.
if ((null != _parameterCollection) && (0 < _parameterCollection.Count))
{
int parameterBufferSize = _parameterCollection.CalcParameterBufferSize(this);
if (null == parameterBuffer || parameterBuffer.Length < parameterBufferSize)
{
if (null != parameterBuffer)
{
parameterBuffer.Dispose();
}
parameterBuffer = new CNativeBuffer(parameterBufferSize);
_cmdWrapper._nativeParameterBuffer = parameterBuffer;
}
else
{
parameterBuffer.ZeroMemory();
}
parameterBuffer.DangerousAddRef(ref mustRelease);
_parameterCollection.Bind(this, _cmdWrapper, parameterBuffer);
}
if (!localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
// Can't get the KeyInfo after command execution (SQL Server only since it does not support multiple
// results on the same connection). Stored procedures (SP) do not return metadata before actual execution
// Need to check the column count since the command type may not be set to SP for a SP.
if ((localReader.IsBehavior(CommandBehavior.KeyInfo) || localReader.IsBehavior(CommandBehavior.SchemaOnly))
&& (CommandType != CommandType.StoredProcedure))
{
short cColsAffected;
retcode = stmt.NumberOfResultColumns(out cColsAffected);
if (retcode == ODBC32.RetCode.SUCCESS || retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)
{
if (cColsAffected > 0)
{
localReader.GetSchemaTable();
}
}
else if (retcode == ODBC32.RetCode.NO_DATA)
{
// do nothing
}
else
{
// any other returncode indicates an error
_connection.HandleError(stmt, retcode);
}
}
switch (odbcApiMethod)
{
case ODBC32.SQL_API.SQLEXECDIRECT:
if (localReader.IsBehavior(CommandBehavior.KeyInfo) || _isPrepared)
{
//Already prepared, so use SQLExecute
retcode = stmt.Execute();
// Build metadata here
// localReader.GetSchemaTable();
}
else
{
#if DEBUG
//if (AdapterSwitches.OleDbTrace.TraceInfo) {
// ADP.DebugWriteLine("SQLExecDirectW: " + CommandText);
//}
#endif
//SQLExecDirect
retcode = stmt.ExecuteDirect(CommandText);
}
break;
case ODBC32.SQL_API.SQLTABLES:
retcode = stmt.Tables((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema,
(string)methodArguments[2], //TableName
(string)methodArguments[3]); //TableType
break;
case ODBC32.SQL_API.SQLCOLUMNS:
retcode = stmt.Columns((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema
(string)methodArguments[2], //TableName
(string)methodArguments[3]); //ColumnName
break;
case ODBC32.SQL_API.SQLPROCEDURES:
retcode = stmt.Procedures((string)methodArguments[0], //ProcedureCatalog
(string)methodArguments[1], //ProcedureSchema
(string)methodArguments[2]); //procedureName
break;
case ODBC32.SQL_API.SQLPROCEDURECOLUMNS:
retcode = stmt.ProcedureColumns((string)methodArguments[0], //ProcedureCatalog
(string)methodArguments[1], //ProcedureSchema
(string)methodArguments[2], //procedureName
(string)methodArguments[3]); //columnName
break;
case ODBC32.SQL_API.SQLSTATISTICS:
retcode = stmt.Statistics((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema
(string)methodArguments[2], //TableName
(short)methodArguments[3], //IndexTrpe
(short)methodArguments[4]); //Accuracy
break;
case ODBC32.SQL_API.SQLGETTYPEINFO:
retcode = stmt.GetTypeInfo((short)methodArguments[0]); //SQL Type
break;
default:
// this should NEVER happen
Debug.Fail("ExecuteReaderObjectcalled with unsupported ODBC API method.");
throw ADP.InvalidOperation(method.ToString());
}
//Note: Execute will return NO_DATA for Update/Delete non-row returning queries
if ((ODBC32.RetCode.SUCCESS != retcode) && (ODBC32.RetCode.NO_DATA != retcode))
{
_connection.HandleError(stmt, retcode);
}
} // end SchemaOnly
}
finally
{
if (mustRelease)
{
parameterBuffer.DangerousRelease();
}
}
_weakDataReaderReference = new WeakReference(localReader);
// XXXCommand.Execute should position reader on first row returning result
// any exceptions in the initial non-row returning results should be thrown
// from from ExecuteXXX not the DataReader
if (!localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
localReader.FirstResult();
}
_cmdState = ConnectionState.Fetching;
}
finally
{
if (ConnectionState.Fetching != _cmdState)
{
if (null != localReader)
{
// clear bindings so we don't grab output parameters on a failed execute
if (null != _parameterCollection)
{
_parameterCollection.ClearBindings();
}
((IDisposable)localReader).Dispose();
}
if (ConnectionState.Closed != _cmdState)
{
_cmdState = ConnectionState.Closed;
}
}
}
return localReader;
}
public override object ExecuteScalar()
{
object value = null;
using (IDataReader reader = ExecuteReaderObject(0, ADP.ExecuteScalar, false))
{
if (reader.Read() && (0 < reader.FieldCount))
{
value = reader.GetValue(0);
}
reader.Close();
}
return value;
}
internal string GetDiagSqlState()
{
return _cmdWrapper.GetDiagSqlState();
}
private void PropertyChanging()
{
_isPrepared = false;
}
// Prepare
//
// if the CommandType property is set to TableDirect Prepare does nothing.
// if the CommandType property is set to StoredProcedure Prepare should succeed but result
// in a no-op
//
// throw InvalidOperationException
// if the connection is not set
// if the connection is not open
//
public override void Prepare()
{
ODBC32.RetCode retcode;
ValidateOpenConnection(ADP.Prepare);
if (0 != (ConnectionState.Fetching & _connection.InternalState))
{
throw ADP.OpenReaderExists();
}
if (CommandType == CommandType.TableDirect)
{
return; // do nothing
}
DisposeDeadDataReader();
GetStatementHandle();
OdbcStatementHandle stmt = _cmdWrapper.StatementHandle;
retcode = stmt.Prepare(CommandText);
if (ODBC32.RetCode.SUCCESS != retcode)
{
_connection.HandleError(stmt, retcode);
}
_isPrepared = true;
}
private void TrySetStatementAttribute(OdbcStatementHandle stmt, ODBC32.SQL_ATTR stmtAttribute, IntPtr value)
{
ODBC32.RetCode retcode = stmt.SetStatementAttribute(
stmtAttribute,
value,
ODBC32.SQL_IS.UINTEGER);
if (retcode == ODBC32.RetCode.ERROR)
{
string sqlState;
stmt.GetDiagnosticField(out sqlState);
if ((sqlState == "HYC00") || (sqlState == "HY092"))
{
Connection.FlagUnsupportedStmtAttr(stmtAttribute);
}
else
{
// now what? Should we throw?
}
}
}
private void ValidateOpenConnection(string methodName)
{
// see if we have a connection
OdbcConnection connection = Connection;
if (null == connection)
{
throw ADP.ConnectionRequired(methodName);
}
// must have an open and available connection
ConnectionState state = connection.State;
if (ConnectionState.Open != state)
{
throw ADP.OpenConnectionRequired(methodName, state);
}
}
private void ValidateConnectionAndTransaction(string method)
{
if (null == _connection)
{
throw ADP.ConnectionRequired(method);
}
_transaction = _connection.SetStateExecuting(method, Transaction);
_cmdState = ConnectionState.Executing;
}
}
internal sealed class CMDWrapper
{
private OdbcStatementHandle _stmt; // hStmt
private OdbcStatementHandle _keyinfostmt; // hStmt for keyinfo
internal OdbcDescriptorHandle _hdesc; // hDesc
internal CNativeBuffer _nativeParameterBuffer; // Native memory for internal memory management
// (Performance optimization)
internal CNativeBuffer _dataReaderBuf; // Reusable DataReader buffer
private readonly OdbcConnection _connection; // Connection
private bool _canceling; // true if the command is canceling
internal bool _hasBoundColumns;
internal bool _ssKeyInfoModeOn; // tells us if the SqlServer specific options are on
internal bool _ssKeyInfoModeOff; // a tri-state value would be much better ...
internal CMDWrapper(OdbcConnection connection)
{
_connection = connection;
}
internal bool Canceling
{
get
{
return _canceling;
}
set
{
_canceling = value;
}
}
internal OdbcConnection Connection
{
get
{
return _connection;
}
}
internal bool HasBoundColumns
{
// get {
// return _hasBoundColumns;
// }
set
{
_hasBoundColumns = value;
}
}
internal OdbcStatementHandle StatementHandle
{
get { return _stmt; }
}
internal OdbcStatementHandle KeyInfoStatement
{
get
{
return _keyinfostmt;
}
}
internal void CreateKeyInfoStatementHandle()
{
DisposeKeyInfoStatementHandle();
_keyinfostmt = _connection.CreateStatementHandle();
}
internal void CreateStatementHandle()
{
DisposeStatementHandle();
_stmt = _connection.CreateStatementHandle();
}
internal void Dispose()
{
if (null != _dataReaderBuf)
{
_dataReaderBuf.Dispose();
_dataReaderBuf = null;
}
DisposeStatementHandle();
CNativeBuffer buffer = _nativeParameterBuffer;
_nativeParameterBuffer = null;
if (null != buffer)
{
buffer.Dispose();
}
_ssKeyInfoModeOn = false;
_ssKeyInfoModeOff = false;
}
private void DisposeDescriptorHandle()
{
OdbcDescriptorHandle handle = _hdesc;
if (null != handle)
{
_hdesc = null;
handle.Dispose();
}
}
internal void DisposeStatementHandle()
{
DisposeKeyInfoStatementHandle();
DisposeDescriptorHandle();
OdbcStatementHandle handle = _stmt;
if (null != handle)
{
_stmt = null;
handle.Dispose();
}
}
internal void DisposeKeyInfoStatementHandle()
{
OdbcStatementHandle handle = _keyinfostmt;
if (null != handle)
{
_keyinfostmt = null;
handle.Dispose();
}
}
internal void FreeStatementHandle(ODBC32.STMT stmt)
{
DisposeDescriptorHandle();
OdbcStatementHandle handle = _stmt;
if (null != handle)
{
try
{
ODBC32.RetCode retcode;
retcode = handle.FreeStatement(stmt);
StatementErrorHandler(retcode);
}
catch (Exception e)
{
//
if (ADP.IsCatchableExceptionType(e))
{
_stmt = null;
handle.Dispose();
}
throw;
}
}
}
internal void FreeKeyInfoStatementHandle(ODBC32.STMT stmt)
{
OdbcStatementHandle handle = _keyinfostmt;
if (null != handle)
{
try
{
handle.FreeStatement(stmt);
}
catch (Exception e)
{
//
if (ADP.IsCatchableExceptionType(e))
{
_keyinfostmt = null;
handle.Dispose();
}
throw;
}
}
}
// Get the Descriptor Handle for the current statement
//
internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute)
{
OdbcDescriptorHandle hdesc = _hdesc;
if (null == _hdesc)
{
_hdesc = hdesc = new OdbcDescriptorHandle(_stmt, attribute);
}
return hdesc;
}
internal string GetDiagSqlState()
{
string sqlstate;
_stmt.GetDiagnosticField(out sqlstate);
return sqlstate;
}
internal void StatementErrorHandler(ODBC32.RetCode retcode)
{
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_connection.HandleErrorNoThrow(_stmt, retcode);
break;
default:
throw _connection.HandleErrorNoThrow(_stmt, retcode);
}
}
internal void UnbindStmtColumns()
{
if (_hasBoundColumns)
{
FreeStatementHandle(ODBC32.STMT.UNBIND);
_hasBoundColumns = false;
}
}
}
}
| |
//***********************************************************************************************
// REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
//***********************************************************************************************
// The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe
// or other piece of equipment they want to hire out to the transportation ministry for day
// labour and emergency projects. The Hired Equipment Program distributes available work to
// local equipment owners. The program is based on seniority and is designed to deliver work
// to registered users fairly and efficiently through the development of local
// area call-out lists.
//***********************************************************************************************
// OpenAPI spec version: v1
//***********************************************************************************************
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http.Features;
using System.Text;
using System.Reflection;
using Hangfire.PostgreSql;
using Hangfire;
using Hangfire.Console;
using HETSAPI.Models;
using HETSAPI.Authorization;
using HETSAPI.Authentication;
namespace HETSAPI
{
/// <summary>
/// The application Startup class
/// </summary>
public class Startup
{
private readonly IHostingEnvironment _hostingEnv;
/// <summary>
/// HETS Configuration
/// </summary>
public IConfigurationRoot Configuration { get; }
/// <summary>
/// Startup HETS Backend Services
/// </summary>
/// <param name="env"></param>
public Startup(IHostingEnvironment env)
{
_hostingEnv = env;
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
/// <summary>
/// Add services to the container
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
string connectionString = GetConnectionString();
// add database context
services.AddDbContext<DbAppContext>(options => options.UseNpgsql(connectionString));
// setup siteminder authentication (core 2.0)
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = SiteMinderAuthOptions.AuthenticationSchemeName;
options.DefaultChallengeScheme = SiteMinderAuthOptions.AuthenticationSchemeName;
}).AddSiteminderAuth(options =>
{
});
// setup authorization
services.AddAuthorization();
services.RegisterPermissionHandler();
// allow for large files to be uploaded
services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = 1073741824; // 1 GB
});
services.AddMvc(options => options.AddDefaultAuthorizationPolicyFilter())
.AddJsonOptions(
opts => {
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
opts.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
opts.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
// ReferenceLoopHandling is set to Ignore to prevent JSON parser issues with the user / roles model.
opts.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
// enable Hangfire
PostgreSqlStorageOptions postgreSqlStorageOptions = new PostgreSqlStorageOptions {
SchemaName = "public"
};
if (connectionString != null)
{
PostgreSqlStorage storage = new PostgreSqlStorage(connectionString, postgreSqlStorageOptions);
services.AddHangfire(config =>
{
config.UseStorage(storage);
config.UseConsole();
});
}
// Configure Swagger - only required in the Development Environment
if (_hostingEnv.IsDevelopment())
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "HETS REST API",
Description = "Hired Equipment Tracking System"
});
options.DescribeAllEnumsAsStrings();
});
}
// Add application services.
services.RegisterApplicationServices();
}
/// <summary>
/// Configure the HTTP request pipeline
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="loggerFactory"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// web site error handler
app.UseWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder =>
{
builder.UseExceptionHandler(Configuration.GetSection("Constants:ErrorUrl").Value);
});
// authenticate users
app.UseAuthentication();
// update database environment
if (Configuration != null)
{
string updateDb = Configuration.GetSection("UpdateLocalDb").Value;
if (env.IsDevelopment() && updateDb.ToLower() != "false")
{
TryMigrateDatabase(app, loggerFactory);
}
else if (!env.IsDevelopment())
{
TryMigrateDatabase(app, loggerFactory);
}
}
// do not start Hangfire if we are running tests.
bool startHangfire = true;
#if DEBUG
foreach (var assem in Assembly.GetEntryAssembly().GetReferencedAssemblies())
{
if (assem.FullName.ToLowerInvariant().StartsWith("xunit"))
{
startHangfire = false;
break;
}
}
#endif
if (startHangfire)
{
// enable Hangfire
app.UseHangfireServer();
// disable the back to site link
DashboardOptions dashboardOptions = new DashboardOptions
{
AppPath = null,
Authorization = new[] { new HangfireAuthorizationFilter() }
};
// enable the hangfire dashboard
app.UseHangfireDashboard(Configuration.GetSection("Constants:HangfireUrl").Value, dashboardOptions);
}
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});
if (_hostingEnv.IsDevelopment())
{
string swaggerApi = Configuration.GetSection("Constants:SwaggerApiUrl").Value;
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint(swaggerApi, "HETS REST API v1");
options.DocExpansion(DocExpansion.None);
});
}
}
/// <summary>
/// Database Migration
/// </summary>
/// <param name="app"></param>
/// <param name="loggerFactory"></param>
private void TryMigrateDatabase(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
ILogger log = loggerFactory.CreateLogger(typeof(Startup));
log.LogInformation("Attempting to migrate the database ...");
try
{
using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
log.LogInformation("Fetching the application's database context ...");
DbContext context = serviceScope.ServiceProvider.GetService<DbAppContext>();
log.LogInformation("Migrating the database ...");
context.Database.Migrate();
log.LogInformation("The database migration complete.");
log.LogInformation("Updating the database documentation ...");
DbCommentsUpdater<DbAppContext> updater = new DbCommentsUpdater<DbAppContext>((DbAppContext)context);
updater.UpdateDatabaseDescriptions();
log.LogInformation("The database documentation has been updated.");
log.LogInformation("Adding/Updating seed data ...");
Seeders.SeedFactory<DbAppContext> seederFactory = new Seeders.SeedFactory<DbAppContext>(Configuration, _hostingEnv, loggerFactory);
seederFactory.Seed((DbAppContext) context);
log.LogInformation("Seeding operations are complete.");
}
log.LogInformation("All database migration activities are complete.");
}
catch (Exception e)
{
StringBuilder msg = new StringBuilder();
msg.AppendLine("The database migration failed!");
msg.AppendLine("The database may not be available and the application will not function as expected.");
msg.AppendLine("Please ensure a database is available and the connection string is correct.");
msg.AppendLine("If you are running in a development environment, ensure your test database and server configuraiotn match the project's default connection string.");
log.LogCritical(new EventId(-1, "Database Migration Failed"), e, msg.ToString());
}
}
/// <summary>
/// Retrieve database connection string
/// </summary>
/// <returns></returns>
private string GetConnectionString()
{
string connectionString;
string host = Configuration["DATABASE_SERVICE_NAME"];
string username = Configuration["POSTGRESQL_USER"];
string password = Configuration["POSTGRESQL_PASSWORD"];
string database = Configuration["POSTGRESQL_DATABASE"];
if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(database))
{
// When things get cleaned up properly, this is the only call we'll have to make.
connectionString = Configuration.GetConnectionString("HETS");
}
else
{
// Environment variables override all other settings; same behaviour as the configuration provider when things get cleaned up.
connectionString = $"Host={host};Username={username};Password={password};Database={database};";
}
return connectionString;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace PlaybasisWeb
{
public static class TokenHelper
{
#region public methods
/// <summary>
/// Configures .Net to trust all certificates when making network calls. This is used so that calls
/// to an https SharePoint server without a valid certificate are not rejected. This should only be used during
/// testing, and should never be used in a production app.
/// </summary>
public static void TrustAllCertificates()
{
//Trust all certificates
ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName];
if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName];
}
return null;
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName];
if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName];
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (ClientCertificate != null)
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (ClientCertificate != null)
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
const string bearer = "Bearer realm=\"";
int realmIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal) + bearer.Length;
if (bearerResponseHeader.Length > realmIndex)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
private const int TokenLifetimeMinutes = 1000000;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.AddMinutes(TokenLifetimeMinutes),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(10),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
private static string EnsureTrailingSlash(string url)
{
if (!String.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
public class OAuthTokenPair
{
public string AccessToken;
public string RefreshToken;
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Security;
using System.Diagnostics;
namespace System.Runtime.Serialization
{
internal class CodeGenerator
{
private static MethodInfo s_getTypeFromHandle;
private static MethodInfo GetTypeFromHandle
{
get
{
if (s_getTypeFromHandle == null)
{
s_getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle");
Debug.Assert(s_getTypeFromHandle != null);
}
return s_getTypeFromHandle;
}
}
private static MethodInfo s_objectEquals;
private static MethodInfo ObjectEquals
{
get
{
if (s_objectEquals == null)
{
s_objectEquals = Globals.TypeOfObject.GetMethod("Equals", BindingFlags.Public | BindingFlags.Static);
Debug.Assert(s_objectEquals != null);
}
return s_objectEquals;
}
}
private static MethodInfo s_arraySetValue;
private static MethodInfo ArraySetValue
{
get
{
if (s_arraySetValue == null)
{
s_arraySetValue = typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) });
Debug.Assert(s_arraySetValue != null);
}
return s_arraySetValue;
}
}
private static MethodInfo s_objectToString;
private static MethodInfo ObjectToString
{
get
{
if (s_objectToString == null)
{
s_objectToString = typeof(object).GetMethod("ToString", Array.Empty<Type>());
Debug.Assert(s_objectToString != null);
}
return s_objectToString;
}
}
private static MethodInfo s_stringFormat;
private static MethodInfo StringFormat
{
get
{
if (s_stringFormat == null)
{
s_stringFormat = typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) });
Debug.Assert(s_stringFormat != null);
}
return s_stringFormat;
}
}
private Type _delegateType;
#if USE_REFEMIT
AssemblyBuilder assemblyBuilder;
ModuleBuilder moduleBuilder;
TypeBuilder typeBuilder;
static int typeCounter;
MethodBuilder methodBuilder;
#else
private static Module s_serializationModule;
private static Module SerializationModule
{
get
{
if (s_serializationModule == null)
{
s_serializationModule = typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false
}
return s_serializationModule;
}
}
private DynamicMethod _dynamicMethod;
#endif
private ILGenerator _ilGen;
private List<ArgBuilder> _argList;
private Stack<object> _blockStack;
private Label _methodEndLabel;
private readonly Dictionary<LocalBuilder, string> _localNames = new Dictionary<LocalBuilder, string>();
private enum CodeGenTrace { None, Save, Tron };
private readonly CodeGenTrace _codeGenTrace;
private LocalBuilder _stringFormatArray;
internal CodeGenerator()
{
//Defaulting to None as thats the default value in WCF
_codeGenTrace = CodeGenTrace.None;
}
#if !USE_REFEMIT
internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess)
{
_dynamicMethod = dynamicMethod;
_ilGen = _dynamicMethod.GetILGenerator();
_delegateType = delegateType;
InitILGeneration(methodName, argTypes);
}
#endif
internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess)
{
MethodInfo signature = delegateType.GetMethod("Invoke");
ParameterInfo[] parameters = signature.GetParameters();
Type[] paramTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramTypes[i] = parameters[i].ParameterType;
BeginMethod(signature.ReturnType, methodName, paramTypes, allowPrivateMemberAccess);
_delegateType = delegateType;
}
private void BeginMethod(Type returnType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess)
{
#if USE_REFEMIT
string typeName = "Type" + (typeCounter++);
InitAssemblyBuilder(typeName + "." + methodName);
this.typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public);
this.methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public|MethodAttributes.Static, returnType, argTypes);
this.ilGen = this.methodBuilder.GetILGenerator();
#else
_dynamicMethod = new DynamicMethod(methodName, returnType, argTypes, SerializationModule, allowPrivateMemberAccess);
_ilGen = _dynamicMethod.GetILGenerator();
#endif
InitILGeneration(methodName, argTypes);
}
private void InitILGeneration(string methodName, Type[] argTypes)
{
_methodEndLabel = _ilGen.DefineLabel();
_blockStack = new Stack<object>();
_argList = new List<ArgBuilder>();
for (int i = 0; i < argTypes.Length; i++)
_argList.Add(new ArgBuilder(i, argTypes[i]));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel("Begin method " + methodName + " {");
}
internal Delegate EndMethod()
{
MarkLabel(_methodEndLabel);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel("} End method");
Ret();
Delegate retVal = null;
#if USE_REFEMIT
Type type = typeBuilder.CreateType();
MethodInfo method = type.GetMethod(methodBuilder.Name);
retVal = Delegate.CreateDelegate(delegateType, method);
methodBuilder = null;
#else
retVal = _dynamicMethod.CreateDelegate(_delegateType);
_dynamicMethod = null;
#endif
_delegateType = null;
_ilGen = null;
_blockStack = null;
_argList = null;
return retVal;
}
internal MethodInfo CurrentMethod
{
get
{
#if USE_REFEMIT
return methodBuilder;
#else
return _dynamicMethod;
#endif
}
}
internal ArgBuilder GetArg(int index)
{
return (ArgBuilder)_argList[index];
}
internal Type GetVariableType(object var)
{
if (var is ArgBuilder)
return ((ArgBuilder)var).ArgType;
else if (var is LocalBuilder)
return ((LocalBuilder)var).LocalType;
else
return var.GetType();
}
internal LocalBuilder DeclareLocal(Type type, string name, object initialValue)
{
LocalBuilder local = DeclareLocal(type, name);
Load(initialValue);
Store(local);
return local;
}
internal LocalBuilder DeclareLocal(Type type, string name)
{
return DeclareLocal(type, name, false);
}
internal LocalBuilder DeclareLocal(Type type, string name, bool isPinned)
{
LocalBuilder local = _ilGen.DeclareLocal(type, isPinned);
if (_codeGenTrace != CodeGenTrace.None)
{
_localNames[local] = name;
EmitSourceComment("Declare local '" + name + "' of type " + type);
}
return local;
}
internal void Set(LocalBuilder local, object value)
{
Load(value);
Store(local);
}
internal object For(LocalBuilder local, object start, object end)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end);
if (forState.Index != null)
{
Load(start);
Stloc(forState.Index);
Br(forState.TestLabel);
}
MarkLabel(forState.BeginLabel);
_blockStack.Push(forState);
return forState;
}
internal void EndFor()
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
if (forState == null)
ThrowMismatchException(stackTop);
if (forState.Index != null)
{
Ldloc(forState.Index);
Ldc(1);
Add();
Stloc(forState.Index);
MarkLabel(forState.TestLabel);
Ldloc(forState.Index);
Load(forState.End);
if (GetVariableType(forState.End).IsArray)
Ldlen();
Blt(forState.BeginLabel);
}
else
Br(forState.BeginLabel);
if (forState.RequiresEndLabel)
MarkLabel(forState.EndLabel);
}
internal void Break(object forState)
{
InternalBreakFor(forState, OpCodes.Br);
}
internal void IfFalseBreak(object forState)
{
InternalBreakFor(forState, OpCodes.Brfalse);
}
internal void InternalBreakFor(object userForState, OpCode branchInstruction)
{
foreach (object block in _blockStack)
{
ForState forState = block as ForState;
if (forState != null && (object)forState == userForState)
{
if (!forState.RequiresEndLabel)
{
forState.EndLabel = DefineLabel();
forState.RequiresEndLabel = true;
}
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(branchInstruction + " " + forState.EndLabel.GetHashCode());
_ilGen.Emit(branchInstruction, forState.EndLabel);
break;
}
}
}
internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType,
LocalBuilder enumerator, MethodInfo getCurrentMethod)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), enumerator);
Br(forState.TestLabel);
MarkLabel(forState.BeginLabel);
Call(enumerator, getCurrentMethod);
ConvertValue(elementType, GetVariableType(local));
Stloc(local);
_blockStack.Push(forState);
}
internal void EndForEach(MethodInfo moveNextMethod)
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
if (forState == null)
ThrowMismatchException(stackTop);
MarkLabel(forState.TestLabel);
object enumerator = forState.End;
Call(enumerator, moveNextMethod);
Brtrue(forState.BeginLabel);
if (forState.RequiresEndLabel)
MarkLabel(forState.EndLabel);
}
internal void IfNotDefaultValue(object value)
{
Type type = GetVariableType(value);
TypeCode typeCode = type.GetTypeCode();
if ((typeCode == TypeCode.Object && type.IsValueType) ||
typeCode == TypeCode.DateTime || typeCode == TypeCode.Decimal)
{
LoadDefaultValue(type);
ConvertValue(type, Globals.TypeOfObject);
Load(value);
ConvertValue(type, Globals.TypeOfObject);
Call(ObjectEquals);
IfNot();
}
else
{
LoadDefaultValue(type);
Load(value);
If(Cmp.NotEqualTo);
}
}
internal void If()
{
InternalIf(false);
}
internal void IfNot()
{
InternalIf(true);
}
private OpCode GetBranchCode(Cmp cmp)
{
switch (cmp)
{
case Cmp.LessThan:
return OpCodes.Bge;
case Cmp.EqualTo:
return OpCodes.Bne_Un;
case Cmp.LessThanOrEqualTo:
return OpCodes.Bgt;
case Cmp.GreaterThan:
return OpCodes.Ble;
case Cmp.NotEqualTo:
return OpCodes.Beq;
default:
DiagnosticUtility.DebugAssert(cmp == Cmp.GreaterThanOrEqualTo, "Unexpected cmp");
return OpCodes.Blt;
}
}
internal void If(Cmp cmpOp)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void If(object value1, Cmp cmpOp, object value2)
{
Load(value1);
Load(value2);
If(cmpOp);
}
internal void Else()
{
IfState ifState = PopIfState();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
ifState.ElseBegin = ifState.EndIf;
_blockStack.Push(ifState);
}
internal void ElseIf(object value1, Cmp cmpOp, object value2)
{
IfState ifState = (IfState)_blockStack.Pop();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
Load(value1);
Load(value2);
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void EndIf()
{
IfState ifState = PopIfState();
if (!ifState.ElseBegin.Equals(ifState.EndIf))
MarkLabel(ifState.ElseBegin);
MarkLabel(ifState.EndIf);
}
internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount)
{
if (methodInfo.GetParameters().Length != expectedCount)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount)));
}
internal void Call(object thisObj, MethodInfo methodInfo)
{
VerifyParameterCount(methodInfo, 0);
LoadThis(thisObj, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1)
{
VerifyParameterCount(methodInfo, 1);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2)
{
VerifyParameterCount(methodInfo, 2);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3)
{
VerifyParameterCount(methodInfo, 3);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4)
{
VerifyParameterCount(methodInfo, 4);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5)
{
VerifyParameterCount(methodInfo, 5);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
LoadParam(param5, 5, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6)
{
VerifyParameterCount(methodInfo, 6);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
LoadParam(param5, 5, methodInfo);
LoadParam(param6, 6, methodInfo);
Call(methodInfo);
}
internal void Call(MethodInfo methodInfo)
{
if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Callvirt, methodInfo);
}
else if (methodInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, methodInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, methodInfo);
}
}
internal void Call(ConstructorInfo ctor)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, ctor);
}
internal void New(ConstructorInfo constructorInfo)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Newobj, constructorInfo);
}
internal void InitObj(Type valueType)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Initobj " + valueType);
_ilGen.Emit(OpCodes.Initobj, valueType);
}
internal void NewArray(Type elementType, object len)
{
Load(len);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Newarr " + elementType);
_ilGen.Emit(OpCodes.Newarr, elementType);
}
internal void LoadArrayElement(object obj, object arrayIndex)
{
Type objType = GetVariableType(obj).GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
{
Ldelema(objType);
Ldobj(objType);
}
else
Ldelem(objType);
}
internal void StoreArrayElement(object obj, object arrayIndex, object value)
{
Type arrayType = GetVariableType(obj);
if (arrayType == Globals.TypeOfArray)
{
Call(obj, ArraySetValue, value, arrayIndex);
}
else
{
Type objType = arrayType.GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
Ldelema(objType);
Load(value);
ConvertValue(GetVariableType(value), objType);
if (IsStruct(objType))
Stobj(objType);
else
Stelem(objType);
}
}
private static bool IsStruct(Type objType)
{
return objType.IsValueType && !objType.IsPrimitive;
}
internal Type LoadMember(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Ldsfld, fieldInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Ldfld, fieldInfo);
}
}
else if (memberInfo is PropertyInfo)
{
PropertyInfo property = memberInfo as PropertyInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property)));
Call(getMethod);
}
}
else if (memberInfo is MethodInfo)
{
MethodInfo method = (MethodInfo)memberInfo;
memberType = method.ReturnType;
Call(method);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown", memberInfo.DeclaringType, memberInfo.Name)));
EmitStackTop(memberType);
return memberType;
}
internal void StoreMember(MemberInfo memberInfo)
{
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
if (fieldInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Stsfld, fieldInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Stfld, fieldInfo);
}
}
else if (memberInfo is PropertyInfo)
{
PropertyInfo property = memberInfo as PropertyInfo;
if (property != null)
{
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property)));
Call(setMethod);
}
}
else if (memberInfo is MethodInfo)
Call((MethodInfo)memberInfo);
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown")));
}
internal void LoadDefaultValue(Type type)
{
if (type.IsValueType)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
Ldc(false);
break;
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
Ldc(0);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
Ldc(0L);
break;
case TypeCode.Single:
Ldc(0.0F);
break;
case TypeCode.Double:
Ldc(0.0);
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
default:
LocalBuilder zero = DeclareLocal(type, "zero");
LoadAddress(zero);
InitObj(type);
Load(zero);
break;
}
}
else
Load(null);
}
internal void Load(object obj)
{
if (obj == null)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldnull");
_ilGen.Emit(OpCodes.Ldnull);
}
else if (obj is ArgBuilder)
Ldarg((ArgBuilder)obj);
else if (obj is LocalBuilder)
Ldloc((LocalBuilder)obj);
else
Ldc(obj);
}
internal void Store(object var)
{
if (var is ArgBuilder)
Starg((ArgBuilder)var);
else if (var is LocalBuilder)
Stloc((LocalBuilder)var);
else
{
DiagnosticUtility.DebugAssert("Data can only be stored into ArgBuilder or LocalBuilder.");
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CanOnlyStoreIntoArgOrLocGot0, DataContract.GetClrTypeFullName(var.GetType()))));
}
}
internal void Dec(object var)
{
Load(var);
Load(1);
Subtract();
Store(var);
}
internal void LoadAddress(object obj)
{
if (obj is ArgBuilder)
LdargAddress((ArgBuilder)obj);
else if (obj is LocalBuilder)
LdlocAddress((LocalBuilder)obj);
else
Load(obj);
}
internal void ConvertAddress(Type source, Type target)
{
InternalConvert(source, target, true);
}
internal void ConvertValue(Type source, Type target)
{
InternalConvert(source, target, false);
}
internal void Castclass(Type target)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Castclass " + target);
_ilGen.Emit(OpCodes.Castclass, target);
}
internal void Box(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Box " + type);
_ilGen.Emit(OpCodes.Box, type);
}
internal void Unbox(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Unbox " + type);
_ilGen.Emit(OpCodes.Unbox, type);
}
private OpCode GetLdindOpCode(TypeCode typeCode) =>
typeCode switch
{
TypeCode.Boolean => OpCodes.Ldind_I1, // TypeCode.Boolean:
TypeCode.Char => OpCodes.Ldind_I2, // TypeCode.Char:
TypeCode.SByte => OpCodes.Ldind_I1, // TypeCode.SByte:
TypeCode.Byte => OpCodes.Ldind_U1, // TypeCode.Byte:
TypeCode.Int16 => OpCodes.Ldind_I2, // TypeCode.Int16:
TypeCode.UInt16 => OpCodes.Ldind_U2, // TypeCode.UInt16:
TypeCode.Int32 => OpCodes.Ldind_I4, // TypeCode.Int32:
TypeCode.UInt32 => OpCodes.Ldind_U4, // TypeCode.UInt32:
TypeCode.Int64 => OpCodes.Ldind_I8, // TypeCode.Int64:
TypeCode.UInt64 => OpCodes.Ldind_I8, // TypeCode.UInt64:
TypeCode.Single => OpCodes.Ldind_R4, // TypeCode.Single:
TypeCode.Double => OpCodes.Ldind_R8, // TypeCode.Double:
TypeCode.String => OpCodes.Ldind_Ref, // TypeCode.String:
_ => OpCodes.Nop,
};
internal void Ldobj(Type type)
{
OpCode opCode = GetLdindOpCode(type.GetTypeCode());
if (!opCode.Equals(OpCodes.Nop))
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldobj " + type);
_ilGen.Emit(OpCodes.Ldobj, type);
}
}
internal void Stobj(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stobj " + type);
_ilGen.Emit(OpCodes.Stobj, type);
}
internal void Ceq()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ceq");
_ilGen.Emit(OpCodes.Ceq);
}
internal void Throw()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Throw");
_ilGen.Emit(OpCodes.Throw);
}
internal void Ldtoken(Type t)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldtoken " + t);
_ilGen.Emit(OpCodes.Ldtoken, t);
}
internal void Ldc(object o)
{
Type valueType = o.GetType();
if (o is Type)
{
Ldtoken((Type)o);
Call(GetTypeFromHandle);
}
else if (valueType.IsEnum)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceComment("Ldc " + o.GetType() + "." + o);
Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null));
}
else
{
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
Ldc((bool)o);
break;
case TypeCode.Char:
DiagnosticUtility.DebugAssert("Char is not a valid schema primitive and should be treated as int in DataContract");
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.CharIsInvalidPrimitive));
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture));
break;
case TypeCode.Int32:
Ldc((int)o);
break;
case TypeCode.UInt32:
Ldc((int)(uint)o);
break;
case TypeCode.UInt64:
Ldc((long)(ulong)o);
break;
case TypeCode.Int64:
Ldc((long)o);
break;
case TypeCode.Single:
Ldc((float)o);
break;
case TypeCode.Double:
Ldc((double)o);
break;
case TypeCode.String:
Ldstr((string)o);
break;
case TypeCode.Object:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.Empty:
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownConstantType, DataContract.GetClrTypeFullName(valueType))));
}
}
}
internal void Ldc(bool boolVar)
{
if (boolVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 1");
_ilGen.Emit(OpCodes.Ldc_I4_1);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 0");
_ilGen.Emit(OpCodes.Ldc_I4_0);
}
}
internal void Ldc(int intVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 " + intVar);
switch (intVar)
{
case -1:
_ilGen.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
_ilGen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
_ilGen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
_ilGen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
_ilGen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
_ilGen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
_ilGen.Emit(OpCodes.Ldc_I4_8);
break;
default:
_ilGen.Emit(OpCodes.Ldc_I4, intVar);
break;
}
}
internal void Ldc(long l)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i8 " + l);
_ilGen.Emit(OpCodes.Ldc_I8, l);
}
internal void Ldc(float f)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.r4 " + f);
_ilGen.Emit(OpCodes.Ldc_R4, f);
}
internal void Ldc(double d)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.r8 " + d);
_ilGen.Emit(OpCodes.Ldc_R8, d);
}
internal void Ldstr(string strVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldstr " + strVar);
_ilGen.Emit(OpCodes.Ldstr, strVar);
}
internal void LdlocAddress(LocalBuilder localBuilder)
{
if (localBuilder.LocalType.IsValueType)
Ldloca(localBuilder);
else
Ldloc(localBuilder);
}
internal void Ldloc(LocalBuilder localBuilder)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldloc " + _localNames[localBuilder]);
_ilGen.Emit(OpCodes.Ldloc, localBuilder);
EmitStackTop(localBuilder.LocalType);
}
internal void Stloc(LocalBuilder local)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stloc " + _localNames[local]);
EmitStackTop(local.LocalType);
_ilGen.Emit(OpCodes.Stloc, local);
}
internal void Ldloca(LocalBuilder localBuilder)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldloca " + _localNames[localBuilder]);
_ilGen.Emit(OpCodes.Ldloca, localBuilder);
EmitStackTop(localBuilder.LocalType);
}
internal void LdargAddress(ArgBuilder argBuilder)
{
if (argBuilder.ArgType.IsValueType)
Ldarga(argBuilder);
else
Ldarg(argBuilder);
}
internal void Ldarg(ArgBuilder arg)
{
Ldarg(arg.Index);
}
internal void Starg(ArgBuilder arg)
{
Starg(arg.Index);
}
internal void Ldarg(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldarg " + slot);
switch (slot)
{
case 0:
_ilGen.Emit(OpCodes.Ldarg_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldarg_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldarg_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldarg_3);
break;
default:
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarg_S, slot);
else
_ilGen.Emit(OpCodes.Ldarg, slot);
break;
}
}
internal void Starg(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Starg " + slot);
if (slot <= 255)
_ilGen.Emit(OpCodes.Starg_S, slot);
else
_ilGen.Emit(OpCodes.Starg, slot);
}
internal void Ldarga(ArgBuilder argBuilder)
{
Ldarga(argBuilder.Index);
}
internal void Ldarga(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldarga " + slot);
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarga_S, slot);
else
_ilGen.Emit(OpCodes.Ldarga, slot);
}
internal void Ldlen()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldlen");
_ilGen.Emit(OpCodes.Ldlen);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Conv.i4");
_ilGen.Emit(OpCodes.Conv_I4);
}
private OpCode GetLdelemOpCode(TypeCode typeCode) =>
typeCode switch
{
TypeCode.Object => OpCodes.Ldelem_Ref, // TypeCode.Object:
TypeCode.Boolean => OpCodes.Ldelem_I1, // TypeCode.Boolean:
TypeCode.Char => OpCodes.Ldelem_I2, // TypeCode.Char:
TypeCode.SByte => OpCodes.Ldelem_I1, // TypeCode.SByte:
TypeCode.Byte => OpCodes.Ldelem_U1, // TypeCode.Byte:
TypeCode.Int16 => OpCodes.Ldelem_I2, // TypeCode.Int16:
TypeCode.UInt16 => OpCodes.Ldelem_U2, // TypeCode.UInt16:
TypeCode.Int32 => OpCodes.Ldelem_I4, // TypeCode.Int32:
TypeCode.UInt32 => OpCodes.Ldelem_U4, // TypeCode.UInt32:
TypeCode.Int64 => OpCodes.Ldelem_I8, // TypeCode.Int64:
TypeCode.UInt64 => OpCodes.Ldelem_I8, // TypeCode.UInt64:
TypeCode.Single => OpCodes.Ldelem_R4, // TypeCode.Single:
TypeCode.Double => OpCodes.Ldelem_R8, // TypeCode.Double:
TypeCode.String => OpCodes.Ldelem_Ref, // TypeCode.String:
_ => OpCodes.Nop,
};
internal void Ldelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
{
Ldelem(Enum.GetUnderlyingType(arrayElementType));
}
else
{
OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType))));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
EmitStackTop(arrayElementType);
}
}
internal void Ldelema(Type arrayElementType)
{
OpCode opCode = OpCodes.Ldelema;
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode, arrayElementType);
EmitStackTop(arrayElementType);
}
private OpCode GetStelemOpCode(TypeCode typeCode) =>
typeCode switch
{
TypeCode.Object => OpCodes.Stelem_Ref, // TypeCode.Object:
TypeCode.Boolean => OpCodes.Stelem_I1, // TypeCode.Boolean:
TypeCode.Char => OpCodes.Stelem_I2, // TypeCode.Char:
TypeCode.SByte => OpCodes.Stelem_I1, // TypeCode.SByte:
TypeCode.Byte => OpCodes.Stelem_I1, // TypeCode.Byte:
TypeCode.Int16 => OpCodes.Stelem_I2, // TypeCode.Int16:
TypeCode.UInt16 => OpCodes.Stelem_I2, // TypeCode.UInt16:
TypeCode.Int32 => OpCodes.Stelem_I4, // TypeCode.Int32:
TypeCode.UInt32 => OpCodes.Stelem_I4, // TypeCode.UInt32:
TypeCode.Int64 => OpCodes.Stelem_I8, // TypeCode.Int64:
TypeCode.UInt64 => OpCodes.Stelem_I8, // TypeCode.UInt64:
TypeCode.Single => OpCodes.Stelem_R4, // TypeCode.Single:
TypeCode.Double => OpCodes.Stelem_R8, // TypeCode.Double:
TypeCode.String => OpCodes.Stelem_Ref, // TypeCode.String:
_ => OpCodes.Nop,
};
internal void Stelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
Stelem(Enum.GetUnderlyingType(arrayElementType));
else
{
OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType))));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
EmitStackTop(arrayElementType);
_ilGen.Emit(opCode);
}
}
internal Label DefineLabel()
{
return _ilGen.DefineLabel();
}
internal void MarkLabel(Label label)
{
_ilGen.MarkLabel(label);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel(label.GetHashCode() + ":");
}
internal void Add()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Add");
_ilGen.Emit(OpCodes.Add);
}
internal void Subtract()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Sub");
_ilGen.Emit(OpCodes.Sub);
}
internal void And()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("And");
_ilGen.Emit(OpCodes.And);
}
internal void Or()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Or");
_ilGen.Emit(OpCodes.Or);
}
internal void Not()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Not");
_ilGen.Emit(OpCodes.Not);
}
internal void Ret()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ret");
_ilGen.Emit(OpCodes.Ret);
}
internal void Br(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Br " + label.GetHashCode());
_ilGen.Emit(OpCodes.Br, label);
}
internal void Blt(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Blt " + label.GetHashCode());
_ilGen.Emit(OpCodes.Blt, label);
}
internal void Brfalse(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Brfalse " + label.GetHashCode());
_ilGen.Emit(OpCodes.Brfalse, label);
}
internal void Brtrue(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Brtrue " + label.GetHashCode());
_ilGen.Emit(OpCodes.Brtrue, label);
}
internal void Pop()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Pop");
_ilGen.Emit(OpCodes.Pop);
}
internal void Dup()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Dup");
_ilGen.Emit(OpCodes.Dup);
}
private void LoadThis(object thisObj, MethodInfo methodInfo)
{
if (thisObj != null && !methodInfo.IsStatic)
{
LoadAddress(thisObj);
ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType);
}
}
private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo)
{
Load(arg);
if (arg != null)
ConvertValue(GetVariableType(arg), methodInfo.GetParameters()[oneBasedArgIndex - 1].ParameterType);
}
private void InternalIf(bool negate)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
if (negate)
Brtrue(ifState.ElseBegin);
else
Brfalse(ifState.ElseBegin);
_blockStack.Push(ifState);
}
private OpCode GetConvOpCode(TypeCode typeCode) =>
typeCode switch
{
TypeCode.Boolean => OpCodes.Conv_I1, // TypeCode.Boolean:
TypeCode.Char => OpCodes.Conv_I2, // TypeCode.Char:
TypeCode.SByte => OpCodes.Conv_I1, // TypeCode.SByte:
TypeCode.Byte => OpCodes.Conv_U1, // TypeCode.Byte:
TypeCode.Int16 => OpCodes.Conv_I2, // TypeCode.Int16:
TypeCode.UInt16 => OpCodes.Conv_U2, // TypeCode.UInt16:
TypeCode.Int32 => OpCodes.Conv_I4, // TypeCode.Int32:
TypeCode.UInt32 => OpCodes.Conv_U4, // TypeCode.UInt32:
TypeCode.Int64 => OpCodes.Conv_I8, // TypeCode.Int64:
TypeCode.UInt64 => OpCodes.Conv_I8, // TypeCode.UInt64:
TypeCode.Single => OpCodes.Conv_R4, // TypeCode.Single:
TypeCode.Double => OpCodes.Conv_R8, // TypeCode.Double:
_ => OpCodes.Nop,
};
private void InternalConvert(Type source, Type target, bool isAddress)
{
if (target == source)
return;
if (target.IsValueType)
{
if (source.IsValueType)
{
OpCode opCode = GetConvOpCode(target.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target))));
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
}
}
else if (source.IsAssignableFrom(target))
{
Unbox(target);
if (!isAddress)
Ldobj(target);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
else if (target.IsAssignableFrom(source))
{
if (source.IsValueType)
{
if (isAddress)
Ldobj(source);
Box(source);
}
}
else if (source.IsAssignableFrom(target))
{
Castclass(target);
}
else if (target.IsInterface || source.IsInterface)
{
Castclass(target);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
private IfState PopIfState()
{
object stackTop = _blockStack.Pop();
IfState ifState = stackTop as IfState;
if (ifState == null)
ThrowMismatchException(stackTop);
return ifState;
}
#if USE_REFEMIT
void InitAssemblyBuilder(string methodName)
{
AssemblyName name = new AssemblyName();
name.Name = "Microsoft.GeneratedCode."+methodName;
//Add SecurityCritical and SecurityTreatAsSafe attributes to the generated method
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name + ".dll", false);
}
#endif
private void ThrowMismatchException(object expected)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString())));
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceInstruction(string line)
{
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceLabel(string line)
{
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceComment(string comment)
{
}
internal void EmitStackTop(Type stackTopType)
{
if (_codeGenTrace != CodeGenTrace.Tron)
return;
}
internal Label[] Switch(int labelCount)
{
SwitchState switchState = new SwitchState(DefineLabel(), DefineLabel());
Label[] caseLabels = new Label[labelCount];
for (int i = 0; i < caseLabels.Length; i++)
caseLabels[i] = DefineLabel();
_ilGen.Emit(OpCodes.Switch, caseLabels);
Br(switchState.DefaultLabel);
_blockStack.Push(switchState);
return caseLabels;
}
internal void Case(Label caseLabel1, string caseLabelName)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("case " + caseLabelName + "{");
MarkLabel(caseLabel1);
}
internal void EndCase()
{
object stackTop = _blockStack.Peek();
SwitchState switchState = stackTop as SwitchState;
if (switchState == null)
ThrowMismatchException(stackTop);
Br(switchState.EndOfSwitchLabel);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("} //end case ");
}
internal void EndSwitch()
{
object stackTop = _blockStack.Pop();
SwitchState switchState = stackTop as SwitchState;
if (switchState == null)
ThrowMismatchException(stackTop);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("} //end switch");
if (!switchState.DefaultDefined)
MarkLabel(switchState.DefaultLabel);
MarkLabel(switchState.EndOfSwitchLabel);
}
private static readonly MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod;
internal void ElseIfIsEmptyString(LocalBuilder strLocal)
{
IfState ifState = (IfState)_blockStack.Pop();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
Load(strLocal);
Call(s_stringLength);
Load(0);
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(Cmp.EqualTo), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void IfNotIsEmptyString(LocalBuilder strLocal)
{
Load(strLocal);
Call(s_stringLength);
Load(0);
If(Cmp.NotEqualTo);
}
internal void BeginWhileCondition()
{
Label startWhile = DefineLabel();
MarkLabel(startWhile);
_blockStack.Push(startWhile);
}
internal void BeginWhileBody(Cmp cmpOp)
{
Label startWhile = (Label)_blockStack.Pop();
If(cmpOp);
_blockStack.Push(startWhile);
}
internal void EndWhile()
{
Label startWhile = (Label)_blockStack.Pop();
Br(startWhile);
EndIf();
}
internal void CallStringFormat(string msg, params object[] values)
{
NewArray(typeof(object), values.Length);
if (_stringFormatArray == null)
_stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray");
Stloc(_stringFormatArray);
for (int i = 0; i < values.Length; i++)
StoreArrayElement(_stringFormatArray, i, values[i]);
Load(msg);
Load(_stringFormatArray);
Call(StringFormat);
}
internal void ToString(Type type)
{
if (type != Globals.TypeOfString)
{
if (type.IsValueType)
{
Box(type);
}
Call(ObjectToString);
}
}
}
internal class ArgBuilder
{
internal int Index;
internal Type ArgType;
internal ArgBuilder(int index, Type argType)
{
this.Index = index;
this.ArgType = argType;
}
}
internal class ForState
{
private readonly LocalBuilder _indexVar;
private readonly Label _beginLabel;
private readonly Label _testLabel;
private Label _endLabel;
private bool _requiresEndLabel;
private readonly object _end;
internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
{
_indexVar = indexVar;
_beginLabel = beginLabel;
_testLabel = testLabel;
_end = end;
}
internal LocalBuilder Index
{
get
{
return _indexVar;
}
}
internal Label BeginLabel
{
get
{
return _beginLabel;
}
}
internal Label TestLabel
{
get
{
return _testLabel;
}
}
internal Label EndLabel
{
get
{
return _endLabel;
}
set
{
_endLabel = value;
}
}
internal bool RequiresEndLabel
{
get
{
return _requiresEndLabel;
}
set
{
_requiresEndLabel = value;
}
}
internal object End
{
get
{
return _end;
}
}
}
internal enum Cmp
{
LessThan,
EqualTo,
LessThanOrEqualTo,
GreaterThan,
NotEqualTo,
GreaterThanOrEqualTo
}
internal class IfState
{
private Label _elseBegin;
private Label _endIf;
internal Label EndIf
{
get
{
return _endIf;
}
set
{
_endIf = value;
}
}
internal Label ElseBegin
{
get
{
return _elseBegin;
}
set
{
_elseBegin = value;
}
}
}
internal class SwitchState
{
private readonly Label _defaultLabel;
private readonly Label _endOfSwitchLabel;
private bool _defaultDefined;
internal SwitchState(Label defaultLabel, Label endOfSwitchLabel)
{
_defaultLabel = defaultLabel;
_endOfSwitchLabel = endOfSwitchLabel;
_defaultDefined = false;
}
internal Label DefaultLabel
{
get
{
return _defaultLabel;
}
}
internal Label EndOfSwitchLabel
{
get
{
return _endOfSwitchLabel;
}
}
internal bool DefaultDefined
{
get
{
return _defaultDefined;
}
set
{
_defaultDefined = value;
}
}
}
}
| |
using System;
using System.Diagnostics;
using NUnit.Framework;
namespace StructureMap.Testing
{
// SAMPLE: auto-wiring-sample
public interface Xman{}
public class Cyclops : Xman{}
public interface Avenger{}
public class IronMan : Avenger{}
public class CrossoverEvent
{
public Xman Xman { get; set; }
public Avenger Avenger { get; set; }
public CrossoverEvent(Xman xman, Avenger avenger)
{
Xman = xman;
Avenger = avenger;
}
}
public class UsingCrossover
{
[Test]
public void showing_auto_wiring()
{
var container = new Container(x => {
x.For<Xman>().Use<Cyclops>();
x.For<Avenger>().Use<IronMan>();
});
// Notice that at no point did we define how to
// build CrossoverEvent.
var @event = container.GetInstance<CrossoverEvent>();
@event.Avenger.ShouldBeOfType<IronMan>();
@event.Xman.ShouldBeOfType<Cyclops>();
}
}
// ENDSAMPLE
public interface IValidator
{
}
public class Validator : IValidator
{
private readonly string _name;
public Validator(string name)
{
_name = name;
}
public override string ToString()
{
return string.Format("Name: {0}", _name);
}
}
public class ClassThatUsesValidators
{
private readonly IValidator[] _validators;
public ClassThatUsesValidators(IValidator[] validators)
{
_validators = validators;
}
public void Write()
{
foreach (var validator in _validators)
{
Debug.WriteLine(validator);
}
}
}
[TestFixture]
public class ValidatorExamples
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
container = new Container(x => {
x.For<IValidator>().AddInstances(o => {
o.Type<Validator>().Ctor<string>("name").Is("Red").Named("Red");
o.Type<Validator>().Ctor<string>("name").Is("Blue").Named("Blue");
o.Type<Validator>().Ctor<string>("name").Is("Purple").Named("Purple");
o.Type<Validator>().Ctor<string>("name").Is("Green").Named("Green");
});
x.For<ClassThatUsesValidators>().AddInstances(o => {
// Define an Instance of ClassThatUsesValidators that depends on AutoWiring
o.Type<ClassThatUsesValidators>().Named("WithAutoWiring");
// Define an Instance of ClassThatUsesValidators that overrides AutoWiring
o.Type<ClassThatUsesValidators>().Named("ExplicitArray")
.EnumerableOf<IValidator>().Contains(y => {
y.TheInstanceNamed("Red");
y.TheInstanceNamed("Green");
});
});
});
}
#endregion
private Container container;
public class DataContext
{
private readonly Guid _id = Guid.NewGuid();
public override string ToString()
{
return string.Format("Id: {0}", _id);
}
}
public class Class1
{
private readonly DataContext _context;
public Class1(DataContext context)
{
_context = context;
}
public override string ToString()
{
return string.Format("Class1 has session: {0}", _context);
}
}
public class Class2
{
private readonly Class1 _class1;
private readonly DataContext _context;
public Class2(Class1 class1, DataContext context)
{
_class1 = class1;
_context = context;
}
public override string ToString()
{
return string.Format("Class2 has session: {0}\n{1}", _context, _class1);
}
}
public class Class3
{
private readonly Class2 _class2;
private readonly DataContext _context;
public Class3(Class2 class2, DataContext context)
{
_class2 = class2;
_context = context;
}
public override string ToString()
{
return string.Format("Class3 has session: {0}\n{1}", _context, _class2);
}
}
[Test]
public void demonstrate_session_identity()
{
var class3 = container.GetInstance<Class3>();
Debug.WriteLine(class3);
}
[Test]
public void demonstrate_session_identity_with_explicit_argument()
{
var context = new DataContext();
Debug.WriteLine("The context being passed in is " + context);
var class3 = container.With(context).GetInstance<Class3>();
Debug.WriteLine(class3);
}
[Test]
public void what_are_the_validators()
{
Debug.WriteLine("With Auto Wiring");
container.GetInstance<ClassThatUsesValidators>("WithAutoWiring").Write();
Debug.WriteLine("=================================");
Debug.WriteLine("With Explicit Configuration");
container.GetInstance<ClassThatUsesValidators>("ExplicitArray").Write();
}
}
}
| |
using System.Net;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Creating;
public sealed class AtomicCreateResourceWithToManyRelationshipTests
: IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext;
private readonly OperationsFakers _fakers = new();
public AtomicCreateResourceWithToManyRelationshipTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OperationsController>();
// These routes need to be registered in ASP.NET for rendering links to resource/relationship endpoints.
testContext.UseController<PlaylistsController>();
testContext.UseController<MusicTracksController>();
}
[Fact]
public async Task Can_create_OneToMany_relationship()
{
// Arrange
List<Performer> existingPerformers = _fakers.Performer.Generate(2);
string newTitle = _fakers.MusicTrack.Generate().Title;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Performers.AddRange(existingPerformers);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
attributes = new
{
title = newTitle
},
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers",
id = existingPerformers[0].StringId
},
new
{
type = "performers",
id = existingPerformers[1].StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(1);
responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.Type.Should().Be("musicTracks");
resource.Attributes.ShouldNotBeEmpty();
resource.Relationships.ShouldNotBeEmpty();
});
Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId);
trackInDatabase.Performers.ShouldHaveCount(2);
trackInDatabase.Performers.Should().ContainSingle(performer => performer.Id == existingPerformers[0].Id);
trackInDatabase.Performers.Should().ContainSingle(performer => performer.Id == existingPerformers[1].Id);
});
}
[Fact]
public async Task Can_create_ManyToMany_relationship()
{
// Arrange
List<MusicTrack> existingTracks = _fakers.MusicTrack.Generate(3);
string newName = _fakers.Playlist.Generate().Name;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.AddRange(existingTracks);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "playlists",
attributes = new
{
name = newName
},
relationships = new
{
tracks = new
{
data = new[]
{
new
{
type = "musicTracks",
id = existingTracks[0].StringId
},
new
{
type = "musicTracks",
id = existingTracks[1].StringId
},
new
{
type = "musicTracks",
id = existingTracks[2].StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(1);
responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.Type.Should().Be("playlists");
resource.Attributes.ShouldNotBeEmpty();
resource.Relationships.ShouldNotBeEmpty();
});
long newPlaylistId = long.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(newPlaylistId);
playlistInDatabase.Tracks.ShouldHaveCount(3);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[0].Id);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[1].Id);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[2].Id);
});
}
[Fact]
public async Task Cannot_create_for_missing_relationship_type()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = new[]
{
new
{
id = Unknown.StringId.For<Performer, int>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/performers/data[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_unknown_relationship_type()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = Unknown.ResourceType,
id = Unknown.StringId.For<Performer, int>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/performers/data[0]/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_missing_relationship_ID()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers"
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'id' or 'lid' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/performers/data[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_unknown_relationship_IDs()
{
// Arrange
string newTitle = _fakers.MusicTrack.Generate().Title;
string performerId1 = Unknown.StringId.For<Performer, int>();
string performerId2 = Unknown.StringId.AltFor<Performer, int>();
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
attributes = new
{
title = newTitle
},
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers",
id = performerId1
},
new
{
type = "performers",
id = performerId2
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.ShouldHaveCount(2);
ErrorObject error1 = responseDocument.Errors[0];
error1.StatusCode.Should().Be(HttpStatusCode.NotFound);
error1.Title.Should().Be("A related resource does not exist.");
error1.Detail.Should().Be($"Related resource of type 'performers' with ID '{performerId1}' in relationship 'performers' does not exist.");
error1.Source.ShouldNotBeNull();
error1.Source.Pointer.Should().Be("/atomic:operations[0]");
error1.Meta.Should().NotContainKey("requestBody");
ErrorObject error2 = responseDocument.Errors[1];
error2.StatusCode.Should().Be(HttpStatusCode.NotFound);
error2.Title.Should().Be("A related resource does not exist.");
error2.Detail.Should().Be($"Related resource of type 'performers' with ID '{performerId2}' in relationship 'performers' does not exist.");
error2.Source.ShouldNotBeNull();
error2.Source.Pointer.Should().Be("/atomic:operations[0]");
error2.Meta.Should().NotContainKey("requestBody");
}
[Fact]
public async Task Cannot_create_on_relationship_type_mismatch()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "playlists",
id = Unknown.StringId.For<Playlist, long>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Conflict);
error.Title.Should().Be("Failed to deserialize request body: Incompatible resource type found.");
error.Detail.Should().Be("Type 'playlists' is incompatible with type 'performers' of relationship 'performers'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/performers/data[0]/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Can_create_with_duplicates()
{
// Arrange
Performer existingPerformer = _fakers.Performer.Generate();
string newTitle = _fakers.MusicTrack.Generate().Title;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Performers.Add(existingPerformer);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
attributes = new
{
title = newTitle
},
relationships = new
{
performers = new
{
data = new[]
{
new
{
type = "performers",
id = existingPerformer.StringId
},
new
{
type = "performers",
id = existingPerformer.StringId
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Results.ShouldHaveCount(1);
responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource =>
{
resource.Type.Should().Be("musicTracks");
resource.Attributes.ShouldNotBeEmpty();
resource.Relationships.ShouldNotBeEmpty();
});
Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId);
trackInDatabase.Performers.ShouldHaveCount(1);
trackInDatabase.Performers[0].Id.Should().Be(existingPerformer.Id);
});
}
[Fact]
public async Task Cannot_create_with_missing_data_in_OneToMany_relationship()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "musicTracks",
relationships = new
{
performers = new
{
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'data' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/performers");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_with_null_data_in_ManyToMany_relationship()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "playlists",
relationships = new
{
tracks = new
{
data = (object?)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of 'null'.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/tracks/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_with_object_data_in_ManyToMany_relationship()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "playlists",
relationships = new
{
tracks = new
{
data = new
{
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of an object.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/tracks/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
}
| |
// 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;
/*********************************************
Notes on tests:
loops:
0,1,2,3,4,5,7,8,9,12,13
Values:
uint, int, long
inc, assignment, adding, double inc.
*********************************************/
internal class test
{
public static int Main()
{
int failed_tests = 0;
// Test 01
if (test_01(3) != 67)
{
Console.WriteLine("FAIL: test_01(3)");
failed_tests++;
}
// Test 02
if (test_02(3) != 131)
{
Console.WriteLine("FAIL: test_02(3)");
failed_tests++;
}
// Test 03
if (test_03(3) != 582636163)
{
Console.WriteLine("FAIL: test_03(3)");
failed_tests++;
}
// Test 04
if (test_04(3) != 643)
{
Console.WriteLine("FAIL: test_04(3)");
failed_tests++;
}
// Test 05
if (test_05(3) != 67)
{
Console.WriteLine("FAIL: test_05(3)");
failed_tests++;
}
// Test 06
if (test_06(3) != 131)
{
Console.WriteLine("FAIL: test_06(3)");
failed_tests++;
}
// Test 07
if (test_07(3) != 582636163)
{
Console.WriteLine("FAIL: test_07(3)");
failed_tests++;
}
// Test 08
if (test_08(3) != 643)
{
Console.WriteLine("FAIL: test_08(3)");
failed_tests++;
}
// Test 09
if (test_09(3) != 67)
{
Console.WriteLine("FAIL: test_09(3)");
failed_tests++;
}
// Test 10
if (test_10(3) != 131)
{
Console.WriteLine("FAIL: test_10(3)");
failed_tests++;
}
// Test 11
if (test_11(3) != -6817972681569578365)
{
Console.WriteLine("FAIL: test_11(3)");
failed_tests++;
}
// Test 12
if (test_12(3) != 643)
{
Console.WriteLine("FAIL: test_12(3)");
failed_tests++;
}
// Test 01
if (test_01(5) != 69)
{
Console.WriteLine("FAIL: test_01(5)");
failed_tests++;
}
// Test 02
if (test_02(5) != 133)
{
Console.WriteLine("FAIL: test_02(5)");
failed_tests++;
}
// Test 03
if (test_03(5) != -1403567675)
{
Console.WriteLine("FAIL: test_03(5)");
failed_tests++;
}
// Test 04
if (test_04(5) != 1029)
{
Console.WriteLine("FAIL: test_04(5)");
failed_tests++;
}
// Test 05
if (test_05(5) != 69)
{
Console.WriteLine("FAIL: test_05(5)");
failed_tests++;
}
// Test 06
if (test_06(5) != 133)
{
Console.WriteLine("FAIL: test_06(5)");
failed_tests++;
}
// Test 07
if (test_07(5) != 2891399621)
{
Console.WriteLine("FAIL: test_07(5)");
failed_tests++;
}
// Test 08
if (test_08(5) != 1029)
{
Console.WriteLine("FAIL: test_08(5)");
failed_tests++;
}
// Test 09
if (test_09(5) != 69)
{
Console.WriteLine("FAIL: test_09(5)");
failed_tests++;
}
// Test 10
if (test_10(5) != 133)
{
Console.WriteLine("FAIL: test_10(5)");
failed_tests++;
}
// Test 11
if (test_11(5) != -1088802703752609339)
{
Console.WriteLine("FAIL: test_11(5)");
failed_tests++;
}
// Test 12
if (test_12(5) != 1029)
{
Console.WriteLine("FAIL: test_12(5)");
failed_tests++;
}
return (failed_tests == 0) ? 100 : 1;
}
public static int test_01(int a)
{
int b = a;
for (int i = 0; i < 0; i++)
{
b++;
}
for (int i = 0; i < 1; i++)
{
b++;
}
for (int i = 0; i < 2; i++)
{
b++;
}
for (int i = 0; i < 3; i++)
{
b++;
}
for (int i = 0; i < 4; i++)
{
b++;
}
for (int i = 0; i < 5; i++)
{
b++;
}
for (int i = 0; i < 7; i++)
{
b++;
}
for (int i = 0; i < 8; i++)
{
b++;
}
for (int i = 0; i < 9; i++)
{
b++;
}
for (int i = 0; i < 12; i++)
{
b++;
}
for (int i = 0; i < 13; i++)
{
b++;
}
return b;
}
public static int test_02(int a)
{
int b = a;
for (int i = 0; i < 0; i++)
{
b++; b++;
}
for (int i = 0; i < 1; i++)
{
b++; b++;
}
for (int i = 0; i < 2; i++)
{
b++; b++;
}
for (int i = 0; i < 3; i++)
{
b++; b++;
}
for (int i = 0; i < 4; i++)
{
b++; b++;
}
for (int i = 0; i < 5; i++)
{
b++; b++;
}
for (int i = 0; i < 7; i++)
{
b++; b++;
}
for (int i = 0; i < 8; i++)
{
b++; b++;
}
for (int i = 0; i < 9; i++)
{
b++; b++;
}
for (int i = 0; i < 12; i++)
{
b++; b++;
}
for (int i = 0; i < 13; i++)
{
b++; b++;
}
return b;
}
public static int test_03(int a)
{
int b = a;
for (int i = 0; i < 0; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 1; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 2; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 3; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 4; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 5; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 7; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 8; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 9; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 12; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 13; i++)
{
b++; b = b * a;
}
return b;
}
public static int test_04(int a)
{
int b = a;
for (int i = 0; i < 0; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 1; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 2; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 3; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 4; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 5; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 7; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 8; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 9; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 12; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 13; i++)
{
b++; b = b + a * 3;
}
return b;
}
public static uint test_05(uint a)
{
uint b = a;
for (int i = 0; i < 0; i++)
{
b++;
}
for (int i = 0; i < 1; i++)
{
b++;
}
for (int i = 0; i < 2; i++)
{
b++;
}
for (int i = 0; i < 3; i++)
{
b++;
}
for (int i = 0; i < 4; i++)
{
b++;
}
for (int i = 0; i < 5; i++)
{
b++;
}
for (int i = 0; i < 7; i++)
{
b++;
}
for (int i = 0; i < 8; i++)
{
b++;
}
for (int i = 0; i < 9; i++)
{
b++;
}
for (int i = 0; i < 12; i++)
{
b++;
}
for (int i = 0; i < 13; i++)
{
b++;
}
return b;
}
public static uint test_06(uint a)
{
uint b = a;
for (int i = 0; i < 0; i++)
{
b++; b++;
}
for (int i = 0; i < 1; i++)
{
b++; b++;
}
for (int i = 0; i < 2; i++)
{
b++; b++;
}
for (int i = 0; i < 3; i++)
{
b++; b++;
}
for (int i = 0; i < 4; i++)
{
b++; b++;
}
for (int i = 0; i < 5; i++)
{
b++; b++;
}
for (int i = 0; i < 7; i++)
{
b++; b++;
}
for (int i = 0; i < 8; i++)
{
b++; b++;
}
for (int i = 0; i < 9; i++)
{
b++; b++;
}
for (int i = 0; i < 12; i++)
{
b++; b++;
}
for (int i = 0; i < 13; i++)
{
b++; b++;
}
return b;
}
public static uint test_07(uint a)
{
uint b = a;
for (int i = 0; i < 0; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 1; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 2; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 3; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 4; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 5; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 7; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 8; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 9; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 12; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 13; i++)
{
b++; b = b * a;
}
return b;
}
public static uint test_08(uint a)
{
uint b = a;
for (int i = 0; i < 0; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 1; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 2; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 3; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 4; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 5; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 7; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 8; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 9; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 12; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 13; i++)
{
b++; b = b + a * 3;
}
return b;
}
public static long test_09(long a)
{
long b = a;
for (int i = 0; i < 0; i++)
{
b++;
}
for (int i = 0; i < 1; i++)
{
b++;
}
for (int i = 0; i < 2; i++)
{
b++;
}
for (int i = 0; i < 3; i++)
{
b++;
}
for (int i = 0; i < 4; i++)
{
b++;
}
for (int i = 0; i < 5; i++)
{
b++;
}
for (int i = 0; i < 7; i++)
{
b++;
}
for (int i = 0; i < 8; i++)
{
b++;
}
for (int i = 0; i < 9; i++)
{
b++;
}
for (int i = 0; i < 12; i++)
{
b++;
}
for (int i = 0; i < 13; i++)
{
b++;
}
return b;
}
public static long test_10(long a)
{
long b = a;
for (int i = 0; i < 0; i++)
{
b++; b++;
}
for (int i = 0; i < 1; i++)
{
b++; b++;
}
for (int i = 0; i < 2; i++)
{
b++; b++;
}
for (int i = 0; i < 3; i++)
{
b++; b++;
}
for (int i = 0; i < 4; i++)
{
b++; b++;
}
for (int i = 0; i < 5; i++)
{
b++; b++;
}
for (int i = 0; i < 7; i++)
{
b++; b++;
}
for (int i = 0; i < 8; i++)
{
b++; b++;
}
for (int i = 0; i < 9; i++)
{
b++; b++;
}
for (int i = 0; i < 12; i++)
{
b++; b++;
}
for (int i = 0; i < 13; i++)
{
b++; b++;
}
return b;
}
public static long test_11(long a)
{
long b = a;
for (int i = 0; i < 0; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 1; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 2; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 3; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 4; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 5; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 7; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 8; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 9; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 12; i++)
{
b++; b = b * a;
}
for (int i = 0; i < 13; i++)
{
b++; b = b * a;
}
return b;
}
public static long test_12(long a)
{
long b = a;
for (int i = 0; i < 0; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 1; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 2; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 3; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 4; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 5; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 7; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 8; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 9; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 12; i++)
{
b++; b = b + a * 3;
}
for (int i = 0; i < 13; i++)
{
b++; b = b + a * 3;
}
return b;
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Linq;
using Internal.Fakeables;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public sealed class LogManager
{
private static readonly LogFactory factory = new LogFactory();
private static IAppDomain currentAppDomain;
private static ICollection<Assembly> _hiddenAssemblies;
private static readonly object lockObject = new object();
/// <summary>
/// Delegate used to set/get the culture in use.
/// </summary>
[Obsolete]
public delegate CultureInfo GetCultureInfo();
#if !SILVERLIGHT && !MONO
/// <summary>
/// Initializes static members of the LogManager class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static LogManager()
{
SetupTerminationEvents();
}
#endif
/// <summary>
/// Prevents a default instance of the LogManager class from being created.
/// </summary>
private LogManager()
{
}
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged
{
add { factory.ConfigurationChanged += value; }
remove { factory.ConfigurationChanged -= value; }
}
#if !SILVERLIGHT
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded
{
add { factory.ConfigurationReloaded += value; }
remove { factory.ConfigurationReloaded -= value; }
}
#endif
/// <summary>
/// Gets or sets a value indicating whether NLog should throw exceptions.
/// By default exceptions are not thrown under any circumstances.
/// </summary>
public static bool ThrowExceptions
{
get { return factory.ThrowExceptions; }
set { factory.ThrowExceptions = value; }
}
internal static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set
{
#if !SILVERLIGHT && !MONO
currentAppDomain.DomainUnload -= TurnOffLogging;
currentAppDomain.ProcessExit -= TurnOffLogging;
#endif
currentAppDomain = value;
}
}
/// <summary>
/// Gets or sets the current logging configuration.
/// </summary>
public static LoggingConfiguration Configuration
{
get { return factory.Configuration; }
set { factory.Configuration = value; }
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public static LogLevel GlobalThreshold
{
get { return factory.GlobalThreshold; }
set { factory.GlobalThreshold = value; }
}
/// <summary>
/// Gets or sets the default culture to use.
/// </summary>
[Obsolete("Use Configuration.DefaultCultureInfo property instead")]
public static GetCultureInfo DefaultCultureInfo
{
get { return () => factory.DefaultCultureInfo ?? CultureInfo.CurrentCulture; }
set { throw new NotSupportedException("Setting the DefaultCultureInfo delegate is no longer supported. Use the Configuration.DefaultCultureInfo property to change the default CultureInfo."); }
}
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
return factory.GetLogger(GetClassFullName());
}
internal static bool IsHiddenAssembly(Assembly assembly)
{
return _hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly);
}
/// <summary>
/// Adds the given assembly which will be skipped
/// when NLog is trying to find the calling method on stack trace.
/// </summary>
/// <param name="assembly">The assembly to skip.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AddHiddenAssembly(Assembly assembly)
{
lock (lockObject)
{
if (_hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly))
return;
_hiddenAssemblies = new HashSet<Assembly>(_hiddenAssemblies ?? Enumerable.Empty<Assembly>())
{
assembly
};
}
}
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(Type loggerType)
{
return factory.GetLogger(GetClassFullName(), loggerType);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger which discards all log messages.</returns>
[CLSCompliant(false)]
public static Logger CreateNullLogger()
{
return factory.CreateNullLogger();
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
[CLSCompliant(false)]
public static Logger GetLogger(string name)
{
return factory.GetLogger(name);
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
[CLSCompliant(false)]
public static Logger GetLogger(string name, Type loggerType)
{
return factory.GetLogger(name, loggerType);
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger.
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public static void ReconfigExistingLoggers()
{
factory.ReconfigExistingLoggers();
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public static void Flush()
{
factory.Flush();
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(TimeSpan timeout)
{
factory.Flush(timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int timeoutMilliseconds)
{
factory.Flush(timeoutMilliseconds);
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public static void Flush(AsyncContinuation asyncContinuation)
{
factory.Flush(asyncContinuation);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
factory.Flush(asyncContinuation, timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
factory.Flush(asyncContinuation, timeoutMilliseconds);
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that implements IDisposable whose Dispose() method reenables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public static IDisposable DisableLogging()
{
return factory.SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static void EnableLogging()
{
factory.ResumeLogging();
}
/// <summary>
/// Checks if logging is currently enabled.
/// </summary>
/// <returns><see langword="true" /> if logging is currently enabled, <see langword="false"/>
/// otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static bool IsLoggingEnabled()
{
return factory.IsLoggingEnabled();
}
/// <summary>
/// Dispose all targets, and shutdown logging.
/// </summary>
public static void Shutdown()
{
foreach (var target in Configuration.AllTargets)
{
target.Dispose();
}
}
#if !SILVERLIGHT && !MONO
private static void SetupTerminationEvents()
{
try
{
CurrentAppDomain.ProcessExit += TurnOffLogging;
CurrentAppDomain.DomainUnload += TurnOffLogging;
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Error setting up termination events: {0}", exception);
}
}
#endif
/// <summary>
/// Gets the fully qualified name of the class invoking the LogManager, including the
/// namespace but not the assembly.
/// </summary>
private static string GetClassFullName()
{
string className;
Type declaringType;
int framesToSkip = 2;
do
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(framesToSkip);
#else
StackFrame frame = new StackFrame(framesToSkip, false);
#endif
MethodBase method = frame.GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
{
className = method.Name;
break;
}
framesToSkip++;
className = declaringType.FullName;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return className;
}
private static void TurnOffLogging(object sender, EventArgs args)
{
// Reset logging configuration to null; this causes old configuration (if any) to be
// closed.
InternalLogger.Info("Shutting down logging...");
Configuration = null;
InternalLogger.Info("Logger has been shut down.");
}
}
}
| |
// Copyright (c) 2015 SharpYaml - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// 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 SharpYaml;
using SharpYaml.Events;
using System.Text;
namespace SharpYaml.Serialization
{
/// <summary>
/// Represents a sequence node in the YAML document.
/// </summary>
[DebuggerDisplay("Count = {children.Count}")]
public class YamlSequenceNode : YamlNode, IEnumerable<YamlNode>
{
private readonly IList<YamlNode> children = new List<YamlNode>();
/// <summary>
/// Gets the collection of child nodes.
/// </summary>
/// <value>The children.</value>
public IList<YamlNode> Children
{
get
{
return children;
}
}
/// <summary>
/// Gets or sets the style of the node.
/// </summary>
/// <value>The style.</value>
public YamlStyle Style { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="state">The state.</param>
internal YamlSequenceNode(EventReader events, DocumentLoadingState state)
{
SequenceStart sequence = events.Expect<SequenceStart>();
Load(sequence, state);
Style = sequence.Style;
bool hasUnresolvedAliases = false;
while (!events.Accept<SequenceEnd>())
{
YamlNode child = ParseNode(events, state);
children.Add(child);
hasUnresolvedAliases |= child is YamlAliasNode;
}
if (hasUnresolvedAliases)
{
state.AddNodeWithUnresolvedAliases(this);
}
#if DEBUG
else
{
foreach (var child in children)
{
if (child is YamlAliasNode)
{
throw new InvalidOperationException("Error in alias resolution.");
}
}
}
#endif
events.Expect<SequenceEnd>();
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
/// </summary>
public YamlSequenceNode()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
/// </summary>
public YamlSequenceNode(params YamlNode[] children)
: this((IEnumerable<YamlNode>)children)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlSequenceNode"/> class.
/// </summary>
public YamlSequenceNode(IEnumerable<YamlNode> children)
{
foreach (var child in children)
{
this.children.Add(child);
}
}
/// <summary>
/// Adds the specified child to the <see cref="Children"/> collection.
/// </summary>
/// <param name="child">The child.</param>
public void Add(YamlNode child)
{
children.Add(child);
}
/// <summary>
/// Adds a scalar node to the <see cref="Children"/> collection.
/// </summary>
/// <param name="child">The child.</param>
public void Add(string child)
{
children.Add(new YamlScalarNode(child));
}
/// <summary>
/// Resolves the aliases that could not be resolved when the node was created.
/// </summary>
/// <param name="state">The state of the document.</param>
internal override void ResolveAliases(DocumentLoadingState state)
{
for (int i = 0; i < children.Count; ++i)
{
if (children[i] is YamlAliasNode)
{
children[i] = state.GetNode(children[i].Anchor, true, children[i].Start, children[i].End);
}
}
}
/// <summary>
/// Saves the current node to the specified emitter.
/// </summary>
/// <param name="emitter">The emitter where the node is to be saved.</param>
/// <param name="state">The state.</param>
internal override void Emit(IEmitter emitter, EmitterState state)
{
emitter.Emit(new SequenceStart(Anchor, Tag, string.IsNullOrEmpty(Tag), Style));
foreach (var node in children)
{
node.Save(emitter, state);
}
emitter.Emit(new SequenceEnd());
}
/// <summary>
/// Accepts the specified visitor by calling the appropriate Visit method on it.
/// </summary>
/// <param name="visitor">
/// A <see cref="IYamlVisitor"/>.
/// </param>
public override void Accept(IYamlVisitor visitor)
{
visitor.Visit(this);
}
/// <summary />
public override bool Equals(object other)
{
var obj = other as YamlSequenceNode;
if (obj == null || !Equals(obj) || children.Count != obj.children.Count)
{
return false;
}
for (int i = 0; i < children.Count; ++i)
{
if (!SafeEquals(children[i], obj.children[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
var hashCode = base.GetHashCode();
foreach (var item in children)
{
hashCode = CombineHashCodes(hashCode, GetHashCode(item));
}
return hashCode;
}
/// <summary>
/// Gets all nodes from the document, starting on the current node.
/// </summary>
public override IEnumerable<YamlNode> AllNodes
{
get
{
yield return this;
foreach (var child in children)
{
foreach (var node in child.AllNodes)
{
yield return node;
}
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var text = new StringBuilder("[ ");
foreach (var child in children)
{
if(text.Length > 2)
{
text.Append(", ");
}
text.Append(child);
}
text.Append(" ]");
return text.ToString();
}
#region IEnumerable<YamlNode> Members
/// <summary />
public IEnumerator<YamlNode> GetEnumerator()
{
return Children.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Data;
using EDEngineer.Localization;
using EDEngineer.Models;
using EDEngineer.Models.Operations;
using EDEngineer.Models.Utils;
using EDEngineer.Properties;
using EDEngineer.Utils;
using EDEngineer.Utils.System;
using EDEngineer.Views.Popups;
using Newtonsoft.Json;
using NodaTime;
namespace EDEngineer.Views
{
public class CommanderViewModel : INotifyPropertyChanged, IDisposable
{
public string CommanderName { get; }
public State State { get; }
public BlueprintFilters Filters { get; private set; }
public ObservableCollection<Entry> HighlightedEntryData { get; } = new ObservableCollection<Entry>();
public ShoppingListViewModel ShoppingList => shoppingList;
private readonly JournalEntryConverter journalEntryConverter;
private readonly BlueprintConverter blueprintConverter;
private readonly HashSet<Blueprint> favoritedBlueprints = new HashSet<Blueprint>();
private Instant lastUpdate = Instant.MinValue;
private ShoppingListViewModel shoppingList;
private readonly CommanderToasts commanderToasts;
public Instant LastUpdate
{
get { return lastUpdate; }
set
{
if (value == lastUpdate)
return;
lastUpdate = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void LoadState(IEnumerable<string> events)
{
commanderToasts?.UnsubscribeToasts();
State.InitLoad();
// Clear state:
State.Cargo.ToList().ForEach(k => State.IncrementCargo(k.Value.Data.Name, -1 * k.Value.Count));
LastUpdate = Instant.MinValue;
ApplyEventsToSate(events);
ThresholdsManagerWindow.InitThresholds(State.Cargo);
commanderToasts?.SubscribeToasts();
State.Cargo.RefreshSort();
State.CompleteLoad();
}
public CommanderViewModel(string commanderName, IEnumerable<string> logs, Languages languages, List<EntryData> entryDatas)
{
CommanderName = commanderName;
var converter = new ItemNameConverter(entryDatas);
State = new State(entryDatas, languages, SettingsManager.Comparer);
if (Environment.OSVersion.Version >= new Version(6, 2, 9200, 0)) // windows 8 or more recent
{
commanderToasts = new CommanderToasts(State, CommanderName);
}
journalEntryConverter = new JournalEntryConverter(converter, State.Cargo, languages);
blueprintConverter = new BlueprintConverter(State.Cargo);
LoadBlueprints(languages);
languages.PropertyChanged += (o, e) => OnPropertyChanged(nameof(Filters));
LoadState(logs);
var datas = State.Cargo.Select(c => c.Value.Data);
var ingredientUsed = State.Blueprints.SelectMany(blueprint => blueprint.Ingredients);
var ingredientUsedNames = ingredientUsed.Select(ingredient => ingredient.Entry.Data.Name).Distinct();
var unusedIngredients = datas.Where(data => !ingredientUsedNames.Contains(data.Name));
foreach (var data in unusedIngredients)
{
data.Unused = true;
}
}
public JournalEntry UserChange(Entry entry, int change)
{
var logEntry = new JournalEntry
{
JournalOperation = new ManualChangeOperation
{
Count = change,
JournalEvent = JournalEvent.ManualUserChange,
Name = entry.Data.Name
},
Timestamp = SystemClock.Instance.Now
};
var json = JsonConvert.SerializeObject(logEntry, journalEntryConverter);
logEntry.OriginalJson = json;
MutateState(logEntry);
return logEntry;
}
public void ApplyEventsToSate(IEnumerable<string> allLogs)
{
var settings = new JsonSerializerSettings()
{
Converters = new List<JsonConverter>() { journalEntryConverter },
Error = (o, e) => e.ErrorContext.Handled = true
};
var entries = allLogs.Select(l => JsonConvert.DeserializeObject<JournalEntry>(l, settings))
.Where(e => e?.Relevant == true)
.OrderBy(e => e.Timestamp)
.ToList();
foreach (var entry in entries.Where(entry => entry.Timestamp >= LastUpdate).ToList())
{
MutateState(entry);
}
}
private void MutateState(JournalEntry entry)
{
State.Operations.AddLast(entry);
entry.JournalOperation.Mutate(State);
LastUpdate = Instant.Max(LastUpdate, entry.Timestamp);
}
public ICollectionView FilterView(MainWindowViewModel parentViewModel, Kind kind, CollectionViewSource source)
{
source.Filter += (o, e) =>
{
var entry = ((KeyValuePair<string, Entry>)e.Item).Value;
e.Accepted = entry.Data.Kind == kind &&
(parentViewModel.ShowZeroes || entry.Count != 0) &&
(!parentViewModel.ShowOnlyForFavorites || favoritedBlueprints.Any(b => b.Ingredients.Any(i => i.Entry == entry)));
};
parentViewModel.PropertyChanged += (o, e) =>
{
if (e.PropertyName == nameof(parentViewModel.ShowZeroes) || e.PropertyName == nameof(parentViewModel.ShowOnlyForFavorites))
{
source.View.Refresh();
}
};
State.Blueprints.ForEach(b => b.PropertyChanged += (o, e) =>
{
if (parentViewModel.ShowOnlyForFavorites && e.PropertyName == "Favorite")
{
Application.Current.Dispatcher.Invoke(source.View.Refresh);
}
});
return source.View;
}
private void LoadBlueprints(ILanguage languages)
{
var blueprintsJson = IOUtils.GetBlueprintsJson();
State.Blueprints = new List<Blueprint>(JsonConvert.DeserializeObject<List<Blueprint>>(blueprintsJson, blueprintConverter));
if (Settings.Default.Favorites == null)
{
Settings.Default.Favorites = new StringCollection();
}
if (Settings.Default.Ignored == null)
{
Settings.Default.Ignored = new StringCollection();
}
if (Settings.Default.ShoppingList == null)
{
Settings.Default.ShoppingList = new StringCollection();
}
foreach (var blueprint in State.Blueprints)
{
var text = $"{CommanderName}:{blueprint}";
if (Settings.Default.Favorites.Contains(text))
{
blueprint.Favorite = true;
favoritedBlueprints.Add(blueprint);
if (Settings.Default.Favorites.Contains($"{blueprint}"))
{
Settings.Default.Favorites.Remove($"{blueprint}");
Settings.Default.Save();
}
}
else if (Settings.Default.Favorites.Contains($"{blueprint}"))
{
blueprint.Favorite = true;
favoritedBlueprints.Add(blueprint);
Settings.Default.Favorites.Remove($"{blueprint}");
Settings.Default.Favorites.Add(text);
Settings.Default.Save();
}
if (Settings.Default.Ignored.Contains(text))
{
blueprint.Ignored = true;
if (Settings.Default.Ignored.Contains($"{blueprint}"))
{
Settings.Default.Ignored.Remove($"{blueprint}");
Settings.Default.Save();
}
}
else if (Settings.Default.Ignored.Contains($"{blueprint}"))
{
blueprint.Ignored = true;
Settings.Default.Ignored.Remove($"{blueprint}");
Settings.Default.Ignored.Add(text);
Settings.Default.Save();
}
blueprint.ShoppingListCount = Settings.Default.ShoppingList.Cast<string>().Count(l => l == text);
blueprint.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "Favorite")
{
if (blueprint.Favorite)
{
Settings.Default.Favorites.Add($"{CommanderName}:{blueprint}");
favoritedBlueprints.Add(blueprint);
}
else
{
Settings.Default.Favorites.Remove($"{CommanderName}:{blueprint}");
favoritedBlueprints.Remove(blueprint);
}
Settings.Default.Save();
}
else if (e.PropertyName == "Ignored")
{
if (blueprint.Ignored)
{
Settings.Default.Ignored.Add($"{CommanderName}:{blueprint}");
}
else
{
Settings.Default.Ignored.Remove($"{CommanderName}:{blueprint}");
}
Settings.Default.Save();
}
else if (e.PropertyName == "ShoppingListCount")
{
while (Settings.Default.ShoppingList.Contains(text))
{
Settings.Default.ShoppingList.Remove(text);
}
for (var i = 0; i < blueprint.ShoppingListCount; i++)
{
Settings.Default.ShoppingList.Add(text);
}
Settings.Default.Save();
}
};
}
Filters = new BlueprintFilters(languages, State.Blueprints);
shoppingList = new ShoppingListViewModel(State.Blueprints, languages);
}
public void ShoppingListChange(Blueprint blueprint, int i)
{
if (blueprint.ShoppingListCount + i >= 0)
{
blueprint.ShoppingListCount += i;
OnPropertyChanged(nameof(ShoppingList));
OnPropertyChanged(nameof(ShoppingListItem));
}
}
public int ShoppingListItem => 0;
public override string ToString()
{
return $"CMDR {CommanderName}";
}
public void Dispose()
{
commanderToasts?.Dispose();
}
public void ToggleHighlight(Entry entry)
{
entry.Highlighted = !entry.Highlighted;
if (entry.Highlighted)
{
HighlightedEntryData.Add(entry);
}
else
{
HighlightedEntryData.Remove(entry);
}
Settings.Default.Save();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NStorage.Utility
{
using System;
/// <summary>
/// A List of int's; as full an implementation of the java.Util.List interface as possible, with an eye toward minimal creation of objects
///
/// the mimicry of List is as follows:
/// <ul>
/// <li> if possible, operations designated 'optional' in the List
/// interface are attempted</li>
/// <li> wherever the List interface refers to an Object, substitute
/// int</li>
/// <li> wherever the List interface refers to a Collection or List,
/// substitute IntList</li>
/// </ul>
///
/// the mimicry is not perfect, however:
/// <ul>
/// <li> operations involving Iterators or ListIterators are not
/// supported</li>
/// <li> Remove(Object) becomes RemoveValue to distinguish it from
/// Remove(int index)</li>
/// <li> subList is not supported</li>
/// </ul>
/// @author Marc Johnson
/// </summary>
public class IntList
{
private int[] _array;
private int _limit;
private int fillval = 0;
private static int _default_size = 128;
/// <summary>
/// create an IntList of default size
/// </summary>
public IntList()
: this(_default_size)
{
}
public IntList(int InitialCapacity)
: this(InitialCapacity, 0)
{
}
/// <summary>
/// create a copy of an existing IntList
/// </summary>
/// <param name="list">the existing IntList</param>
public IntList(IntList list)
: this(list._array.Length)
{
Array.Copy(list._array, 0, _array, 0, _array.Length);
_limit = list._limit;
}
/// <summary>
/// create an IntList with a predefined Initial size
/// </summary>
/// <param name="initialCapacity">the size for the internal array</param>
/// <param name="fillvalue"></param>
public IntList(int initialCapacity, int fillvalue)
{
_array = new int[initialCapacity];
if (fillval != 0)
{
fillval = fillvalue;
FillArray(fillval, _array, 0);
}
_limit = 0;
}
private void FillArray(int val, int[] array, int index)
{
for (int k = index; k < array.Length; k++)
{
array[k] = val;
}
}
/// <summary>
/// add the specfied value at the specified index
/// </summary>
/// <param name="index">the index where the new value is to be Added</param>
/// <param name="value">the new value</param>
public void Add(int index, int value)
{
if (index > _limit)
{
throw new IndexOutOfRangeException();
}
else if (index == _limit)
{
Add(value);
}
else
{
// index < limit -- insert into the middle
if (_limit == _array.Length)
{
growArray(_limit * 2);
}
Array.Copy(_array, index, _array, index + 1,
_limit - index);
_array[index] = value;
_limit++;
}
}
/// <summary>
/// Appends the specified element to the end of this list
/// </summary>
/// <param name="value">element to be Appended to this list.</param>
/// <returns>return true (as per the general contract of the Collection.add method</returns>
public bool Add(int value)
{
if (_limit == _array.Length)
{
growArray(_limit * 2);
}
_array[_limit++] = value;
return true;
}
/// <summary>
/// Appends all of the elements in the specified collection to the
/// end of this list, in the order that they are returned by the
/// specified collection's iterator. The behavior of this
/// operation is unspecified if the specified collection is
/// modified while the operation is in progress. (Note that this
/// will occur if the specified collection is this list, and it's
/// nonempty.)
/// </summary>
/// <param name="c">collection whose elements are to be Added to this list.</param>
/// <returns>return true if this list Changed as a result of the call.</returns>
public bool AddAll(IntList c)
{
if (c._limit != 0)
{
if ((_limit + c._limit) > _array.Length)
{
growArray(_limit + c._limit);
}
Array.Copy(c._array, 0, _array, _limit, c._limit);
_limit += c._limit;
}
return true;
}
/// <summary>
/// Inserts all of the elements in the specified collection into
/// this list at the specified position. Shifts the element
/// currently at that position (if any) and any subsequent elements
/// to the right (increases their indices). The new elements will
/// appear in this list in the order that they are returned by the
/// specified collection's iterator. The behavior of this
/// operation is unspecified if the specified collection is
/// modified while the operation is in progress. (Note that this
/// will occur if the specified collection is this list, and it's
/// nonempty.)
/// </summary>
/// <param name="index">index at which to insert first element from the specified collection.</param>
/// <param name="c">elements to be inserted into this list.</param>
/// <returns>return true if this list Changed as a result of the call.</returns>
public bool AddAll(int index, IntList c)
{
if (index > _limit)
{
throw new IndexOutOfRangeException();
}
if (c._limit != 0)
{
if ((_limit + c._limit) > _array.Length)
{
growArray(_limit + c._limit);
}
// make a hole
Array.Copy(_array, index, _array, index + c._limit,
_limit - index);
// fill it in
Array.Copy(c._array, 0, _array, index, c._limit);
_limit += c._limit;
}
return true;
}
/// <summary>
/// Removes all of the elements from this list. This list will be
/// empty After this call returns (unless it throws an exception).
/// </summary>
public void Clear()
{
_limit = 0;
}
/// <summary>
/// Returns true if this list Contains the specified element. More
/// formally, returns true if and only if this list Contains at
/// least one element e such that o == e
/// </summary>
/// <param name="o">element whose presence in this list is to be Tested.</param>
/// <returns>return true if this list Contains the specified element.</returns>
public bool Contains(int o)
{
bool rval = false;
for (int j = 0; !rval && (j < _limit); j++)
{
if (_array[j] == o)
{
rval = true;
}
}
return rval;
}
/// <summary>
/// Returns true if this list Contains all of the elements of the
/// specified collection.
/// </summary>
/// <param name="c">collection to be Checked for Containment in this list.</param>
/// <returns>return true if this list Contains all of the elements of the specified collection.</returns>
public bool ContainsAll(IntList c)
{
bool rval = true;
if (this != c)
{
for (int j = 0; rval && (j < c._limit); j++)
{
if (!Contains(c._array[j]))
{
rval = false;
}
}
}
return rval;
}
/// <summary>
/// Compares the specified object with this list for Equality.
/// Returns true if and only if the specified object is also a
/// list, both lists have the same size, and all corresponding
/// pairs of elements in the two lists are Equal. (Two elements e1
/// and e2 are equal if e1 == e2.) In other words, two lists are
/// defined to be equal if they contain the same elements in the
/// same order. This defInition ensures that the Equals method
/// works properly across different implementations of the List
/// interface.
/// </summary>
/// <param name="o">the object to be Compared for Equality with this list.</param>
/// <returns>return true if the specified object is equal to this list.</returns>
public override bool Equals(Object o)
{
bool rval = this == o;
if (!rval && (o != null) && (o.GetType() == this.GetType()))
{
IntList other = (IntList)o;
if (other._limit == _limit)
{
// assume match
rval = true;
for (int j = 0; rval && (j < _limit); j++)
{
rval = _array[j] == other._array[j];
}
}
}
return rval;
}
/// <summary>
/// Returns the element at the specified position in this list.
/// </summary>
/// <param name="index">index of element to return.</param>
/// <returns>return the element at the specified position in this list.</returns>
public int Get(int index)
{
if (index >= _limit)
{
throw new IndexOutOfRangeException(
index + " not accessible in a list of length " + _limit
);
}
return _array[index];
}
/// <summary>
/// Returns the hash code value for this list. The hash code of a
/// list is defined to be the result of the following calculation:
///
/// <code>
/// hashCode = 1;
/// Iterator i = list.Iterator();
/// while (i.HasNext()) {
/// Object obj = i.Next();
/// hashCode = 31*hashCode + (obj==null ? 0 : obj.HashCode());
/// }
/// </code>
///
/// This ensures that list1.Equals(list2) implies that
/// list1.HashCode()==list2.HashCode() for any two lists, list1 and
/// list2, as required by the general contract of Object.HashCode.
///
/// </summary>
/// <returns>return the hash code value for this list.</returns>
public override int GetHashCode()
{
int hash = 0;
for (int j = 0; j < _limit; j++)
{
hash = (31 * hash) + _array[j];
}
return hash;
}
/// <summary>
/// Returns the index in this list of the first occurrence of the
/// specified element, or -1 if this list does not contain this
/// element. More formally, returns the lowest index i such that
/// (o == Get(i)), or -1 if there is no such index.
/// </summary>
/// <param name="o">element to search for.</param>
/// <returns>return the index in this list of the first occurrence of the
/// specified element, or -1 if this list does not contain
/// this element.</returns>
public int IndexOf(int o)
{
int rval = 0;
for (; rval < _limit; rval++)
{
if (o == _array[rval])
{
break;
}
}
if (rval == _limit)
{
rval = -1; // didn't find it
}
return rval;
}
/// <summary>
/// Returns true if this list Contains no elements.
/// </summary>
/// <returns>return true if this list Contains no elements.</returns>
public bool IsEmpty()
{
return _limit == 0;
}
/// <summary>
/// Returns the index in this list of the last occurrence of the
/// specified element, or -1 if this list does not contain this
/// element. More formally, returns the highest index i such that
/// (o == Get(i)), or -1 if there is no such index.
/// </summary>
/// <param name="o">element to search for.</param>
/// <returns>the index in this list of the last occurrence of the
/// specified element, or -1 if this list does not contain
/// this element.
/// </returns>
public int LastIndexOf(int o)
{
int rval = _limit - 1;
for (; rval >= 0; rval--)
{
if (o == _array[rval])
{
break;
}
}
return rval;
}
/// <summary>
/// Removes the element at the specified position in this list.
/// Shifts any subsequent elements to the left (subtracts one from
/// their indices). Returns the element that was Removed from the
/// list.
/// </summary>
/// <param name="index">the index of the element to Removed.</param>
/// <returns>return the element previously at the specified position.</returns>
public int Remove(int index)
{
if (index >= _limit)
{
throw new IndexOutOfRangeException();
}
int rval = _array[index];
Array.Copy(_array, index + 1, _array, index, _limit - index);
_limit--;
return rval;
}
/// <summary>
/// Removes the first occurrence in this list of the specified
/// element (optional operation). If this list does not contain
/// the element, it is unChanged. More formally, Removes the
/// element with the lowest index i such that (o.Equals(get(i)))
/// (if such an element exists).
/// </summary>
/// <param name="o">element to be Removed from this list, if present.</param>
/// <returns>return true if this list Contained the specified element.</returns>
public bool RemoveValue(int o)
{
bool rval = false;
for (int j = 0; !rval && (j < _limit); j++)
{
if (o == _array[j])
{
if (j + 1 < _limit)
{
Array.Copy(_array, j + 1, _array, j, _limit - j);
}
_limit--;
rval = true;
}
}
return rval;
}
/// <summary>
/// Removes from this list all the elements that are Contained in
/// the specified collection
/// </summary>
/// <param name="c">collection that defines which elements will be Removed from the list.</param>
/// <returns>return true if this list Changed as a result of the call.</returns>
public bool RemoveAll(IntList c)
{
bool rval = false;
for (int j = 0; j < c._limit; j++)
{
if (RemoveValue(c._array[j]))
{
rval = true;
}
}
return rval;
}
/// <summary>
/// Retains only the elements in this list that are Contained in
/// the specified collection. In other words, Removes from this
/// list all the elements that are not Contained in the specified
/// collection.
/// </summary>
/// <param name="c">collection that defines which elements this Set will retain.</param>
/// <returns>return true if this list Changed as a result of the call.</returns>
public bool RetainAll(IntList c)
{
bool rval = false;
for (int j = 0; j < _limit; )
{
if (!c.Contains(_array[j]))
{
Remove(j);
rval = true;
}
else
{
j++;
}
}
return rval;
}
/// <summary>
/// Replaces the element at the specified position in this list with the specified element
/// </summary>
/// <param name="index">index of element to Replace.</param>
/// <param name="element">element to be stored at the specified position.</param>
/// <returns>the element previously at the specified position.</returns>
public int Set(int index, int element)
{
if (index >= _limit)
{
throw new IndexOutOfRangeException();
}
int rval = _array[index];
_array[index] = element;
return rval;
}
/// <summary>
/// Returns the number of elements in this list. If this list
/// Contains more than Int32.MaxValue elements, returns
/// Int32.MaxValue.
/// </summary>
/// <returns>the number of elements in this IntList</returns>
public int Size()
{
return _limit;
}
/// <summary>
/// the number of elements in this IntList
/// </summary>
public int Count
{
get { return _limit; }
}
/// <summary>
/// Returns an array Containing all of the elements in this list in
/// proper sequence. Obeys the general contract of the
/// Collection.ToArray method.
/// </summary>
/// <returns>an array Containing all of the elements in this list in proper sequence.</returns>
public int[] ToArray()
{
int[] rval = new int[_limit];
Array.Copy(_array, 0, rval, 0, _limit);
return rval;
}
/// <summary>
/// Returns an array Containing all of the elements in this list in
/// proper sequence. Obeys the general contract of the
/// Collection.ToArray(Object[]) method.
/// </summary>
/// <param name="a">the array into which the elements of this list are to
/// be stored, if it is big enough; otherwise, a new array
/// is allocated for this purpose.</param>
/// <returns>return an array Containing the elements of this list.</returns>
public int[] ToArray(int[] a)
{
int[] rval;
if (a.Length == _limit)
{
Array.Copy(_array, 0, a, 0, _limit);
rval = a;
}
else
{
rval = ToArray();
}
return rval;
}
private void growArray(int new_size)
{
int size = (new_size == _array.Length) ? new_size + 1
: new_size;
int[] new_array = new int[size];
if (fillval != 0)
{
FillArray(fillval, new_array, _array.Length);
}
Array.Copy(_array, 0, new_array, 0, _limit);
_array = new_array;
}
} // end public class IntList
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using CoreFoundation;
using Foundation;
using HomeKit;
using UIKit;
namespace HomeKitCatalog
{
// A view controller that provides a list of services and lets the user select services to be added to the provided Service Group.
// The services are not added to the service group until the 'Done' button is pressed.
public partial class AddServicesViewController : HMCatalogViewController, IHMAccessoryDelegate
{
static readonly NSString ServiceCell = (NSString)"ServiceCell";
readonly List<HMAccessory> displayedAccessories = new List<HMAccessory> ();
readonly Dictionary<HMAccessory, List<HMService>> displayedServicesForAccessory = new Dictionary<HMAccessory, List<HMService>> ();
readonly List<HMService> selectedServices = new List<HMService> ();
public HMServiceGroup ServiceGroup { get; set; }
#region ctors
public AddServicesViewController (IntPtr handle)
: base (handle)
{
}
[Export ("initWithCoder:")]
public AddServicesViewController (NSCoder coder)
: base (coder)
{
}
#endregion
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
selectedServices.Clear ();
ReloadTable ();
}
protected override void RegisterAsDelegate ()
{
base.RegisterAsDelegate ();
foreach (var accessory in HomeStore.Home.Accessories)
accessory.Delegate = this;
}
#region Table View Methods
public override nint NumberOfSections (UITableView tableView)
{
return displayedAccessories.Count;
}
public override nint RowsInSection (UITableView tableView, nint section)
{
var accessory = displayedAccessories [(int)section];
return displayedServicesForAccessory [accessory].Count;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var cell = (ServiceCell)tableView.DequeueReusableCell (ServiceCell, indexPath);
var service = ServiceAtIndexPath (indexPath);
cell.IncludeAccessoryText = false;
cell.Service = service;
cell.Accessory = selectedServices.Contains (service) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None;
return cell;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
// Get the service associated with this index.
var service = ServiceAtIndexPath (indexPath);
// Call the appropriate add/remove operation with the closure from above.
var index = selectedServices.IndexOf (service);
if (index >= 0)
selectedServices.RemoveAt (index);
else
selectedServices.Add (service);
tableView.ReloadRows (new []{ indexPath }, UITableViewRowAnimation.Automatic);
}
public override string TitleForHeader (UITableView tableView, nint section)
{
return displayedAccessories [(int)section].Name;
}
#endregion
#region Helper Methods
void AddSelectedServices (Action completion)
{
// Create a dispatch group for each of the service additions.
var addServicesGroup = DispatchGroup.Create ();
foreach (var service in selectedServices) {
addServicesGroup.Enter ();
ServiceGroup.AddService (service, error => {
if (error != null)
DisplayError (error);
addServicesGroup.Leave ();
});
}
addServicesGroup.Notify (DispatchQueue.MainQueue, completion);
}
HMService ServiceAtIndexPath (NSIndexPath indexPath)
{
var accessory = displayedAccessories [indexPath.Section];
var services = displayedServicesForAccessory [accessory];
return services [indexPath.Row];
}
[Export ("dismiss")]
void Dismiss ()
{
AddSelectedServices (() => DismissViewController (true, null));
}
// Resets internal data and view.
void ReloadTable ()
{
ResetDisplayedServices ();
TableView.ReloadData ();
}
// Updates internal array of accessories and the mapping of accessories to selected services.
void ResetDisplayedServices ()
{
displayedAccessories.Clear ();
var allAccessories = new List<HMAccessory> (Home.Accessories);
allAccessories.SortByLocalizedName (a => a.Name);
displayedServicesForAccessory.Clear ();
foreach (var accessory in allAccessories) {
var displayedServices = new List<HMService> ();
foreach (var service in accessory.Services) {
if (!ServiceGroup.Services.Contains (service) && service.ServiceType != HMServiceType.AccessoryInformation)
displayedServices.Add (service);
}
// Only add the accessory if it has displayed services.
if (displayedServices.Count > 0) {
displayedServices.SortByLocalizedName (a => a.Name);
displayedServicesForAccessory [accessory] = displayedServices;
displayedAccessories.Add (accessory);
}
}
}
#endregion
#region HMHomeDelegate Methods
[Export ("home:didRemoveServiceGroup:")]
public void DidRemoveServiceGroup (HMHome home, HMServiceGroup group)
{
if (ServiceGroup == group)
DismissViewController (true, null);
}
[Export ("home:didAddAccessory:")]
public void DidAddAccessory (HMHome home, HMAccessory accessory)
{
ReloadTable ();
accessory.Delegate = this;
}
[Export ("home:didRemoveAccessory:")]
public void DidRemoveAccessory (HMHome home, HMAccessory accessory)
{
if (home.Accessories.Length == 0)
NavigationController.DismissViewController (true, null);
ReloadTable ();
}
#endregion
#region HMAccessoryDelegate Methods
[Export ("accessory:didUpdateNameForService:")]
public void DidUpdateNameForService (HMAccessory accessory, HMService service)
{
ReloadTable ();
}
[Export ("accessoryDidUpdateServices:")]
public void DidUpdateServices (HMAccessory accessory)
{
ReloadTable ();
}
#endregion
}
}
| |
using System.IO;
using dropkick.FileSystem;
using dropkick.Tasks.Files;
using NUnit.Framework;
namespace dropkick.tests.Tasks.Files
{
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class CopyDirectoryTaskSpecs
{
public abstract class CopyDirectoryTaskSpecsBase : TinySpec
{
protected CopyDirectoryTask task;
protected readonly DotNetPath Path = new DotNetPath();
protected string baseDirectory = @".\CopyDirectoryTests";
protected string sourceDir = @".\CopyDirectoryTests\source";
protected string destDir = @".\CopyDirectoryTests\dest";
public override void Context()
{
if (Directory.Exists(baseDirectory)) { Directory.Delete(baseDirectory, true); }
Directory.CreateDirectory(baseDirectory);
Directory.CreateDirectory(sourceDir);
File.WriteAllLines(Path.Combine(sourceDir, "test.txt"), new[] { "the test" });
}
public override void Because()
{
task.Execute();
}
public override void AfterObservations()
{
Directory.Delete(baseDirectory, true);
}
}
public class when_copying_files_to_a_local_directory_and_the_directory_does_not_exist : CopyDirectoryTaskSpecsBase
{
public override void Context()
{
base.Context();
task = new CopyDirectoryTask(sourceDir, destDir, null, DestinationCleanOptions.None, null, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
}
public class when_copying_files_to_a_local_directory_and_the_directory_exists : CopyDirectoryTaskSpecsBase
{
public override void Context()
{
base.Context();
Directory.CreateDirectory(destDir);
task = new CopyDirectoryTask(sourceDir, destDir, null, DestinationCleanOptions.None, null, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
}
public class when_copying_files_to_a_local_directory_and_the_directory_exists_and_is_read_only : CopyDirectoryTaskSpecsBase
{
public override void Context()
{
base.Context();
Directory.CreateDirectory(base.destDir);
var destDir = new DirectoryInfo(base.destDir);
destDir.Attributes = FileAttributes.ReadOnly;
task = new CopyDirectoryTask(sourceDir, base.destDir, null, DestinationCleanOptions.None, null, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
}
public class when_copying_files_to_a_local_directory_and_the_destination_file_is_readonly : CopyDirectoryTaskSpecsBase
{
public override void Context()
{
base.Context();
Directory.CreateDirectory(destDir);
var dest = Path.Combine(destDir, "test.txt");
File.WriteAllLines(dest, new[] { "bad file" });
var destFile = new FileInfo(dest);
destFile.IsReadOnly = true;
Assert.IsTrue(destFile.IsReadOnly, "Expected the destination file to be readonly");
task = new CopyDirectoryTask(sourceDir, destDir, null, DestinationCleanOptions.None, null, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
}
public class when_copying_files_to_a_local_directory_and_excluding_certain_items : CopyDirectoryTaskSpecsBase
{
public override void Context()
{
base.Context();
File.WriteAllLines(Path.Combine(sourceDir, "notcopied.txt"), new[] { "new" });
Directory.CreateDirectory(destDir);
var dest = Path.Combine(destDir, "test.txt");
File.WriteAllLines(dest, new[] { "bad file" });
IList<Regex> ignoredCopyPatterns = new List<Regex>();
ignoredCopyPatterns.Add(new Regex("notcopied*"));
task = new CopyDirectoryTask(sourceDir, destDir, ignoredCopyPatterns, DestinationCleanOptions.Clear, null, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
[Fact]
public void should_not_include_the_excluded_file()
{
Assert.AreEqual(false, File.Exists(Path.Combine(destDir, "notcopied.txt")));
}
}
public class when_copying_files_to_a_local_directory_and_cleaning_the_files_prior : CopyDirectoryTaskSpecsBase
{
private string subdirectory;
public override void Context()
{
base.Context();
Directory.CreateDirectory(destDir);
subdirectory = Path.Combine(destDir, "sub");
Directory.CreateDirectory(subdirectory);
var dest = Path.Combine(destDir, "test.txt");
File.WriteAllLines(dest, new[] { "bad file" });
task = new CopyDirectoryTask(sourceDir, destDir, null, DestinationCleanOptions.Clear, null, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
[Fact]
public void should_still_have_a_sub_directory()
{
Assert.AreEqual(true, Directory.Exists(subdirectory));
}
}
public class when_copying_files_to_a_local_directory_and_cleaning_the_files_prior_excluding_some_items : CopyDirectoryTaskSpecsBase
{
private string subdirectoryFile;
public override void Context()
{
base.Context();
Directory.CreateDirectory(destDir);
string subdirectory = Path.Combine(destDir, "sub");
Directory.CreateDirectory(subdirectory);
var dest = Path.Combine(destDir, "test.txt");
File.WriteAllLines(dest, new[] { "bad file" });
File.WriteAllLines(Path.Combine(destDir, "notcleared.txt"), new[] { "old" });
subdirectoryFile = Path.Combine(subdirectory, "app_offline.htm");
File.WriteAllLines(subdirectoryFile, new[] { "ignored" });
IList<Regex> clearIgnoredPatterns = new List<Regex>();
clearIgnoredPatterns.Add(new Regex("notcleared*"));
clearIgnoredPatterns.Add(new Regex(@"[Aa]pp_[Oo]ffline\.htm"));
task = new CopyDirectoryTask(sourceDir, destDir, null, DestinationCleanOptions.Clear, clearIgnoredPatterns, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
[Fact]
public void should_not_delete_the_excluded_file()
{
Assert.AreEqual(true, File.Exists(Path.Combine(destDir, "notcleared.txt")));
}
[Fact]
public void should_not_delete_the_excluded_file_in_a_subdirectory()
{
Assert.AreEqual(true, File.Exists(subdirectoryFile));
}
}
public class when_copying_files_to_a_local_directory_and_deleting_the_files_prior : CopyDirectoryTaskSpecsBase
{
public override void Context()
{
base.Context();
Directory.CreateDirectory(destDir);
var dest = Path.Combine(destDir, "test.txt");
File.WriteAllLines(dest, new[] { "bad file" });
task = new CopyDirectoryTask(sourceDir, destDir, null, DestinationCleanOptions.Delete, null, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
}
public class when_copying_files_to_a_local_directory_and_deleting_the_files_prior_and_the_directory_exists_and_is_read_only : CopyDirectoryTaskSpecsBase
{
public override void Context()
{
base.Context();
Directory.CreateDirectory(base.destDir);
var destDir = new DirectoryInfo(base.destDir);
destDir.Attributes = FileAttributes.ReadOnly;
task = new CopyDirectoryTask(sourceDir, base.destDir, null, DestinationCleanOptions.Delete, null, new DotNetPath());
}
[Fact]
public void should_be_able_to_get_the_contents_of_a_copied_file()
{
var s = File.ReadAllText(Path.Combine(destDir, "test.txt"));
Assert.AreEqual("the test\r\n", s);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.Project
{
internal class ProjectReferenceNode : ReferenceNode
{
#region fields
/// <summary>
/// The name of the assembly this refernce represents
/// </summary>
private Guid referencedProjectGuid;
private string referencedProjectName = string.Empty;
private string referencedProjectRelativePath = string.Empty;
private string referencedProjectFullPath = string.Empty;
private BuildDependency buildDependency;
/// <summary>
/// This is a reference to the automation object for the referenced project.
/// </summary>
private EnvDTE.Project referencedProject;
/// <summary>
/// This state is controlled by the solution events.
/// The state is set to false by OnBeforeUnloadProject.
/// The state is set to true by OnBeforeCloseProject event.
/// </summary>
private bool canRemoveReference = true;
/// <summary>
/// Possibility for solution listener to update the state on the dangling reference.
/// It will be set in OnBeforeUnloadProject then the nopde is invalidated then it is reset to false.
/// </summary>
private bool isNodeValid;
#endregion
#region properties
public override string Url => this.referencedProjectFullPath;
public override string Caption => this.referencedProjectName;
internal Guid ReferencedProjectGuid => this.referencedProjectGuid;
/// <summary>
/// Possiblity to shortcut and set the dangling project reference icon.
/// It is ussually manipulated by solution listsneres who handle reference updates.
/// </summary>
internal protected bool IsNodeValid
{
get
{
return this.isNodeValid;
}
set
{
this.isNodeValid = value;
}
}
/// <summary>
/// Controls the state whether this reference can be removed or not. Think of the project unload scenario where the project reference should not be deleted.
/// </summary>
internal bool CanRemoveReference
{
get
{
return this.canRemoveReference;
}
set
{
this.canRemoveReference = value;
}
}
internal string ReferencedProjectName => this.referencedProjectName;
/// <summary>
/// Gets the automation object for the referenced project.
/// </summary>
internal EnvDTE.Project ReferencedProjectObject
{
get
{
// If the referenced project is null then re-read.
if (this.referencedProject == null)
{
// Search for the project in the collection of the projects in the
// current solution.
var dte = (EnvDTE.DTE)this.ProjectMgr.GetService(typeof(EnvDTE.DTE));
if (null == dte || null == dte.Solution)
{
return null;
}
var unmodeled = new Guid(EnvDTE.Constants.vsProjectKindUnmodeled);
this.referencedProject = dte.Solution.Projects
.Cast<EnvDTE.Project>()
.Where(prj => !Utilities.GuidEquals(unmodeled, prj.Kind))
.FirstOrDefault(prj => CommonUtils.IsSamePath(this.referencedProjectFullPath, prj.FullName));
}
return this.referencedProject;
}
set
{
this.referencedProject = value;
}
}
/// <summary>
/// Gets the full path to the assembly generated by this project.
/// </summary>
internal string ReferencedProjectOutputPath
{
get
{
// Make sure that the referenced project implements the automation object.
if (null == this.ReferencedProjectObject)
{
return null;
}
// Get the configuration manager from the project.
var confManager = this.ReferencedProjectObject.ConfigurationManager;
if (null == confManager)
{
return null;
}
// Get the active configuration.
var config = confManager.ActiveConfiguration;
if (null == config)
{
return null;
}
if (null == config.Properties)
{
return null;
}
// Get the output path for the current configuration.
var outputPathProperty = config.Properties.Item("OutputPath");
if (null == outputPathProperty || outputPathProperty.Value == null)
{
return null;
}
// Usually the output path is relative to the project path. If it is set as an
// absolute path, this call has no effect.
var outputPath = CommonUtils.GetAbsoluteDirectoryPath(
Path.GetDirectoryName(this.referencedProjectFullPath),
outputPathProperty.Value.ToString());
// Now get the name of the assembly from the project.
// Some project system throw if the property does not exist. We expect an ArgumentException.
string outputName = null;
try
{
outputName = this.ReferencedProjectObject.Properties.Item("OutputFileName").Value.ToString();
}
catch (ArgumentException)
{
}
catch (NullReferenceException)
{
}
if (outputName == null)
{
try
{
outputName = ((object[])config.OutputGroups.Item("Built").FileNames)
.OfType<string>()
.FirstOrDefault();
}
catch (ArgumentException)
{
}
catch (NullReferenceException)
{
}
catch (InvalidCastException)
{
}
}
// build the full path adding the name of the assembly to the output path.
return string.IsNullOrEmpty(outputName) ?
null :
CommonUtils.GetAbsoluteFilePath(outputPath, outputName);
}
}
internal string AssemblyName
{
get
{
// Now get the name of the assembly from the project.
// Some project system throw if the property does not exist. We expect an ArgumentException.
EnvDTE.Property assemblyNameProperty = null;
if (this.ReferencedProjectObject != null &&
!(this.ReferencedProjectObject is Automation.OAProject)) // our own projects don't have assembly names
{
try
{
assemblyNameProperty = this.ReferencedProjectObject.Properties.Item(ProjectFileConstants.AssemblyName);
}
catch (ArgumentException)
{
}
if (assemblyNameProperty != null)
{
return assemblyNameProperty.Value.ToString();
}
}
return null;
}
}
private Automation.OAProjectReference projectReference;
internal override object Object
{
get
{
if (null == this.projectReference)
{
this.projectReference = new Automation.OAProjectReference(this);
}
return this.projectReference;
}
}
#endregion
#region ctors
/// <summary>
/// Constructor for the ReferenceNode. It is called when the project is reloaded, when the project element representing the refernce exists.
/// </summary>
public ProjectReferenceNode(ProjectNode root, ProjectElement element)
: base(root, element)
{
this.referencedProjectRelativePath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
Debug.Assert(!string.IsNullOrEmpty(this.referencedProjectRelativePath), "Could not retrieve referenced project path form project file");
var guidString = this.ItemNode.GetMetadata(ProjectFileConstants.Project);
// Continue even if project setttings cannot be read.
try
{
this.referencedProjectGuid = new Guid(guidString);
this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
this.ProjectMgr.AddBuildDependency(this.buildDependency);
}
finally
{
Debug.Assert(this.referencedProjectGuid != Guid.Empty, "Could not retrive referenced project guidproject file");
this.referencedProjectName = this.ItemNode.GetMetadata(ProjectFileConstants.Name);
Debug.Assert(!string.IsNullOrEmpty(this.referencedProjectName), "Could not retrive referenced project name form project file");
}
// TODO: Maybe referenced projects should be relative to ProjectDir?
this.referencedProjectFullPath = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, this.referencedProjectRelativePath);
}
/// <summary>
/// constructor for the ProjectReferenceNode
/// </summary>
public ProjectReferenceNode(ProjectNode root, string referencedProjectName, string projectPath, string projectReference)
: base(root)
{
Debug.Assert(root != null && !string.IsNullOrEmpty(referencedProjectName) && !string.IsNullOrEmpty(projectReference)
&& !string.IsNullOrEmpty(projectPath), "Can not add a reference because the input for adding one is invalid.");
if (projectReference == null)
{
throw new ArgumentNullException("projectReference");
}
this.referencedProjectName = referencedProjectName;
var indexOfSeparator = projectReference.IndexOf('|');
var fileName = string.Empty;
// Unfortunately we cannot use the path part of the projectReference string since it is not resolving correctly relative pathes.
if (indexOfSeparator != -1)
{
var projectGuid = projectReference.Substring(0, indexOfSeparator);
this.referencedProjectGuid = new Guid(projectGuid);
if (indexOfSeparator + 1 < projectReference.Length)
{
var remaining = projectReference.Substring(indexOfSeparator + 1);
indexOfSeparator = remaining.IndexOf('|');
if (indexOfSeparator == -1)
{
fileName = remaining;
}
else
{
fileName = remaining.Substring(0, indexOfSeparator);
}
}
}
Debug.Assert(!string.IsNullOrEmpty(fileName), "Can not add a project reference because the input for adding one is invalid.");
var justTheFileName = Path.GetFileName(fileName);
this.referencedProjectFullPath = CommonUtils.GetAbsoluteFilePath(projectPath, justTheFileName);
// TODO: Maybe referenced projects should be relative to ProjectDir?
this.referencedProjectRelativePath = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, this.referencedProjectFullPath);
this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
}
#endregion
#region methods
protected override NodeProperties CreatePropertiesObject()
{
return new ProjectReferencesProperties(this);
}
/// <summary>
/// The node is added to the hierarchy and then updates the build dependency list.
/// </summary>
public override void AddReference()
{
if (this.ProjectMgr == null)
{
return;
}
base.AddReference();
this.ProjectMgr.AddBuildDependency(this.buildDependency);
return;
}
/// <summary>
/// Overridden method. The method updates the build dependency list before removing the node from the hierarchy.
/// </summary>
public override void Remove(bool removeFromStorage)
{
if (this.ProjectMgr == null || !this.CanRemoveReference)
{
return;
}
this.ProjectMgr.RemoveBuildDependency(this.buildDependency);
base.Remove(removeFromStorage);
return;
}
/// <summary>
/// Links a reference node to the project file.
/// </summary>
protected override void BindReferenceData()
{
Debug.Assert(!string.IsNullOrEmpty(this.referencedProjectName), "The referencedProjectName field has not been initialized");
Debug.Assert(this.referencedProjectGuid != Guid.Empty, "The referencedProjectName field has not been initialized");
this.ItemNode = new MsBuildProjectElement(this.ProjectMgr, this.referencedProjectRelativePath, ProjectFileConstants.ProjectReference);
this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.referencedProjectName);
this.ItemNode.SetMetadata(ProjectFileConstants.Project, this.referencedProjectGuid.ToString("B"));
this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString());
}
/// <summary>
/// Defines whether this node is valid node for painting the refererence icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon()
{
if (this.referencedProjectGuid == Guid.Empty || this.ProjectMgr == null || this.ProjectMgr.IsClosed || this.isNodeValid)
{
return false;
}
IVsHierarchy hierarchy = null;
hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, this.referencedProjectGuid);
if (hierarchy == null)
{
return false;
}
//If the Project is unloaded return false
if (this.ReferencedProjectObject == null)
{
return false;
}
return File.Exists(this.referencedProjectFullPath);
}
/// <summary>
/// Checks if a project reference can be added to the hierarchy. It calls base to see if the reference is not already there, then checks for circular references.
/// </summary>
/// <param name="errorHandler">The error handler delegate to return</param>
/// <returns></returns>
protected override bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler)
{
// When this method is called this refererence has not yet been added to the hierarchy, only instantiated.
if (!base.CanAddReference(out errorHandler))
{
return false;
}
errorHandler = null;
if (this.IsThisProjectReferenceInCycle())
{
errorHandler = new CannotAddReferenceErrorMessage(this.ShowCircularReferenceErrorMessage);
return false;
}
return true;
}
private bool IsThisProjectReferenceInCycle()
{
return IsReferenceInCycle(this.referencedProjectGuid);
}
private void ShowCircularReferenceErrorMessage()
{
var message = SR.GetString(SR.ProjectContainsCircularReferences, this.referencedProjectName);
var title = string.Empty;
var icon = OLEMSGICON.OLEMSGICON_CRITICAL;
var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
/// <summary>
/// Recursively search if this project reference guid is in cycle.
/// </summary>
private bool IsReferenceInCycle(Guid projectGuid)
{
// TODO: This has got to be wrong, it doesn't work w/ other project types.
var hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, projectGuid);
var provider = hierarchy.GetProject().GetCommonProject() as IReferenceContainerProvider;
if (provider != null)
{
var referenceContainer = provider.GetReferenceContainer();
Utilities.CheckNotNull(referenceContainer, "Could not found the References virtual node");
foreach (var refNode in referenceContainer.EnumReferences())
{
var projRefNode = refNode as ProjectReferenceNode;
if (projRefNode != null)
{
if (projRefNode.ReferencedProjectGuid == this.ProjectMgr.ProjectIDGuid)
{
return true;
}
if (this.IsReferenceInCycle(projRefNode.ReferencedProjectGuid))
{
return true;
}
}
}
}
return false;
}
#endregion
}
}
| |
//
// BaseAssemblyResolver.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2007 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.
//
// This code is a modified version of the assembly resolver implemented in Cecil.
// Keep in synch as much as possible.
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using Mono.Cecil;
namespace Stetic {
internal class AssemblyResolver : BaseAssemblyResolver {
Hashtable _assemblies;
ApplicationBackend app;
public IDictionary AssemblyCache {
get { return _assemblies; }
}
public AssemblyResolver (ApplicationBackend app)
{
this.app = app;
_assemblies = new Hashtable ();
}
public StringCollection Directories = new StringCollection ();
public override AssemblyDefinition Resolve (AssemblyNameReference name)
{
AssemblyDefinition asm = (AssemblyDefinition) _assemblies [name.Name];
if (asm == null) {
asm = base.Resolve (name);
asm.Resolver = this;
_assemblies [name.Name] = asm;
}
return asm;
}
public TypeDefinition Resolve (TypeReference type)
{
if (type is TypeDefinition)
return (TypeDefinition) type;
AssemblyNameReference reference = type.Scope as AssemblyNameReference;
if (reference != null) {
AssemblyDefinition assembly = Resolve (reference);
return assembly.MainModule.Types [type.FullName];
}
ModuleDefinition module = type.Scope as ModuleDefinition;
if (module != null)
return module.Types [type.FullName];
throw new NotImplementedException ();
}
public void CacheAssembly (AssemblyDefinition assembly)
{
_assemblies [assembly.Name.FullName] = assembly;
assembly.Resolver = this;
}
public string Resolve (string assemblyName, string basePath)
{
if (app != null) {
string ares = app.ResolveAssembly (assemblyName);
if (ares != null)
return ares;
}
StringCollection col = new StringCollection ();
col.Add (basePath);
foreach (string s in Directories)
col.Add (s);
try {
return Resolve (AssemblyNameReference.Parse (assemblyName), col);
} catch {
}
return null;
}
public string Resolve (AssemblyNameReference name, StringCollection basePaths)
{
string [] exts = new string [] { ".dll", ".exe" };
if (basePaths != null) {
foreach (string dir in basePaths) {
foreach (string ext in exts) {
string file = Path.Combine (dir, name.Name + ext);
if (File.Exists (file))
return file;
}
}
}
if (name.Name == "mscorlib")
return GetCorlib (name);
string asm = GetAssemblyInGac (name);
if (asm != null)
return asm;
throw new FileNotFoundException ("Could not resolve: " + name);
}
string GetCorlib (AssemblyNameReference reference)
{
if (typeof (object).Assembly.GetName ().Version == reference.Version)
return typeof (object).Assembly.Location;
string path = Directory.GetParent (
Directory.GetParent (
typeof (object).Module.FullyQualifiedName).FullName
).FullName;
if (OnMono ()) {
if (reference.Version.Major == 1)
path = Path.Combine (path, "1.0");
else if (reference.Version.Major == 2)
path = Path.Combine (path, "2.0");
else
throw new NotSupportedException ("Version not supported: " + reference.Version);
} else {
if (reference.Version.ToString () == "1.0.3300.0")
path = Path.Combine (path, "v1.0.3705");
else if (reference.Version.ToString () == "1.0.5000.0")
path = Path.Combine (path, "v1.1.4322");
else if (reference.Version.ToString () == "2.0.0.0")
path = Path.Combine (path, "v2.0.50727");
else
throw new NotSupportedException ("Version not supported: " + reference.Version);
}
return Path.Combine (path, "mscorlib.dll");
}
static string GetAssemblyInGac (AssemblyNameReference reference)
{
if (reference.PublicKeyToken == null || reference.PublicKeyToken.Length == 0)
return null;
string currentGac = GetCurrentGacPath ();
if (OnMono ()) {
string s = GetAssemblyFile (reference, currentGac);
if (File.Exists (s))
return s;
} else {
string [] gacs = new string [] {"GAC_MSIL", "GAC_32", "GAC"};
for (int i = 0; i < gacs.Length; i++) {
string gac = Path.Combine (Directory.GetParent (currentGac).FullName, gacs [i]);
string asm = GetAssemblyFile (reference, gac);
if (Directory.Exists (gac) && File.Exists (asm))
return asm;
}
}
return null;
}
static string GetAssemblyFile (AssemblyNameReference reference, string gac)
{
StringBuilder sb = new StringBuilder ();
sb.Append (reference.Version);
sb.Append ("__");
for (int i = 0; i < reference.PublicKeyToken.Length; i++)
sb.Append (reference.PublicKeyToken [i].ToString ("x2"));
return Path.Combine (
Path.Combine (
Path.Combine (gac, reference.Name), sb.ToString ()),
string.Concat (reference.Name, ".dll"));
}
static string GetCurrentGacPath ()
{
return Directory.GetParent (
Directory.GetParent (
Path.GetDirectoryName (
typeof (Uri).Module.FullyQualifiedName)
).FullName
).FullName;
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.Config.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Currencies.
/// </summary>
[RoutePrefix("api/v1.0/config/currency")]
public class CurrencyController : FrapidApiController
{
/// <summary>
/// The Currency repository.
/// </summary>
private readonly ICurrencyRepository CurrencyRepository;
public CurrencyController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.CurrencyRepository = new Frapid.Config.DataAccess.Currency
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public CurrencyController(ICurrencyRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.CurrencyRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "currency" entity.
/// </summary>
/// <returns>Returns the "currency" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/config/currency/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "currency_code",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "currency_code", PropertyName = "CurrencyCode", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = true, IsSerial = false, Value = "", MaxLength = 12 },
new EntityColumn { ColumnName = "currency_symbol", PropertyName = "CurrencySymbol", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 12 },
new EntityColumn { ColumnName = "currency_name", PropertyName = "CurrencyName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 48 },
new EntityColumn { ColumnName = "hundredth_name", PropertyName = "HundredthName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 48 },
new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }
}
};
}
/// <summary>
/// Counts the number of currencies.
/// </summary>
/// <returns>Returns the count of the currencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/config/currency/count")]
[Authorize]
public long Count()
{
try
{
return this.CurrencyRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of currency.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/config/currency/all")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Currency> GetAll()
{
try
{
return this.CurrencyRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of currency for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/config/currency/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.CurrencyRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of currency.
/// </summary>
/// <param name="currencyCode">Enter CurrencyCode to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{currencyCode}")]
[Route("~/api/config/currency/{currencyCode}")]
[Authorize]
public Frapid.Config.Entities.Currency Get(string currencyCode)
{
try
{
return this.CurrencyRepository.Get(currencyCode);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/config/currency/get")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Currency> Get([FromUri] string[] currencyCodes)
{
try
{
return this.CurrencyRepository.Get(currencyCodes);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of currency.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/config/currency/first")]
[Authorize]
public Frapid.Config.Entities.Currency GetFirst()
{
try
{
return this.CurrencyRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of currency.
/// </summary>
/// <param name="currencyCode">Enter CurrencyCode to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{currencyCode}")]
[Route("~/api/config/currency/previous/{currencyCode}")]
[Authorize]
public Frapid.Config.Entities.Currency GetPrevious(string currencyCode)
{
try
{
return this.CurrencyRepository.GetPrevious(currencyCode);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of currency.
/// </summary>
/// <param name="currencyCode">Enter CurrencyCode to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{currencyCode}")]
[Route("~/api/config/currency/next/{currencyCode}")]
[Authorize]
public Frapid.Config.Entities.Currency GetNext(string currencyCode)
{
try
{
return this.CurrencyRepository.GetNext(currencyCode);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of currency.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/config/currency/last")]
[Authorize]
public Frapid.Config.Entities.Currency GetLast()
{
try
{
return this.CurrencyRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 currencies on each page, sorted by the property CurrencyCode.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/config/currency")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Currency> GetPaginatedResult()
{
try
{
return this.CurrencyRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 currencies on each page, sorted by the property CurrencyCode.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/config/currency/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Currency> GetPaginatedResult(long pageNumber)
{
try
{
return this.CurrencyRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of currencies using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered currencies.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/config/currency/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.CurrencyRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 currencies on each page, sorted by the property CurrencyCode.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/config/currency/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Currency> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.CurrencyRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of currencies using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered currencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/config/currency/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.CurrencyRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 currencies on each page, sorted by the property CurrencyCode.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/config/currency/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Currency> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.CurrencyRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of currencies.
/// </summary>
/// <returns>Returns an enumerable key/value collection of currencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/config/currency/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.CurrencyRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for currencies.
/// </summary>
/// <returns>Returns an enumerable custom field collection of currencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/config/currency/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.CurrencyRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for currencies.
/// </summary>
/// <returns>Returns an enumerable custom field collection of currencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/config/currency/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.CurrencyRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of Currency class.
/// </summary>
/// <param name="currency">Your instance of currencies class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/config/currency/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic currency = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (currency == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.CurrencyRepository.AddOrEdit(currency, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of Currency class.
/// </summary>
/// <param name="currency">Your instance of currencies class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{currency}")]
[Route("~/api/config/currency/add/{currency}")]
[Authorize]
public void Add(Frapid.Config.Entities.Currency currency)
{
if (currency == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.CurrencyRepository.Add(currency);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of Currency class.
/// </summary>
/// <param name="currency">Your instance of Currency class to edit.</param>
/// <param name="currencyCode">Enter the value for CurrencyCode in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{currencyCode}")]
[Route("~/api/config/currency/edit/{currencyCode}")]
[Authorize]
public void Edit(string currencyCode, [FromBody] Frapid.Config.Entities.Currency currency)
{
if (currency == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.CurrencyRepository.Update(currency, currencyCode);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of Currency class.
/// </summary>
/// <param name="collection">Your collection of Currency class to bulk import.</param>
/// <returns>Returns list of imported currencyCodes.</returns>
/// <exception cref="DataAccessException">Thrown when your any Currency class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/config/currency/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> currencyCollection = this.ParseCollection(collection);
if (currencyCollection == null || currencyCollection.Count.Equals(0))
{
return null;
}
try
{
return this.CurrencyRepository.BulkImport(currencyCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of Currency class via CurrencyCode.
/// </summary>
/// <param name="currencyCode">Enter the value for CurrencyCode in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{currencyCode}")]
[Route("~/api/config/currency/delete/{currencyCode}")]
[Authorize]
public void Delete(string currencyCode)
{
try
{
this.CurrencyRepository.Delete(currencyCode);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Timer = System.Timers.Timer;
namespace TestTimer.Android
{
public enum CountdownTimerStates
{
Started,
Stopped
}
public enum QuestionTimeRemainingStates
{
Positive,
Negative
}
public class CountdownTimerEventArgs : EventArgs
{
public string QuestionsRemaining { get; }
public string TotalTimeRemainingText { get; }
public string TimeRemainingForCurrentQuestionText { get; }
public CountdownTimerEventArgs(string totalTimeRemainingText, string timeRemainingForCurrentQuestionText, string questionsRemaining)
{
TotalTimeRemainingText = totalTimeRemainingText;
TimeRemainingForCurrentQuestionText = timeRemainingForCurrentQuestionText;
QuestionsRemaining = questionsRemaining;
}
}
public class CountdownTimerStopped : EventArgs
{
public TimeSpan TotalTimeRemainingBeforeStopped { get; }
public bool CountdownComplete { get; }
public int QuestionsRemaining { get; }
public CountdownTimerStopped(TimeSpan totalTimeRemaining, int questionsRemaining)
{
TotalTimeRemainingBeforeStopped = totalTimeRemaining;
CountdownComplete = totalTimeRemaining.TotalSeconds < 1;
QuestionsRemaining = questionsRemaining;
}
}
public class TestCoundownTimer
{
private const string TimeFormat = "{0}:{1}:{2}";
private const string TimeFormatNegative = "-{0}:{1}:{2}";
public int Hours { get; }
public int Minutes { get; }
public int TotalQuestions { get; }
public int QuestionsRemaining { get; private set; }
private double _questionsRemainingDigitCount;
public TimeSpan TotalTimeRemaining { get; private set; }
public TimeSpan TimeLeftForCurrentQuestion { get; private set; }
public bool IsOverTimeForCurrentQuestion { get; private set; }
public CountdownTimerStates State { get; private set; }
public QuestionTimeRemainingStates QuestionTimeRemainingState { get; private set; }
private readonly Timer _countdownTimer = new Timer(1000);
public event EventHandler<CountdownTimerEventArgs> TimerUpdated;
public event EventHandler<CountdownTimerStopped> TimerStopped;
public event EventHandler<EventArgs> QuestionTimeRemainingNegative;
public event EventHandler<EventArgs> QuestionTimeRemainingPositive;
public TestCoundownTimer(int hours, int minutes, int totalQuestions, ISynchronizeInvoke screen)
{
Hours = hours;
Minutes = minutes;
QuestionsRemaining = TotalQuestions = totalQuestions;
_questionsRemainingDigitCount = Math.Floor(Math.Log10(QuestionsRemaining) + 1);
TotalTimeRemaining = new TimeSpan(Hours, Minutes, 0);
TimeLeftForCurrentQuestion = CalculateTimeForQuestion(TotalTimeRemaining, QuestionsRemaining);
//setting this property to the instance of the currently running screen will make the Elapsed event run on the UI Thread.
_countdownTimer.SynchronizingObject = screen;
_countdownTimer.Elapsed += CountdownTimerOnElapsed;
}
private void CountdownTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
System.Diagnostics.Debug.WriteLine("Timer Elasped Thread ID: {0}", Thread.CurrentThread.ManagedThreadId);
_countdownTimer.SynchronizingObject.Invoke(new Action(() =>
{
System.Diagnostics.Debug.WriteLine("Timer Elasped SynchronizedObject.Invoke Thread ID: {0}", Thread.CurrentThread.ManagedThreadId);
TotalTimeRemaining = TotalTimeRemaining.Subtract(new TimeSpan(0, 0, 1));
TimeLeftForCurrentQuestion = TimeLeftForCurrentQuestion.Subtract(new TimeSpan(0, 0, 1));
IsOverTimeForCurrentQuestion = TimeLeftForCurrentQuestion.TotalSeconds < 0;
if (IsOverTimeForCurrentQuestion)
{
OnQuestionTimeRemainingNegative();
}
else
{
OnQuestionTimeRemainingPositive();
}
if (TotalTimeRemaining.TotalSeconds < 1)
{
Stop();
}
else
{
OnTimerUpdated(new CountdownTimerEventArgs(GetTotalTimeRemaining(), GetTimeRemainingForCurrentQuestion(), GetNumberOfQuestionsRemaining()));
}
}), null);
}
private TimeSpan CalculateTimeForQuestion(TimeSpan totalTimeRemaining, int questionsRemaining)
{
var ticksRemaining = totalTimeRemaining.Ticks;
var ticksForQuestion = questionsRemaining > 0 ? ticksRemaining / questionsRemaining : 0;
var timeForQuestion = TimeSpan.FromTicks(ticksForQuestion);
if (totalTimeRemaining < timeForQuestion)
{
return totalTimeRemaining;
}
else
{
return timeForQuestion;
}
}
public void Start()
{
_countdownTimer.Start();
State = CountdownTimerStates.Started;
}
public void Stop(bool fireEvent = true)
{
_countdownTimer.Stop();
State = CountdownTimerStates.Stopped;
if (fireEvent)
{
OnTimerStopped();
}
}
public void NextQuestion()
{
QuestionsRemaining--;
TimeLeftForCurrentQuestion = CalculateTimeForQuestion(TotalTimeRemaining, QuestionsRemaining);
if (QuestionsRemaining == 0)
{
Stop();
}
}
public void PreviousQuestion()
{
QuestionsRemaining++;
TimeLeftForCurrentQuestion = CalculateTimeForQuestion(TotalTimeRemaining, QuestionsRemaining);
}
public string GetTimeRemainingForCurrentQuestion()
{
if (TimeLeftForCurrentQuestion.TotalSeconds < 0)
{
return string.Format(TimeFormatNegative, Math.Abs(TimeLeftForCurrentQuestion.Hours).ToString("D2"), Math.Abs(TimeLeftForCurrentQuestion.Minutes).ToString("D2"), Math.Abs(TimeLeftForCurrentQuestion.Seconds).ToString("D2"));
}
else
{
return string.Format(TimeFormat, TimeLeftForCurrentQuestion.Hours.ToString("D2"), TimeLeftForCurrentQuestion.Minutes.ToString("D2"), TimeLeftForCurrentQuestion.Seconds.ToString("D2"));
}
}
public string GetTotalTimeRemaining()
{
if (TotalTimeRemaining.TotalSeconds < 0)
{
return string.Format(TimeFormatNegative, Math.Abs(TotalTimeRemaining.Hours).ToString("D2"), Math.Abs(TotalTimeRemaining.Minutes).ToString("D2"), Math.Abs(TotalTimeRemaining.Seconds).ToString("D2"));
}
else
{
return string.Format(TimeFormat, TotalTimeRemaining.Hours.ToString("D2"), TotalTimeRemaining.Minutes.ToString("D2"), TotalTimeRemaining.Seconds.ToString("D2"));
}
}
public string GetNumberOfQuestionsRemaining()
{
return QuestionsRemaining.ToString("D" + _questionsRemainingDigitCount);
}
protected virtual void OnTimerUpdated(CountdownTimerEventArgs args)
{
TimerUpdated?.Invoke(this, args);
}
protected virtual void OnTimerStopped()
{
TimerStopped?.Invoke(this, new CountdownTimerStopped(TotalTimeRemaining, QuestionsRemaining));
}
protected virtual void OnQuestionTimeRemainingNegative()
{
if (QuestionTimeRemainingState == QuestionTimeRemainingStates.Positive)
{
QuestionTimeRemainingState = TimeLeftForCurrentQuestion.CompareTo(TimeSpan.Zero) < 0
? QuestionTimeRemainingStates.Negative
: QuestionTimeRemainingStates.Positive;
QuestionTimeRemainingNegative?.Invoke(this, EventArgs.Empty);
}
}
protected virtual void OnQuestionTimeRemainingPositive()
{
if (QuestionTimeRemainingState == QuestionTimeRemainingStates.Negative)
{
QuestionTimeRemainingState = TimeLeftForCurrentQuestion.CompareTo(TimeSpan.Zero) < 0
? QuestionTimeRemainingStates.Negative
: QuestionTimeRemainingStates.Positive;
QuestionTimeRemainingPositive?.Invoke(this, EventArgs.Empty);
}
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using log4net.Util;
namespace log4net.Core
{
/// <summary>
/// The internal representation of caller location information.
/// </summary>
/// <remarks>
/// <para>
/// This class uses the <c>System.Diagnostics.StackTrace</c> class to generate
/// a call stack. The caller's information is then extracted from this stack.
/// </para>
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class is not supported on the
/// .NET Compact Framework 1.0 therefore caller location information is not
/// available on that framework.
/// </para>
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds:
/// </para>
/// <para>
/// "StackTrace information will be most informative with Debug build configurations.
/// By default, Debug builds include debug symbols, while Release builds do not. The
/// debug symbols contain most of the file, method name, line number, and column
/// information used in constructing StackFrame and StackTrace objects. StackTrace
/// might not report as many method calls as expected, due to code transformations
/// that occur during optimization."
/// </para>
/// <para>
/// This means that in a Release build the caller information may be incomplete or may
/// not exist at all! Therefore caller location information cannot be relied upon in a Release build.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
#if !NETCF
[Serializable]
#endif
public class LocationInfo
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
/// the stack boundary into the logging system for this call.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LocationInfo" />
/// class based on the current thread.
/// </para>
/// </remarks>
public LocationInfo(Type callerStackBoundaryDeclaringType)
{
// Initialize all fields
m_className = NA;
m_fileName = NA;
m_lineNumber = NA;
m_methodName = NA;
m_fullInfo = NA;
#if !NETCF
if (callerStackBoundaryDeclaringType != null)
{
try
{
StackTrace st = new StackTrace(true);
int frameIndex = 0;
// skip frames not from fqnOfCallingClass
while (frameIndex < st.FrameCount)
{
StackFrame frame = st.GetFrame(frameIndex);
if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType)
{
break;
}
frameIndex++;
}
// skip frames from fqnOfCallingClass
while (frameIndex < st.FrameCount)
{
StackFrame frame = st.GetFrame(frameIndex);
if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType)
{
break;
}
frameIndex++;
}
if (frameIndex < st.FrameCount)
{
// take into account the frames we skip above
int adjustedFrameCount = st.FrameCount - frameIndex;
ArrayList stackFramesList = new ArrayList(adjustedFrameCount);
m_stackFrames = new StackFrameItem[adjustedFrameCount];
for (int i=frameIndex; i < st.FrameCount; i++)
{
stackFramesList.Add(new StackFrameItem(st.GetFrame(i)));
}
stackFramesList.CopyTo(m_stackFrames, 0);
// now frameIndex is the first 'user' caller frame
StackFrame locationFrame = st.GetFrame(frameIndex);
if (locationFrame != null)
{
System.Reflection.MethodBase method = locationFrame.GetMethod();
if (method != null)
{
m_methodName = method.Name;
if (method.DeclaringType != null)
{
m_className = method.DeclaringType.FullName;
}
}
m_fileName = locationFrame.GetFileName();
m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
// Combine all location info
m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + ':' + m_lineNumber + ')';
}
}
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// some undefined set of SecurityPermission flags.
LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available.");
}
}
#endif
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="className">The fully qualified class name.</param>
/// <param name="methodName">The method name.</param>
/// <param name="fileName">The file name.</param>
/// <param name="lineNumber">The line number of the method within the file.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LocationInfo" />
/// class with the specified data.
/// </para>
/// </remarks>
public LocationInfo(string className, string methodName, string fileName, string lineNumber)
{
m_className = className;
m_fileName = fileName;
m_lineNumber = lineNumber;
m_methodName = methodName;
m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName +
':' + m_lineNumber + ')';
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets the fully qualified class name of the caller making the logging
/// request.
/// </summary>
/// <value>
/// The fully qualified class name of the caller making the logging
/// request.
/// </value>
/// <remarks>
/// <para>
/// Gets the fully qualified class name of the caller making the logging
/// request.
/// </para>
/// </remarks>
public string ClassName
{
get { return m_className; }
}
/// <summary>
/// Gets the file name of the caller.
/// </summary>
/// <value>
/// The file name of the caller.
/// </value>
/// <remarks>
/// <para>
/// Gets the file name of the caller.
/// </para>
/// </remarks>
public string FileName
{
get { return m_fileName; }
}
/// <summary>
/// Gets the line number of the caller.
/// </summary>
/// <value>
/// The line number of the caller.
/// </value>
/// <remarks>
/// <para>
/// Gets the line number of the caller.
/// </para>
/// </remarks>
public string LineNumber
{
get { return m_lineNumber; }
}
/// <summary>
/// Gets the method name of the caller.
/// </summary>
/// <value>
/// The method name of the caller.
/// </value>
/// <remarks>
/// <para>
/// Gets the method name of the caller.
/// </para>
/// </remarks>
public string MethodName
{
get { return m_methodName; }
}
/// <summary>
/// Gets all available caller information
/// </summary>
/// <value>
/// All available caller information, in the format
/// <c>fully.qualified.classname.of.caller.methodName(Filename:line)</c>
/// </value>
/// <remarks>
/// <para>
/// Gets all available caller information, in the format
/// <c>fully.qualified.classname.of.caller.methodName(Filename:line)</c>
/// </para>
/// </remarks>
public string FullInfo
{
get { return m_fullInfo; }
}
#if !NETCF && !NETMF
/// <summary>
/// Gets the stack frames from the stack trace of the caller making the log request
/// </summary>
public StackFrameItem[] StackFrames
{
get { return m_stackFrames; }
}
#endif
#endregion Public Instance Properties
#region Private Instance Fields
private readonly string m_className;
private readonly string m_fileName;
private readonly string m_lineNumber;
private readonly string m_methodName;
private readonly string m_fullInfo;
#if !NETCF && !NETMF
private readonly StackFrameItem[] m_stackFrames;
#endif
#endregion Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the LocationInfo class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(LocationInfo);
/// <summary>
/// When location information is not available the constant
/// <c>NA</c> is returned. Current value of this string
/// constant is <b>?</b>.
/// </summary>
private const string NA = "?";
#endregion Private Static Fields
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.
*********************************************************************/
#region Using directives
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using log4net;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Collections;
using Axiom.Graphics;
using Multiverse.Network;
using Multiverse.Lib.LogUtil;
using TimeTool = Multiverse.Utility.TimeTool;
#endregion
namespace Multiverse.Base
{
/// <summary>
/// Big nodes have perceptionRadii; little nodes don't
/// generation fo static geometry
/// </summary>
public enum StaticGeometryKind {
BigNode = 1,
LittleNode,
BigOrLittleNode
}
/// <summary>
/// This class maintains the records necessary to drive the
/// generation fo static geometry
/// </summary>
public class StaticGeometryHelper {
// Create a logger for use in this class
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(StaticGeometryHelper));
protected WorldManager worldMgr;
protected StaticGeometryKind kind;
protected string name;
protected StaticGeometry objectGeometry;
protected int nodesAddedSinceLastRebuild;
protected int nodesRemovedSinceLastRebuild;
protected int lastNodesAdded;
protected long lastRebuildCheckTime;
protected long timeOfLastRebuild;
protected bool enabled;
protected bool force;
// If enough nodes have changed in this many milliseconds,
// we rebuild
protected int rebuildTimeThreshold;
// If this many nodes have been added, and the time
// threshold has expired, we rebuild the geometry
protected int nodesAddedThreshold;
// If this many nodes have been added, and the time
// threshold has expired, we rebuild the geometry
protected int nodesRemovedThreshold;
// We won't rebuild unless the nodes added in the last
// second drops below this number
protected int nodesAddedInLastSecondThreshold;
// The set of static nodes from last time
protected Dictionary<ObjectNode, int> lastStaticNodes = null;
public StaticGeometryHelper(WorldManager worldMgr, StaticGeometryKind kind, int rebuildTimeThreshold,
int nodesAddedThreshold, int nodesRemovedThreshold,
int nodesAddedInLastSecondThreshold) {
this.worldMgr = worldMgr;
this.kind = kind;
this.name = (kind == StaticGeometryKind.BigOrLittleNode ? "StaticGeom" :
(kind == StaticGeometryKind.BigNode ? "BigNodes" : "LittleNodes"));
this.objectGeometry = null;
this.rebuildTimeThreshold = rebuildTimeThreshold;
this.nodesAddedThreshold = nodesAddedThreshold;
this.nodesRemovedThreshold = nodesRemovedThreshold;
this.nodesAddedInLastSecondThreshold = nodesAddedInLastSecondThreshold;
this.nodesAddedSinceLastRebuild = 0;
this.nodesRemovedSinceLastRebuild = 0;
this.lastNodesAdded = 0;
this.timeOfLastRebuild = 0;
this.lastRebuildCheckTime = 0;
this.enabled = false;
this.force = false;
}
public void RebuildIfFinishedLoading(ExtensionMessage msg, bool loadingState) {
if (!loadingState) {
log.DebugFormat("StaticGeometryHelper.RebuildIfFinishedLoading: Rebuilding because loadingState is {0}", loadingState);
Rebuild();
}
}
public void NodeAdded(ObjectNode node) {
if (RightKind(node))
nodesAddedSinceLastRebuild++;
}
public void NodeRemoved(ObjectNode node) {
if (RightKind(node))
nodesRemovedSinceLastRebuild++;
}
public void RebuildIfNecessary(SceneManager mgr, Dictionary<long, WorldEntity> nodeDictionary) {
if (TimeToRebuild())
Rebuild();
}
public bool Enabled {
set {
enabled = value;
}
}
public bool Force {
set {
force = value;
}
}
protected bool RightKind(ObjectNode node) {
return (kind == StaticGeometryKind.BigOrLittleNode ||
(node.PerceptionRadius == 0) == (kind == StaticGeometryKind.LittleNode))
&& (node.Entity == null || node.Entity.Mesh.Skeleton == null);
}
// Is it time to rebuild the static geometry?
protected bool TimeToRebuild() {
long thisTick = TimeTool.CurrentTime;
// Only check every second, because this is how we get
// the nodesAddedInLastSecondThreshold mechanism to work
int timeSinceLastCheck = (int)(thisTick - lastRebuildCheckTime);
if (timeSinceLastCheck < 1000)
return false;
lastRebuildCheckTime = thisTick;
// If more nodes were added in the last second than
// nodesAddedInLastSecondThreshold, don't rebuild yet.
int recentNodesAdded = nodesAddedSinceLastRebuild - lastNodesAdded;
lastNodesAdded = nodesAddedSinceLastRebuild;
if (recentNodesAdded > nodesAddedInLastSecondThreshold)
return false;
return force ||
(enabled &&
((nodesAddedSinceLastRebuild >= nodesAddedThreshold) ||
(nodesRemovedSinceLastRebuild >= nodesRemovedThreshold)) &&
(int)(thisTick - timeOfLastRebuild) >= rebuildTimeThreshold);
}
public void Rebuild() {
Rebuild(worldMgr.SceneManager, worldMgr.NodeDictionary);
}
public class MaterialAndNodeCounts {
public int materialUseCount = 0;
public Dictionary<ObjectNode, int> submeshUseCounts = new Dictionary<ObjectNode, int>();
}
// Lock the node dictionary, and rebuild the static
// geometry for objects of this kind
protected void Rebuild(SceneManager mgr, Dictionary<long, WorldEntity> nodeDictionary) {
log.DebugFormat("Entering StaticGeometryHelper.Rebuild for geometry '{0}'", name);
long tickStart = TimeTool.CurrentTime;
try {
nodesAddedSinceLastRebuild = 0;
nodesRemovedSinceLastRebuild = 0;
force = false;
Monitor.Enter(mgr);
if (objectGeometry != null)
objectGeometry.Reset();
else
objectGeometry = new StaticGeometry(mgr, name);
// Dictionary mapping Material into a list of
// ObjectNodes in which some submesh uses the material
Dictionary<Material, MaterialAndNodeCounts> materialsUsedMap = new Dictionary<Material, MaterialAndNodeCounts>();
lock(nodeDictionary) {
foreach (WorldEntity entity in nodeDictionary.Values) {
if (entity is ObjectNode) {
ObjectNode node = (ObjectNode)entity;
// For now, we only consider "props" that have an associated SceneNode
// and are direct descendants of the root scene node, and are of the right
// kind, i.e., don't have a perception radius if this static geometry is for
// little nodes, and vice versa.
// log.DebugFormat("StaticGeometry.Rebuild: Examining node {0}, oid {1}, type {2}, sceneNode {3}, InStaticGeometry {4}, top-level {5}",
// node.Name, node.Oid, node.ObjectType, node.SceneNode, node.InStaticGeometry, node.SceneNode.Parent == mgr.RootSceneNode);
if (node.ObjectType == ObjectNodeType.Prop &&
(node.InStaticGeometry || (node.SceneNode != null && node.SceneNode.Parent == mgr.RootSceneNode)) &&
RightKind(node)) {
foreach (Material m in node.Entity.SubEntityMaterials) {
MaterialAndNodeCounts nodesUsingMaterial;
if (!materialsUsedMap.TryGetValue(m, out nodesUsingMaterial)) {
nodesUsingMaterial = new MaterialAndNodeCounts();
materialsUsedMap[m] = nodesUsingMaterial;
}
nodesUsingMaterial.materialUseCount++;
int subMeshUseCount;
Dictionary<ObjectNode, int> submeshUseCounts = nodesUsingMaterial.submeshUseCounts;
if (!submeshUseCounts.TryGetValue(node, out subMeshUseCount))
submeshUseCounts[node] = 1;
else
submeshUseCounts[node] = subMeshUseCount + 1;
}
}
}
}
}
// Now we have a count of uses of each material, and
// for each node, the number of subentities that use the
// material. Now we need to calculate the number of
// instance of sharings for each object node
Dictionary<ObjectNode, bool> candidateNodes = new Dictionary<ObjectNode, bool>();
foreach (MaterialAndNodeCounts counts in materialsUsedMap.Values) {
if (counts.materialUseCount > 1) {
foreach (KeyValuePair<ObjectNode, int> pair in counts.submeshUseCounts)
candidateNodes[pair.Key] = true;
}
}
Dictionary<ObjectNode, int> staticNodes = new Dictionary<ObjectNode, int>();
foreach (KeyValuePair<ObjectNode, bool> pair in candidateNodes) {
ObjectNode candidate = pair.Key;
bool useIt = pair.Value;
if (useIt)
staticNodes[candidate] = 0;
}
if (staticNodes.Count == 0)
log.InfoFormat("StaticGeometryHelper.Rebuild: Didn't build static geometry {0} because object count was zero", name);
else {
log.InfoFormat("StaticGeometryHelper.Rebuild: {0} ObjectNodes", staticNodes.Count);
foreach(ObjectNode staticNode in staticNodes.Keys) {
SceneNode sc = staticNode.SceneNode;
if (!staticNode.InStaticGeometry) {
sc.RemoveFromParent();
staticNode.InStaticGeometry = true;
}
log.DebugFormat("StaticGeometryHelper.Rebuild: Add node {0} with name {1} to static geometry",
staticNode.Oid, staticNode.Name);
objectGeometry.AddSceneNode(sc);
}
}
if (lastStaticNodes != null) {
foreach(ObjectNode node in lastStaticNodes.Keys) {
if (!staticNodes.ContainsKey(node)) {
// Only 1 instance of the mesh, so make sure that if in a former build it was in
// static geometry, that we add it back to the scene graph.
if (node.InStaticGeometry) {
SceneNode sn = node.SceneNode;
if (sn != null)
mgr.RootSceneNode.AddChild(sn);
node.InStaticGeometry = false;
}
}
}
}
if (staticNodes.Count > 0)
objectGeometry.Build();
lastStaticNodes = staticNodes;
timeOfLastRebuild = TimeTool.CurrentTime;
}
finally {
Monitor.Exit(mgr);
}
log.InfoFormat("StaticGeometryHelper.Rebuild: Rebuild of geometry '{0}' took {1} ms",
name, TimeTool.CurrentTime - tickStart);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Forms;
using KabMan.Controls;
using KabMan.Data;
using KabMan.Text;
using KabMan.Windows;
using System.Data;
using DevExpress.XtraEditors;
namespace KabMan.Forms
{
public partial class NewSwitchForm : DevExpress.XtraEditors.XtraForm
{
public NewSwitchForm()
{
this.Icon = Resources.GetIcon("KabManIcon");
InitializeComponent();
InitializeManager();
}
private void InitializeManager()
{
CSwitchType.StoredProcedure = sproc.SwitchType_Select_All;
CSwitchModel.StoredProcedure = sproc.SwitchModel_Select_All;
CSwitchModel.Columns.Clear();
CSwitchModel.AddColumn("Name", "Select Switch Model");
CCoreSwitch.StoredProcedure = sproc.Switch_Select_ByTypeName;
CLocation.StoredProcedure = sproc.Location_Select_All;
CDataCenter.StoredProcedure = sproc.DataCenter_Select_ByLocationID;
CDataCenter.Columns.Clear();
CDataCenter.AddColumn("Name", "Select Data Center");
CSanGroup.StoredProcedure = sproc.SanGroup_Select_All;
CSan.StoredProcedure = sproc.San_Select_ByGroupID;
CSan.Columns.Clear();
CSan.AddColumn("Name", "Select SAN");
CVtPort.StoredProcedure = sproc.VtPort_Select_BySanID;
CFirstTrunk.StoredProcedure = sproc.Cable_Select_FirstTrunk_BySanValue;
CFirstTrunk.Columns.Clear();
CFirstTrunk.AddColumn("Name", "Select Start Trunk Cable");
CBlechType.StoredProcedure = sproc.BlechType_Select_All;
CBlech.StoredProcedure = sproc.Blech_Select_ForServer_ByTypeID;
CBlech.Columns.Clear();
CBlech.AddColumn("Name", "Select Blech");
CLcLength.StoredProcedure = sproc.Cable_Select_LengthsByCategory;
CLcCable.StoredProcedure = sproc.Cable_Select_LcByLength;
CLcCable.Columns.Clear();
CLcCable.AddColumn("Name", "Select LC URM Cable");
CSwitchType.FormToShow = typeof(SwitchTypeManagerForm);
/// CSwitchModel.FormToShow =
CSwitchType.Columns.Clear();
CSwitchType.AddColumn("Name", "Select Switch Type");
CLocation.FormToShow = typeof(LocationManagerForm);
CLocation.Columns.Clear();
CLocation.AddColumn("Name", "Select Location");
CDataCenter.FormToShow = typeof(DataCenterManagerForm);
CSanGroup.FormToShow = typeof(SanGroupManagerForm);
CSanGroup.Columns.Clear();
CSanGroup.AddColumn("Name", "Select San Group");
CSan.FormToShow = typeof(SanManagerForm);
CVtPort.FormToShow = typeof(NewVTPortForm);
CVtPort.Columns.Clear();
CVtPort.AddColumn("Name", "Select VT Port");
CFirstTrunk.FormToShow = typeof(CableManagerForm);
CBlechType.FormToShow = typeof(BlechTypeManagerForm);
CBlechType.Columns.Clear();
CBlechType.AddColumn("Name", "Select Blech Type");
CBlech.FormToShow = typeof(NewBlechForm);
CLcLength.FormToShow = typeof(CableModelManagerForm);
CLcCable.FormToShow = typeof(CableManagerForm);
}
private void defaultButton_Click(object sender, EventArgs e)
{
Save();
}
private bool Save()
{
object coreSwitch = CCoreSwitch.EditValue == null ? DBNull.Value : CCoreSwitch.EditValue;
if (CManagerValidator.Validate())
{
if (Convert.ToInt32(CSwitchType.EditValue) == 1)
{
DataSet ds = DBAssistant.ExecProcedure(sproc.Switch_Insert_Check_Record, new object[]
{
"@DatacenterID", CDataCenter.EditValue,
"@SanID", CSan.EditValue
});
if (ds.Tables[0].DefaultView.Count > 0)
{
XtraMessageBox.Show("Same Switch does already exist on the records!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
ds.Dispose();
return false;
}
ds.Dispose();
}
DBAssistant.ExecProcedure
(sproc.Switch_Insert_WithDetails, new object[]
{
"@SerialNo", CSwitchSerial.Text,
"@SanID", CSan.EditValue,
"@DatacenterID", CDataCenter.EditValue,
"@VtPortID", CVtPort.EditValue,
"@BlechID", CBlech.EditValue,
"@SwitchTypeID", CSwitchType.EditValue,
"@SwitchModelID", CSwitchModel.EditValue,
"@IpNo", CSwitchIP.Text,
"@CoreSwitchID", coreSwitch,
"@TrunkNo", CFirstTrunk.EditValue,
"@StartLcUrmID", CLcCable.EditValue,
"@LcUrmCount", CLcCount.Value
}
);
RefreshAssistant.RefreshTrees();
return true;
}
else
return false;
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
Close();
}
private void CSwitchType_EditValueChanged(object sender, EventArgs e)
{
CCoreSwitch.Enabled = CSwitchType.GetColumnValue("Name").ToString().Contains("Edge") ? true : false;
}
private void CFirstTrunk_Triggering(KabMan.Controls.C_LookUpControl sender, CancelEventArgs e)
{
e.Cancel = true;
sender.Properties.Buttons[2].Enabled = true;
sender.Parameters = new NameValuePair[] { new NameValuePair("@SanValue", (Convert.ToInt32(sender.TriggerControl.GetColumnValue("Value")) % 2).ToString()) };
sender.LoadDataSource(sender.StoredProcedure, sender.ParametersToArray(), sender.DisplayMember, sender.ValueMember);
}
private void CBlech_Triggering(C_LookUpControl sender, CancelEventArgs e)
{
e.Cancel = true;
this.FillBlechLookUp();
}
private void CDataCenter_EditValueChanged(object sender, EventArgs e)
{
this.FillBlechLookUp();
}
private void FillBlechLookUp()
{
if (CDataCenter.EditValue != null && CBlechType.EditValue != null)
{
CBlech.Properties.Buttons[2].Enabled = true;
}
CBlech.Parameters = null;
CBlech.Parameters = new NameValuePair[]
{
new NameValuePair("BlechTypeID", TextAssistant.TryConvertToString(CBlechType.EditValue)),
new NameValuePair("DeviceName", "Switch"),
new NameValuePair("DataCenterID", TextAssistant.TryConvertToString(CDataCenter.EditValue))
};
CBlech.LoadDataSource();
}
private void CLocation_EditValueChanged(object sender, EventArgs e)
{
CDataCenter.FormParameters.Clear();
CDataCenter.FormParameters.Add(CLocation.EditValue);
}
private void CSanGroup_EditValueChanged(object sender, EventArgs e)
{
CSan.FormParameters.Clear();
CSan.FormParameters.Add(CSanGroup.EditValue);
}
private void CLcLength_EditValueChanged(object sender, EventArgs e)
{
}
private void btnSaveClose_Click(object sender, EventArgs e)
{
if (Save()) Close();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Binary.Structure;
/// <summary>
/// Binary writer implementation.
/// </summary>
internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Stream. */
private readonly IBinaryStream _stream;
/** Builder (used only during build). */
private BinaryObjectBuilder _builder;
/** Handles. */
private BinaryHandleDictionary<object, long> _hnds;
/** Metadatas collected during this write session. */
private IDictionary<int, BinaryType> _metas;
/** Current type ID. */
private int _curTypeId;
/** Current name converter */
private IBinaryNameMapper _curConverter;
/** Current mapper. */
private IBinaryIdMapper _curMapper;
/** Current object start position. */
private int _curPos;
/** Current raw position. */
private int _curRawPos;
/** Whether we are currently detaching an object. */
private bool _detaching;
/** Current type structure tracker, */
private BinaryStructureTracker _curStruct;
/** Schema holder. */
private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current;
/// <summary>
/// Gets the marshaller.
/// </summary>
internal Marshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Write named boolean value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(string fieldName, bool val)
{
WriteFieldId(fieldName, BinaryUtils.TypeBool);
_stream.WriteByte(BinaryUtils.TypeBool);
_stream.WriteBool(val);
}
/// <summary>
/// Write boolean value.
/// </summary>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(bool val)
{
_stream.WriteBool(val);
}
/// <summary>
/// Write named boolean array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(string fieldName, bool[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayBool);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write boolean array.
/// </summary>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(bool[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write named byte value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte value.</param>
public void WriteByte(string fieldName, byte val)
{
WriteFieldId(fieldName, BinaryUtils.TypeBool);
_stream.WriteByte(BinaryUtils.TypeByte);
_stream.WriteByte(val);
}
/// <summary>
/// Write byte value.
/// </summary>
/// <param name="val">Byte value.</param>
public void WriteByte(byte val)
{
_stream.WriteByte(val);
}
/// <summary>
/// Write named byte array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte array.</param>
public void WriteByteArray(string fieldName, byte[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayByte);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
public void WriteByteArray(byte[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write named short value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short value.</param>
public void WriteShort(string fieldName, short val)
{
WriteFieldId(fieldName, BinaryUtils.TypeShort);
_stream.WriteByte(BinaryUtils.TypeShort);
_stream.WriteShort(val);
}
/// <summary>
/// Write short value.
/// </summary>
/// <param name="val">Short value.</param>
public void WriteShort(short val)
{
_stream.WriteShort(val);
}
/// <summary>
/// Write named short array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short array.</param>
public void WriteShortArray(string fieldName, short[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayShort);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="val">Short array.</param>
public void WriteShortArray(short[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write named char value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char value.</param>
public void WriteChar(string fieldName, char val)
{
WriteFieldId(fieldName, BinaryUtils.TypeChar);
_stream.WriteByte(BinaryUtils.TypeChar);
_stream.WriteChar(val);
}
/// <summary>
/// Write char value.
/// </summary>
/// <param name="val">Char value.</param>
public void WriteChar(char val)
{
_stream.WriteChar(val);
}
/// <summary>
/// Write named char array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char array.</param>
public void WriteCharArray(string fieldName, char[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayChar);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="val">Char array.</param>
public void WriteCharArray(char[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write named int value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int value.</param>
public void WriteInt(string fieldName, int val)
{
WriteFieldId(fieldName, BinaryUtils.TypeInt);
_stream.WriteByte(BinaryUtils.TypeInt);
_stream.WriteInt(val);
}
/// <summary>
/// Write int value.
/// </summary>
/// <param name="val">Int value.</param>
public void WriteInt(int val)
{
_stream.WriteInt(val);
}
/// <summary>
/// Write named int array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int array.</param>
public void WriteIntArray(string fieldName, int[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayInt);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="val">Int array.</param>
public void WriteIntArray(int[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write named long value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long value.</param>
public void WriteLong(string fieldName, long val)
{
WriteFieldId(fieldName, BinaryUtils.TypeLong);
_stream.WriteByte(BinaryUtils.TypeLong);
_stream.WriteLong(val);
}
/// <summary>
/// Write long value.
/// </summary>
/// <param name="val">Long value.</param>
public void WriteLong(long val)
{
_stream.WriteLong(val);
}
/// <summary>
/// Write named long array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long array.</param>
public void WriteLongArray(string fieldName, long[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayLong);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="val">Long array.</param>
public void WriteLongArray(long[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write named float value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float value.</param>
public void WriteFloat(string fieldName, float val)
{
WriteFieldId(fieldName, BinaryUtils.TypeFloat);
_stream.WriteByte(BinaryUtils.TypeFloat);
_stream.WriteFloat(val);
}
/// <summary>
/// Write float value.
/// </summary>
/// <param name="val">Float value.</param>
public void WriteFloat(float val)
{
_stream.WriteFloat(val);
}
/// <summary>
/// Write named float array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float array.</param>
public void WriteFloatArray(string fieldName, float[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayFloat);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="val">Float array.</param>
public void WriteFloatArray(float[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write named double value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double value.</param>
public void WriteDouble(string fieldName, double val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDouble);
_stream.WriteByte(BinaryUtils.TypeDouble);
_stream.WriteDouble(val);
}
/// <summary>
/// Write double value.
/// </summary>
/// <param name="val">Double value.</param>
public void WriteDouble(double val)
{
_stream.WriteDouble(val);
}
/// <summary>
/// Write named double array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(string fieldName, double[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayDouble);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(double[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write named decimal value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(string fieldName, decimal? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write decimal value.
/// </summary>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(decimal? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write named decimal array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(string fieldName, decimal?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write decimal array.
/// </summary>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(decimal?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write named date value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date value.</param>
public void WriteTimestamp(string fieldName, DateTime? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeTimestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeTimestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write date value.
/// </summary>
/// <param name="val">Date value.</param>
public void WriteTimestamp(DateTime? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeTimestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write named date array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(string fieldName, DateTime?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeTimestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write date array.
/// </summary>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(DateTime?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write named string value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String value.</param>
public void WriteString(string fieldName, string val)
{
WriteFieldId(fieldName, BinaryUtils.TypeString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write string value.
/// </summary>
/// <param name="val">String value.</param>
public void WriteString(string val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write named string array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String array.</param>
public void WriteStringArray(string fieldName, string[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write string array.
/// </summary>
/// <param name="val">String array.</param>
public void WriteStringArray(string[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write named GUID value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID value.</param>
public void WriteGuid(string fieldName, Guid? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write GUID value.
/// </summary>
/// <param name="val">GUID value.</param>
public void WriteGuid(Guid? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write named GUID array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(string fieldName, Guid?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write GUID array.
/// </summary>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(Guid?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write named enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryUtils.TypeEnum);
WriteEnum(val);
}
/// <summary>
/// Write enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(T val)
{
if (val == null)
WriteNullField();
else
{
var desc = _marsh.GetDescriptor(val.GetType());
if (desc != null)
{
var metaHnd = _marsh.GetBinaryTypeHandler(desc);
_stream.WriteByte(BinaryUtils.TypeEnum);
BinaryUtils.WriteEnum(this, val);
SaveMetadata(desc, metaHnd.OnObjectWriteFinished());
}
else
{
// Unregistered enum, write as serializable
Write(new SerializableObjectHolder(val));
}
}
}
/// <summary>
/// Write named enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayEnum);
WriteEnumArray(val);
}
/// <summary>
/// Write enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(T[] val)
{
WriteEnumArrayInternal(val, null);
}
/// <summary>
/// Writes the enum array.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="elementTypeId">The element type id.</param>
public void WriteEnumArrayInternal(Array val, int? elementTypeId)
{
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayEnum);
var elTypeId = elementTypeId ?? BinaryUtils.GetEnumTypeId(val.GetType().GetElementType(), Marshaller);
BinaryUtils.WriteArray(val, this, elTypeId);
}
}
/// <summary>
/// Write named object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object value.</param>
public void WriteObject<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryUtils.TypeObject);
if (val == null)
WriteNullField();
else
Write(val);
}
/// <summary>
/// Write object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Object value.</param>
public void WriteObject<T>(T val)
{
Write(val);
}
/// <summary>
/// Write named object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object array.</param>
public void WriteArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArray);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArray);
BinaryUtils.WriteArray(val, this);
}
}
/// <summary>
/// Write object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="val">Object array.</param>
public void WriteArray<T>(T[] val)
{
WriteArrayInternal(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <param name="val">Object array.</param>
public void WriteArrayInternal(Array val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArray);
BinaryUtils.WriteArray(val, this);
}
}
/// <summary>
/// Write named collection.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Collection.</param>
public void WriteCollection(string fieldName, ICollection val)
{
WriteFieldId(fieldName, BinaryUtils.TypeCollection);
if (val == null)
WriteNullField();
else
WriteCollection(val);
}
/// <summary>
/// Write collection.
/// </summary>
/// <param name="val">Collection.</param>
public void WriteCollection(ICollection val)
{
WriteByte(BinaryUtils.TypeCollection);
BinaryUtils.WriteCollection(val, this);
}
/// <summary>
/// Write named dictionary.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(string fieldName, IDictionary val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDictionary);
if (val == null)
WriteNullField();
else
WriteDictionary(val);
}
/// <summary>
/// Write dictionary.
/// </summary>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(IDictionary val)
{
WriteByte(BinaryUtils.TypeDictionary);
BinaryUtils.WriteDictionary(val, this);
}
/// <summary>
/// Write NULL field.
/// </summary>
private void WriteNullField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Write NULL raw field.
/// </summary>
private void WriteNullRawField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Get raw writer.
/// </summary>
/// <returns>
/// Raw writer.
/// </returns>
public IBinaryRawWriter GetRawWriter()
{
if (_curRawPos == 0)
_curRawPos = _stream.Position;
return this;
}
/// <summary>
/// Set new builder.
/// </summary>
/// <param name="builder">Builder.</param>
/// <returns>Previous builder.</returns>
internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder)
{
BinaryObjectBuilder ret = _builder;
_builder = builder;
return ret;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Stream.</param>
internal BinaryWriter(Marshaller marsh, IBinaryStream stream)
{
_marsh = marsh;
_stream = stream;
}
/// <summary>
/// Write object.
/// </summary>
/// <param name="obj">Object.</param>
public void Write<T>(T obj)
{
// Handle special case for null.
if (obj == null)
{
_stream.WriteByte(BinaryUtils.HdrNull);
return;
}
// We use GetType() of a real object instead of typeof(T) to take advantage of
// automatic Nullable'1 unwrapping.
Type type = obj.GetType();
// Handle common case when primitive is written.
if (type.IsPrimitive)
{
WritePrimitive(obj, type);
return;
}
// Handle enums.
if (type.IsEnum)
{
WriteEnum(obj);
return;
}
// Handle special case for builder.
if (WriteBuilderSpecials(obj))
return;
// Suppose that we faced normal object and perform descriptor lookup.
IBinaryTypeDescriptor desc = _marsh.GetDescriptor(type);
if (desc != null)
{
// Writing normal object.
var pos = _stream.Position;
// Dealing with handles.
if (!(desc.Serializer is IBinarySystemTypeSerializer) && WriteHandle(pos, obj))
return;
// Skip header length as not everything is known now
_stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current);
// Preserve old frame.
int oldTypeId = _curTypeId;
IBinaryNameMapper oldConverter = _curConverter;
IBinaryIdMapper oldMapper = _curMapper;
int oldRawPos = _curRawPos;
var oldPos = _curPos;
var oldStruct = _curStruct;
// Push new frame.
_curTypeId = desc.TypeId;
_curConverter = desc.NameMapper;
_curMapper = desc.IdMapper;
_curRawPos = 0;
_curPos = pos;
_curStruct = new BinaryStructureTracker(desc, desc.WriterTypeStructure);
var schemaIdx = _schema.PushSchema();
try
{
// Write object fields.
desc.Serializer.WriteBinary(obj, this);
// Write schema
var schemaOffset = _stream.Position - pos;
int schemaId;
var flags = desc.UserType
? BinaryObjectHeader.Flag.UserType
: BinaryObjectHeader.Flag.None;
var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags);
if (hasSchema)
{
flags |= BinaryObjectHeader.Flag.HasSchema;
// Calculate and write header.
if (_curRawPos > 0)
_stream.WriteInt(_curRawPos - pos); // raw offset is in the last 4 bytes
}
else
schemaOffset = BinaryObjectHeader.Size;
if (_curRawPos > 0)
flags |= BinaryObjectHeader.Flag.HasRaw;
var len = _stream.Position - pos;
var header = new BinaryObjectHeader(desc.TypeId, obj.GetHashCode(), len,
schemaId, schemaOffset, flags);
BinaryObjectHeader.Write(header, _stream, pos);
Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end
}
finally
{
_schema.PopSchema(schemaIdx);
}
// Apply structure updates if any.
_curStruct.UpdateWriterStructure(this);
// Restore old frame.
_curTypeId = oldTypeId;
_curConverter = oldConverter;
_curMapper = oldMapper;
_curRawPos = oldRawPos;
_curPos = oldPos;
_curStruct = oldStruct;
}
else
{
// Are we dealing with a well-known type?
var handler = BinarySystemHandlers.GetWriteHandler(type);
if (handler == null) // We did our best, object cannot be marshalled.
throw new BinaryObjectException("Unsupported object type [type=" + type + ", object=" + obj + ']');
handler(this, obj);
}
}
/// <summary>
/// Write primitive type.
/// </summary>
/// <param name="val">Object.</param>
/// <param name="type">Type.</param>
private unsafe void WritePrimitive<T>(T val, Type type)
{
// .Net defines 14 primitive types. We support 12 - excluding IntPtr and UIntPtr.
// Types check sequence is designed to minimize comparisons for the most frequent types.
if (type == typeof(int))
{
_stream.WriteByte(BinaryUtils.TypeInt);
_stream.WriteInt((int)(object)val);
}
else if (type == typeof(long))
{
_stream.WriteByte(BinaryUtils.TypeLong);
_stream.WriteLong((long)(object)val);
}
else if (type == typeof(bool))
{
_stream.WriteByte(BinaryUtils.TypeBool);
_stream.WriteBool((bool)(object)val);
}
else if (type == typeof(byte))
{
_stream.WriteByte(BinaryUtils.TypeByte);
_stream.WriteByte((byte)(object)val);
}
else if (type == typeof(short))
{
_stream.WriteByte(BinaryUtils.TypeShort);
_stream.WriteShort((short)(object)val);
}
else if (type == typeof (char))
{
_stream.WriteByte(BinaryUtils.TypeChar);
_stream.WriteChar((char)(object)val);
}
else if (type == typeof(float))
{
_stream.WriteByte(BinaryUtils.TypeFloat);
_stream.WriteFloat((float)(object)val);
}
else if (type == typeof(double))
{
_stream.WriteByte(BinaryUtils.TypeDouble);
_stream.WriteDouble((double)(object)val);
}
else if (type == typeof(sbyte))
{
sbyte val0 = (sbyte)(object)val;
_stream.WriteByte(BinaryUtils.TypeByte);
_stream.WriteByte(*(byte*)&val0);
}
else if (type == typeof(ushort))
{
ushort val0 = (ushort)(object)val;
_stream.WriteByte(BinaryUtils.TypeShort);
_stream.WriteShort(*(short*)&val0);
}
else if (type == typeof(uint))
{
uint val0 = (uint)(object)val;
_stream.WriteByte(BinaryUtils.TypeInt);
_stream.WriteInt(*(int*)&val0);
}
else if (type == typeof(ulong))
{
ulong val0 = (ulong)(object)val;
_stream.WriteByte(BinaryUtils.TypeLong);
_stream.WriteLong(*(long*)&val0);
}
else
throw new BinaryObjectException("Unsupported object type [type=" + type.FullName + ", object=" + val + ']');
}
/// <summary>
/// Try writing object as special builder type.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>True if object was written, false otherwise.</returns>
private bool WriteBuilderSpecials<T>(T obj)
{
if (_builder != null)
{
// Special case for binary object during build.
BinaryObject portObj = obj as BinaryObject;
if (portObj != null)
{
if (!WriteHandle(_stream.Position, portObj))
_builder.ProcessBinary(_stream, portObj);
return true;
}
// Special case for builder during build.
BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder;
if (portBuilder != null)
{
if (!WriteHandle(_stream.Position, portBuilder))
_builder.ProcessBuilder(_stream, portBuilder);
return true;
}
}
return false;
}
/// <summary>
/// Add handle to handles map.
/// </summary>
/// <param name="pos">Position in stream.</param>
/// <param name="obj">Object.</param>
/// <returns><c>true</c> if object was written as handle.</returns>
private bool WriteHandle(long pos, object obj)
{
if (_hnds == null)
{
// Cache absolute handle position.
_hnds = new BinaryHandleDictionary<object, long>(obj, pos);
return false;
}
long hndPos;
if (!_hnds.TryGetValue(obj, out hndPos))
{
// Cache absolute handle position.
_hnds.Add(obj, pos);
return false;
}
_stream.WriteByte(BinaryUtils.HdrHnd);
// Handle is written as difference between position before header and handle position.
_stream.WriteInt((int)(pos - hndPos));
return true;
}
/// <summary>
/// Perform action with detached semantics.
/// </summary>
/// <param name="a"></param>
internal void WithDetach(Action<BinaryWriter> a)
{
if (_detaching)
a(this);
else
{
_detaching = true;
BinaryHandleDictionary<object, long> oldHnds = _hnds;
_hnds = null;
try
{
a(this);
}
finally
{
_detaching = false;
if (oldHnds != null)
{
// Merge newly recorded handles with old ones and restore old on the stack.
// Otherwise we can use current handles right away.
if (_hnds != null)
oldHnds.Merge(_hnds);
_hnds = oldHnds;
}
}
}
}
/// <summary>
/// Stream.
/// </summary>
internal IBinaryStream Stream
{
get { return _stream; }
}
/// <summary>
/// Gets collected metadatas.
/// </summary>
/// <returns>Collected metadatas (if any).</returns>
internal ICollection<BinaryType> GetBinaryTypes()
{
return _metas == null ? null : _metas.Values;
}
/// <summary>
/// Check whether the given object is binarizeble, i.e. it can be serialized with binary marshaller.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>True if binarizable.</returns>
internal bool IsBinarizable(object obj)
{
if (obj != null)
{
Type type = obj.GetType();
// We assume object as binarizable only in case it has descriptor.
// Collections, Enums and non-primitive arrays do not have descriptors
// and this is fine here because we cannot know whether their members are binarizable.
return _marsh.GetDescriptor(type) != null || BinarySystemHandlers.GetWriteHandler(type) != null;
}
return true;
}
/// <summary>
/// Write field ID.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="fieldTypeId">Field type ID.</param>
private void WriteFieldId(string fieldName, byte fieldTypeId)
{
if (_curRawPos != 0)
throw new BinaryObjectException("Cannot write named fields after raw data is written.");
var fieldId = _curStruct.GetFieldId(fieldName, fieldTypeId);
_schema.PushField(fieldId, _stream.Position - _curPos);
}
/// <summary>
/// Saves metadata for this session.
/// </summary>
/// <param name="desc">The descriptor.</param>
/// <param name="fields">Fields metadata.</param>
internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, int> fields)
{
Debug.Assert(desc != null);
if (_metas == null)
{
_metas = new Dictionary<int, BinaryType>(1)
{
{desc.TypeId, new BinaryType(desc, fields)}
};
}
else
{
BinaryType meta;
if (_metas.TryGetValue(desc.TypeId, out meta))
{
if (fields != null)
{
IDictionary<string, int> existingFields = meta.GetFieldsMap();
foreach (KeyValuePair<string, int> field in fields)
{
if (!existingFields.ContainsKey(field.Key))
existingFields[field.Key] = field.Value;
}
}
}
else
_metas[desc.TypeId] = new BinaryType(desc, fields);
}
}
}
}
| |
//#define COSMOSDEBUG
using System;
using System.IO;
using Cosmos.System;
using Cosmos.Common;
using Cosmos.Debug.Kernel;
using IL2CPU.API;
using IL2CPU.API.Attribs;
using Cosmos.System.FileSystem;
using Cosmos.System.FileSystem.VFS;
namespace Cosmos.System_Plugs.System.IO
{
[Plug(Target = typeof(Path))]
public static class PathImpl
{
public static void Cctor(
[FieldAccess(Name = "System.Char System.IO.Path.AltDirectorySeparatorChar")] ref char aAltDirectorySeparatorChar,
[FieldAccess(Name = "System.Char System.IO.Path.DirectorySeparatorChar")] ref char aDirectorySeparatorChar,
[FieldAccess(Name = "System.Char System.IO.Path.VolumeSeparatorChar")] ref char aVolumeSeparatorChar)
{
aAltDirectorySeparatorChar = VFSManager.GetAltDirectorySeparatorChar();
aDirectorySeparatorChar = VFSManager.GetDirectorySeparatorChar();
aVolumeSeparatorChar = VFSManager.GetVolumeSeparatorChar();
}
public static string ChangeExtension(string aPath, string aExtension)
{
if (aPath != null)
{
CheckInvalidPathChars(aPath);
string xText = aPath;
int xNum = aPath.Length;
while (--xNum >= 0)
{
char xC = aPath[xNum];
if (xC == '.')
{
xText = aPath.Substring(0, xNum);
break;
}
if (xC == Path.DirectorySeparatorChar || xC == Path.AltDirectorySeparatorChar
|| xC == Path.VolumeSeparatorChar)
{
break;
}
}
if (aExtension != null && aPath.Length != 0)
{
if (aExtension.Length == 0 || aExtension[0] != '.')
{
xText += ".";
}
xText += aExtension;
}
Global.mFileSystemDebugger.SendInternal($"Path.ChangeExtension : aPath = {aPath}, aExtension = {aExtension}, returning {xText}");
return xText;
}
return null;
}
public static string Combine(string aPath1, string aPath2)
{
if (aPath1 == null || aPath2 == null)
{
throw new ArgumentNullException((aPath1 == null) ? "path1" : "path2");
}
CheckInvalidPathChars(aPath1);
CheckInvalidPathChars(aPath2);
string result = CombineNoChecks(aPath1, aPath2);
Global.mFileSystemDebugger.SendInternal($"Path.Combine : aPath1 = {aPath1}, aPath2 = {aPath2}, returning {result}");
return result;
}
public static string CombineNoChecks(string aPath1, string aPath2)
{
if (aPath2.Length == 0)
{
Global.mFileSystemDebugger.SendInternal($"Path.CombineNoChecks : aPath2 has 0 length, returning {aPath1}");
return aPath1;
}
if (aPath1.Length == 0)
{
Global.mFileSystemDebugger.SendInternal($"Path.CombineNoChecks : aPath1 has 0 length, returning {aPath2}");
return aPath2;
}
if (IsPathRooted(aPath2))
{
Global.mFileSystemDebugger.SendInternal($"Path.CombineNoChecks : aPath2 is root, returning {aPath2}");
return aPath2;
}
string xResult = string.Empty;
char xC = aPath1[aPath1.Length - 1];
if (xC != Path.DirectorySeparatorChar && xC != Path.AltDirectorySeparatorChar && xC != Path.VolumeSeparatorChar)
{
xResult = string.Concat(aPath1, "\\", aPath2);
Global.mFileSystemDebugger.SendInternal($"Path.CombineNoChecks : aPath1 = {aPath1}, aPath2 = {aPath2}, returning {xResult}");
return xResult;
}
xResult = string.Concat(aPath1, aPath2);
Global.mFileSystemDebugger.SendInternal($"Path.CombineNoChecks : aPath1 = {aPath1}, aPath2 = {aPath2}, returning {xResult}");
return xResult;
}
public static string GetExtension(string aPath)
{
Global.mFileSystemDebugger.SendInternal("Path.GetExtension");
if (aPath == null)
{
return null;
}
CheckInvalidPathChars(aPath);
int xLength = aPath.Length;
int xNum = xLength;
while (--xNum >= 0)
{
char xC = aPath[xNum];
if (xC == '.')
{
if (xNum != xLength - 1)
{
return aPath.Substring(xNum, xLength - xNum);
}
return string.Empty;
}
if (xC == Path.DirectorySeparatorChar || xC == Path.AltDirectorySeparatorChar || xC == Path.VolumeSeparatorChar)
{
break;
}
}
return string.Empty;
}
public static string GetFileName(string aPath)
{
Global.mFileSystemDebugger.SendInternal($"Path.GetFileName : aPath = {aPath}");
if (aPath != null)
{
CheckInvalidPathChars(aPath);
int xLength = aPath.Length;
int xNum = xLength;
while (--xNum >= 0)
{
char xC = aPath[xNum];
if (xC == Path.DirectorySeparatorChar || xC == Path.AltDirectorySeparatorChar
|| xC == Path.VolumeSeparatorChar)
{
return aPath.Substring(xNum + 1, xLength - xNum - 1);
}
}
}
Global.mFileSystemDebugger.SendInternal($"Path.GetFileName : returning {aPath}");
return aPath;
}
public static string GetFileNameWithoutExtension(string aPath)
{
Global.mFileSystemDebugger.SendInternal($"Path.GetFileNameWithoutExtension : aPath = {aPath}");
aPath = GetFileName(aPath);
if (aPath == null)
{
Global.mFileSystemDebugger.SendInternal($"Path.GetFileNameWithoutExtension : returning null");
return null;
}
int xLength;
if ((xLength = aPath.LastIndexOf('.')) == -1)
{
Global.mFileSystemDebugger.SendInternal($"Path.GetFileNameWithoutExtension : returning {aPath}");
return aPath;
}
string xResult = aPath.Substring(0, xLength);
Global.mFileSystemDebugger.SendInternal($"Path.GetFileNameWithoutExtension : returning {xResult}");
return xResult;
}
public static string GetFullPath(string aPath)
{
if (aPath == null)
{
Global.mFileSystemDebugger.SendInternal($"Path.GetFullPath : aPath is null");
throw new ArgumentNullException("aPath");
}
string result = NormalizePath(aPath, true);
Global.mFileSystemDebugger.SendInternal($"Path.GetFullPath : aPath = {aPath}, returning {result}");
return result;
}
public static char[] GetInvalidFileNameChars()
{
return VFSManager.GetInvalidFileNameChars();
}
public static char[] GetInvalidPathChars()
{
return VFSManager.GetRealInvalidPathChars();
}
public static string GetPathRoot(string aPath)
{
if (aPath == null)
{
Global.mFileSystemDebugger.SendInternal($"Path.GetPathRoot : aPath is null");
throw new ArgumentNullException(nameof(aPath));
}
aPath = NormalizePath(aPath, false);
int xRootLength = GetRootLength(aPath);
string xResult = aPath.Substring(0, xRootLength);
if (xResult[xResult.Length - 1] != Path.DirectorySeparatorChar)
{
xResult = string.Concat(xResult, Path.DirectorySeparatorChar);
}
Global.mFileSystemDebugger.SendInternal($"Path.GetPathRoot : aPath = {aPath}, xResult = {xResult}");
return xResult;
}
public static string GetRandomFileName()
{
return "random.tmp";
}
public static string GetTempFileName()
{
return "tempfile.tmp";
}
public static string GetTempPath()
{
return @"0:\Temp";
}
public static string RemoveLongPathPrefix(string aPath)
{
return aPath;
}
public static bool HasExtension(string aPath)
{
if (aPath != null)
{
CheckInvalidPathChars(aPath);
int xNum = aPath.Length;
while (--xNum >= 0)
{
char xC = aPath[xNum];
if (xC == '.')
{
return xNum != aPath.Length - 1;
}
if (xC == Path.DirectorySeparatorChar || xC == Path.AltDirectorySeparatorChar
|| xC == Path.VolumeSeparatorChar)
{
break;
}
}
}
return false;
}
[PlugMethod(IsOptional = true)]
public static bool HasIllegalCharacters(string aPath, bool aCheckAdditional)
{
if (aCheckAdditional)
{
char[] xInvalidWithAdditional = VFSManager.GetInvalidPathCharsWithAdditionalChecks();
for (int i = 0; i < xInvalidWithAdditional.Length; i++)
{
for (int j = 0; j < aPath.Length; j++)
{
if (xInvalidWithAdditional[i] == aPath[j])
{
return true;
}
}
}
}
char[] xInvalid = VFSManager.GetRealInvalidPathChars();
for (int i = 0; i < xInvalid.Length; i++)
{
for (int j = 0; j < aPath.Length; j++)
{
if (xInvalid[i] == aPath[j])
{
return true;
}
}
}
return false;
}
public static bool IsDirectorySeparator(char aC)
{
if (aC == Path.DirectorySeparatorChar)
{
return true;
}
if (aC == Path.AltDirectorySeparatorChar)
{
return true;
}
return false;
}
public static bool IsPathRooted(string aPath)
{
Global.mFileSystemDebugger.SendInternal("Path.IsPathRooted");
if (aPath != null)
{
CheckInvalidPathChars(aPath);
int xLength = aPath.Length;
if ((xLength >= 1 && (aPath[0] == Path.DirectorySeparatorChar || aPath[0] == Path.AltDirectorySeparatorChar)) || (xLength >= 2 && aPath[1] == Path.VolumeSeparatorChar))
{
return true;
}
}
return false;
}
private static bool IsRelative(string aPath)
{
if (aPath == null)
{
throw new ArgumentNullException("aPath");
}
if (aPath.Length < 3)
{
return true;
}
if (aPath[1] != Path.VolumeSeparatorChar)
{
return true;
}
if (aPath[2] != Path.DirectorySeparatorChar)
{
return true;
}
return false;
}
internal static void CheckInvalidPathChars(string aPath, bool aCheckAdditional = false)
{
Global.mFileSystemDebugger.SendInternal("Path.CheckInvalidPathChars");
if (aPath == null)
{
throw new ArgumentNullException("aPath");
}
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
var xChars = VFSManager.GetRealInvalidPathChars();
for (int i = 0; i < xChars.Length; i++)
{
if (aPath.IndexOf(xChars[i]) >= 0)
{
throw new ArgumentException("The path contains invalid characters.", aPath);
}
}
}
public static string GetDirectoryName(string aPath)
{
Global.mFileSystemDebugger.SendInternal("Path.GetDirectoryName");
if (aPath != null)
{
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
CheckInvalidPathChars(aPath);
string xText = NormalizePath(aPath, false);
if (aPath.Length > 0)
{
try
{
string text2 = aPath;
int num = 0;
while ((num < text2.Length) && (text2[num] != '?') && (text2[num] != '*'))
{
num++;
}
if (num > 0)
{
Path.GetFullPath(text2.Substring(0, num));
}
}
catch (PathTooLongException)
{
}
catch (NotSupportedException)
{
}
catch (ArgumentException)
{
}
}
aPath = xText;
int rootLength = GetRootLength(aPath);
int num2 = aPath.Length;
if (num2 > rootLength)
{
num2 = aPath.Length;
if (num2 == rootLength)
{
return null;
}
while ((num2 > rootLength) && (aPath[--num2] != Path.DirectorySeparatorChar) && (aPath[num2] != Path.AltDirectorySeparatorChar))
{
}
return aPath.Substring(0, num2);
}
}
return null;
}
internal static int GetRootLength(string aPath)
{
Global.mFileSystemDebugger.SendInternal("Path.GetRootLength");
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
int i = 0;
int xLength = aPath.Length;
if ((xLength >= 1) && IsDirectorySeparator(aPath[0]))
{
i = 1;
if ((xLength >= 2) && IsDirectorySeparator(aPath[1]))
{
i = 2;
int xNum = 2;
while (i < xLength)
{
if (((aPath[i] == Path.DirectorySeparatorChar) || (aPath[i] == Path.AltDirectorySeparatorChar)) && (--xNum <= 0))
{
break;
}
i++;
}
}
}
else if ((xLength >= 2) && (aPath[1] == VFSManager.GetVolumeSeparatorChar()))
{
i = 2;
if ((xLength >= 3) && IsDirectorySeparator(aPath[2]))
{
i++;
}
}
return i;
}
public static string NormalizePath(string aPath, bool aFullCheck)
{
Global.mFileSystemDebugger.SendInternal("Path.NormalizePath");
if (aPath == null)
{
Global.mFileSystemDebugger.SendInternal("aPath is null");
throw new ArgumentNullException("aPath");
}
string result = aPath;
if (IsRelative(result))
{
result = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + result;
Global.mFileSystemDebugger.SendInternal("aPath is relative");
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
Global.mFileSystemDebugger.SendInternal("result =");
Global.mFileSystemDebugger.SendInternal(result);
}
if (IsDirectorySeparator(result[result.Length - 1]))
{
Global.mFileSystemDebugger.SendInternal("Found directory seprator");
if (result.Length > 3)
{
result = result.Remove(result.Length - 1);
}
}
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
Global.mFileSystemDebugger.SendInternal("result =");
Global.mFileSystemDebugger.SendInternal(result);
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NSubstitute.Core;
using NSubstitute.Core.Arguments;
using NSubstitute.Routing;
using NSubstitute.Specs.Infrastructure;
using NSubstitute.Specs.SampleStructures;
using NUnit.Framework;
namespace NSubstitute.Specs
{
public class CallRouterSpecs
{
public abstract class Concern : ConcernFor<CallRouter>
{
protected readonly object _returnValueFromRecordReplayRoute = "value from record replay route";
protected ISubstitutionContext _context;
protected ICall _call;
protected IConfigureCall ConfigureCall;
protected IRouteFactory _routeFactory;
protected IReceivedCalls _receivedCalls;
protected ISubstituteState _state;
protected IResultsForType _resultsForType;
public override void Context()
{
_context = mock<ISubstitutionContext>();
_call = mock<ICall>();
_state = mock<ISubstituteState>();
_receivedCalls = mock<IReceivedCalls>();
ConfigureCall = mock<IConfigureCall>();
_routeFactory = mock<IRouteFactory>();
_resultsForType = mock<IResultsForType>();
_state.stub(x => x.ReceivedCalls).Return(_receivedCalls);
_state.stub(x => x.ConfigureCall).Return(ConfigureCall);
_state.stub(x => x.CallActions).Return(mock<ICallActions>());
_state.stub(x => x.CallResults).Return(mock<ICallResults>());
_state.stub(x => x.ResultsForType).Return(_resultsForType);
var recordReplayRoute = CreateRouteThatReturns(_returnValueFromRecordReplayRoute);
recordReplayRoute.stub(x => x.IsRecordReplayRoute).Return(true);
_routeFactory.stub(x => x.RecordReplay(_state)).Return(recordReplayRoute);
}
public override CallRouter CreateSubjectUnderTest()
{
return new CallRouter(_state, _context, _routeFactory);
}
protected IRoute CreateRouteThatReturns(object returnValue)
{
var route = mock<IRoute>();
route.stub(x => x.Handle(_call)).Return(returnValue);
return route;
}
}
public class When_a_route_is_set_and_a_member_is_called : Concern
{
readonly object _returnValueFromRoute = new object();
object _result;
IRoute _route;
[Test]
public void Should_update_last_call_router_on_substitution_context()
{
_context.received(x => x.LastCallRouter(sut));
}
[Test]
public void Should_send_call_to_route_and_return_response()
{
Assert.That(_result, Is.SameAs(_returnValueFromRoute));
}
[Test]
public void Should_send_next_call_to_record_replay_route_by_default()
{
var nextResult = sut.Route(_call);
Assert.That(nextResult, Is.EqualTo(_returnValueFromRecordReplayRoute));
}
public override void Because()
{
sut.SetRoute(x => _route);
_result = sut.Route(_call);
}
public override void Context()
{
base.Context();
_route = CreateRouteThatReturns(_returnValueFromRoute);
}
}
public class When_using_default_route : Concern
{
readonly object _returnValueFromRecordCallSpecRoute = "value from call spec route";
IRoute _recordCallSpecRoute;
[Test]
public void Should_record_call_spec_if_argument_matchers_have_been_specified_and_the_call_takes_arguments()
{
_call.stub(x => x.GetArguments()).Return(new object[4]);
_call.stub(x => x.GetArgumentSpecifications()).Return(CreateArgSpecs(3));
var result = sut.Route(_call);
Assert.That(result, Is.SameAs(_returnValueFromRecordCallSpecRoute));
}
[Test]
public void Should_record_call_and_replay_configured_result_if_this_looks_like_a_regular_call()
{
_call.stub(x => x.GetArguments()).Return(new object[4]);
_call.stub(x => x.GetArgumentSpecifications()).Return(CreateArgSpecs(0));
var result = sut.Route(_call);
Assert.That(result, Is.SameAs(_returnValueFromRecordReplayRoute));
}
[Test]
public void Should_record_call_and_replay_configured_result_if_there_are_arg_matchers_but_the_call_does_not_take_args()
{
_call.stub(x => x.GetArguments()).Return(new object[0]);
_call.stub(x => x.GetArgumentSpecifications()).Return(CreateArgSpecs(2));
var result = sut.Route(_call);
Assert.That(result, Is.SameAs(_returnValueFromRecordReplayRoute));
}
public override void Context()
{
base.Context();
_recordCallSpecRoute = CreateRouteThatReturns(_returnValueFromRecordCallSpecRoute);
_routeFactory.stub(x => x.RecordCallSpecification(_state)).Return(_recordCallSpecRoute);
}
IList<IArgumentSpecification> CreateArgSpecs(int count)
{
return Enumerable.Range(1, count).Select(x => mock<IArgumentSpecification>()).ToList();
}
}
public class When_setting_result_of_last_call : Concern
{
readonly MatchArgs _argMatching = MatchArgs.AsSpecifiedInCall;
IReturn _returnValue;
[Test]
public void Should_set_result()
{
ConfigureCall.received(x => x.SetResultForLastCall(_returnValue, _argMatching));
}
public override void Because()
{
sut.LastCallShouldReturn(_returnValue, _argMatching);
}
public override void Context()
{
base.Context();
_returnValue = mock<IReturn>();
}
}
public class When_setting_result_for_type : Concern
{
private readonly Type _type = typeof(IFoo);
IReturn _returnValue;
[Test]
public void Should_set_result()
{
_resultsForType.received(x => x.SetResult(_type, _returnValue));
}
public override void Because()
{
sut.SetReturnForType(_type, _returnValue);
}
public override void Context()
{
base.Context();
_returnValue = mock<IReturn>();
}
}
public class When_clearing : Concern
{
[Test]
public void Clear_received_calls()
{
sut.Clear(ClearOptions.ReceivedCalls);
_state.ReceivedCalls.received(x => x.Clear());
}
[Test]
public void Clear_call_actions()
{
sut.Clear(ClearOptions.CallActions);
_state.CallActions.received(x => x.Clear());
}
[Test]
public void Clear_return_values()
{
sut.Clear(ClearOptions.ReturnValues);
_state.CallResults.received(x => x.Clear());
_state.ResultsForType.received(x => x.Clear());
}
[Test]
public void Clear_all_the_things()
{
sut.Clear(ClearOptions.All);
_state.CallActions.received(x => x.Clear());
_state.CallResults.received(x => x.Clear());
_state.ResultsForType.received(x => x.Clear());
_state.ReceivedCalls.received(x => x.Clear());
}
[Test]
public void Clear_nothing()
{
sut.Clear(0);
_state.CallActions.did_not_receive(x => x.Clear());
_state.CallResults.did_not_receive(x => x.Clear());
_state.ResultsForType.did_not_receive(x => x.Clear());
_state.ReceivedCalls.did_not_receive(x => x.Clear());
}
}
public class When_getting_received_calls : Concern
{
private IEnumerable<ICall> _result;
private IEnumerable<ICall> _allCalls;
[Test]
public void Should_return_all_calls()
{
Assert.That(_result, Is.SameAs(_allCalls));
}
public override void Because()
{
_result = sut.ReceivedCalls();
}
public override void Context()
{
base.Context();
_allCalls = new ICall[0];
_receivedCalls.stub(x => x.AllCalls()).Return(_allCalls);
}
}
public class When_handling_a_call_while_querying : Concern
{
private readonly object _resultFromQueryRoute = new object();
private object _result;
public override void Context()
{
base.Context();
_context.stub(x => x.IsQuerying).Return(true);
_routeFactory.stub(x => x.CallQuery(_state)).Return(CreateRouteThatReturns(_resultFromQueryRoute));
}
public override void Because()
{
_result = sut.Route(_call);
}
[Test]
public void Should_handle_via_query_route()
{
Assert.That(_result, Is.EqualTo(_resultFromQueryRoute));
}
}
}
}
| |
// 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.InteropServices;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class zip_UpdateTests
{
[Theory]
[InlineData("normal.zip", "normal")]
[InlineData("fake64.zip", "small")]
[InlineData("empty.zip", "empty")]
[InlineData("appended.zip", "small")]
[InlineData("prepended.zip", "small")]
[InlineData("emptydir.zip", "emptydir")]
[InlineData("small.zip", "small")]
[InlineData("unicode.zip", "unicode")]
public static async Task UpdateReadNormal(string zipFile, string zipFolder)
{
ZipTest.IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile(zipFile)), ZipTest.zfolder(zipFolder), ZipArchiveMode.Update, false, false);
}
[Fact]
public static async Task UpdateReadTwice()
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("small.zip")), ZipArchiveMode.Update))
{
ZipArchiveEntry entry = archive.Entries[0];
String contents1, contents2;
using (StreamReader s = new StreamReader(entry.Open()))
{
contents1 = s.ReadToEnd();
}
using (StreamReader s = new StreamReader(entry.Open()))
{
contents2 = s.ReadToEnd();
}
Assert.Equal(contents1, contents2);
}
}
[InlineData("normal")]
[InlineData("empty")]
[InlineData("unicode")]
public static async Task UpdateCreate(string zipFolder)
{
var zs = new LocalMemoryStream();
await ZipTest.CreateFromDir(ZipTest.zfolder(zipFolder), zs, ZipArchiveMode.Update);
ZipTest.IsZipSameAsDir(zs.Clone(), ZipTest.zfolder(zipFolder), ZipArchiveMode.Read, false, false);
}
[Theory]
[InlineData(ZipArchiveMode.Create)]
[InlineData(ZipArchiveMode.Update)]
public static void EmptyEntryTest(ZipArchiveMode mode)
{
String data1 = "test data written to file.";
String data2 = "more test data written to file.";
DateTimeOffset lastWrite = new DateTimeOffset(1992, 4, 5, 12, 00, 30, new TimeSpan(-5, 0, 0));
var baseline = new LocalMemoryStream();
using (ZipArchive archive = new ZipArchive(baseline, mode))
{
ZipTest.AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
using (Stream s = e.Open()) { }
ZipTest.AddEntry(archive, "data2.txt", data2, lastWrite);
}
var test = new LocalMemoryStream();
using (ZipArchive archive = new ZipArchive(test, mode))
{
ZipTest.AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
ZipTest.AddEntry(archive, "data2.txt", data2, lastWrite);
}
//compare
Assert.True(ZipTest.ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match");
//second test, this time empty file at end
baseline = baseline.Clone();
using (ZipArchive archive = new ZipArchive(baseline, mode))
{
ZipTest.AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
using (Stream s = e.Open()) { }
}
test = test.Clone();
using (ZipArchive archive = new ZipArchive(test, mode))
{
ZipTest.AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
}
//compare
Assert.True(ZipTest.ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match after update");
}
[Fact]
public static async Task DeleteAndMoveEntries()
{
//delete and move
var testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
ZipArchiveEntry toBeDeleted = archive.GetEntry("binary.wmv");
toBeDeleted.Delete();
toBeDeleted.Delete(); //delete twice should be okay
ZipArchiveEntry moved = archive.CreateEntry("notempty/secondnewname.txt");
ZipArchiveEntry orig = archive.GetEntry("notempty/second.txt");
using (Stream origMoved = orig.Open(), movedStream = moved.Open())
{
origMoved.CopyTo(movedStream);
}
moved.LastWriteTime = orig.LastWriteTime;
orig.Delete();
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("deleteMove"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task AppendToEntry()
{
//append
Stream testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
ZipArchiveEntry e = archive.GetEntry("first.txt");
using (StreamWriter s = new StreamWriter(e.Open()))
{
s.BaseStream.Seek(0, SeekOrigin.End);
s.Write("\r\n\r\nThe answer my friend, is blowin' in the wind.");
}
var file = FileData.GetFile(ZipTest.zmodified(Path.Combine("append", "first.txt")));
e.LastWriteTime = file.LastModifiedDate;
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("append"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task OverwriteEntry()
{
//Overwrite file
Stream testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
String fileName = ZipTest.zmodified(Path.Combine("overwrite", "first.txt"));
ZipArchiveEntry e = archive.GetEntry("first.txt");
var file = FileData.GetFile(fileName);
e.LastWriteTime = file.LastModifiedDate;
using (var stream = await StreamHelpers.CreateTempCopyStream(fileName))
{
using (Stream es = e.Open())
{
es.SetLength(0);
stream.CopyTo(es);
}
}
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("overwrite"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task AddFileToArchive()
{
//add file
var testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified ("addFile"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task AddFileToArchive_AfterReading()
{
//add file and read entries before
Stream testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
var x = archive.Entries;
await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("addFile"), ZipArchiveMode.Read, false, false);
}
[Fact]
public static async Task AddFileToArchive_ThenReadEntries()
{
//add file and read entries after
Stream testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
var x = archive.Entries;
}
ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("addFile"), ZipArchiveMode.Read, false, false);
}
private static async Task updateArchive(ZipArchive archive, String installFile, String entryName)
{
ZipArchiveEntry e = archive.CreateEntry(entryName);
var file = FileData.GetFile(installFile);
e.LastWriteTime = file.LastModifiedDate;
Assert.Equal(e.LastWriteTime, file.LastModifiedDate);
using (var stream = await StreamHelpers.CreateTempCopyStream(installFile))
{
using (Stream es = e.Open())
{
es.SetLength(0);
stream.CopyTo(es);
}
}
}
[Fact]
public static async Task UpdateModeInvalidOperations()
{
using (LocalMemoryStream ms = await LocalMemoryStream.readAppFileAsync(ZipTest.zfile("normal.zip")))
{
ZipArchive target = new ZipArchive(ms, ZipArchiveMode.Update, true);
ZipArchiveEntry edeleted = target.GetEntry("first.txt");
Stream s = edeleted.Open();
//invalid ops while entry open
Assert.Throws<IOException>(() => edeleted.Open());
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; });
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; });
Assert.Throws<IOException>(() => edeleted.Delete());
s.Dispose();
//invalid ops on stream after entry closed
Assert.Throws<ObjectDisposedException>(() => s.ReadByte());
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; });
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; });
edeleted.Delete();
//invalid ops while entry deleted
Assert.Throws<InvalidOperationException>(() => edeleted.Open());
Assert.Throws<InvalidOperationException>(() => { edeleted.LastWriteTime = new DateTimeOffset(); });
ZipArchiveEntry e = target.GetEntry("notempty/second.txt");
target.Dispose();
Assert.Throws<ObjectDisposedException>(() => { var x = target.Entries; });
Assert.Throws<ObjectDisposedException>(() => target.CreateEntry("dirka"));
Assert.Throws<ObjectDisposedException>(() => e.Open());
Assert.Throws<ObjectDisposedException>(() => e.Delete());
Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); });
}
}
}
}
| |
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 openCaseApi.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) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Layouts
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using NLog.Config;
/// <summary>
/// A specialized layout that renders JSON-formatted events.
/// </summary>
[Layout("JsonLayout")]
[ThreadAgnostic]
[ThreadSafe]
public class JsonLayout : Layout
{
private LimitRecursionJsonConvert JsonConverter
{
get => _jsonConverter ?? (_jsonConverter = new LimitRecursionJsonConvert(MaxRecursionLimit, ConfigurationItemFactory.Default.JsonConverter));
set => _jsonConverter = value;
}
private LimitRecursionJsonConvert _jsonConverter;
private IValueFormatter ValueFormatter
{
get => _valueFormatter ?? (_valueFormatter = ConfigurationItemFactory.Default.ValueFormatter);
set => _valueFormatter = value;
}
private IValueFormatter _valueFormatter;
class LimitRecursionJsonConvert : IJsonConverter
{
readonly IJsonConverter _converter;
readonly Targets.DefaultJsonSerializer _serializer;
readonly Targets.JsonSerializeOptions _serializerOptions;
public LimitRecursionJsonConvert(int maxRecursionLimit, IJsonConverter converter)
{
_converter = converter;
_serializer = converter as Targets.DefaultJsonSerializer;
_serializerOptions = new Targets.JsonSerializeOptions() { MaxRecursionLimit = Math.Max(0, maxRecursionLimit) };
}
public bool SerializeObject(object value, StringBuilder builder)
{
if (_serializer != null)
return _serializer.SerializeObject(value, builder, _serializerOptions);
else
return _converter.SerializeObject(value, builder);
}
public bool SerializeObjectNoLimit(object value, StringBuilder builder)
{
return _converter.SerializeObject(value, builder);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonLayout"/> class.
/// </summary>
public JsonLayout()
{
Attributes = new List<JsonAttribute>();
RenderEmptyObject = true;
IncludeAllProperties = false;
ExcludeProperties = new HashSet<string>();
MaxRecursionLimit = 0; // Will enumerate simple collections but not object properties. TODO NLog 5.0 change to 1 (or higher)
}
/// <summary>
/// Gets the array of attributes' configurations.
/// </summary>
/// <docgen category='JSON Output' order='10' />
[ArrayParameter(typeof(JsonAttribute), "attribute")]
public IList<JsonAttribute> Attributes { get; private set; }
/// <summary>
/// Gets or sets the option to suppress the extra spaces in the output json
/// </summary>
/// <docgen category='JSON Formating' order='10' />
[DefaultValue(false)]
public bool SuppressSpaces { get; set; }
/// <summary>
/// Gets or sets the option to render the empty object value {}
/// </summary>
/// <docgen category='JSON Formating' order='10' />
[DefaultValue(true)]
public bool RenderEmptyObject { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="GlobalDiagnosticsContext"/> dictionary.
/// </summary>
/// <docgen category='JSON Output' order='10' />
[DefaultValue(false)]
public bool IncludeGdc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary.
/// </summary>
/// <docgen category='JSON Output' order='10' />
[DefaultValue(false)]
public bool IncludeMdc { get; set; }
#if !SILVERLIGHT
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary.
/// </summary>
/// <docgen category='JSON Output' order='10' />
[DefaultValue(false)]
public bool IncludeMdlc { get; set; }
#endif
/// <summary>
/// Gets or sets the option to include all properties from the log event (as JSON)
/// </summary>
/// <docgen category='JSON Output' order='10' />
[DefaultValue(false)]
public bool IncludeAllProperties { get; set; }
/// <summary>
/// Gets or sets the option to exclude null/empty properties from the log event (as JSON)
/// </summary>
/// <docgen category='JSON Output' order='10' />
[DefaultValue(false)]
public bool ExcludeEmptyProperties { get; set; }
/// <summary>
/// List of property names to exclude when <see cref="IncludeAllProperties"/> is true
/// </summary>
/// <docgen category='JSON Output' order='10' />
#if NET3_5
public HashSet<string> ExcludeProperties { get; set; }
#else
public ISet<string> ExcludeProperties { get; set; }
#endif
/// <summary>
/// How far should the JSON serializer follow object references before backing off
/// </summary>
/// <docgen category='JSON Output' order='10' />
[DefaultValue(0)]
public int MaxRecursionLimit { get; set; }
/// <summary>
/// Should forward slashes be escaped? If true, / will be converted to \/
/// </summary>
/// <remarks>
/// If not set explicitly then the value of the parent will be used as default.
/// </remarks>
/// <docgen category='JSON Formating' order='10' />
[DefaultValue(true)] // TODO NLog 5 change to nullable (with default fallback to false)
public bool EscapeForwardSlash
{
get => _escapeForwardSlashInternal ?? true;
set => _escapeForwardSlashInternal = value;
}
private bool? _escapeForwardSlashInternal;
/// <summary>
/// Initializes the layout.
/// </summary>
protected override void InitializeLayout()
{
base.InitializeLayout();
if (IncludeMdc)
{
ThreadAgnostic = false;
}
#if !SILVERLIGHT
if (IncludeMdlc)
{
ThreadAgnostic = false;
}
#endif
if (IncludeAllProperties)
{
MutableUnsafe = true;
}
if (_escapeForwardSlashInternal.HasValue && Attributes?.Count > 0)
{
foreach (var attribute in Attributes)
{
if (!attribute.LayoutWrapper.EscapeForwardSlashInternal.HasValue)
{
attribute.LayoutWrapper.EscapeForwardSlashInternal = _escapeForwardSlashInternal.Value;
}
}
}
}
/// <summary>
/// Closes the layout.
/// </summary>
protected override void CloseLayout()
{
JsonConverter = null;
ValueFormatter = null;
base.CloseLayout();
}
internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target)
{
PrecalculateBuilderInternal(logEvent, target);
}
/// <summary>
/// Formats the log event as a JSON document for writing.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="target"><see cref="StringBuilder"/> for the result</param>
protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
int orgLength = target.Length;
RenderJsonFormattedMessage(logEvent, target);
if (target.Length == orgLength && RenderEmptyObject)
{
target.Append(SuppressSpaces ? "{}" : "{ }");
}
}
/// <summary>
/// Formats the log event as a JSON document for writing.
/// </summary>
/// <param name="logEvent">The log event to be formatted.</param>
/// <returns>A JSON string representation of the log event.</returns>
protected override string GetFormattedMessage(LogEventInfo logEvent)
{
return RenderAllocateBuilder(logEvent);
}
private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb)
{
int orgLength = sb.Length;
//Memory profiling pointed out that using a foreach-loop was allocating
//an Enumerator. Switching to a for-loop avoids the memory allocation.
for (int i = 0; i < Attributes.Count; i++)
{
var attrib = Attributes[i];
int beforeAttribLength = sb.Length;
if (!RenderAppendJsonPropertyValue(attrib, logEvent, sb, sb.Length == orgLength))
{
sb.Length = beforeAttribLength;
}
}
if(IncludeGdc)
{
foreach (string key in GlobalDiagnosticsContext.GetNames())
{
if (string.IsNullOrEmpty(key))
continue;
object propertyValue = GlobalDiagnosticsContext.GetObject(key);
AppendJsonPropertyValue(key, propertyValue, null, null, MessageTemplates.CaptureType.Unknown, sb, sb.Length == orgLength);
}
}
if (IncludeMdc)
{
foreach (string key in MappedDiagnosticsContext.GetNames())
{
if (string.IsNullOrEmpty(key))
continue;
object propertyValue = MappedDiagnosticsContext.GetObject(key);
AppendJsonPropertyValue(key, propertyValue, null, null, MessageTemplates.CaptureType.Unknown, sb, sb.Length == orgLength);
}
}
#if !SILVERLIGHT
if (IncludeMdlc)
{
foreach (string key in MappedDiagnosticsLogicalContext.GetNames())
{
if (string.IsNullOrEmpty(key))
continue;
object propertyValue = MappedDiagnosticsLogicalContext.GetObject(key);
AppendJsonPropertyValue(key, propertyValue, null, null, MessageTemplates.CaptureType.Unknown, sb, sb.Length == orgLength);
}
}
#endif
if (IncludeAllProperties && logEvent.HasProperties)
{
IEnumerable<MessageTemplates.MessageTemplateParameter> propertiesList = logEvent.CreateOrUpdatePropertiesInternal(true);
foreach (var prop in propertiesList)
{
if (string.IsNullOrEmpty(prop.Name))
continue;
if (ExcludeProperties.Contains(prop.Name))
continue;
AppendJsonPropertyValue(prop.Name, prop.Value, prop.Format, logEvent.FormatProvider, prop.CaptureType, sb, sb.Length == orgLength);
}
}
if (sb.Length > orgLength)
CompleteJsonMessage(sb);
}
private void BeginJsonProperty(StringBuilder sb, string propName, bool beginJsonMessage, bool ensureStringEscape)
{
if (beginJsonMessage)
{
sb.Append(SuppressSpaces ? "{\"" : "{ \"");
}
else
{
sb.Append(SuppressSpaces ? ",\"" : ", \"");
}
if (ensureStringEscape)
Targets.DefaultJsonSerializer.AppendStringEscape(sb, propName, false, false);
else
sb.Append(propName);
sb.Append(SuppressSpaces ? "\":" : "\": ");
}
private void CompleteJsonMessage(StringBuilder sb)
{
sb.Append(SuppressSpaces ? "}" : " }");
}
private void AppendJsonPropertyValue(string propName, object propertyValue, string format, IFormatProvider formatProvider, MessageTemplates.CaptureType captureType, StringBuilder sb, bool beginJsonMessage)
{
if (ExcludeEmptyProperties && propertyValue == null)
return;
var initialLength = sb.Length;
BeginJsonProperty(sb, propName, beginJsonMessage, true);
if (MaxRecursionLimit <= 1 && captureType == MessageTemplates.CaptureType.Serialize)
{
// Overrides MaxRecursionLimit as message-template tells us it is safe
if (!JsonConverter.SerializeObjectNoLimit(propertyValue, sb))
{
sb.Length = initialLength;
return;
}
}
else if (captureType == MessageTemplates.CaptureType.Stringify)
{
// Overrides MaxRecursionLimit as message-template tells us it is unsafe
int originalStart = sb.Length;
ValueFormatter.FormatValue(propertyValue, format, captureType, formatProvider, sb);
PerformJsonEscapeIfNeeded(sb, originalStart, EscapeForwardSlash);
}
else
{
if (!JsonConverter.SerializeObject(propertyValue, sb))
{
sb.Length = initialLength;
return;
}
}
if (ExcludeEmptyProperties && (sb[sb.Length-1] == '"' && sb[sb.Length-2] == '"'))
{
sb.Length = initialLength;
}
}
private static void PerformJsonEscapeIfNeeded(StringBuilder sb, int valueStart, bool escapeForwardSlash)
{
if (sb.Length - valueStart <= 2)
return;
for (int i = valueStart + 1; i < sb.Length - 1; ++i)
{
if (Targets.DefaultJsonSerializer.RequiresJsonEscape(sb[i], false, escapeForwardSlash))
{
var jsonEscape = sb.ToString(valueStart + 1, sb.Length - valueStart - 2);
sb.Length = valueStart;
sb.Append('"');
Targets.DefaultJsonSerializer.AppendStringEscape(sb, jsonEscape, false, escapeForwardSlash);
sb.Append('"');
break;
}
}
}
private bool RenderAppendJsonPropertyValue(JsonAttribute attrib, LogEventInfo logEvent, StringBuilder sb, bool beginJsonMessage)
{
BeginJsonProperty(sb, attrib.Name, beginJsonMessage, false);
if (attrib.Encode)
{
// "\"{0}\":{1}\"{2}\""
sb.Append('"');
}
int beforeValueLength = sb.Length;
attrib.LayoutWrapper.RenderAppendBuilder(logEvent, sb);
if (!attrib.IncludeEmptyValue && beforeValueLength == sb.Length)
{
return false;
}
if (attrib.Encode)
{
sb.Append('"');
}
return true;
}
/// <summary>
/// Generate description of JSON Layout
/// </summary>
/// <returns>JSON Layout String Description</returns>
public override string ToString()
{
return ToStringWithNestedItems(Attributes, a => string.Concat(a.Name, "-", a.Layout?.ToString()));
}
}
}
| |
using LambdicSql.ConverterServices;
using LambdicSql.ConverterServices.SymbolConverters;
using System;
namespace LambdicSql.SqlServer
{
public static partial class Symbol
{
/// <summary>
/// CURRENT_TIMESTAMP function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/current-timestamp-transact-sql</para>
/// </summary>
/// <returns>current database system timestamp as a datetime value without the database time zone offset.</returns>
[ClauseStyleConverter]
public static DateTime Current_TimeStamp() { throw new InvalitContextException(nameof(Current_TimeStamp)); }
/// <summary>
/// DATEADD function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="number">added to datepart of date.</param>
/// <param name="date">The date data.</param>
/// <returns>number added to a specified datepart of that date.</returns>
[FuncStyleConverter]
public static DateTime DateAdd(DateAddElement datepart, int number, DateTime date) { throw new InvalitContextException(nameof(DateAdd)); }
/// <summary>
/// DATEADD function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="number">added to datepart of date.</param>
/// <param name="date">The date data.</param>
/// <returns>number added to a specified datepart of that date.</returns>
[FuncStyleConverter]
public static DateTime DateAdd(DateAddElement datepart, int number, DateTimeOffset date) { throw new InvalitContextException(nameof(DateAdd)); }
/// <summary>
/// DATEDIFF function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="startdate">start date.</param>
/// <param name="enddate">end date.</param>
/// <returns>Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate. </returns>
[FuncStyleConverter]
public static int DateDiff(DateDiffElement datepart, DateTime startdate, DateTime enddate) { throw new InvalitContextException(nameof(DateDiff)); }
/// <summary>
/// DATEDIFF function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="startdate">start date.</param>
/// <param name="enddate">end date.</param>
/// <returns>Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate. </returns>
[FuncStyleConverter]
public static int DateDiff(DateDiffElement datepart, DateTime startdate, DateTimeOffset enddate) { throw new InvalitContextException(nameof(DateDiff)); }
/// <summary>
/// DATEDIFF function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="startdate">start date.</param>
/// <param name="enddate">end date.</param>
/// <returns>Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate. </returns>
[FuncStyleConverter]
public static int DateDiff(DateDiffElement datepart, DateTimeOffset startdate, DateTime enddate) { throw new InvalitContextException(nameof(DateDiff)); }
/// <summary>
/// DATEDIFF function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="startdate">start date.</param>
/// <param name="enddate">end date.</param>
/// <returns>Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate. </returns>
[FuncStyleConverter]
public static int DateDiff(DateDiffElement datepart, DateTimeOffset startdate, DateTimeOffset enddate) { throw new InvalitContextException(nameof(DateDiff)); }
/// <summary>
/// DATEDIFF_BIG function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-big-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="startdate">start date.</param>
/// <param name="enddate">end date.</param>
/// <returns>Returns count (signed bigint) of the specified datepart boundaries crossed between the specified startdate and enddate.</returns>
[FuncStyleConverter]
public static long DateDiff_Big(DateDiffElement datepart, DateTime startdate, DateTime enddate) { throw new InvalitContextException(nameof(DateDiff)); }
/// <summary>
/// DATEDIFF_BIG function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-big-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="startdate">start date.</param>
/// <param name="enddate">end date.</param>
/// <returns>Returns count (signed bigint) of the specified datepart boundaries crossed between the specified startdate and enddate.</returns>
[FuncStyleConverter]
public static long DateDiff_Big(DateDiffElement datepart, DateTime startdate, DateTimeOffset enddate) { throw new InvalitContextException(nameof(DateDiff)); }
/// <summary>
/// DATEDIFF_BIG function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-big-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="startdate">start date.</param>
/// <param name="enddate">end date.</param>
/// <returns>Returns count (signed bigint) of the specified datepart boundaries crossed between the specified startdate and enddate.</returns>
[FuncStyleConverter]
public static long DateDiff_Big(DateDiffElement datepart, DateTimeOffset startdate, DateTime enddate) { throw new InvalitContextException(nameof(DateDiff)); }
/// <summary>
/// DATEDIFF_BIG function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-big-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="startdate">start date.</param>
/// <param name="enddate">end date.</param>
/// <returns>Returns count (signed bigint) of the specified datepart boundaries crossed between the specified startdate and enddate.</returns>
[FuncStyleConverter]
public static long DateDiff_Big(DateDiffElement datepart, DateTimeOffset startdate, DateTimeOffset enddate) { throw new InvalitContextException(nameof(DateDiff)); }
/// <summary>
/// DATEFROMPARTS functions.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datefromparts-transact-sql</para>
/// </summary>
/// <param name="year">specifying a year.</param>
/// <param name="month">specifying a month from 1 to 12.</param>
/// <param name="day">specifying a day.</param>
/// <returns>Returns a date value for the specified year, month, and day.</returns>
[FuncStyleConverter]
public static DateTime DateFromParts(int year, int month, int day) { throw new InvalitContextException(nameof(DateFromParts)); }
/// <summary>
/// DATENAME functions.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datename-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="date">The date data.</param>
/// <returns>Returns a character string that represents the specified datepart of the specified date</returns>
[FuncStyleConverter]
public static string DateName(DateNameElement datepart, DateTime date) { throw new InvalitContextException(nameof(DateName)); }
/// <summary>
/// DATENAME functions.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datename-transact-sql</para>
/// </summary>
/// <param name="datepart">Part type.</param>
/// <param name="date">The date data.</param>
/// <returns>Returns a character string that represents the specified datepart of the specified date</returns>
[FuncStyleConverter]
public static string DateName(DateNameElement datepart, DateTimeOffset date) { throw new InvalitContextException(nameof(DateName)); }
/// <summary>
/// DATEPART function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql</para>
/// </summary>
/// <param name="element">Part type.</param>
/// <param name="src">The date data.</param>
/// <returns>A part from the date data.</returns>
[FuncStyleConverter]
public static int DatePart(DatePartElement element, DateTime src) { throw new InvalitContextException(nameof(DatePart)); }
/// <summary>
/// DATEPART function.
/// </summary>
/// <param name="element">Part type.</param>
/// <param name="src">The date data.</param>
/// <returns>A part from the date data.</returns>
[FuncStyleConverter]
public static int DatePart(DatePartElement element, DateTimeOffset src) { throw new InvalitContextException(nameof(DatePart)); }
/// <summary>
/// DATETIME2FROMPARTS functions.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datetime2fromparts-transact-sql</para>
/// </summary>
/// <param name="year">specifying a year.</param>
/// <param name="month">specifying a month from 1 to 12.</param>
/// <param name="day">specifying a day.</param>
/// <param name="hour">specifying a hours.</param>
/// <param name="minute">specifying a minutes.</param>
/// <param name="seconds">specifying a seconds.</param>
/// <param name="fractions">specifying a fractions.</param>
/// <param name="precision">specifying a precision of the datetime2 value to be returned.</param>
/// <returns>Returns a date value for the specified year, month, and day.</returns>
[MethodFormatConverter(Format = "DATETIME2FROMPARTS([0], [1], [2], [3], [4], [5], [6], [$7])")]
public static DateTime DateTime2FromParts(int year, int month, int day, int hour, int minute, int seconds, int fractions, int precision) { throw new InvalitContextException(nameof(DateTime2FromParts)); }
/// <summary>
/// DATETIMEFROMPARTS functions.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datetimefromparts-transact-sql</para>
/// </summary>
/// <param name="year">specifying a year.</param>
/// <param name="month">specifying a month from 1 to 12.</param>
/// <param name="day">specifying a day.</param>
/// <param name="hour">specifying a hours.</param>
/// <param name="minute">specifying a minutes.</param>
/// <param name="seconds">specifying a seconds.</param>
/// <param name="milliseconds">specifying milliseconds.</param>
/// <returns>Returns a date value for the specified year, month, and day.</returns>
[FuncStyleConverter]
public static DateTime DateTimeFromParts(int year, int month, int day, int hour, int minute, int seconds, int milliseconds) { throw new InvalitContextException(nameof(DateTimeFromParts)); }
/// <summary>
/// DATETIMEOFFSETFROMPARTS functions.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/datetimeoffsetfromparts-transact-sql</para>
/// </summary>
/// <param name="year">specifying a year.</param>
/// <param name="month">specifying a month from 1 to 12.</param>
/// <param name="day">specifying a day.</param>
/// <param name="hour">specifying a hours.</param>
/// <param name="minute">specifying a minutes.</param>
/// <param name="seconds">specifying a seconds.</param>
/// <param name="fractions">specifying a fractions.</param>
/// <param name="hour_offset">specifying the hour portion of the time zone offset.</param>
/// <param name="minute_offset">specifying the minute portion of the time zone offset.</param>
/// <param name="precision">specifying a precision of the datetimeoffset value to be returned.</param>
/// <returns>Returns a date value for the specified year, month, and day.</returns>
[MethodFormatConverter(Format = "DATETIMEOFFSETFROMPARTS([0], [1], [2], [3], [4], [5], [6], [7], [8], [$9])")]
public static DateTimeOffset DateTimeOffsetFromParts(int year, int month, int day, int hour, int minute, int seconds, int fractions, int hour_offset, int minute_offset, int precision) { throw new InvalitContextException(nameof(DateTimeOffsetFromParts)); }
/// <summary>
/// DAY function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/day-transact-sql</para>
/// </summary>
/// <param name="src">The date data.</param>
/// <returns>an integer representing the day (day of the month) of the specified date.</returns>
[FuncStyleConverter]
public static int Day(DateTime src) { throw new InvalitContextException(nameof(Day)); }
/// <summary>
/// DAY function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/day-transact-sql</para>
/// </summary>
/// <param name="src">The date data.</param>
/// <returns>an integer representing the day (day of the month) of the specified date.</returns>
[FuncStyleConverter]
public static int Day(DateTimeOffset src) { throw new InvalitContextException(nameof(Day)); }
/// <summary>
/// EOMONTH function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql</para>
/// </summary>
/// <param name="start_date">Date expression specifying the date for which to return the last day of the month.</param>
/// <returns>the last day of the month that contains the specified date, with an optional offset.</returns>
[FuncStyleConverter]
public static DateTime EOMonth(DateTime start_date) { throw new InvalitContextException(nameof(EOMonth)); }
/// <summary>
/// EOMONTH function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql</para>
/// </summary>
/// <param name="start_date">Date expression specifying the date for which to return the last day of the month.</param>
/// <param name="month_to_add">Optional integer expression specifying the number of months to add to start_date.</param>
/// <returns>the last day of the month that contains the specified date, with an optional offset.</returns>
[FuncStyleConverter]
public static DateTime EOMonth(DateTime start_date, int month_to_add) { throw new InvalitContextException(nameof(EOMonth)); }
/// <summary>
/// EOMONTH function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql</para>
/// </summary>
/// <param name="start_date">Date expression specifying the date for which to return the last day of the month.</param>
/// <returns>the last day of the month that contains the specified date, with an optional offset.</returns>
[FuncStyleConverter]
public static DateTime EOMonth(DateTimeOffset start_date) { throw new InvalitContextException(nameof(EOMonth)); }
/// <summary>
/// EOMONTH function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql</para>
/// </summary>
/// <param name="start_date">Date expression specifying the date for which to return the last day of the month.</param>
/// <param name="month_to_add">Optional integer expression specifying the number of months to add to start_date.</param>
/// <returns>the last day of the month that contains the specified date, with an optional offset.</returns>
[FuncStyleConverter]
public static DateTime EOMonth(DateTimeOffset start_date, int month_to_add) { throw new InvalitContextException(nameof(EOMonth)); }
/// <summary>
/// GETDATE function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql
/// </summary>
/// <returns>the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.</returns>
[FuncStyleConverter]
public static DateTime GetDate() { throw new InvalitContextException(nameof(GetDate)); }
/// <summary>
/// GETUTCDATE function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/getutcdate-transact-sql
/// </summary>
/// <returns>the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.</returns>
[FuncStyleConverter]
public static DateTime GetUtcDate() { throw new InvalitContextException(nameof(GetUtcDate)); }
/// <summary>
/// ISDATE function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/isdate-transact-sql
/// </summary>
/// <param name="expression">Is a character string or expression that can be converted to a character string. The expression must be less than 4,000 characters. Date and time data types, except datetime and smalldatetime, are not allowed as the argument for ISDATE.</param>
/// <returns>1 if the expression is a valid date, time, or datetime value; otherwise, 0.</returns>
[FuncStyleConverter]
public static int IsDate(object expression) { throw new InvalitContextException(nameof(IsDate)); }
/// <summary>
/// MONTH function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/month-transact-sql</para>
/// </summary>
/// <param name="src">The date data.</param>
/// <returns>an integer representing the month of the specified date.</returns>
[FuncStyleConverter]
public static int Month(DateTime src) { throw new InvalitContextException(nameof(Month)); }
/// <summary>
/// MONTH function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/month-transact-sql</para>
/// </summary>
/// <param name="src">The date data.</param>
/// <returns>an integer representing the month of the specified date.</returns>
[FuncStyleConverter]
public static int Month(DateTimeOffset src) { throw new InvalitContextException(nameof(Month)); }
/// <summary>
/// SMALLDATETIMEFROMPARTS functions.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/smalldatetimefromparts-transact-sql</para>
/// </summary>
/// <param name="year">specifying a year.</param>
/// <param name="month">specifying a month from 1 to 12.</param>
/// <param name="day">specifying a day.</param>
/// <param name="hour">specifying a hours.</param>
/// <param name="minute">specifying a minutes.</param>
/// <returns>a smalldatetime value for the specified date and time.</returns>
[FuncStyleConverter]
public static DateTime SmallDateTimeFromParts(int year, int month, int day, int hour, int minute) { throw new InvalitContextException(nameof(SmallDateTimeFromParts)); }
/// <summary>
/// SWITCHOFFSET function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/switchoffset-transact-sql</para>
/// </summary>
/// <param name="datetimeoffset">Is an expression that can be resolved to a datetimeoffset(n) value.</param>
/// <param name="time_zone">Is a character string in the format [+|-]TZH:TZM or a signed integer (of minutes) that represents the time zone offset, and is assumed to be daylight-saving aware and adjusted.</param>
/// <returns>a datetimeoffset value that is changed from the stored time zone offset to a specified new time zone offset.</returns>
[FuncStyleConverter]
public static DateTimeOffset SwitchOffset(DateTimeOffset datetimeoffset, string time_zone) { throw new InvalitContextException(nameof(SwitchOffset)); }
/// <summary>
/// SYSDATETIME function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sysdatetime-transact-sql
/// </summary>
/// <returns>datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running.</returns>
[FuncStyleConverter]
public static DateTime SysDateTime() { throw new InvalitContextException(nameof(SysDateTime)); }
/// <summary>
/// SYSDATETIMEOFFSET function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sysdatetimeoffset-transact-sql
/// </summary>
/// <returns>datetimeoffset(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The time zone offset is included. </returns>
[FuncStyleConverter]
public static DateTimeOffset SysDateTimeOffset() { throw new InvalitContextException(nameof(SysDateTimeOffset)); }
/// <summary>
/// SYSUTCDATETIME function.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sysutcdatetime-transact-sql
/// </summary>
/// <returns> datetime2 value that contains the date and time of the computer on which the instance of SQL Server is running. The date and time is returned as UTC time (Coordinated Universal Time). The fractional second precision specification has a range from 1 to 7 digits. The default precision is 7 digits. </returns>
[FuncStyleConverter]
public static DateTime SysUtcDateTime() { throw new InvalitContextException(nameof(SysUtcDateTime)); }
/// <summary>
/// TIMEFROMPARTS functions.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/timefromparts-transact-sql</para>
/// </summary>
/// <param name="hour">specifying a hours.</param>
/// <param name="minute">specifying a minutes.</param>
/// <param name="seconds">specifying a seconds.</param>
/// <param name="fractions">specifying a fractions.</param>
/// <param name="precision">specifying a precision of the datetime2 value to be returned.</param>
/// <returns>Returns a date value for the specified year, month, and day.</returns>
[MethodFormatConverter(Format = "TIMEFROMPARTS([0], [1], [2], [3], [$4])")]
public static TimeSpan TimeFromParts(int hour, int minute, int seconds, int fractions, int precision) { throw new InvalitContextException(nameof(TimeFromParts)); }
/// <summary>
/// TODATETIMEOFFSET function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/todatetimeoffset-transact-sql</para>
/// </summary>
/// <param name="expression">Is an expression that resolves to a datetime2 value. </param>
/// <param name="time_zone">Is a character string in the format [+|-]TZH:TZM or a signed integer (of minutes) that represents the time zone offset, and is assumed to be daylight-saving aware and adjusted.</param>
/// <returns>a datetimeoffset value that is translated from a datetime2 expression.</returns>
[FuncStyleConverter]
public static DateTimeOffset ToDateTimeOffset(DateTime expression, string time_zone) { throw new InvalitContextException(nameof(ToDateTimeOffset)); }
/// <summary>
/// YEAR function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/year-transact-sql</para>
/// </summary>
/// <param name="src">The date data.</param>
/// <returns>an integer representing the year of the specified date.</returns>
[FuncStyleConverter]
public static int Year(DateTime src) { throw new InvalitContextException(nameof(Year)); }
/// <summary>
/// YEAR function.
/// <para>https://docs.microsoft.com/en-us/sql/t-sql/functions/year-transact-sql</para>
/// </summary>
/// <param name="src">The date data.</param>
/// <returns>an integer representing the year of the specified date.</returns>
[FuncStyleConverter]
public static int Year(DateTimeOffset src) { throw new InvalitContextException(nameof(Year)); }
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace LTreesLibrary.Trees
{
/// <summary>
/// Renders a tree mesh and corresponding leaves. Contains a tree skeleton and the corresponding
/// tree mesh, leaf cloud, animation state, effects, and textures.
/// </summary>
/// <remarks>
/// Because effects should be loaded by the content manager, they must be set manually before the
/// can be rendered.
///
/// This is a good place to get started, but to gain more flexibility and performance, you will
/// eventually need to use the TreeMesh, TreeLeafCloud, TreeAnimationState and TreeSkeleton classes directly.
/// In a serious application, it is recommended that you write your own application-specific substitute for this class.
/// </remarks>
public class SimpleTree
{
private GraphicsDevice device;
private TreeSkeleton skeleton;
private TreeMesh trunk;
private TreeLeafCloud leaves;
private TreeAnimationState animationState;
private Effect trunkEffect;
private Effect leafEffect;
private Texture2D trunkTexture;
private Texture2D leafTexture;
private Matrix[] bindingMatrices;
private BasicEffect boneEffect;
public GraphicsDevice GraphicsDevice
{
get { return device; }
}
/// <summary>
/// The tree structure displayed.
/// Setting this will reset the current animation state and result in new meshes being generated.
/// </summary>
public TreeSkeleton Skeleton
{
get { return skeleton; }
set { skeleton = value; UpdateSkeleton(); }
}
public TreeMesh TrunkMesh
{
get { return trunk; }
}
public TreeLeafCloud LeafCloud
{
get { return leaves; }
}
/// <summary>
/// The current position of all the bones.
/// Setting this to a new animation state has no performance hit.
/// </summary>
public TreeAnimationState AnimationState
{
get { return animationState; }
set { animationState = value; }
}
/// <summary>
/// Effect used to draw the trunk.
/// </summary>
public Effect TrunkEffect
{
get { return trunkEffect; }
set { trunkEffect = value; }
}
/// <summary>
/// Effect used to draw the leaves.
/// </summary>
public Effect LeafEffect
{
get { return leafEffect; }
set { leafEffect = value; }
}
/// <summary>
/// Texture on the trunk.
/// </summary>
public Texture2D TrunkTexture
{
get { return trunkTexture; }
set { trunkTexture = value; }
}
/// <summary>
/// Leaves on the trunk.
/// </summary>
public Texture2D LeafTexture
{
get { return leafTexture; }
set { leafTexture = value; }
}
private void UpdateSkeleton()
{
this.trunk = new TreeMesh(device, skeleton);
this.leaves = new TreeLeafCloud(device, skeleton);
this.animationState = new TreeAnimationState(skeleton);
this.bindingMatrices = new Matrix[skeleton.Bones.Count];
}
public SimpleTree(GraphicsDevice device)
{
this.device = device;
this.boneEffect = new BasicEffect(device);
}
public SimpleTree(GraphicsDevice device, TreeSkeleton skeleton)
{
this.device = device;
this.skeleton = skeleton;
this.boneEffect = new BasicEffect(device);
UpdateSkeleton();
}
/// <summary>
/// Draws the trunk using the specified world, view, and projection matrices.
/// </summary>
/// <param name="world">World matrix.</param>
/// <param name="view">View matrix.</param>
/// <param name="projection">Projection matrix.</param>
/// <exception cref="InvalidOperationException">If no trunk effect is set.</exception>
/// <exception cref="InvalidOperationException">If no skeleton is set.</exception>
/// <remarks>
/// This method sets all the appropriate effect parameters.
/// </remarks>
public void DrawTrunk(Matrix world, Matrix view, Matrix projection)
{
if (skeleton == null)
throw new InvalidOperationException("A skeleton must be set before trunk can be rendered.");
if (trunkEffect == null)
throw new InvalidOperationException("TrunkEffect must be set before trunk can be rendered.");
trunkEffect.Parameters["World"].SetValue(world);
trunkEffect.Parameters["View"].SetValue(view);
trunkEffect.Parameters["Projection"].SetValue(projection);
skeleton.CopyBoneBindingMatricesTo(bindingMatrices, animationState.BoneRotations);
trunkEffect.Parameters["Bones"].SetValue(bindingMatrices);
trunkEffect.Parameters["Texture"].SetValue(trunkTexture);
trunk.Draw(trunkEffect);
}
/// <summary>
/// Draws the leaves using the specified world, view, and projection matrices.
/// </summary>
/// <param name="world">World matrix.</param>
/// <param name="view">View matrix.</param>
/// <param name="projection">Projection matrix.</param>
/// <exception cref="InvalidOperationException">If no leaf effect is set.</exception>
/// <exception cref="InvalidOperationException">If no skeleton is set.</exception>
/// <remarks>
/// This method sets all the appropriate effect parameters.
/// </remarks>
public void DrawLeaves(Matrix world, Matrix view, Matrix projection)
{
if (skeleton == null)
throw new InvalidOperationException("A skeleton must be set before leaves can be rendered.");
if (leafEffect == null)
throw new InvalidOperationException("LeafEffect must be set before leaves can be rendered.");
leafEffect.Parameters["WorldView"].SetValue(world * view);
leafEffect.Parameters["View"].SetValue(view);
leafEffect.Parameters["Projection"].SetValue(projection);
leafEffect.Parameters["LeafScale"].SetValue(world.Right.Length());
if (skeleton.LeafAxis == null)
{
leafEffect.Parameters["BillboardRight"].SetValue(Vector3.Right);
leafEffect.Parameters["BillboardUp"].SetValue(Vector3.Up);
}
else
{
Vector3 axis = skeleton.LeafAxis.Value;
Vector3 forward = new Vector3(view.M13, view.M23, view.M33);
Vector3 right = Vector3.Cross(forward, axis);
right.Normalize();
Vector3 up = axis;
Vector3.TransformNormal(ref right, ref view, out right);
Vector3.TransformNormal(ref up, ref view, out up);
leafEffect.Parameters["BillboardRight"].SetValue(right);
leafEffect.Parameters["BillboardUp"].SetValue(up);
}
skeleton.CopyBoneBindingMatricesTo(bindingMatrices, animationState.BoneRotations);
leafEffect.Parameters["Bones"].SetValue(bindingMatrices);
leafEffect.Parameters["Texture"].SetValue(leafTexture);
leaves.Draw(leafEffect);
}
/// <summary>
/// Draws the tree's bones as lines. Useful for testing and debugging.
/// </summary>
/// <param name="world">World matrix.</param>
/// <param name="view">View matrix.</param>
/// <param name="projection">Projection matrix.</param>
public void DrawBonesAsLines(Matrix world, Matrix view, Matrix projection)
{
if (skeleton == null)
throw new InvalidOperationException("A skeleton must be set before bones can be rendered.");
if (leafEffect == null)
throw new InvalidOperationException("LeafEffect must be set before leaves can be rendered.");
if (skeleton.Bones.Count == 0)
return;
boneEffect.World = world;
boneEffect.View = view;
boneEffect.Projection = projection;
bool wasDepthBufferOn = device.DepthStencilState.DepthBufferEnable;
device.DepthStencilState = DepthStencilState.None;
device.BlendState = BlendState.Opaque;
Matrix[] transforms = new Matrix[skeleton.Bones.Count];
skeleton.CopyAbsoluteBoneTranformsTo(transforms, animationState.BoneRotations);
VertexPositionColor[] vertices = new VertexPositionColor[skeleton.Bones.Count * 2];
for (int i = 0; i < skeleton.Bones.Count; i++)
{
vertices[2 * i] = new VertexPositionColor(transforms[i].Translation, Color.Red);
vertices[2 * i + 1] = new VertexPositionColor(transforms[i].Translation + transforms[i].Up * skeleton.Bones[i].Length, Color.Red);
}
foreach (EffectPass pass in boneEffect.CurrentTechnique.Passes)
{
pass.Apply();
device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, vertices, 0, skeleton.Bones.Count);
}
if (wasDepthBufferOn)
device.DepthStencilState = DepthStencilState.Default;
}
}
}
| |
//
// 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 Microsoft.Cci.Pdb;
using Mono.Cecil.Cil;
namespace Mono.Cecil.Pdb {
public class PdbReader : ISymbolReader {
int age;
Guid guid;
readonly Stream pdb_file;
readonly Dictionary<string, Document> documents = new Dictionary<string, Document> ();
readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction> ();
internal PdbReader (Stream file)
{
this.pdb_file = file;
}
/*
uint Magic = 0x53445352;
Guid Signature;
uint Age;
string FileName;
*/
public bool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header)
{
if (header.Length < 24)
return false;
var magic = ReadInt32 (header, 0);
if (magic != 0x53445352)
return false;
var guid_bytes = new byte [16];
Buffer.BlockCopy (header, 4, guid_bytes, 0, 16);
this.guid = new Guid (guid_bytes);
this.age = ReadInt32 (header, 20);
return PopulateFunctions ();
}
static int ReadInt32 (byte [] bytes, int start)
{
return (bytes [start]
| (bytes [start + 1] << 8)
| (bytes [start + 2] << 16)
| (bytes [start + 3] << 24));
}
bool PopulateFunctions ()
{
using (pdb_file) {
Dictionary<uint, PdbTokenLine> tokenToSourceMapping;
string sourceServerData;
int age;
Guid guid;
var funcs = PdbFile.LoadFunctions (pdb_file, out tokenToSourceMapping, out sourceServerData, out age, out guid);
if (this.guid != guid)
return false;
foreach (PdbFunction function in funcs)
functions.Add (function.token, function);
}
return true;
}
public void Read (MethodBody body, InstructionMapper mapper)
{
var method_token = body.Method.MetadataToken;
PdbFunction function;
if (!functions.TryGetValue (method_token.ToUInt32 (), out function))
return;
ReadSequencePoints (function, mapper);
ReadScopeAndLocals (function.scopes, null, body, mapper);
}
static void ReadScopeAndLocals (PdbScope [] scopes, Scope parent, MethodBody body, InstructionMapper mapper)
{
foreach (PdbScope scope in scopes)
ReadScopeAndLocals (scope, parent, body, mapper);
CreateRootScope (body);
}
static void CreateRootScope (MethodBody body)
{
if (!body.HasVariables)
return;
var instructions = body.Instructions;
var root = new Scope ();
root.Start = instructions [0];
root.End = instructions [instructions.Count - 1];
var variables = body.Variables;
for (int i = 0; i < variables.Count; i++)
root.Variables.Add (variables [i]);
body.Scope = root;
}
static void ReadScopeAndLocals (PdbScope scope, Scope parent, MethodBody body, InstructionMapper mapper)
{
//Scope s = new Scope ();
//s.Start = GetInstruction (body, instructions, (int) scope.address);
//s.End = GetInstruction (body, instructions, (int) scope.length - 1);
//if (parent != null)
// parent.Scopes.Add (s);
//else
// body.Scopes.Add (s);
if (scope == null)
return;
foreach (PdbSlot slot in scope.slots) {
int index = (int) slot.slot;
if (index < 0 || index >= body.Variables.Count)
continue;
VariableDefinition variable = body.Variables [index];
variable.Name = slot.name;
//s.Variables.Add (variable);
}
ReadScopeAndLocals (scope.scopes, null /* s */, body, mapper);
}
void ReadSequencePoints (PdbFunction function, InstructionMapper mapper)
{
if (function.lines == null)
return;
foreach (PdbLines lines in function.lines)
ReadLines (lines, mapper);
}
void ReadLines (PdbLines lines, InstructionMapper mapper)
{
var document = GetDocument (lines.file);
foreach (var line in lines.lines)
ReadLine (line, document, mapper);
}
static void ReadLine (PdbLine line, Document document, InstructionMapper mapper)
{
var instruction = mapper ((int) line.offset);
if (instruction == null)
return;
var sequence_point = new SequencePoint (document);
sequence_point.StartLine = (int) line.lineBegin;
sequence_point.StartColumn = (int) line.colBegin;
sequence_point.EndLine = (int) line.lineEnd;
sequence_point.EndColumn = (int) line.colEnd;
instruction.SequencePoint = sequence_point;
}
Document GetDocument (PdbSource source)
{
string name = source.name;
Document document;
if (documents.TryGetValue (name, out document))
return document;
document = new Document (name) {
Language = source.language.ToLanguage (),
LanguageVendor = source.vendor.ToVendor (),
Type = source.doctype.ToType (),
};
documents.Add (name, document);
return document;
}
public void Read (MethodSymbols symbols)
{
PdbFunction function;
if (!functions.TryGetValue (symbols.MethodToken.ToUInt32 (), out function))
return;
ReadSequencePoints (function, symbols);
ReadLocals (function.scopes, symbols);
}
void ReadLocals (PdbScope [] scopes, MethodSymbols symbols)
{
foreach (var scope in scopes)
ReadLocals (scope, symbols);
}
void ReadLocals (PdbScope scope, MethodSymbols symbols)
{
if (scope == null)
return;
foreach (var slot in scope.slots) {
int index = (int) slot.slot;
if (index < 0 || index >= symbols.Variables.Count)
continue;
var variable = symbols.Variables [index];
variable.Name = slot.name;
}
ReadLocals (scope.scopes, symbols);
}
void ReadSequencePoints (PdbFunction function, MethodSymbols symbols)
{
if (function.lines == null)
return;
foreach (PdbLines lines in function.lines)
ReadLines (lines, symbols);
}
void ReadLines (PdbLines lines, MethodSymbols symbols)
{
for (int i = 0; i < lines.lines.Length; i++) {
var line = lines.lines [i];
symbols.Instructions.Add (new InstructionSymbol ((int) line.offset, new SequencePoint (GetDocument (lines.file)) {
StartLine = (int) line.lineBegin,
StartColumn = (int) line.colBegin,
EndLine = (int) line.lineEnd,
EndColumn = (int) line.colEnd,
}));
}
}
public void Dispose ()
{
pdb_file.Close ();
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The original content was ported from the C language from the 4.6 version of Proj4 libraries.
// Frank Warmerdam has released the full content of that version under the MIT license which is
// recognized as being approximately equivalent to public domain. The original work was done
// mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here:
// http://trac.osgeo.org/proj/
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/12/2009 2:42:59 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
namespace DotSpatial.Projections.Transforms
{
public class BipolarObliqueConformalConic : Transform
{
#region Private Variables
private const double EPS = 1e-10;
private const double ONEEPS = 1.000000001;
private const int NITER = 10;
private const double LAM_B = -.34894976726250681539;
private const double N = .63055844881274687180;
private const double F = 1.89724742567461030582;
private const double AZAB = .81650043674686363166;
private const double AZBA = 1.82261843856185925133;
private const double T = 1.27246578267089012270;
private const double RHOC = 1.20709121521568721927;
private const double C_AZC = .69691523038678375519;
private const double S_AZC = .71715351331143607555;
private const double C45 = .70710678118654752469;
private const double S45 = .70710678118654752410;
private const double C20 = .93969262078590838411;
private const double S20 = -.34202014332566873287;
private const double R110 = 1.91986217719376253360;
private const double R104 = 1.81514242207410275904;
private bool _noskew;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of BipolarObliqueConformalConic
/// </summary>
public BipolarObliqueConformalConic()
{
Proj4Name = "bipc";
Name = "Bipolar_Oblique_Conformal_Conic";
}
#endregion
#region Methods
/// <inheritdoc />
protected override void OnForward(double[] lp, double[] xy, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
double tphi, t, al, az, z, av, sdlam;
double cphi = Math.Cos(lp[phi]);
double sphi = Math.Sin(lp[phi]);
double cdlam = Math.Cos(sdlam = LAM_B - lp[lam]);
sdlam = Math.Sin(sdlam);
if (Math.Abs(Math.Abs(lp[phi]) - HALF_PI) < EPS10)
{
az = lp[phi] < 0 ? Math.PI : 0;
tphi = double.MaxValue;
}
else
{
tphi = sphi / cphi;
az = Math.Atan2(sdlam, C45 * (tphi - cdlam));
}
bool tag = az > AZBA;
if (tag)
{
cdlam = Math.Cos(sdlam = lp[lam] + R110);
sdlam = Math.Sin(sdlam);
z = S20 * sphi + C20 * cphi * cdlam;
if (Math.Abs(z) > 1)
{
if (Math.Abs(z) > ONEEPS)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//throw new ProjectionException(20);
}
z = z < 0 ? -1 : 1;
}
else
z = Math.Acos(z);
if (tphi != double.MaxValue)
az = Math.Atan2(sdlam, (C20 * tphi - S20 * cdlam));
av = AZAB;
xy[y] = RHOC;
}
else
{
z = S45 * (sphi + cphi * cdlam);
if (Math.Abs(z) > 1)
{
if (Math.Abs(z) > ONEEPS)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//throw new ProjectionException(20);
}
z = z < 0 ? -1 : 1;
}
else
z = Math.Acos(z);
av = AZBA;
xy[y] = -RHOC;
}
if (z < 0)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//throw new ProjectionException(20);
}
double r = F * (t = Math.Pow(Math.Tan(.5 * z), N));
if ((al = .5 * (R104 - z)) < 0)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//throw new ProjectionException(20);
}
al = (t + Math.Pow(al, N)) / T;
if (Math.Abs(al) > 1)
{
if (Math.Abs(al) > ONEEPS)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//throw new ProjectionException(20);
}
al = al < 0 ? -1 : 1;
}
else
al = Math.Acos(al);
if (Math.Abs(t = N * (av - az)) < al)
r /= Math.Cos(al + (tag ? t : -t));
xy[x] = r * Math.Sin(t);
xy[y] += (tag ? -r : r) * Math.Cos(t);
if (_noskew)
{
t = xy[x];
xy[x] = -xy[x] * C_AZC - xy[y] * S_AZC;
xy[y] = -xy[y] * C_AZC + t * S_AZC;
}
}
}
/// <inheritdoc />
protected override void OnInverse(double[] xy, double[] lp, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
double r, rp;
double z = 0, az, s, c, av;
int j;
if (_noskew)
{
double t = xy[x];
xy[x] = -xy[x] * C_AZC + xy[y] * S_AZC;
xy[y] = -xy[y] * C_AZC - t * S_AZC;
}
bool neg = (xy[x] < 0);
if (neg)
{
xy[y] = RHOC - xy[y];
s = S20;
c = C20;
av = AZAB;
}
else
{
xy[y] += RHOC;
s = S45;
c = C45;
av = AZBA;
}
double rl = rp = r = Proj.Hypot(xy[x], xy[y]);
double fAz = Math.Abs(az = Math.Atan2(xy[x], xy[y]));
for (j = NITER; j > 0; --j)
{
z = 2 * Math.Atan(Math.Pow(r / F, 1 / N));
double al = Math.Acos((Math.Pow(Math.Tan(.5 * z), N) +
Math.Pow(Math.Tan(.5 * (R104 - z)), N)) / T);
if (fAz < al)
r = rp * Math.Cos(al + (neg ? az : -az));
if (Math.Abs(rl - r) < EPS)
break;
rl = r;
}
if (j == 0)
{
lp[phi] = double.NaN;
lp[lam] = double.NaN;
continue;
//throw new ProjectionException(20);
}
az = av - az / N;
lp[phi] = Math.Asin(s * Math.Cos(z) + c * Math.Sin(z) * Math.Cos(az));
lp[lam] = Math.Atan2(Math.Sin(az), c / Math.Tan(z) - s * Math.Cos(az));
if (neg)
lp[lam] -= R110;
else
lp[lam] = LAM_B - lp[lam];
}
}
/// <summary>
/// Initializes the transform using the parameters from the specified coordinate system information
/// </summary>
/// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param>
protected override void OnInit(ProjectionInfo projInfo)
{
if (projInfo.bns.HasValue)
{
if (projInfo.bns != 0)
_noskew = true;
}
}
#endregion
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Http;
namespace OpenMetaverse
{
public class RegistrationApi
{
const int REQUEST_TIMEOUT = 1000 * 100;
private struct UserInfo
{
public string FirstName;
public string LastName;
public string Password;
}
private struct RegistrationCaps
{
public Uri CreateUser;
public Uri CheckName;
public Uri GetLastNames;
public Uri GetErrorCodes;
}
public struct LastName
{
public int ID;
public string Name;
}
/// <summary>
/// See https://secure-web6.secondlife.com/developers/third_party_reg/#service_create_user or
/// https://wiki.secondlife.com/wiki/RegAPIDoc for description
/// </summary>
public class CreateUserParam
{
public string FirstName;
public LastName LastName;
public string Email;
public string Password;
public DateTime Birthdate;
// optional:
public Nullable<int> LimitedToEstate;
public string StartRegionName;
public Nullable<Vector3> StartLocation;
public Nullable<Vector3> StartLookAt;
}
private UserInfo _userInfo;
private RegistrationCaps _caps;
private int _initializing;
private List<LastName> _lastNames = new List<LastName>();
private Dictionary<int, string> _errors = new Dictionary<int, string>();
public bool Initializing
{
get
{
System.Diagnostics.Debug.Assert(_initializing <= 0);
return (_initializing < 0);
}
}
public List<LastName> LastNames
{
get
{
lock (_lastNames)
{
if (_lastNames.Count <= 0)
GatherLastNames();
}
return _lastNames;
}
}
public RegistrationApi(string firstName, string lastName, string password)
{
_initializing = -2;
_userInfo = new UserInfo();
_userInfo.FirstName = firstName;
_userInfo.LastName = lastName;
_userInfo.Password = password;
GatherCaps();
}
public void WaitForInitialization()
{
while (Initializing)
System.Threading.Thread.Sleep(10);
}
public Uri RegistrationApiCaps
{
get { return new Uri("https://cap.secondlife.com/get_reg_capabilities"); }
}
private void GatherCaps()
{
// build post data
byte[] postData = Encoding.ASCII.GetBytes(
String.Format("first_name={0}&last_name={1}&password={2}", _userInfo.FirstName, _userInfo.LastName,
_userInfo.Password));
CapsClient request = new CapsClient(RegistrationApiCaps);
request.OnComplete += new CapsClient.CompleteCallback(GatherCapsResponse);
request.BeginGetResponse(postData, "application/x-www-form-urlencoded", REQUEST_TIMEOUT);
}
private void GatherCapsResponse(CapsClient client, OSD response, Exception error)
{
if (response is OSDMap)
{
OSDMap respTable = (OSDMap)response;
// parse
_caps = new RegistrationCaps();
_caps.CreateUser = respTable["create_user"].AsUri();
_caps.CheckName = respTable["check_name"].AsUri();
_caps.GetLastNames = respTable["get_last_names"].AsUri();
_caps.GetErrorCodes = respTable["get_error_codes"].AsUri();
// finalize
_initializing++;
GatherErrorMessages();
}
}
private void GatherErrorMessages()
{
if (_caps.GetErrorCodes == null)
throw new InvalidOperationException("access denied"); // this should work even for not-approved users
CapsClient request = new CapsClient(_caps.GetErrorCodes);
request.OnComplete += new CapsClient.CompleteCallback(GatherErrorMessagesResponse);
request.BeginGetResponse(REQUEST_TIMEOUT);
}
private void GatherErrorMessagesResponse(CapsClient client, OSD response, Exception error)
{
if (response is OSDMap)
{
// parse
//FIXME: wtf?
//foreach (KeyValuePair<string, object> error in (Dictionary<string, object>)response)
//{
//StringBuilder sb = new StringBuilder();
//sb.Append(error[1]);
//sb.Append(" (");
//sb.Append(error[0]);
//sb.Append("): ");
//sb.Append(error[2]);
//_errors.Add((int)error[0], sb.ToString());
//}
// finalize
_initializing++;
}
}
public void GatherLastNames()
{
if (Initializing)
throw new InvalidOperationException("still initializing");
if (_caps.GetLastNames == null)
throw new InvalidOperationException("access denied: only approved developers have access to the registration api");
CapsClient request = new CapsClient(_caps.GetLastNames);
request.OnComplete += new CapsClient.CompleteCallback(GatherLastNamesResponse);
request.BeginGetResponse(REQUEST_TIMEOUT);
// FIXME: Block
}
private void GatherLastNamesResponse(CapsClient client, OSD response, Exception error)
{
if (response is OSDMap)
{
//LLSDMap respTable = (LLSDMap)response;
//FIXME:
//_lastNames = new List<LastName>(respTable.Count);
//for (Dictionary<string, object>.Enumerator it = respTable.GetEnumerator(); it.MoveNext(); )
//{
// LastName ln = new LastName();
// ln.ID = int.Parse(it.Current.Key.ToString());
// ln.Name = it.Current.Value.ToString();
// _lastNames.Add(ln);
//}
//_lastNames.Sort(new Comparison<LastName>(delegate(LastName a, LastName b) { return a.Name.CompareTo(b.Name); }));
}
}
public bool CheckName(string firstName, LastName lastName)
{
if (Initializing)
throw new InvalidOperationException("still initializing");
if (_caps.CheckName == null)
throw new InvalidOperationException("access denied; only approved developers have access to the registration api");
// Create the POST data
OSDMap query = new OSDMap();
query.Add("username", OSD.FromString(firstName));
query.Add("last_name_id", OSD.FromInteger(lastName.ID));
//byte[] postData = OSDParser.SerializeXmlBytes(query);
CapsClient request = new CapsClient(_caps.CheckName);
request.OnComplete += new CapsClient.CompleteCallback(CheckNameResponse);
request.BeginGetResponse(REQUEST_TIMEOUT);
// FIXME:
return false;
}
private void CheckNameResponse(CapsClient client, OSD response, Exception error)
{
if (response.Type == OSDType.Boolean)
{
// FIXME:
//(bool)response;
}
else
{
// FIXME:
}
}
/// <summary>
/// Returns the new user ID or throws an exception containing the error code
/// The error codes can be found here: https://wiki.secondlife.com/wiki/RegAPIError
/// </summary>
/// <param name="user">New user account to create</param>
/// <returns>The UUID of the new user account</returns>
public UUID CreateUser(CreateUserParam user)
{
if (Initializing)
throw new InvalidOperationException("still initializing");
if (_caps.CreateUser == null)
throw new InvalidOperationException("access denied; only approved developers have access to the registration api");
// Create the POST data
OSDMap query = new OSDMap();
query.Add("username", OSD.FromString(user.FirstName));
query.Add("last_name_id", OSD.FromInteger(user.LastName.ID));
query.Add("email", OSD.FromString(user.Email));
query.Add("password", OSD.FromString(user.Password));
query.Add("dob", OSD.FromString(user.Birthdate.ToString("yyyy-MM-dd")));
if (user.LimitedToEstate != null)
query.Add("limited_to_estate", OSD.FromInteger(user.LimitedToEstate.Value));
if (!string.IsNullOrEmpty(user.StartRegionName))
query.Add("start_region_name", OSD.FromInteger(user.LimitedToEstate.Value));
if (user.StartLocation != null)
{
query.Add("start_local_x", OSD.FromReal(user.StartLocation.Value.X));
query.Add("start_local_y", OSD.FromReal(user.StartLocation.Value.Y));
query.Add("start_local_z", OSD.FromReal(user.StartLocation.Value.Z));
}
if (user.StartLookAt != null)
{
query.Add("start_look_at_x", OSD.FromReal(user.StartLookAt.Value.X));
query.Add("start_look_at_y", OSD.FromReal(user.StartLookAt.Value.Y));
query.Add("start_look_at_z", OSD.FromReal(user.StartLookAt.Value.Z));
}
//byte[] postData = OSDParser.SerializeXmlBytes(query);
// Make the request
CapsClient request = new CapsClient(_caps.CreateUser);
request.OnComplete += new CapsClient.CompleteCallback(CreateUserResponse);
request.BeginGetResponse(REQUEST_TIMEOUT);
// FIXME: Block
return UUID.Zero;
}
private void CreateUserResponse(CapsClient client, OSD response, Exception error)
{
if (response is OSDMap)
{
// everything is okay
// FIXME:
//return new UUID(((Dictionary<string, object>)response)["agent_id"].ToString());
}
else
{
// an error happened
OSDArray al = (OSDArray)response;
StringBuilder sb = new StringBuilder();
foreach (OSD ec in al)
{
if (sb.Length > 0)
sb.Append("; ");
sb.Append(_errors[ec.AsInteger()]);
}
// FIXME:
//throw new Exception("failed to create user: " + sb.ToString());
}
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Kodestruct.Common.CalculationLogger;
using Kodestruct.Common.Entities;
using Kodestruct.Common.Exceptions;
using Kodestruct.Common.Section.Interfaces;
using Kodestruct.Common.Section.SectionTypes;
namespace Kodestruct.Common.Section.Predefined
{
public class AiscShapeFactory
{
public ISection GetShape(string ShapeId, AngleOrientation AngleOrientation = AngleOrientation.LongLegVertical, AngleRotation AngleRotation = AngleRotation.FlatLegBottom)
{
ShapeTypeSteel shapeType = DetermineShapeType(ShapeId);
return GetShape( ShapeId, shapeType, AngleOrientation, AngleRotation);
}
private ShapeTypeSteel DetermineShapeType(string ShapeId)
{
ShapeId = ShapeId.ToUpper();
if (ShapeId.StartsWith("W") || ShapeId.StartsWith("S") || ShapeId.StartsWith("HP"))
{
return ShapeTypeSteel.IShapeRolled;
}
else if (ShapeId.StartsWith("C") || ShapeId.StartsWith("MC"))
{
return ShapeTypeSteel.Channel;
}
else if (ShapeId.StartsWith("L") )
{
return ShapeTypeSteel.Angle;
}
else if (ShapeId.StartsWith("2L"))
{
return ShapeTypeSteel.DoubleAngle;
}
else if (ShapeId.StartsWith("WT") || ShapeId.StartsWith("MT") || ShapeId.StartsWith("ST"))
{
return ShapeTypeSteel.TeeRolled;
}
else if (ShapeId.StartsWith("PIPE"))
{
return ShapeTypeSteel.CircularHSS;
}
else if (ShapeId.StartsWith("HSS"))
{
List<string> substrs = ShapeId.Split('X').ToList();
if (substrs.Count == 2)
{
return ShapeTypeSteel.CircularHSS;
}
else
{
return ShapeTypeSteel.RectangularHSS;
}
}
else
{
throw new Exception("Shape not recognized. Specify AISC database name.");
}
}
public ISection GetShape(string ShapeId, ShapeTypeSteel shapeType, AngleOrientation AngleOrientation = AngleOrientation.LongLegVertical, AngleRotation AngleRotation = AngleRotation.FlatLegBottom)
{
string DEFAULT_EXCEPTION_STRING = "Selected shape is not supported. Specify a different shape.";
AiscCatalogShape cs = new AiscCatalogShape(ShapeId,null);
CalcLog log = new CalcLog();
ISection sec = null;
switch (shapeType)
{
case ShapeTypeSteel.IShapeRolled:
sec = new PredefinedSectionI(cs);
break;
case ShapeTypeSteel.IShapeBuiltUp:
throw new Exception(DEFAULT_EXCEPTION_STRING);
break;
case ShapeTypeSteel.Channel:
sec = new PredefinedSectionChannel(cs);
break;
case ShapeTypeSteel.Angle:
sec = new PredefinedSectionAngle(cs, AngleOrientation,AngleRotation);
break;
case ShapeTypeSteel.TeeRolled:
throw new Exception(DEFAULT_EXCEPTION_STRING);
break;
case ShapeTypeSteel.TeeBuiltUp:
throw new Exception(DEFAULT_EXCEPTION_STRING);
break;
case ShapeTypeSteel.DoubleAngle:
throw new Exception(DEFAULT_EXCEPTION_STRING);
break;
case ShapeTypeSteel.CircularHSS:
sec = new PredefinedSectionCHS(cs);
break;
case ShapeTypeSteel.RectangularHSS:
sec = new PredefinedSectionRHS(cs);
break;
case ShapeTypeSteel.Box:
throw new Exception(DEFAULT_EXCEPTION_STRING);
break;
case ShapeTypeSteel.Rectangular:
throw new Exception(DEFAULT_EXCEPTION_STRING);
break;
case ShapeTypeSteel.Circular:
throw new Exception(DEFAULT_EXCEPTION_STRING);
break;
case ShapeTypeSteel.IShapeAsym:
throw new Exception(DEFAULT_EXCEPTION_STRING);
break;
default:
break;
}
return sec;
}
public ISliceableSection GetSliceableSection(string ShapeId, ShapeTypeSteel shapeType)
{
ISection section = this.GetShape(ShapeId, ShapeTypeSteel.IShapeRolled);
ISliceableSection sec;
switch (shapeType)
{
case ShapeTypeSteel.IShapeRolled:
PredefinedSectionI catI = section as PredefinedSectionI;
sec = new SectionIRolled("", catI.d, catI.b_fTop, catI.t_f, catI.t_w, catI.k);
break;
case ShapeTypeSteel.IShapeBuiltUp:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.Channel:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.Angle:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.TeeRolled:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.TeeBuiltUp:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.DoubleAngle:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.CircularHSS:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.RectangularHSS:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.Box:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.Rectangular:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.Circular:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
case ShapeTypeSteel.IShapeAsym:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
default:
throw new ShapeTypeNotSupportedException("ISliceableSection property ");
break;
}
return sec;
}
private double GetAngleGap(string ShapeId)
{
double gap=0;
string[] strings = ShapeId.Split('X');
if (strings.Count() == 4)
{
string gapStr = strings[3];
string gs;
if (gapStr.Contains("LLBB") || gapStr.Contains("SLBB"))
{
gs = gapStr.Substring(0, gapStr.Length - 5);
}
else
{
gs = gapStr;
}
string[] gsFraction = gs.Split('/');
if (gsFraction.Count() ==2)
{
double num = double.Parse(gsFraction[0]);
double den = double.Parse(gsFraction[1]);
gap = num / den;
}
}
return gap;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableControl;
using Roslyn.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Suppression
{
/// <summary>
/// Service to compute and apply bulk suppression fixes.
/// </summary>
[Export(typeof(IVisualStudioSuppressionFixService))]
internal sealed class VisualStudioSuppressionFixService : IVisualStudioSuppressionFixService
{
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly IWpfTableControl _tableControl;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ExternalErrorDiagnosticUpdateSource _buildErrorDiagnosticService;
private readonly ICodeFixService _codeFixService;
private readonly IFixMultipleOccurrencesService _fixMultipleOccurencesService;
private readonly ICodeActionEditHandlerService _editHandlerService;
private readonly VisualStudioDiagnosticListSuppressionStateService _suppressionStateService;
private readonly IWaitIndicator _waitIndicator;
[ImportingConstructor]
public VisualStudioSuppressionFixService(
SVsServiceProvider serviceProvider,
VisualStudioWorkspaceImpl workspace,
IDiagnosticAnalyzerService diagnosticService,
ExternalErrorDiagnosticUpdateSource buildErrorDiagnosticService,
ICodeFixService codeFixService,
ICodeActionEditHandlerService editHandlerService,
IVisualStudioDiagnosticListSuppressionStateService suppressionStateService,
IWaitIndicator waitIndicator)
{
_workspace = workspace;
_diagnosticService = diagnosticService;
_buildErrorDiagnosticService = buildErrorDiagnosticService;
_codeFixService = codeFixService;
_suppressionStateService = (VisualStudioDiagnosticListSuppressionStateService)suppressionStateService;
_editHandlerService = editHandlerService;
_waitIndicator = waitIndicator;
_fixMultipleOccurencesService = workspace.Services.GetService<IFixMultipleOccurrencesService>();
var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList;
_tableControl = errorList?.TableControl;
}
public bool AddSuppressions(IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
// Apply suppressions fix in global suppressions file for non-compiler diagnostics and
// in source only for compiler diagnostics.
var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly: false, isAddSuppression: true);
if (!ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: false))
{
return false;
}
return ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: true, onlyCompilerDiagnostics: true, showPreviewChangesDialog: false);
}
public bool AddSuppressions(bool selectedErrorListEntriesOnly, bool suppressInSource, IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
return ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: true, isSuppressionInSource: suppressInSource, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true);
}
public bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
return ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: false, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true);
}
private static Func<Project, bool> GetShouldFixInProjectDelegate(VisualStudioWorkspaceImpl workspace, IVsHierarchy projectHierarchyOpt)
{
if (projectHierarchyOpt == null)
{
return p => true;
}
else
{
var projectIdsForHierarchy = workspace.ProjectTracker.ImmutableProjects
.Where(p => p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic)
.Where(p => p.Hierarchy == projectHierarchyOpt)
.Select(p => workspace.CurrentSolution.GetProject(p.Id).Id)
.ToImmutableHashSet();
return p => projectIdsForHierarchy.Contains(p.Id);
}
}
private async Task<ImmutableArray<DiagnosticData>> GetAllBuildDiagnosticsAsync(Func<Project, bool> shouldFixInProject, CancellationToken cancellationToken)
{
var builder = ImmutableArray.CreateBuilder<DiagnosticData>();
var buildDiagnostics = _buildErrorDiagnosticService.GetBuildErrors().Where(d => d.ProjectId != null && d.Severity != DiagnosticSeverity.Hidden);
var solution = _workspace.CurrentSolution;
foreach (var diagnosticsByProject in buildDiagnostics.GroupBy(d => d.ProjectId))
{
cancellationToken.ThrowIfCancellationRequested();
if (diagnosticsByProject.Key == null)
{
// Diagnostics with no projectId cannot be suppressed.
continue;
}
var project = solution.GetProject(diagnosticsByProject.Key);
if (project != null && shouldFixInProject(project))
{
var diagnosticsByDocument = diagnosticsByProject.GroupBy(d => d.DocumentId);
foreach (var group in diagnosticsByDocument)
{
var documentId = group.Key;
if (documentId == null)
{
// Project diagnostics, just add all of them.
builder.AddRange(group);
continue;
}
// For document diagnostics, build does not have the computed text span info.
// So we explicitly calculate the text span from the source text for the diagnostics.
var document = project.GetDocument(documentId);
if (document != null)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var text = await tree.GetTextAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in group)
{
builder.Add(diagnostic.WithCalculatedSpan(text));
}
}
}
}
}
return builder.ToImmutable();
}
private static string GetFixTitle(bool isAddSuppression)
{
return isAddSuppression ? ServicesVSResources.Suppress_diagnostics : ServicesVSResources.Remove_suppressions;
}
private static string GetWaitDialogMessage(bool isAddSuppression)
{
return isAddSuppression ? ServicesVSResources.Computing_suppressions_fix : ServicesVSResources.Computing_remove_suppressions_fix;
}
private IEnumerable<DiagnosticData> GetDiagnosticsToFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression)
{
var diagnosticsToFix = ImmutableHashSet<DiagnosticData>.Empty;
Action<IWaitContext> computeDiagnosticsToFix = context =>
{
var cancellationToken = context.CancellationToken;
// If we are fixing selected diagnostics in error list, then get the diagnostics from error list entry snapshots.
// Otherwise, get all diagnostics from the diagnostic service.
var diagnosticsToFixTask = selectedEntriesOnly ?
_suppressionStateService.GetSelectedItemsAsync(isAddSuppression, cancellationToken) :
GetAllBuildDiagnosticsAsync(shouldFixInProject, cancellationToken);
diagnosticsToFix = diagnosticsToFixTask.WaitAndGetResult(cancellationToken).ToImmutableHashSet();
};
var title = GetFixTitle(isAddSuppression);
var waitDialogMessage = GetWaitDialogMessage(isAddSuppression);
var result = InvokeWithWaitDialog(computeDiagnosticsToFix, title, waitDialogMessage);
// Bail out if the user cancelled.
if (result == WaitIndicatorResult.Canceled)
{
return null;
}
return diagnosticsToFix;
}
private bool ApplySuppressionFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog)
{
var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly, isAddSuppression);
return ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, selectedEntriesOnly, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics, showPreviewChangesDialog);
}
private bool ApplySuppressionFix(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog)
{
if (diagnosticsToFix == null)
{
return false;
}
diagnosticsToFix = FilterDiagnostics(diagnosticsToFix, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics);
if (diagnosticsToFix.IsEmpty())
{
// Nothing to fix.
return true;
}
ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap = null;
ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap = null;
var title = GetFixTitle(isAddSuppression);
var waitDialogMessage = GetWaitDialogMessage(isAddSuppression);
var noDiagnosticsToFix = false;
var cancelled = false;
var newSolution = _workspace.CurrentSolution;
HashSet<string> languages = null;
Action<IWaitContext> computeDiagnosticsAndFix = context =>
{
var cancellationToken = context.CancellationToken;
cancellationToken.ThrowIfCancellationRequested();
documentDiagnosticsToFixMap = GetDocumentDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken)
.WaitAndGetResult(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
projectDiagnosticsToFixMap = isSuppressionInSource ?
ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty :
GetProjectDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken)
.WaitAndGetResult(cancellationToken);
if (documentDiagnosticsToFixMap == null ||
projectDiagnosticsToFixMap == null ||
(documentDiagnosticsToFixMap.IsEmpty && projectDiagnosticsToFixMap.IsEmpty))
{
// Nothing to fix.
noDiagnosticsToFix = true;
return;
}
cancellationToken.ThrowIfCancellationRequested();
// Equivalence key determines what fix will be applied.
// Make sure we don't include any specific diagnostic ID, as we want all of the given diagnostics (which can have varied ID) to be fixed.
var equivalenceKey = isAddSuppression ?
(isSuppressionInSource ? FeaturesResources.in_Source : FeaturesResources.in_Suppression_File) :
FeaturesResources.Remove_Suppression;
// We have different suppression fixers for every language.
// So we need to group diagnostics by the containing project language and apply fixes separately.
languages = new HashSet<string>(projectDiagnosticsToFixMap.Keys.Select(p => p.Language).Concat(documentDiagnosticsToFixMap.Select(kvp => kvp.Key.Project.Language)));
foreach (var language in languages)
{
// Use the Fix multiple occurrences service to compute a bulk suppression fix for the specified document and project diagnostics,
// show a preview changes dialog and then apply the fix to the workspace.
cancellationToken.ThrowIfCancellationRequested();
var documentDiagnosticsPerLanguage = GetDocumentDiagnosticsMappedToNewSolution(documentDiagnosticsToFixMap, newSolution, language);
if (!documentDiagnosticsPerLanguage.IsEmpty)
{
var suppressionFixer = GetSuppressionFixer(documentDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
if (suppressionFixer != null)
{
var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
newSolution = _fixMultipleOccurencesService.GetFix(
documentDiagnosticsPerLanguage,
_workspace,
suppressionFixer,
suppressionFixAllProvider,
equivalenceKey,
title,
waitDialogMessage,
cancellationToken);
if (newSolution == null)
{
// User cancelled or fixer threw an exception, so we just bail out.
cancelled = true;
return;
}
}
}
var projectDiagnosticsPerLanguage = GetProjectDiagnosticsMappedToNewSolution(projectDiagnosticsToFixMap, newSolution, language);
if (!projectDiagnosticsPerLanguage.IsEmpty)
{
var suppressionFixer = GetSuppressionFixer(projectDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
if (suppressionFixer != null)
{
var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
newSolution = _fixMultipleOccurencesService.GetFix(
projectDiagnosticsPerLanguage,
_workspace,
suppressionFixer,
suppressionFixAllProvider,
equivalenceKey,
title,
waitDialogMessage,
cancellationToken);
if (newSolution == null)
{
// User cancelled or fixer threw an exception, so we just bail out.
cancelled = true;
return;
}
}
}
}
};
var result = InvokeWithWaitDialog(computeDiagnosticsAndFix, title, waitDialogMessage);
// Bail out if the user cancelled.
if (cancelled || result == WaitIndicatorResult.Canceled)
{
return false;
}
else if (noDiagnosticsToFix || newSolution == _workspace.CurrentSolution)
{
// No changes.
return true;
}
if (showPreviewChangesDialog)
{
newSolution = FixAllGetFixesService.PreviewChanges(
_workspace.CurrentSolution,
newSolution,
fixAllPreviewChangesTitle: title,
fixAllTopLevelHeader: title,
languageOpt: languages?.Count == 1 ? languages.Single() : null,
workspace: _workspace);
if (newSolution == null)
{
return false;
}
}
waitDialogMessage = isAddSuppression ? ServicesVSResources.Applying_suppressions_fix : ServicesVSResources.Applying_remove_suppressions_fix;
Action<IWaitContext> applyFix = context =>
{
var operations = SpecializedCollections.SingletonEnumerable(new ApplyChangesOperation(newSolution));
var cancellationToken = context.CancellationToken;
_editHandlerService.ApplyAsync(
_workspace,
fromDocument: null,
operations: operations,
title: title,
progressTracker: context.ProgressTracker,
cancellationToken: cancellationToken).Wait(cancellationToken);
};
result = InvokeWithWaitDialog(applyFix, title, waitDialogMessage);
if (result == WaitIndicatorResult.Canceled)
{
return false;
}
// Kick off diagnostic re-analysis for affected projects so that diagnostics gets refreshed.
Task.Run(() =>
{
var reanalyzeDocuments = diagnosticsToFix.Where(d => d.DocumentId != null).Select(d => d.DocumentId).Distinct();
_diagnosticService.Reanalyze(_workspace, documentIds: reanalyzeDocuments, highPriority: true);
});
return true;
}
private static IEnumerable<DiagnosticData> FilterDiagnostics(IEnumerable<DiagnosticData> diagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics)
{
foreach (var diagnostic in diagnostics)
{
var isCompilerDiagnostic = SuppressionHelpers.IsCompilerDiagnostic(diagnostic);
if (onlyCompilerDiagnostics && !isCompilerDiagnostic)
{
continue;
}
if (isAddSuppression)
{
// Compiler diagnostics can only be suppressed in source.
if (!diagnostic.IsSuppressed &&
(isSuppressionInSource || !isCompilerDiagnostic))
{
yield return diagnostic;
}
}
else if (diagnostic.IsSuppressed)
{
yield return diagnostic;
}
}
}
private WaitIndicatorResult InvokeWithWaitDialog(
Action<IWaitContext> action, string waitDialogTitle, string waitDialogMessage)
{
var cancelled = false;
var result = _waitIndicator.Wait(
waitDialogTitle,
waitDialogMessage,
allowCancel: true,
showProgress: true,
action: waitContext =>
{
try
{
action(waitContext);
}
catch (OperationCanceledException)
{
cancelled = true;
}
});
return cancelled ? WaitIndicatorResult.Canceled : result;
}
private static ImmutableDictionary<Document, ImmutableArray<Diagnostic>> GetDocumentDiagnosticsMappedToNewSolution(ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap, Solution newSolution, string language)
{
ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Builder builder = null;
foreach (var kvp in documentDiagnosticsToFixMap)
{
if (kvp.Key.Project.Language != language)
{
continue;
}
var document = newSolution.GetDocument(kvp.Key.Id);
if (document != null)
{
builder = builder ?? ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>();
builder.Add(document, kvp.Value);
}
}
return builder != null ? builder.ToImmutable() : ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
}
private static ImmutableDictionary<Project, ImmutableArray<Diagnostic>> GetProjectDiagnosticsMappedToNewSolution(ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap, Solution newSolution, string language)
{
ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Builder projectDiagsBuilder = null;
foreach (var kvp in projectDiagnosticsToFixMap)
{
if (kvp.Key.Language != language)
{
continue;
}
var project = newSolution.GetProject(kvp.Key.Id);
if (project != null)
{
projectDiagsBuilder = projectDiagsBuilder ?? ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>();
projectDiagsBuilder.Add(project, kvp.Value);
}
}
return projectDiagsBuilder != null ? projectDiagsBuilder.ToImmutable() : ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty;
}
private static CodeFixProvider GetSuppressionFixer(IEnumerable<Diagnostic> diagnostics, string language, ICodeFixService codeFixService)
{
// Fetch the suppression fixer to apply the fix.
return codeFixService.GetSuppressionFixer(language, diagnostics.Select(d => d.Id));
}
private async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken)
{
Func<DiagnosticData, bool> isDocumentDiagnostic = d => d.DataLocation != null && d.HasTextSpan;
var builder = ImmutableDictionary.CreateBuilder<DocumentId, List<DiagnosticData>>();
foreach (var diagnosticData in diagnosticsToFix.Where(isDocumentDiagnostic))
{
List<DiagnosticData> diagnosticsPerDocument;
if (!builder.TryGetValue(diagnosticData.DocumentId, out diagnosticsPerDocument))
{
diagnosticsPerDocument = new List<DiagnosticData>();
builder[diagnosticData.DocumentId] = diagnosticsPerDocument;
}
diagnosticsPerDocument.Add(diagnosticData);
}
if (builder.Count == 0)
{
return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
}
var finalBuilder = ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>();
var latestDocumentDiagnosticsMapOpt = filterStaleDiagnostics ? new Dictionary<DocumentId, ImmutableHashSet<DiagnosticData>>() : null;
foreach (var group in builder.GroupBy(kvp => kvp.Key.ProjectId))
{
var projectId = group.Key;
var project = _workspace.CurrentSolution.GetProject(projectId);
if (project == null || !shouldFixInProject(project))
{
continue;
}
if (filterStaleDiagnostics)
{
var uniqueDiagnosticIds = group.SelectMany(kvp => kvp.Value.Select(d => d.Id)).ToImmutableHashSet();
var latestProjectDiagnostics = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken)
.ConfigureAwait(false)).Where(isDocumentDiagnostic);
latestDocumentDiagnosticsMapOpt.Clear();
foreach (var kvp in latestProjectDiagnostics.Where(d => d.DocumentId != null).GroupBy(d => d.DocumentId))
{
latestDocumentDiagnosticsMapOpt.Add(kvp.Key, kvp.ToImmutableHashSet());
}
}
foreach (var documentDiagnostics in group)
{
var document = project.GetDocument(documentDiagnostics.Key);
if (document == null)
{
continue;
}
IEnumerable<DiagnosticData> documentDiagnosticsToFix;
if (filterStaleDiagnostics)
{
ImmutableHashSet<DiagnosticData> latestDocumentDiagnostics;
if (!latestDocumentDiagnosticsMapOpt.TryGetValue(document.Id, out latestDocumentDiagnostics))
{
// Ignore stale diagnostics in error list.
latestDocumentDiagnostics = ImmutableHashSet<DiagnosticData>.Empty;
}
// Filter out stale diagnostics in error list.
documentDiagnosticsToFix = documentDiagnostics.Value.Where(d => latestDocumentDiagnostics.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d));
}
else
{
documentDiagnosticsToFix = documentDiagnostics.Value;
}
if (documentDiagnosticsToFix.Any())
{
var diagnostics = await documentDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
finalBuilder.Add(document, diagnostics.ToImmutableArray());
}
}
}
return finalBuilder.ToImmutableDictionary();
}
private async Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken)
{
Func<DiagnosticData, bool> isProjectDiagnostic = d => d.DataLocation == null && d.ProjectId != null;
var builder = ImmutableDictionary.CreateBuilder<ProjectId, List<DiagnosticData>>();
foreach (var diagnosticData in diagnosticsToFix.Where(isProjectDiagnostic))
{
List<DiagnosticData> diagnosticsPerProject;
if (!builder.TryGetValue(diagnosticData.ProjectId, out diagnosticsPerProject))
{
diagnosticsPerProject = new List<DiagnosticData>();
builder[diagnosticData.ProjectId] = diagnosticsPerProject;
}
diagnosticsPerProject.Add(diagnosticData);
}
if (builder.Count == 0)
{
return ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty;
}
var finalBuilder = ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>();
var latestDiagnosticsToFixOpt = filterStaleDiagnostics ? new HashSet<DiagnosticData>() : null;
foreach (var kvp in builder)
{
var projectId = kvp.Key;
var project = _workspace.CurrentSolution.GetProject(projectId);
if (project == null || !shouldFixInProject(project))
{
continue;
}
var diagnostics = kvp.Value;
IEnumerable<DiagnosticData> projectDiagnosticsToFix;
if (filterStaleDiagnostics)
{
var uniqueDiagnosticIds = diagnostics.Select(d => d.Id).ToImmutableHashSet();
var latestDiagnosticsFromDiagnosticService = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken)
.ConfigureAwait(false));
latestDiagnosticsToFixOpt.Clear();
latestDiagnosticsToFixOpt.AddRange(latestDiagnosticsFromDiagnosticService.Where(isProjectDiagnostic));
// Filter out stale diagnostics in error list.
projectDiagnosticsToFix = diagnostics.Where(d => latestDiagnosticsFromDiagnosticService.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d));
}
else
{
projectDiagnosticsToFix = diagnostics;
}
if (projectDiagnosticsToFix.Any())
{
var projectDiagnostics = await projectDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
finalBuilder.Add(project, projectDiagnostics.ToImmutableArray());
}
}
return finalBuilder.ToImmutableDictionary();
}
}
}
| |
// https://github.com/MonoGame/MonoGame
// MIT License - Copyright (C) The Mono.Xna Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace Microsoft.Xna.Framework
{
internal class PlaneHelper
{
/// <summary>
/// Returns a value indicating what side (positive/negative) of a plane a point is
/// </summary>
/// <param name="point">The point to check with</param>
/// <param name="plane">The plane to check against</param>
/// <returns>Greater than zero if on the positive side, less than zero if on the negative size, 0 otherwise</returns>
public static float ClassifyPoint(ref Vector3 point, ref Plane plane)
{
return point.X * plane.Normal.X + point.Y * plane.Normal.Y + point.Z * plane.Normal.Z + plane.D;
}
/// <summary>
/// Returns the perpendicular distance from a point to a plane
/// </summary>
/// <param name="point">The point to check</param>
/// <param name="plane">The place to check</param>
/// <returns>The perpendicular distance from the point to the plane</returns>
public static float PerpendicularDistance(ref Vector3 point, ref Plane plane)
{
// dist = (ax + by + cz + d) / sqrt(a*a + b*b + c*c)
return (float)Math.Abs((plane.Normal.X * point.X + plane.Normal.Y * point.Y + plane.Normal.Z * point.Z)
/ Math.Sqrt(plane.Normal.X * plane.Normal.X + plane.Normal.Y * plane.Normal.Y + plane.Normal.Z * plane.Normal.Z));
}
}
[DataContract]
[DebuggerDisplay("{DebugDisplayString,nq}")]
public struct Plane : IEquatable<Plane>
{
#region Public Fields
[DataMember]
public float D;
[DataMember]
public Vector3 Normal;
#endregion Public Fields
#region Constructors
public Plane(Vector4 value)
: this(new Vector3(value.X, value.Y, value.Z), value.W)
{
}
public Plane(Vector3 normal, float d)
{
Normal = normal;
D = d;
}
public Plane(Vector3 a, Vector3 b, Vector3 c)
{
Vector3 ab = b - a;
Vector3 ac = c - a;
Vector3 cross = Vector3.Cross(ab, ac);
Normal = Vector3.Normalize(cross);
D = -(Vector3.Dot(Normal, a));
}
public Plane(float a, float b, float c, float d)
: this(new Vector3(a, b, c), d)
{
}
#endregion Constructors
#region Public Methods
public float Dot(Vector4 value)
{
return ((((this.Normal.X * value.X) + (this.Normal.Y * value.Y)) + (this.Normal.Z * value.Z)) + (this.D * value.W));
}
public void Dot(ref Vector4 value, out float result)
{
result = (((this.Normal.X * value.X) + (this.Normal.Y * value.Y)) + (this.Normal.Z * value.Z)) + (this.D * value.W);
}
public float DotCoordinate(Vector3 value)
{
return ((((this.Normal.X * value.X) + (this.Normal.Y * value.Y)) + (this.Normal.Z * value.Z)) + this.D);
}
public void DotCoordinate(ref Vector3 value, out float result)
{
result = (((this.Normal.X * value.X) + (this.Normal.Y * value.Y)) + (this.Normal.Z * value.Z)) + this.D;
}
public float DotNormal(Vector3 value)
{
return (((this.Normal.X * value.X) + (this.Normal.Y * value.Y)) + (this.Normal.Z * value.Z));
}
public void DotNormal(ref Vector3 value, out float result)
{
result = ((this.Normal.X * value.X) + (this.Normal.Y * value.Y)) + (this.Normal.Z * value.Z);
}
/// <summary>
/// Transforms a normalized plane by a matrix.
/// </summary>
/// <param name="plane">The normalized plane to transform.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed plane.</returns>
public static Plane Transform(Plane plane, Matrix matrix)
{
Plane result;
Transform(ref plane, ref matrix, out result);
return result;
}
/// <summary>
/// Transforms a normalized plane by a matrix.
/// </summary>
/// <param name="plane">The normalized plane to transform.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <param name="result">The transformed plane.</param>
public static void Transform(ref Plane plane, ref Matrix matrix, out Plane result)
{
// See "Transforming Normals" in http://www.glprogramming.com/red/appendixf.html
// for an explanation of how this works.
Matrix transformedMatrix;
Matrix.Invert(ref matrix, out transformedMatrix);
Matrix.Transpose(ref transformedMatrix, out transformedMatrix);
var vector = new Vector4(plane.Normal, plane.D);
Vector4 transformedVector;
Vector4.Transform(ref vector, ref transformedMatrix, out transformedVector);
result = new Plane(transformedVector);
}
/// <summary>
/// Transforms a normalized plane by a quaternion rotation.
/// </summary>
/// <param name="plane">The normalized plane to transform.</param>
/// <param name="rotation">The quaternion rotation.</param>
/// <returns>The transformed plane.</returns>
public static Plane Transform(Plane plane, Quaternion rotation)
{
Plane result;
Transform(ref plane, ref rotation, out result);
return result;
}
/// <summary>
/// Transforms a normalized plane by a quaternion rotation.
/// </summary>
/// <param name="plane">The normalized plane to transform.</param>
/// <param name="rotation">The quaternion rotation.</param>
/// <param name="result">The transformed plane.</param>
public static void Transform(ref Plane plane, ref Quaternion rotation, out Plane result)
{
Vector3.Transform(ref plane.Normal, ref rotation, out result.Normal);
result.D = plane.D;
}
public void Normalize()
{
float factor;
Vector3 normal = Normal;
Normal = Vector3.Normalize(Normal);
factor = (float)Math.Sqrt(Normal.X * Normal.X + Normal.Y * Normal.Y + Normal.Z * Normal.Z) /
(float)Math.Sqrt(normal.X * normal.X + normal.Y * normal.Y + normal.Z * normal.Z);
D = D * factor;
}
public static Plane Normalize(Plane value)
{
Plane ret;
Normalize(ref value, out ret);
return ret;
}
public static void Normalize(ref Plane value, out Plane result)
{
float factor;
result.Normal = Vector3.Normalize(value.Normal);
factor = (float)Math.Sqrt(result.Normal.X * result.Normal.X + result.Normal.Y * result.Normal.Y + result.Normal.Z * result.Normal.Z) /
(float)Math.Sqrt(value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z);
result.D = value.D * factor;
}
public static bool operator !=(Plane plane1, Plane plane2)
{
return !plane1.Equals(plane2);
}
public static bool operator ==(Plane plane1, Plane plane2)
{
return plane1.Equals(plane2);
}
public override bool Equals(object other)
{
return (other is Plane) ? this.Equals((Plane)other) : false;
}
public bool Equals(Plane other)
{
return ((Normal == other.Normal) && (D == other.D));
}
public override int GetHashCode()
{
return Normal.GetHashCode() ^ D.GetHashCode();
}
public PlaneIntersectionType Intersects(BoundingBox box)
{
return box.Intersects(this);
}
public void Intersects(ref BoundingBox box, out PlaneIntersectionType result)
{
box.Intersects(ref this, out result);
}
public PlaneIntersectionType Intersects(BoundingFrustum frustum)
{
return frustum.Intersects(this);
}
public PlaneIntersectionType Intersects(BoundingSphere sphere)
{
return sphere.Intersects(this);
}
public void Intersects(ref BoundingSphere sphere, out PlaneIntersectionType result)
{
sphere.Intersects(ref this, out result);
}
internal PlaneIntersectionType Intersects(ref Vector3 point)
{
float distance;
DotCoordinate(ref point, out distance);
if (distance > 0)
return PlaneIntersectionType.Front;
if (distance < 0)
return PlaneIntersectionType.Back;
return PlaneIntersectionType.Intersecting;
}
internal string DebugDisplayString
{
get
{
return string.Concat(
this.Normal.DebugDisplayString, " ",
this.D.ToString()
);
}
}
public override string ToString()
{
return "{Normal:" + Normal + " D:" + D + "}";
}
#endregion
}
}
| |
using NUnit.Framework;
namespace Lucene.Net.Search
{
using Lucene.Net.Search.Spans;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Occur = Lucene.Net.Search.BooleanClause.Occur;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Term = Lucene.Net.Index.Term;
/// <summary>
/// TestExplanations subclass that builds up super crazy complex queries
/// on the assumption that if the explanations work out right for them,
/// they should work for anything.
/// </summary>
[TestFixture]
public class TestComplexExplanations : TestExplanations
{
/// <summary>
/// Override the Similarity used in our searcher with one that plays
/// nice with boosts of 0.0
/// </summary>
[SetUp]
public override void SetUp()
{
base.SetUp();
Searcher.Similarity = CreateQnorm1Similarity();
}
[TearDown]
public override void TearDown()
{
Searcher.Similarity = IndexSearcher.DefaultSimilarity;
base.TearDown();
}
// must be static for weight serialization tests
private static DefaultSimilarity CreateQnorm1Similarity()
{
return new DefaultSimilarityAnonymousInnerClassHelper();
}
private class DefaultSimilarityAnonymousInnerClassHelper : DefaultSimilarity
{
public DefaultSimilarityAnonymousInnerClassHelper()
{
}
public override float QueryNorm(float sumOfSquaredWeights)
{
return 1.0f; // / (float) Math.sqrt(1.0f + sumOfSquaredWeights);
}
}
[Test]
public virtual void Test1()
{
BooleanQuery q = new BooleanQuery();
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Slop = 1;
phraseQuery.Add(new Term(FIELD, "w1"));
phraseQuery.Add(new Term(FIELD, "w2"));
q.Add(phraseQuery, Occur.MUST);
q.Add(Snear(St("w2"), Sor("w5", "zz"), 4, true), Occur.SHOULD);
q.Add(Snear(Sf("w3", 2), St("w2"), St("w3"), 5, true), Occur.SHOULD);
Query t = new FilteredQuery(new TermQuery(new Term(FIELD, "xx")), new ItemizedFilter(new int[] { 1, 3 }));
t.Boost = 1000;
q.Add(t, Occur.SHOULD);
t = new ConstantScoreQuery(new ItemizedFilter(new int[] { 0, 2 }));
t.Boost = 30;
q.Add(t, Occur.SHOULD);
DisjunctionMaxQuery dm = new DisjunctionMaxQuery(0.2f);
dm.Add(Snear(St("w2"), Sor("w5", "zz"), 4, true));
dm.Add(new TermQuery(new Term(FIELD, "QQ")));
BooleanQuery xxYYZZ = new BooleanQuery();
xxYYZZ.Add(new TermQuery(new Term(FIELD, "xx")), Occur.SHOULD);
xxYYZZ.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD);
xxYYZZ.Add(new TermQuery(new Term(FIELD, "zz")), Occur.MUST_NOT);
dm.Add(xxYYZZ);
BooleanQuery xxW1 = new BooleanQuery();
xxW1.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT);
xxW1.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST_NOT);
dm.Add(xxW1);
DisjunctionMaxQuery dm2 = new DisjunctionMaxQuery(0.5f);
dm2.Add(new TermQuery(new Term(FIELD, "w1")));
dm2.Add(new TermQuery(new Term(FIELD, "w2")));
dm2.Add(new TermQuery(new Term(FIELD, "w3")));
dm.Add(dm2);
q.Add(dm, Occur.SHOULD);
BooleanQuery b = new BooleanQuery();
b.MinimumNumberShouldMatch = 2;
b.Add(Snear("w1", "w2", 1, true), Occur.SHOULD);
b.Add(Snear("w2", "w3", 1, true), Occur.SHOULD);
b.Add(Snear("w1", "w3", 3, true), Occur.SHOULD);
q.Add(b, Occur.SHOULD);
Qtest(q, new int[] { 0, 1, 2 });
}
[Test]
public virtual void Test2()
{
BooleanQuery q = new BooleanQuery();
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Slop = 1;
phraseQuery.Add(new Term(FIELD, "w1"));
phraseQuery.Add(new Term(FIELD, "w2"));
q.Add(phraseQuery, Occur.MUST);
q.Add(Snear(St("w2"), Sor("w5", "zz"), 4, true), Occur.SHOULD);
q.Add(Snear(Sf("w3", 2), St("w2"), St("w3"), 5, true), Occur.SHOULD);
Query t = new FilteredQuery(new TermQuery(new Term(FIELD, "xx")), new ItemizedFilter(new int[] { 1, 3 }));
t.Boost = 1000;
q.Add(t, Occur.SHOULD);
t = new ConstantScoreQuery(new ItemizedFilter(new int[] { 0, 2 }));
t.Boost = -20.0f;
q.Add(t, Occur.SHOULD);
DisjunctionMaxQuery dm = new DisjunctionMaxQuery(0.2f);
dm.Add(Snear(St("w2"), Sor("w5", "zz"), 4, true));
dm.Add(new TermQuery(new Term(FIELD, "QQ")));
BooleanQuery xxYYZZ = new BooleanQuery();
xxYYZZ.Add(new TermQuery(new Term(FIELD, "xx")), Occur.SHOULD);
xxYYZZ.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD);
xxYYZZ.Add(new TermQuery(new Term(FIELD, "zz")), Occur.MUST_NOT);
dm.Add(xxYYZZ);
BooleanQuery xxW1 = new BooleanQuery();
xxW1.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT);
xxW1.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST_NOT);
dm.Add(xxW1);
DisjunctionMaxQuery dm2 = new DisjunctionMaxQuery(0.5f);
dm2.Add(new TermQuery(new Term(FIELD, "w1")));
dm2.Add(new TermQuery(new Term(FIELD, "w2")));
dm2.Add(new TermQuery(new Term(FIELD, "w3")));
dm.Add(dm2);
q.Add(dm, Occur.SHOULD);
BooleanQuery b = new BooleanQuery();
b.MinimumNumberShouldMatch = 2;
b.Add(Snear("w1", "w2", 1, true), Occur.SHOULD);
b.Add(Snear("w2", "w3", 1, true), Occur.SHOULD);
b.Add(Snear("w1", "w3", 3, true), Occur.SHOULD);
b.Boost = 0.0f;
q.Add(b, Occur.SHOULD);
Qtest(q, new int[] { 0, 1, 2 });
}
// :TODO: we really need more crazy complex cases.
// //////////////////////////////////////////////////////////////////
// The rest of these aren't that complex, but they are <i>somewhat</i>
// complex, and they expose weakness in dealing with queries that match
// with scores of 0 wrapped in other queries
[Test]
public virtual void TestT3()
{
TermQuery query = new TermQuery(new Term(FIELD, "w1"));
query.Boost = 0;
Bqtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMA3()
{
Query q = new MatchAllDocsQuery();
q.Boost = 0;
Bqtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestFQ5()
{
TermQuery query = new TermQuery(new Term(FIELD, "xx"));
query.Boost = 0;
Bqtest(new FilteredQuery(query, new ItemizedFilter(new int[] { 1, 3 })), new int[] { 3 });
}
[Test]
public virtual void TestCSQ4()
{
Query q = new ConstantScoreQuery(new ItemizedFilter(new int[] { 3 }));
q.Boost = 0;
Bqtest(q, new int[] { 3 });
}
[Test]
public virtual void TestDMQ10()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5"));
boostedQuery.Boost = 100;
query.Add(boostedQuery, Occur.SHOULD);
q.Add(query);
TermQuery xxBoostedQuery = new TermQuery(new Term(FIELD, "xx"));
xxBoostedQuery.Boost = 0;
q.Add(xxBoostedQuery);
q.Boost = 0.0f;
Bqtest(q, new int[] { 0, 2, 3 });
}
[Test]
public virtual void TestMPQ7()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new string[] { "w1" }));
q.Add(Ta(new string[] { "w2" }));
q.Slop = 1;
q.Boost = 0.0f;
Bqtest(q, new int[] { 0, 1, 2 });
}
[Test]
public virtual void TestBQ12()
{
// NOTE: using qtest not bqtest
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w2"));
boostedQuery.Boost = 0;
query.Add(boostedQuery, Occur.SHOULD);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ13()
{
// NOTE: using qtest not bqtest
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5"));
boostedQuery.Boost = 0;
query.Add(boostedQuery, Occur.MUST_NOT);
Qtest(query, new int[] { 1, 2, 3 });
}
[Test]
public virtual void TestBQ18()
{
// NOTE: using qtest not bqtest
BooleanQuery query = new BooleanQuery();
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w1"));
boostedQuery.Boost = 0;
query.Add(boostedQuery, Occur.MUST);
query.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ21()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST);
query.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD);
query.Boost = 0;
Bqtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ22()
{
BooleanQuery query = new BooleanQuery();
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w1"));
boostedQuery.Boost = 0;
query.Add(boostedQuery, Occur.MUST);
query.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD);
query.Boost = 0;
Bqtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestST3()
{
SpanQuery q = St("w1");
q.Boost = 0;
Bqtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestST6()
{
SpanQuery q = St("xx");
q.Boost = 0;
Qtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestSF3()
{
SpanQuery q = Sf(("w1"), 1);
q.Boost = 0;
Bqtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSF7()
{
SpanQuery q = Sf(("xx"), 3);
q.Boost = 0;
Bqtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestSNot3()
{
SpanQuery q = Snot(Sf("w1", 10), St("QQ"));
q.Boost = 0;
Bqtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSNot6()
{
SpanQuery q = Snot(Sf("w1", 10), St("xx"));
q.Boost = 0;
Bqtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSNot8()
{
// NOTE: using qtest not bqtest
SpanQuery f = Snear("w1", "w3", 10, true);
f.Boost = 0;
SpanQuery q = Snot(f, St("xx"));
Qtest(q, new int[] { 0, 1, 3 });
}
[Test]
public virtual void TestSNot9()
{
// NOTE: using qtest not bqtest
SpanQuery t = St("xx");
t.Boost = 0;
SpanQuery q = Snot(Snear("w1", "w3", 10, true), t);
Qtest(q, new int[] { 0, 1, 3 });
}
}
}
| |
// Minifier.cs
//
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Microsoft.Ajax.Utilities
{
/// <summary>
/// Minifier class for quick minification of JavaScript or Stylesheet code without needing to
/// access or modify any abstract syntax tree nodes. Just put in source code and get our minified
/// code as strings.
/// </summary>
public class Minifier
{
#region Properties
/// <summary>
/// Warning level threshold for reporting errors.
/// Default value is zero: syntax/run-time errors.
/// </summary>
public int WarningLevel
{
get; set;
}
/// <summary>
/// File name to use in error reporting.
/// Default value is null: use Minify... method name.
/// </summary>
public string FileName
{
get; set;
}
/// <summary>
/// Collection of ContextError objects found during minification process
/// </summary>
public ICollection<ContextError> ErrorList { get { return m_errorList; } }
private List<ContextError> m_errorList; // = null;
/// <summary>
/// Collection of any error strings found during the crunch process.
/// </summary>
public ICollection<string> Errors
{
get
{
var errorList = new List<string>(ErrorList.Count);
foreach (var error in ErrorList)
{
errorList.Add(error.ToString());
}
return errorList;
}
}
#endregion
#region JavaScript methods
/// <summary>
/// MinifyJavaScript JS string passed to it using default code minification settings.
/// The ErrorList property will be set with any errors found during the minification process.
/// </summary>
/// <param name="source">source Javascript</param>
/// <returns>minified Javascript</returns>
public string MinifyJavaScript(string source)
{
// just pass in default settings
return MinifyJavaScript(source, new CodeSettings());
}
/// <summary>
/// Crunched JS string passed to it, returning crunched string.
/// The ErrorList property will be set with any errors found during the minification process.
/// </summary>
/// <param name="source">source Javascript</param>
/// <param name="codeSettings">code minification settings</param>
/// <returns>minified Javascript</returns>
public string MinifyJavaScript(string source, CodeSettings codeSettings)
{
// default is an empty string
var crunched = string.Empty;
// reset the errors builder
m_errorList = new List<ContextError>();
// create the parser and hook the engine error event
var parser = new JSParser();
parser.CompilerError += OnJavaScriptError;
var sb = StringBuilderPool.Acquire();
try
{
var preprocessOnly = codeSettings != null && codeSettings.PreprocessOnly;
using (var stringWriter = new StringWriter(sb, CultureInfo.InvariantCulture))
{
if (preprocessOnly)
{
parser.EchoWriter = stringWriter;
}
// parse the input
var scriptBlock = parser.Parse(new DocumentContext(source) { FileContext = this.FileName }, codeSettings);
if (scriptBlock != null && !preprocessOnly)
{
// we'll return the crunched code
if (codeSettings != null && codeSettings.Format == JavaScriptFormat.JSON)
{
// we're going to use a different output visitor -- one
// that specifically returns valid JSON.
if (!JSONOutputVisitor.Apply(stringWriter, scriptBlock, codeSettings))
{
m_errorList.Add(new ContextError()
{
Severity = 0,
File = this.FileName,
Message = CommonStrings.InvalidJSONOutput,
});
}
}
else
{
// just use the normal output visitor
OutputVisitor.Apply(stringWriter, scriptBlock, codeSettings);
// if we are asking for a symbols map, give it a chance to output a little something
// to the minified file.
if (codeSettings != null && codeSettings.SymbolsMap != null)
{
codeSettings.SymbolsMap.EndFile(stringWriter, codeSettings.LineTerminator);
}
}
}
}
crunched = sb.ToString();
}
catch (Exception e)
{
m_errorList.Add(new ContextError()
{
Severity = 0,
File = this.FileName,
Message = e.Message,
});
throw;
}
finally
{
sb.Release();
}
return crunched;
}
#endregion
#region CSS methods
#if !JSONLY
/// <summary>
/// MinifyJavaScript CSS string passed to it using default code minification settings.
/// The ErrorList property will be set with any errors found during the minification process.
/// </summary>
/// <param name="source">source Javascript</param>
/// <returns>minified Javascript</returns>
public string MinifyStyleSheet(string source)
{
// just pass in default settings
return MinifyStyleSheet(source, new CssSettings(), new CodeSettings());
}
/// <summary>
/// Minifies the CSS stylesheet passes to it using the given settings, returning the minified results
/// The ErrorList property will be set with any errors found during the minification process.
/// </summary>
/// <param name="source">CSS Source</param>
/// <param name="settings">CSS minification settings</param>
/// <returns>Minified StyleSheet</returns>
public string MinifyStyleSheet(string source, CssSettings settings)
{
// just pass in default settings
return MinifyStyleSheet(source, settings, new CodeSettings());
}
/// <summary>
/// Minifies the CSS stylesheet passes to it using the given settings, returning the minified results
/// The ErrorList property will be set with any errors found during the minification process.
/// </summary>
/// <param name="source">CSS Source</param>
/// <param name="settings">CSS minification settings</param>
/// <param name="scriptSettings">JS minification settings to use for expression-minification</param>
/// <returns>Minified StyleSheet</returns>
public string MinifyStyleSheet(string source, CssSettings settings, CodeSettings scriptSettings)
{
// initialize some values, including the error list (which shoudl start off empty)
string minifiedResults = string.Empty;
m_errorList = new List<ContextError>();
// create the parser object and if we specified some settings,
// use it to set the Parser's settings object
CssParser parser = new CssParser();
parser.FileContext = FileName;
if (settings != null)
{
parser.Settings = settings;
}
if (scriptSettings != null)
{
parser.JSSettings = scriptSettings;
}
// hook the error handler
parser.CssError += new EventHandler<ContextErrorEventArgs>(OnCssError);
// try parsing the source and return the results
try
{
minifiedResults = parser.Parse(source);
}
catch (Exception e)
{
m_errorList.Add(new ContextError()
{
Severity = 0,
File = this.FileName,
Message = e.Message,
});
throw;
}
return minifiedResults;
}
#endif
#endregion
#region Error-handling Members
#if !JSONLY
private void OnCssError(object sender, ContextErrorEventArgs e)
{
var error = e.Error;
if (error.Severity <= WarningLevel)
{
m_errorList.Add(error);
}
}
#endif
private void OnJavaScriptError(object sender, ContextErrorEventArgs e)
{
var error = e.Error;
if (error.Severity <= WarningLevel)
{
m_errorList.Add(error);
}
}
#endregion
}
}
| |
// Copyright(c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// 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 Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace triage.database
{
public static class TriageDb
{
private static string s_connStr;
public static void Init(string connStr)
{
s_connStr = connStr;
}
public static async Task<Dump> GetDumpAsync(int dumpId)
{
using (var context = new TriageDbContext(s_connStr))
{
return await context.Dumps.FindAsync(dumpId);
}
}
public static async Task<int> AddDumpAsync(Dump dump)
{
using (var context = new TriageDbContext(s_connStr))
{
context.Dumps.Add(dump);
await context.SaveChangesAsync();
}
return dump.DumpId;
}
public static async Task UpdateDumpTriageInfo(int dumpId, Dictionary<string, string> triageData)
{
await UpdateDumpTriageInfo(dumpId, TriageData.FromDictionary(triageData));
}
public static async Task UpdateDumpTriageInfo(int dumpId, TriageData triageData)
{
if (triageData == null) throw new ArgumentNullException("triageData");
Dump dump = null;
using (var context = new TriageDbContext(s_connStr))
{
//find the dump to update
dump = await context.Dumps.FindAsync(dumpId);
if (dump == null)
{
throw new ArgumentException($"Could not update dump. No dump was found with id {dumpId}", "dumpId");
}
await UpdateUniquelyNamedEntitiesAsync(context, triageData);
//if the bucket id is set on the triage data and it is different than the dump id
//update the bucket of the dump with the new triage data bucket
if (triageData.BucketId.HasValue && dump.BucketId != triageData.BucketId)
{
dump.Bucket = null;
dump.BucketId = triageData.BucketId;
}
//if the triage info contains the thread information delete the previous threads and frames
if (triageData.Threads.Count > 0)
{
//remove all the dump frames from the context before updating
//this is needed because frame has a required FK to dumpId so
//frames without an associated dump are not allowed
var frames = dump.Threads.SelectMany(t => t.Frames).ToArray();
context.Frames.RemoveRange(frames);
context.Threads.RemoveRange(dump.Threads);
dump.Threads.Clear();
//add the new threads to the dump
foreach(var t in triageData.Threads)
{
dump.Threads.Add(t);
}
}
//if there are more properties specified in the triage data
if(triageData.Properties.Count > 0)
{
//load the existing properties into a dictionary keyed by property name
var existingProps = dump.Properties.ToDictionary(p => p.Name);
//add or update the properties of the dump
foreach (var p in triageData.Properties)
{
//if a property with the same name already exists update it, otherwise add it
//NOTE: currently this only supports adding or updating properties. It's possible we will
// want to update this later on to support removing properties by passing null or empty
// string as the value
if (existingProps.ContainsKey(p.Name))
{
existingProps[p.Name].Value = p.Value;
}
else
{
dump.Properties.Add(p);
}
}
}
await context.SaveChangesAsync();
}
}
private static async Task UpdateUniquelyNamedEntitiesAsync(TriageDbContext context, TriageData triageData)
{
//add or update the bucket if it exists
if (triageData.Bucket != null && triageData.Bucket.BucketId == 0)
{
triageData.Bucket = await GetUniquelyNamedEntityAsync(context, context.Buckets, triageData.Bucket);
}
var addedModules = triageData.Threads.Where(t => t.ThreadId == 0).SelectMany(t => t.Frames).Select(f => f.Module).Where(m => m.ModuleId == 0).OrderBy(m => m.Name).ToArray();
for (int i = 0; i < addedModules.Length; i++)
{
if (i > 0 && addedModules[i].Name == addedModules[i - 1].Name)
{
addedModules[i].ModuleId = addedModules[i - 1].ModuleId;
}
else
{
addedModules[i].ModuleId = (await GetUniquelyNamedEntityAsync(context, context.Modules, addedModules[i])).ModuleId;
}
}
var addedRoutines = triageData.Threads.Where(t => t.ThreadId == 0).SelectMany(t => t.Frames).Select(f => f.Routine).Where(r => r.RoutineId == 0).OrderBy(r => r.Name).ToArray();
for (int i = 0; i < addedRoutines.Length; i++)
{
if (i > 0 && addedRoutines[i].Name == addedRoutines[i - 1].Name)
{
addedRoutines[i].RoutineId = addedRoutines[i - 1].RoutineId;
}
else
{
addedRoutines[i].RoutineId = (await GetUniquelyNamedEntityAsync(context, context.Routines, addedRoutines[i])).RoutineId;
}
}
foreach (var frame in triageData.Threads.SelectMany(t => t.Frames))
{
frame.ModuleId = frame.Module.ModuleId;
frame.Module = null;
frame.RoutineId = frame.Routine.RoutineId;
frame.Routine = null;
}
}
private static async Task<T> GetUniquelyNamedEntityAsync<T>(TriageDbContext context, IDbSet<T> set, T entity) where T : UniquelyNamedEntity
{
if (entity.Name.Length > 450)
{
entity.Name = entity.Name.Substring(0, 450);
}
T tempEntity = await set.FirstOrDefaultAsync(e => e.Name == entity.Name);
if (tempEntity != null)
{
return tempEntity;
}
set.Add(entity);
await context.SaveChangesAsync();
return entity;
}
private const string BUCKET_DATA_QUERY = @"
WITH [BucketHits]([BucketId], [HitCount], [StartTime], [EndTime]) AS
(
SELECT [B].[BucketId] AS [BucketId], COUNT([D].[DumpId]) AS [HitCount], @p0 AS [StartTime], @p1 AS [EndTime]
FROM [Dumps] [D]
JOIN [Buckets] [B]
ON [D].[BucketId] = [B].[BucketId]
AND [D].[DumpTime] >= @p0
AND [D].[DumpTime] <= @p1
GROUP BY [B].[BucketId]
)
SELECT [B].[BucketId], [B].[Name], [B].[BugUrl], [H].[HitCount], [H].[StartTime], [H].[EndTime]
FROM [Buckets] AS [B]
JOIN [BucketHits] AS [H]
ON [B].[BucketId] = [H].[BucketId]
ORDER BY [H].[HitCount] DESC
";
public static async Task<IEnumerable<BucketData>> GetBucketDataAsync(DateTime start, DateTime end)
{
using (var context = new TriageDbContext(s_connStr))
{
var data = context.Database.SqlQuery<BucketData>(BUCKET_DATA_QUERY, start, end);
var returnValue = await data.ToArrayAsync();
return returnValue;
}
}
private const string BUCKET_DATA_DUMPS_QUERY = @"
SELECT *
FROM [Dumps]
WHERE [BucketId] = @p0
AND [DumpTime] >= @p1
AND [DumpTime] <= @p2
ORDER BY [Dumps].[DumpId] DESC
";
public static async Task<IEnumerable<Dump>> GetBucketDataDumpsAsync(BucketData bucketData)
{
using (var context = new TriageDbContext(s_connStr))
{
return await context.Dumps.SqlQuery(BUCKET_DATA_DUMPS_QUERY, bucketData.BucketId, bucketData.StartTime, bucketData.EndTime).ToArrayAsync();
}
}
private const string PROPERTIES_QUERY = @"
SELECT *
FROM [Properties]
WHERE [DumpId] = @p0
";
public static string GetPropertiesAsJsonAsync(Dump dump)
{
using (var context = new TriageDbContext(s_connStr))
{
var data = from property in context.Properties.Where(x => x.DumpId == dump.DumpId)
select new
{
DumpId = property.DumpId,
Name = property.Name,
Value = property.Value
};
return JsonConvert.SerializeObject(data);
}
}
}
}
| |
using UnityEngine;
namespace NGUI.Internal
{
public static class NGUIMath
{
public static Vector3 ApplyHalfPixelOffset(Vector3 pos)
{
switch (Application.platform)
{
case RuntimePlatform.WindowsPlayer:
case RuntimePlatform.WindowsWebPlayer:
case RuntimePlatform.WindowsEditor:
case RuntimePlatform.XBOX360:
pos.x -= 0.5f;
pos.y += 0.5f;
break;
}
return pos;
}
public static Vector3 ApplyHalfPixelOffset(Vector3 pos, Vector3 scale)
{
switch (Application.platform)
{
case RuntimePlatform.WindowsPlayer:
case RuntimePlatform.WindowsWebPlayer:
case RuntimePlatform.WindowsEditor:
case RuntimePlatform.XBOX360:
if (Mathf.RoundToInt(scale.x) == Mathf.RoundToInt(scale.x * 0.5f) * 2)
{
pos.x -= 0.5f;
}
if (Mathf.RoundToInt(scale.y) == Mathf.RoundToInt(scale.y * 0.5f) * 2)
{
pos.y += 0.5f;
}
break;
}
return pos;
}
public static Bounds CalculateAbsoluteWidgetBounds(Transform trans)
{
UIWidget[] componentsInChildren = trans.GetComponentsInChildren<UIWidget>();
if (componentsInChildren.Length == 0)
{
return new Bounds(trans.position, Vector3.zero);
}
Vector3 rhs = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3 vector2 = new Vector3(float.MinValue, float.MinValue, float.MinValue);
int index = 0;
int length = componentsInChildren.Length;
while (index < length)
{
UIWidget widget = componentsInChildren[index];
Vector2 relativeSize = widget.relativeSize;
Vector2 pivotOffset = widget.pivotOffset;
float num3 = (pivotOffset.x + 0.5f) * relativeSize.x;
float num4 = (pivotOffset.y - 0.5f) * relativeSize.y;
relativeSize = relativeSize * 0.5f;
Transform cachedTransform = widget.cachedTransform;
Vector3 lhs = cachedTransform.TransformPoint(new Vector3(num3 - relativeSize.x, num4 - relativeSize.y, 0f));
vector2 = Vector3.Max(lhs, vector2);
rhs = Vector3.Min(lhs, rhs);
lhs = cachedTransform.TransformPoint(new Vector3(num3 - relativeSize.x, num4 + relativeSize.y, 0f));
vector2 = Vector3.Max(lhs, vector2);
rhs = Vector3.Min(lhs, rhs);
lhs = cachedTransform.TransformPoint(new Vector3(num3 + relativeSize.x, num4 - relativeSize.y, 0f));
vector2 = Vector3.Max(lhs, vector2);
rhs = Vector3.Min(lhs, rhs);
lhs = cachedTransform.TransformPoint(new Vector3(num3 + relativeSize.x, num4 + relativeSize.y, 0f));
vector2 = Vector3.Max(lhs, vector2);
rhs = Vector3.Min(lhs, rhs);
index++;
}
Bounds bounds = new Bounds(rhs, Vector3.zero);
bounds.Encapsulate(vector2);
return bounds;
}
public static Bounds CalculateRelativeInnerBounds(Transform root, UISprite sprite)
{
if (sprite.type != UISprite.Type.Sliced)
{
return CalculateRelativeWidgetBounds(root, sprite.cachedTransform);
}
Matrix4x4 worldToLocalMatrix = root.worldToLocalMatrix;
Vector2 relativeSize = sprite.relativeSize;
Vector2 pivotOffset = sprite.pivotOffset;
Transform cachedTransform = sprite.cachedTransform;
float num = (pivotOffset.x + 0.5f) * relativeSize.x;
float num2 = (pivotOffset.y - 0.5f) * relativeSize.y;
relativeSize = relativeSize * 0.5f;
float x = cachedTransform.localScale.x;
float y = cachedTransform.localScale.y;
Vector4 border = sprite.border;
if (x != 0f)
{
border.x /= x;
border.z /= x;
}
if (y != 0f)
{
border.y /= y;
border.w /= y;
}
float num5 = num - relativeSize.x + border.x;
float num6 = num + relativeSize.x - border.z;
float num7 = num2 - relativeSize.y + border.y;
float num8 = num2 + relativeSize.y - border.w;
Vector3 position = new Vector3(num5, num7, 0f);
position = cachedTransform.TransformPoint(position);
position = worldToLocalMatrix.MultiplyPoint3x4(position);
Bounds bounds = new Bounds(position, Vector3.zero);
position = new Vector3(num5, num8, 0f);
position = cachedTransform.TransformPoint(position);
position = worldToLocalMatrix.MultiplyPoint3x4(position);
bounds.Encapsulate(position);
position = new Vector3(num6, num8, 0f);
position = cachedTransform.TransformPoint(position);
position = worldToLocalMatrix.MultiplyPoint3x4(position);
bounds.Encapsulate(position);
position = new Vector3(num6, num7, 0f);
position = cachedTransform.TransformPoint(position);
position = worldToLocalMatrix.MultiplyPoint3x4(position);
bounds.Encapsulate(position);
return bounds;
}
public static Bounds CalculateRelativeWidgetBounds(Transform trans)
{
return CalculateRelativeWidgetBounds(trans, trans);
}
public static Bounds CalculateRelativeWidgetBounds(Transform root, Transform child)
{
UIWidget[] componentsInChildren = child.GetComponentsInChildren<UIWidget>();
if (componentsInChildren.Length == 0)
{
return new Bounds(Vector3.zero, Vector3.zero);
}
Vector3 rhs = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3 vector2 = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Matrix4x4 worldToLocalMatrix = root.worldToLocalMatrix;
int index = 0;
int length = componentsInChildren.Length;
while (index < length)
{
UIWidget widget = componentsInChildren[index];
Vector2 relativeSize = widget.relativeSize;
Vector2 pivotOffset = widget.pivotOffset;
Transform cachedTransform = widget.cachedTransform;
float num3 = (pivotOffset.x + 0.5f) * relativeSize.x;
float num4 = (pivotOffset.y - 0.5f) * relativeSize.y;
relativeSize = relativeSize * 0.5f;
Vector3 position = new Vector3(num3 - relativeSize.x, num4 - relativeSize.y, 0f);
position = cachedTransform.TransformPoint(position);
position = worldToLocalMatrix.MultiplyPoint3x4(position);
vector2 = Vector3.Max(position, vector2);
rhs = Vector3.Min(position, rhs);
position = new Vector3(num3 - relativeSize.x, num4 + relativeSize.y, 0f);
position = cachedTransform.TransformPoint(position);
position = worldToLocalMatrix.MultiplyPoint3x4(position);
vector2 = Vector3.Max(position, vector2);
rhs = Vector3.Min(position, rhs);
position = new Vector3(num3 + relativeSize.x, num4 - relativeSize.y, 0f);
position = cachedTransform.TransformPoint(position);
position = worldToLocalMatrix.MultiplyPoint3x4(position);
vector2 = Vector3.Max(position, vector2);
rhs = Vector3.Min(position, rhs);
position = new Vector3(num3 + relativeSize.x, num4 + relativeSize.y, 0f);
position = cachedTransform.TransformPoint(position);
position = worldToLocalMatrix.MultiplyPoint3x4(position);
vector2 = Vector3.Max(position, vector2);
rhs = Vector3.Min(position, rhs);
index++;
}
Bounds bounds = new Bounds(rhs, Vector3.zero);
bounds.Encapsulate(vector2);
return bounds;
}
public static Vector3[] CalculateWidgetCorners(UIWidget w)
{
Vector2 relativeSize = w.relativeSize;
Vector2 pivotOffset = w.pivotOffset;
Vector4 relativePadding = w.relativePadding;
float x = pivotOffset.x * relativeSize.x - relativePadding.x;
float y = pivotOffset.y * relativeSize.y + relativePadding.y;
float num3 = x + relativeSize.x + relativePadding.x + relativePadding.z;
float num4 = y - relativeSize.y - relativePadding.y - relativePadding.w;
Transform cachedTransform = w.cachedTransform;
return new[] { cachedTransform.TransformPoint(x, y, 0f), cachedTransform.TransformPoint(x, num4, 0f), cachedTransform.TransformPoint(num3, num4, 0f), cachedTransform.TransformPoint(num3, y, 0f) };
}
public static int ColorToInt(Color c)
{
int num = 0;
num |= Mathf.RoundToInt(c.r * 255f) << 24;
num |= Mathf.RoundToInt(c.g * 255f) << 16;
num |= Mathf.RoundToInt(c.b * 255f) << 8;
return num | Mathf.RoundToInt(c.a * 255f);
}
public static Vector2 ConstrainRect(Vector2 minRect, Vector2 maxRect, Vector2 minArea, Vector2 maxArea)
{
Vector2 zero = Vector2.zero;
float num = maxRect.x - minRect.x;
float num2 = maxRect.y - minRect.y;
float num3 = maxArea.x - minArea.x;
float num4 = maxArea.y - minArea.y;
if (num > num3)
{
float num5 = num - num3;
minArea.x -= num5;
maxArea.x += num5;
}
if (num2 > num4)
{
float num6 = num2 - num4;
minArea.y -= num6;
maxArea.y += num6;
}
if (minRect.x < minArea.x)
{
zero.x += minArea.x - minRect.x;
}
if (maxRect.x > maxArea.x)
{
zero.x -= maxRect.x - maxArea.x;
}
if (minRect.y < minArea.y)
{
zero.y += minArea.y - minRect.y;
}
if (maxRect.y > maxArea.y)
{
zero.y -= maxRect.y - maxArea.y;
}
return zero;
}
public static Rect ConvertToPixels(Rect rect, int width, int height, bool round)
{
Rect rect2 = rect;
if (round)
{
rect2.xMin = Mathf.RoundToInt(rect.xMin * width);
rect2.xMax = Mathf.RoundToInt(rect.xMax * width);
rect2.yMin = Mathf.RoundToInt((1f - rect.yMax) * height);
rect2.yMax = Mathf.RoundToInt((1f - rect.yMin) * height);
return rect2;
}
rect2.xMin = rect.xMin * width;
rect2.xMax = rect.xMax * width;
rect2.yMin = (1f - rect.yMax) * height;
rect2.yMax = (1f - rect.yMin) * height;
return rect2;
}
public static Rect ConvertToTexCoords(Rect rect, int width, int height)
{
Rect rect2 = rect;
if (width != 0f && height != 0f)
{
rect2.xMin = rect.xMin / width;
rect2.xMax = rect.xMax / width;
rect2.yMin = 1f - rect.yMax / height;
rect2.yMax = 1f - rect.yMin / height;
}
return rect2;
}
/// <summary>
/// Converts <paramref name="num"/> to a <b>six-digit</b> hexadecimal number
/// </summary>
/// <param name="num">The number to convert</param>
/// <returns>The six-digit hexadecimal number representation of <paramref name="num"/></returns>
public static string DecimalToHex(int num)
{
num &= 16777215;
return num.ToString("X6");
}
private static float DistancePointToLineSegment(Vector2 point, Vector2 a, Vector2 b)
{
Vector2 vector = b - a;
float sqrMagnitude = vector.sqrMagnitude;
if (sqrMagnitude == 0f)
{
Vector2 vector2 = point - a;
return vector2.magnitude;
}
float num2 = Vector2.Dot(point - a, b - a) / sqrMagnitude;
if (num2 < 0f)
{
Vector2 vector3 = point - a;
return vector3.magnitude;
}
if (num2 > 1f)
{
Vector2 vector4 = point - b;
return vector4.magnitude;
}
Vector2 vector5 = a + num2 * (b - a);
Vector2 vector6 = point - vector5;
return vector6.magnitude;
}
public static float DistanceToRectangle(Vector2[] screenPoints, Vector2 mousePos)//unsafe
{
bool flag = false;
int val = 4;
for (int i = 0; i < 5; i++)
{
Vector3 vector = screenPoints[RepeatIndex(i, 4)];
Vector3 vector2 = screenPoints[RepeatIndex(val, 4)];
if (vector.y > mousePos.y != vector2.y > mousePos.y && mousePos.x < (vector2.x - vector.x) * (mousePos.y - vector.y) / (vector2.y - vector.y) + vector.x)
{
flag = !flag;
}
val = i;
}
if (flag)
{
return 0f;
}
float num3 = -1f;
for (int j = 0; j < 4; j++)
{
Vector3 a = screenPoints[j];
Vector3 b = screenPoints[RepeatIndex(j + 1, 4)];
float num5 = DistancePointToLineSegment(mousePos, a, b);
if (num5 < num3 || num3 < 0f)
{
num3 = num5;
}
}
return num3;
}
public static float DistanceToRectangle(Vector3[] worldPoints, Vector2 mousePos, Camera cam)
{
Vector2[] screenPoints = new Vector2[4];
for (int i = 0; i < 4; i++)
{
screenPoints[i] = cam.WorldToScreenPoint(worldPoints[i]);
}
return DistanceToRectangle(screenPoints, mousePos);
}
public static Color HexToColor(uint val)
{
return IntToColor((int)val);
}
public static int HexToDecimal(char c)
{
int value = c;
// Return value if less than 10
if (value >= '0' && value <= '9')
return value - '0';
// Return HexValue
if (value >= 'a' && value <= 'f')
return 10 + value - 'a';
// Return HexValue
if (value >= 'A' && value <= 'F')
return 10 + value - 'A';
// c is not an hexadecimal number
return 15;
}
public static string IntToBinary(int val, int bits)
{
string str = string.Empty;
int num = bits;
while (num > 0)
{
switch (num)
{
case 8:
case 16:
case 24:
str = str + " ";
break;
}
str = str + ((val & 1 << --num) == 0 ? '0' : '1');
}
return str;
}
public static Color IntToColor(int val)
{
float num = 0.003921569f;
Color black = Color.black;
black.r = num * ((val >> 24) & 255);
black.g = num * ((val >> 16) & 255);
black.b = num * ((val >> 8) & 255);
black.a = num * (val & 255);
return black;
}
public static float Lerp(float from, float to, float factor)
{
return @from * (1f - factor) + to * factor;
}
public static Rect MakePixelPerfect(Rect rect)
{
rect.xMin = Mathf.RoundToInt(rect.xMin);
rect.yMin = Mathf.RoundToInt(rect.yMin);
rect.xMax = Mathf.RoundToInt(rect.xMax);
rect.yMax = Mathf.RoundToInt(rect.yMax);
return rect;
}
public static Rect MakePixelPerfect(Rect rect, int width, int height)
{
rect = ConvertToPixels(rect, width, height, true);
rect.xMin = Mathf.RoundToInt(rect.xMin);
rect.yMin = Mathf.RoundToInt(rect.yMin);
rect.xMax = Mathf.RoundToInt(rect.xMax);
rect.yMax = Mathf.RoundToInt(rect.yMax);
return ConvertToTexCoords(rect, width, height);
}
public static int RepeatIndex(int val, int max)
{
if (max < 1)
{
return 0;
}
while (val < 0)
{
val += max;
}
while (val >= max)
{
val -= max;
}
return val;
}
public static float RotateTowards(float from, float to, float maxAngle)
{
float f = WrapAngle(to - from);
if (Mathf.Abs(f) > maxAngle)
{
f = maxAngle * Mathf.Sign(f);
}
return @from + f;
}
public static Vector2 SpringDampen(ref Vector2 velocity, float strength, float deltaTime)
{
if (deltaTime > 1f)
{
deltaTime = 1f;
}
float num = 1f - strength * 0.001f;
int num2 = Mathf.RoundToInt(deltaTime * 1000f);
Vector2 zero = Vector2.zero;
for (int i = 0; i < num2; i++)
{
zero += velocity * 0.06f;
velocity = velocity * num;
}
return zero;
}
public static Vector3 SpringDampen(ref Vector3 velocity, float strength, float deltaTime)
{
if (deltaTime > 1f)
{
deltaTime = 1f;
}
float num = 1f - strength * 0.001f;
int num2 = Mathf.RoundToInt(deltaTime * 1000f);
Vector3 zero = Vector3.zero;
for (int i = 0; i < num2; i++)
{
zero += velocity * 0.06f;
velocity = velocity * num;
}
return zero;
}
public static float SpringLerp(float strength, float deltaTime)
{
if (deltaTime > 1f)
{
deltaTime = 1f;
}
int num = Mathf.RoundToInt(deltaTime * 1000f);
deltaTime = 0.001f * strength;
float from = 0f;
for (int i = 0; i < num; i++)
{
from = Mathf.Lerp(from, 1f, deltaTime);
}
return from;
}
public static float SpringLerp(float from, float to, float strength, float deltaTime)
{
if (deltaTime > 1f)
{
deltaTime = 1f;
}
int num = Mathf.RoundToInt(deltaTime * 1000f);
deltaTime = 0.001f * strength;
for (int i = 0; i < num; i++)
{
from = Mathf.Lerp(from, to, deltaTime);
}
return from;
}
public static Quaternion SpringLerp(Quaternion from, Quaternion to, float strength, float deltaTime)
{
return Quaternion.Slerp(from, to, SpringLerp(strength, deltaTime));
}
public static Vector2 SpringLerp(Vector2 from, Vector2 to, float strength, float deltaTime)
{
return Vector2.Lerp(from, to, SpringLerp(strength, deltaTime));
}
public static Vector3 SpringLerp(Vector3 from, Vector3 to, float strength, float deltaTime)
{
return Vector3.Lerp(from, to, SpringLerp(strength, deltaTime));
}
public static float Wrap01(float val)
{
return val - Mathf.FloorToInt(val);
}
public static float WrapAngle(float angle)
{
while (angle > 180f)
{
angle -= 360f;
}
while (angle < -180f)
{
angle += 360f;
}
return angle;
}
}
}
| |
// codesettings.cs
//
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace Baker.Text
{
/// <summary>
/// Settings for how local variables and functions can be renamed
/// </summary>
public enum JsLocalRenaming
{
/// <summary>
/// Keep all names; don't rename anything
/// </summary>
KeepAll,
/// <summary>
/// Rename all local variables and functions that do not begin with "L_"
/// </summary>
KeepLocalizationVars,
/// <summary>
/// Rename all local variables and functions. (default)
/// </summary>
CrunchAll
}
/// <summary>
/// Settings for how to treat eval statements
/// </summary>
public enum JsEvalTreatment
{
/// <summary>
/// Ignore all eval statements (default). This assumes that code that is eval'd will not attempt
/// to access any local variables or functions, as those variables and function may be renamed.
/// </summary>
Ignore = 0,
/// <summary>
/// Assume any code that is eval'd will attempt to access local variables and functions declared
/// in the same scope as the eval statement. This will turn off local variable and function renaming
/// in any scope that contains an eval statement.
/// </summary>
MakeImmediateSafe,
/// <summary>
/// Assume that any local variable or function in any accessible scope chain may be referenced by
/// code that is eval'd. This will turn off local variable and function renaming for all scopes that
/// contain an eval statement, and all their parent scopes up the chain to the global scope.
/// </summary>
MakeAllSafe
}
/// <summary>
/// Enum describing the type of input expected
/// </summary>
public enum JsSourceMode
{
/// <summary>Default input mode: a program, a block of top-level global statements</summary>
Program = 0,
/// <summary>Input is a single JavaScript Expression</summary>
Expression,
/// <summary>Input is an implicit function block, as in the value of an HTML onclick attribute</summary>
EventHandler
}
/// <summary>
/// Enum describing how to treat the output JavaScript
/// </summary>
public enum JsFormat
{
/// <summary>normal JavaScript code</summary>
Normal = 0,
/// <summary>JSON code</summary>
JSON
}
/// <summary>
/// Object used to store code settings for JavaScript parsing, minification, and output
/// </summary>
public class JsSettings : MinifierSettings
{
#region private fields
private bool m_minify;
#endregion
/// <summary>
/// Instantiate a CodeSettings object with the default settings
/// </summary>
public JsSettings()
{
// setting this property sets other fields as well
this.MinifyCode = true;
// other fields we want initialized
this.EvalTreatment = JsEvalTreatment.Ignore;
this.InlineSafeStrings = true;
this.MacSafariQuirks = true;
this.PreserveImportantComments = true;
this.QuoteObjectLiteralProperties = false;
this.StrictMode = false;
this.StripDebugStatements = true;
this.ManualRenamesProperties = true;
this.OutputMode = MinifierOutputMode.SingleLine;
// no default globals
this.m_knownGlobals = new HashSet<string>();
// by default there are five names in the debug lookup collection
var initialList = new string[] { "Debug", "$Debug", "WAssert", "Msn.Debug", "Web.Debug" };
this.m_debugLookups = new HashSet<string>(initialList);
// by default, let's NOT rename $super, so we don't break the Prototype library.
// going to try to come up with a better solution, so this is just a stop-gap for now.
this.m_noRenameSet = new HashSet<string>(new string[] { "$super" });
// nothing renamed by default
this.m_identifierReplacementMap = new Dictionary<string, string>();
}
/// <summary>
/// Instantiate a new CodeSettings object with the same settings as the current object.
/// </summary>
/// <returns>a copy CodeSettings object</returns>
public JsSettings Clone()
{
// create a new settings object and set all the properties using this settings object
var newSettings = new JsSettings()
{
// set the field, not the property. Setting the property will set a bunch of
// other properties, which may not represent their actual values.
m_minify = this.m_minify,
AllowEmbeddedAspNetBlocks = this.AllowEmbeddedAspNetBlocks,
AlwaysEscapeNonAscii = this.AlwaysEscapeNonAscii,
CollapseToLiteral = this.CollapseToLiteral,
ConstStatementsMozilla = this.ConstStatementsMozilla,
DebugLookupList = this.DebugLookupList,
EvalLiteralExpressions = this.EvalLiteralExpressions,
EvalTreatment = this.EvalTreatment,
Format = this.Format,
IgnoreConditionalCompilation = this.IgnoreConditionalCompilation,
IgnoreAllErrors = this.IgnoreAllErrors,
IgnoreErrorList = this.IgnoreErrorList,
IgnorePreprocessorDefines = this.IgnorePreprocessorDefines,
IndentSize = this.IndentSize,
InlineSafeStrings = this.InlineSafeStrings,
KillSwitch = this.KillSwitch,
KnownGlobalNamesList = this.KnownGlobalNamesList,
LineBreakThreshold = this.LineBreakThreshold,
LocalRenaming = this.LocalRenaming,
MacSafariQuirks = this.MacSafariQuirks,
ManualRenamesProperties = this.ManualRenamesProperties,
NoAutoRenameList = this.NoAutoRenameList,
OutputMode = this.OutputMode,
PreprocessOnly = this.PreprocessOnly,
PreprocessorDefineList = this.PreprocessorDefineList,
PreserveFunctionNames = this.PreserveFunctionNames,
PreserveImportantComments = this.PreserveImportantComments,
QuoteObjectLiteralProperties = this.QuoteObjectLiteralProperties,
RemoveFunctionExpressionNames = this.RemoveFunctionExpressionNames,
RemoveUnneededCode = this.RemoveUnneededCode,
RenamePairs = this.RenamePairs,
ReorderScopeDeclarations = this.ReorderScopeDeclarations,
SourceMode = this.SourceMode,
StrictMode = this.StrictMode,
StripDebugStatements = this.StripDebugStatements,
TermSemicolons = this.TermSemicolons,
BlocksStartOnSameLine = this.BlocksStartOnSameLine,
ErrorIfNotInlineSafe = this.ErrorIfNotInlineSafe,
SymbolsMap = this.SymbolsMap,
};
// set the resource strings if there are any
newSettings.AddResourceStrings(this.ResourceStrings);
return newSettings;
}
#region Manually rename
/// <summary>
/// dictionary of identifiers we want to manually rename
/// </summary>
private Dictionary<string, string> m_identifierReplacementMap;
/// <summary>
/// Add a rename pair to the identifier rename map
/// </summary>
/// <param name="sourceName">name of the identifier in the source code</param>
/// <param name="newName">new name with which to replace the source name</param>
/// <returns>true if added; false if either name is not a valid JavaScript identifier</returns>
public bool AddRenamePair(string sourceName, string newName)
{
bool successfullyAdded = false;
// both names MUST be valid JavaScript identifiers
if (JsScanner.IsValidIdentifier(sourceName) && JsScanner.IsValidIdentifier(newName))
{
if (m_identifierReplacementMap.ContainsKey(sourceName))
{
// just replace the value
m_identifierReplacementMap[sourceName] = newName;
}
else
{
// add the new pair
m_identifierReplacementMap.Add(sourceName, newName);
}
// if we get here, we added it (or updated it if it's a dupe)
successfullyAdded = true;
}
return successfullyAdded;
}
/// <summary>
/// Clear any rename pairs from the identifier rename map
/// </summary>
public void ClearRenamePairs()
{
m_identifierReplacementMap.Clear();
}
/// <summary>
/// returns whether or not there are any rename pairs in this settings object
/// </summary>
public bool HasRenamePairs
{
get
{
return m_identifierReplacementMap.Count > 0;
}
}
/// <summary>
/// Given a source identifier, return a new name for it, if one has already been added
/// </summary>
/// <param name="sourceName">source name to check</param>
/// <returns>new name if it exists, null otherwise</returns>
public string GetNewName(string sourceName)
{
string newName;
if (!m_identifierReplacementMap.TryGetValue(sourceName, out newName))
{
newName = null;
}
return newName;
}
/// <summary>
/// Gets or sets a string representation of all the indentifier replacements as a comma-separated
/// list of "source=target" identifiers.
/// </summary>
public string RenamePairs
{
get
{
StringBuilder sb = new StringBuilder();
foreach (var entry in m_identifierReplacementMap)
{
if (sb.Length > 0)
{
sb.Append(',');
}
sb.Append(entry.Key);
sb.Append('=');
sb.Append(entry.Value);
}
return sb.ToString();
}
set
{
if (!string.IsNullOrEmpty(value))
{
// pairs are comma-separated
foreach (var pair in value.Split(',', ';'))
{
// source name and new name are separated by an equal sign
var parts = pair.Split('=');
// must be exactly one equal sign
if (parts.Length == 2)
{
// try adding the trimmed pair to the collection
AddRenamePair(parts[0].Trim(), parts[1].Trim());
}
}
}
else
{
m_identifierReplacementMap.Clear();
}
}
}
#endregion
#region No automatic rename
private HashSet<string> m_noRenameSet;
/// <summary>
/// read-only collection of identifiers we do not want renamed
/// </summary>
[Obsolete("This property is deprecated; use NoAutoRenameCollection instead")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ReadOnlyCollection<string> NoAutoRenameIdentifiers
{
get
{
return new ReadOnlyCollection<string>(new List<string>(NoAutoRenameCollection));
}
}
/// <summary>
/// sets the collection of known global names to the array of string passed to this method
/// </summary>
/// <param name="noRenameNames">Array of names to exclude from renaming process.</param>
[Obsolete("This property is deprecated; use SetnoAutoRenames instead")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int SetNoAutoRename(params string[] noRenameNames)
{
return SetNoAutoRenames(noRenameNames);
}
/// <summary>
/// Gets the list of excluded identifiers from auto-renaming process.
/// </summary>
public IEnumerable<string> NoAutoRenameCollection { get { return m_noRenameSet; } }
/// <summary>
/// sets the collection of known global names to the enumeration of strings passed to this method
/// </summary>
/// <param name="noRenameNames">Array of names to exclude from renaming process.</param>
public int SetNoAutoRenames(IEnumerable<string> noRenameNames)
{
m_noRenameSet.Clear();
if (noRenameNames != null)
{
// validate that each name in the array is a valid JS identifier
foreach (var name in noRenameNames)
{
AddNoAutoRename(name);
}
}
return m_noRenameSet.Count;
}
/// <summary>
/// Adds an identifier to the auto-rename exclusion list.
/// </summary>
/// <param name="noRename">The identifier to avoid renaming.</param>
/// <returns>Whether it was added or not.</returns>
public bool AddNoAutoRename(string noRename)
{
if (!JsScanner.IsValidIdentifier(noRename))
{
return false;
}
m_noRenameSet.Add(noRename);
return true;
}
/// <summary>
/// Get or sets the no-automatic-renaming list as a single string of comma-separated identifiers
/// </summary>
public string NoAutoRenameList
{
get
{
StringBuilder sb = new StringBuilder();
foreach (var noRename in m_noRenameSet)
{
if (sb.Length > 0)
{
sb.Append(',');
}
sb.Append(noRename);
}
return sb.ToString();
}
set
{
if (!string.IsNullOrEmpty(value))
{
foreach (var noRename in value.Split(',', ';'))
{
AddNoAutoRename(noRename);
}
}
else
{
m_noRenameSet.Clear();
}
}
}
#endregion
#region known globals
private HashSet<string> m_knownGlobals;
/// <summary>
/// read-only collection of known global names
/// </summary>
[Obsolete("This property is deprecated; use KnownGlobalsCollection instead")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ReadOnlyCollection<string> KnownGlobalNames
{
get
{
return new ReadOnlyCollection<string>(new List<string>(KnownGlobalCollection));
}
}
/// <summary>
/// sets the collection of known global names to the array of string passed to this method
/// </summary>
/// <param name="globalArray">array of known global names</param>
[Obsolete("This property is deprecated; use SetKnownGlobalIdentifiers instead")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int SetKnownGlobalNames(params string[] globalArray)
{
return SetKnownGlobalIdentifiers(globalArray);
}
/// <summary>
/// Gets the known global name collection
/// </summary>
public IEnumerable<string> KnownGlobalCollection { get { return m_knownGlobals; } }
/// <summary>
/// sets the collection of known global names to the array of string passed to this method
/// </summary>
/// <param name="globalArray">collection of known global names</param>
public int SetKnownGlobalIdentifiers(IEnumerable<string> globalArray)
{
m_knownGlobals.Clear();
if (globalArray != null)
{
foreach (var name in globalArray)
{
AddKnownGlobal(name);
}
}
return m_knownGlobals.Count;
}
/// <summary>
/// Add a known global identifier to the list
/// </summary>
/// <param name="identifier">global identifier</param>
/// <returns>true if valid identifier; false if invalid identifier</returns>
public bool AddKnownGlobal(string identifier)
{
if (JsScanner.IsValidIdentifier(identifier))
{
m_knownGlobals.Add(identifier);
return true;
}
return false;
}
/// <summary>
/// Gets or sets the known global names list as a single comma-separated string
/// </summary>
public string KnownGlobalNamesList
{
get
{
StringBuilder sb = new StringBuilder();
foreach (var knownGlobal in m_knownGlobals)
{
if (sb.Length > 0)
{
sb.Append(',');
}
sb.Append(knownGlobal);
}
return sb.ToString();
}
set
{
if (!string.IsNullOrEmpty(value))
{
foreach (var knownGlobal in value.Split(',', ';'))
{
AddKnownGlobal(knownGlobal);
}
}
else
{
m_knownGlobals.Clear();
}
}
}
#endregion
#region Debug lookups
private HashSet<string> m_debugLookups;
/// <summary>
/// Collection of "debug" lookup identifiers
/// </summary>
[Obsolete("This property is deprecated; use DebugLookupCollection instead")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ReadOnlyCollection<string> DebugLookups
{
get
{
return new ReadOnlyCollection<string>(new List<string>(DebugLookupCollection));
}
}
/// <summary>
/// Gets the set of debug lookups
/// </summary>
public IEnumerable<string> DebugLookupCollection { get { return m_debugLookups; } }
/// <summary>
/// Set the collection of debug "lookup" identifiers
/// </summary>
/// <param name="debugLookups">array of debug lookup identifier strings</param>
/// <returns>number of names successfully added to the collection</returns>
[Obsolete("This property is deprecated; use SetDebugNamespaces instead")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int SetDebugLookups(params string[] debugLookups)
{
return SetDebugNamespaces(debugLookups);
}
/// <summary>
/// Set the collection of debug "lookup" identifiers
/// </summary>
/// <param name="debugLookups">collection of debug lookup identifier strings</param>
/// <returns>number of names successfully added to the collection</returns>
public int SetDebugNamespaces(IEnumerable<string> debugLookups)
{
m_debugLookups.Clear();
if (debugLookups != null)
{
// validate that each name in the array is a valid JS identifier
foreach (var lookup in debugLookups)
{
AddDebugLookup(lookup);
}
}
return m_debugLookups.Count;
}
/// <summary>
/// Adds a debug lookup namespace to this settings object.
/// </summary>
/// <param name="debugNamespace">The debug namespace to add.</param>
/// <returns>Whether it was added or not.</returns>
public bool AddDebugLookup(string debugNamespace)
{
// a blank identifier is okay -- we just ignore it
if (!string.IsNullOrEmpty(debugNamespace))
{
// but if it's not blank, it better be a valid JavaScript identifier or member chain
if (debugNamespace.IndexOf('.') > 0)
{
// it's a member chain -- check that each part is a valid JS identifier
var names = debugNamespace.Split('.');
foreach (var name in names)
{
if (!JsScanner.IsValidIdentifier(name))
{
return false;
}
}
}
else
{
// no dot -- just an identifier
if (!JsScanner.IsValidIdentifier(debugNamespace))
{
return false;
}
}
m_debugLookups.Add(debugNamespace);
return true;
}
return false;
}
/// <summary>
/// string representation of the list of debug lookups, comma-separated
/// </summary>
public string DebugLookupList
{
get
{
// createa string builder and add each of the debug lookups to it
// one-by-one, separating them with a comma
var sb = new StringBuilder();
foreach (var debugLookup in m_debugLookups)
{
if (sb.Length > 0)
{
sb.Append(',');
}
sb.Append(debugLookup);
}
return sb.ToString();
}
set
{
m_debugLookups.Clear();
if (!string.IsNullOrEmpty(value))
{
foreach(var debugLookup in value.Split(',', ';'))
{
AddDebugLookup(debugLookup);
}
}
}
}
#endregion
#region properties
/// <summary>
/// Gets or sets a flag indicating whether to always escape non-ASCII characters as \uXXXX
/// or to let the output encoding object handle that via the JsEncoderFallback object for the
/// specified output encoding format. Default is false (let the Encoding object handle it).
/// </summary>
public bool AlwaysEscapeNonAscii
{
get;
set;
}
/// <summary>
/// collapse new Array() to [] and new Object() to {} [true]
/// or leave ais [false]. Default is true.
/// </summary>
public bool CollapseToLiteral
{
get; set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether to use old-style const statements (just var-statements that
/// define unchangeable fields) or new EcmaScript 6 lexical declarations.
/// </summary>
public bool ConstStatementsMozilla
{
get;
set;
}
/// <summary>
/// Throw an error if a source string is not safe for inclusion
/// in an HTML inline script block. Default is false.
/// </summary>
public bool ErrorIfNotInlineSafe
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether eval-statements are "safe."
/// Deprecated in favor of <see cref="JsSettings.EvalTreatment" />, which is an enumeration
/// allowing for more options than just true or false.
/// True for this property is the equivalent of EvalTreament.Ignore;
/// False is the equivalent to EvalTreament.MakeAllSafe
/// </summary>
[Obsolete("This property is deprecated; use EvalTreatment instead")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public bool EvalsAreSafe
{
get
{
return EvalTreatment == JsEvalTreatment.Ignore;
}
set
{
EvalTreatment = (value ? JsEvalTreatment.Ignore : JsEvalTreatment.MakeAllSafe);
}
}
/// <summary>
/// Evaluate expressions containing only literal bool, string, numeric, or null values [true]
/// Leave literal expressions alone and do not evaluate them [false]. Default is true.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Eval")]
public bool EvalLiteralExpressions
{
get;
set;
}
/// <summary>
/// Gets or sets a settings value indicating how "safe" eval-statements are to be assumed.
/// Ignore (default) means we can assume eval-statements will not reference any local variables and functions.
/// MakeImmediateSafe assumes eval-statements will reference local variables and function within the same scope.
/// MakeAllSafe assumes eval-statements will reference any accessible local variable or function.
/// Local variables that we assume may be referenced by eval-statements cannot be automatically renamed.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Eval")]
public JsEvalTreatment EvalTreatment
{
get; set;
}
/// <summary>
/// Gets or sets the format to use for the JavaScript processing.
/// </summary>
public JsFormat Format
{
get; set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether or not to ignore conditional-compilation comment syntax (true) or
/// to try to retain the comments in the output (false; default)
/// </summary>
public bool IgnoreConditionalCompilation { get; set; }
/// <summary>
/// Gets or sets a boolean value indicating whether or not to ignore preprocessor defines comment syntax (true) or
/// to evaluate them (false; default)
/// </summary>
public bool IgnorePreprocessorDefines { get; set; }
/// <summary>
/// Gets or sets a boolean value indicating whether to break up string literals containing </script> so inline code won't break [true, default]
/// or to leave string literals as-is [false]
/// </summary>
public bool InlineSafeStrings
{
get; set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether/how local variables and functions should be automatically renamed:
/// KeepAll - do not rename local variables and functions;
/// CrunchAll - rename all local variables and functions to shorter names;
/// KeepLocalizationVars - rename all local variables and functions that do NOT start with L_
/// </summary>
public JsLocalRenaming LocalRenaming
{
get; set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether to add characters to the output to make sure Mac Safari bugs are not generated [true, default], or to
/// disregard potential known Mac Safari bugs in older versions [false]
/// </summary>
public bool MacSafariQuirks
{
get; set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether any operations are to be applied to the parsed tree [true, default],
/// or whether to return it as-is [false].
/// </summary>
public bool MinifyCode
{
get
{
// just return the minify flag
return m_minify;
}
set
{
// when we set this flag, we want to turn other things on and off at the same time
m_minify = value;
// aligned properties
this.CollapseToLiteral = m_minify;
this.EvalLiteralExpressions = m_minify;
this.RemoveFunctionExpressionNames = m_minify;
this.RemoveUnneededCode = m_minify;
this.ReorderScopeDeclarations = m_minify;
// opposite properties
this.PreserveFunctionNames = !m_minify;
this.PreserveImportantComments = !m_minify;
// dependent switches
this.LocalRenaming = m_minify ? JsLocalRenaming.CrunchAll : JsLocalRenaming.KeepAll;
this.KillSwitch = m_minify ? 0 : ~((long)JsTreeModifications.PreserveImportantComments);
}
}
/// <summary>
/// Gets or sets a boolean value indicating whether object property names with the specified "from" names will
/// get renamed to the corresponding "to" names (true, default) when using the manual-rename feature, or left alone (false)
/// </summary>
public bool ManualRenamesProperties
{
get; set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether or not the input files should be preprocessed only (default is false)
/// </summary>
public bool PreprocessOnly
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether all function names must be preserved and remain as-named (true),
/// or can be automatically renamed (false, default).
/// </summary>
public bool PreserveFunctionNames
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether to preserve important comments in the output.
/// Default is true, preserving important comments. Important comments have an exclamation
/// mark as the very first in-comment character (//! or /*!).
/// </summary>
public bool PreserveImportantComments
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether to always quote object literal property names.
/// Default is false.
/// </summary>
public bool QuoteObjectLiteralProperties
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether or not to reorder function and variable
/// declarations within scopes (true, default), or to leave the order as specified in
/// the original source.
/// </summary>
public bool ReorderScopeDeclarations
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether or not to remove unreferenced function expression names (true, default)
/// or to leave the names of function expressions, even if they are unreferenced (false).
/// </summary>
public bool RemoveFunctionExpressionNames
{
get; set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether to remove unneeded code, such as uncalled local functions or unreachable code [true, default],
/// or to keep such code in the output [false].
/// </summary>
public bool RemoveUnneededCode
{
get; set;
}
/// <summary>
/// Gets or sets the source mode
/// </summary>
public JsSourceMode SourceMode
{
get; set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether or not to force the input code into strict mode (true)
/// or rely on the sources to turn on strict mode via the "use strict" prologue directive (false, default).
/// </summary>
public bool StrictMode
{
get;
set;
}
/// <summary>
/// Gets or sets a boolean value indicating whether to strip debug statements [true, default],
/// or leave debug statements in the output [false]
/// </summary>
public bool StripDebugStatements
{
get; set;
}
/// <summary>
/// Gets or sets the <see cref="IJsSourceMap"/> instance. Default is null, which won't output a symbol map.
/// </summary>
internal IJsSourceMap SymbolsMap
{
get;
set;
}
#endregion
#region public methods
/// <summary>
/// Determine whether a particular AST tree modification is allowed, or has
/// been squelched (regardless of any other settings)
/// </summary>
/// <param name="modification">one or more tree modification settings</param>
/// <returns>true only if NONE of the passed modifications have their kill bits set</returns>
public bool IsModificationAllowed(JsTreeModifications modification)
{
return (KillSwitch & (long)modification) == 0;
}
#endregion
}
/// <summary>
/// Enum describing tree modifications on the javascript code file.
/// </summary>
[Flags]
public enum JsTreeModifications : long
{
/// <summary>
/// Default. No specific tree modification
/// </summary>
None = 0x0000000000000000,
/// <summary>
/// Preserve "important" comments in output: /*! ... */
/// </summary>
PreserveImportantComments = 0x0000000000000001,
/// <summary>
/// Replace a member-bracket call with a member-dot construct if the member
/// name is a string literal that can be an identifier.
/// A["B"] ==> A.B
/// </summary>
BracketMemberToDotMember = 0x0000000000000002,
/// <summary>
/// Replace a new Object constructor call with an object literal
/// new Object() ==> {}
/// </summary>
NewObjectToObjectLiteral = 0x0000000000000004,
/// <summary>
/// Change Array constructor calls with array literals.
/// Does not replace constructors called with a single numeric parameter
/// (could be a capacity contructor call).
/// new Array() ==> []
/// new Array(A,B,C) ==> [A,B,C]
/// </summary>
NewArrayToArrayLiteral = 0x0000000000000008,
/// <summary>
/// Remove the default case in a switch statement if the block contains
/// only a break statement.
/// remove default:break;
/// </summary>
RemoveEmptyDefaultCase = 0x0000000000000010,
/// <summary>
/// If there is no default case, remove any case statements that contain
/// only a single break statement.
/// remove case A:break;
/// </summary>
RemoveEmptyCaseWhenNoDefault = 0x0000000000000020,
/// <summary>
/// Remove the break statement from the last case block of a switch statement.
/// switch(A){case B: C;break;} ==> switch(A){case B:C;}
/// </summary>
RemoveBreakFromLastCaseBlock = 0x0000000000000040,
/// <summary>
/// Remove an empty finally statement if there is a non-empty catch block.
/// try{...}catch(E){...}finally{} ==> try{...}catch(E){...}
/// </summary>
RemoveEmptyFinally = 0x0000000000000080,
/// <summary>
/// Remove duplicate var declarations in a var statement that have no initializers.
/// var A,A=B ==> var A=B
/// var A=B,A ==> var A=B
/// </summary>
RemoveDuplicateVar = 0x0000000000000100,
/// <summary>
/// Combine adjacent var statements.
/// var A;var B ==> var A,B
/// </summary>
CombineVarStatements = 0x0000000000000200,
/// <summary>
/// Move preceeding var statement into the initializer of the for statement.
/// var A;for(var B;;); ==> for(var A,B;;);
/// var A;for(;;) ==> for(var A;;)
/// </summary>
MoveVarIntoFor = 0x0000000000000400,
/// <summary>
/// Combine adjacent var statement and return statement to a single return statement
/// var A=B;return A ==> return B
/// </summary>
VarInitializeReturnToReturnInitializer = 0x0000000000000800,
/// <summary>
/// Replace an if-statement that has empty true and false branches with just the
/// condition expression.
/// if(A);else; ==> A;
/// </summary>
IfEmptyToExpression = 0x0000000000001000,
/// <summary>
/// replace if-statement that only has a single call statement in the true branch
/// with a logical-and statement
/// if(A)B() ==> A&&B()
/// </summary>
IfConditionCallToConditionAndCall = 0x0000000000002000,
/// <summary>
/// Replace an if-else-statement where both branches are only a single return
/// statement with a single return statement and a conditional operator.
/// if(A)return B;else return C ==> return A?B:C
/// </summary>
IfElseReturnToReturnConditional = 0x0000000000004000,
/// <summary>
/// If a function ends in an if-statement that only has a true-branch containing
/// a single return statement with no operand, replace the if-statement with just
/// the condition expression.
/// function A(...){...;if(B)return} ==> function A(...){...;B}
/// </summary>
IfConditionReturnToCondition = 0x0000000000008000,
/// <summary>
/// If the true-block of an if-statment is empty and the else-block is not,
/// negate the condition and move the else-block to the true-block.
/// if(A);else B ==> if(!A)B
/// </summary>
IfConditionFalseToIfNotConditionTrue = 0x0000000000010000,
/// <summary>
/// Combine adjacent string literals.
/// "A"+"B" ==> "AB"
/// </summary>
CombineAdjacentStringLiterals = 0x0000000000020000,
/// <summary>
/// Remove unary-plus operators when the operand is a numeric literal
/// +123 ==> 123
/// </summary>
RemoveUnaryPlusOnNumericLiteral = 0x0000000000040000,
/// <summary>
/// Apply (and cascade) unary-minus operators to the value of a numeric literal
/// -(4) ==> -4 (unary minus applied to a numeric 4 ==> numeric -4)
/// -(-4) ==> 4 (same as above, but cascading)
/// </summary>
ApplyUnaryMinusToNumericLiteral = 0x0000000000080000,
/// <summary>
/// Apply minification technics to string literals
/// </summary>
MinifyStringLiterals = 0x0000000000100000,
/// <summary>
/// Apply minification techniques to numeric literals
/// </summary>
MinifyNumericLiterals = 0x0000000000200000,
/// <summary>
/// Remove unused function parameters
/// </summary>
RemoveUnusedParameters = 0x0000000000400000,
/// <summary>
/// remove "debug" statements
/// </summary>
StripDebugStatements = 0x0000000000800000,
/// <summary>
/// Rename local variables and functions
/// </summary>
LocalRenaming = 0x0000000001000000,
/// <summary>
/// Remove unused function expression names
/// </summary>
RemoveFunctionExpressionNames = 0x0000000002000000,
/// <summary>
/// Remove unnecessary labels from break or continue statements
/// </summary>
RemoveUnnecessaryLabels = 0x0000000004000000,
/// <summary>
/// Remove unnecessary @cc_on statements
/// </summary>
RemoveUnnecessaryCCOnStatements = 0x0000000008000000,
/// <summary>
/// Convert (new Date()).getTime() to +new Date
/// </summary>
DateGetTimeToUnaryPlus = 0x0000000010000000,
/// <summary>
/// Evaluate numeric literal expressions.
/// 1 + 2 ==> 3
/// </summary>
EvaluateNumericExpressions = 0x0000000020000000,
/// <summary>
/// Simplify a common method on converting string to numeric:
/// lookup - 0 ==> +lookup
/// (Subtracting zero converts lookup to number, then doesn't modify
/// it; unary plus also converts operand to numeric)
/// </summary>
SimplifyStringToNumericConversion = 0x0000000040000000,
/// <summary>
/// Rename properties in object literals, member-dot, and member-bracket operations
/// </summary>
PropertyRenaming = 0x0000000080000000,
/// <summary>
/// Remove the quotes arounf objectl literal property names when
/// the names are valid identifiers.
/// </summary>
RemoveQuotesFromObjectLiteralNames = 0x0000000200000000,
/// <summary>
/// Change boolean literals to not operators.
/// true -> !0
/// false -> !1
/// </summary>
BooleanLiteralsToNotOperators = 0x0000000400000000,
/// <summary>
/// Change if-statements with expression statements as their branches to expressions
/// </summary>
IfExpressionsToExpression = 0x0000000800000000,
/// <summary>
/// Combine adjacent expression statements into a single expression statement
/// using the comma operator
/// </summary>
CombineAdjacentExpressionStatements = 0x0000001000000000,
/// <summary>
/// If the types of both sides of a strict operator (=== or !==) are known
/// to be the same, we can reduce the operators to == or !=
/// </summary>
ReduceStrictOperatorIfTypesAreSame = 0x0000002000000000,
/// <summary>
/// If the types of both sides of a strict operator (=== or !==) are known
/// to be different, than we can reduct the binary operator to false or true (respectively)
/// </summary>
ReduceStrictOperatorIfTypesAreDifferent = 0x0000004000000000,
/// <summary>
/// Move function declarations to the top of the containing scope
/// </summary>
MoveFunctionToTopOfScope = 0x0000008000000000,
/// <summary>
/// Combine var statements at the top of the containing scope
/// </summary>
CombineVarStatementsToTopOfScope = 0x0000010000000000,
/// <summary>
/// If the condition of an if-statement or conditional starts with a not-operator,
/// get rid of the not-operator and swap the true/false branches.
/// </summary>
IfNotTrueFalseToIfFalseTrue = 0x0000020000000000,
/// <summary>
/// Whether it's okay to move an expression containing an in-operator into a for-statement.
/// </summary>
MoveInExpressionsIntoForStatement = 0x0000040000000000,
/// <summary>
/// Whether it's okay to convert function...{...if(cond)return;s1;s2} to function...{...if(!cond){s1;s2}}
/// </summary>
InvertIfReturn = 0x0000080000000000,
/// <summary>
/// Whether it's okay to combine nested if-statments if(cond1)if(cond2){...} to if(cond1&&cond2){...}
/// </summary>
CombineNestedIfs = 0x0000100000000000,
/// <summary>
/// Whether it's okay to combine equivalent if-statments that return the same expression.
/// if(cond1)return expr;if(cond2)return expr; => if(cond1||cond2)return expr;
/// </summary>
CombineEquivalentIfReturns = 0x0000200000000000,
/// <summary>
/// Whether to convert certain while-statements to for-statements.
/// while(1)... => for(;;)...
/// var ...;while(1)... => for(var ...;;)
/// var ...;while(cond)... => for(var ...;cond;)...
/// </summary>
ChangeWhileToFor = 0x0000400000000000,
/// <summary>
/// Whether to invert iterator{if(cond)continue;st1;st2} to iterator{if(!cond){st1;st2}}
/// </summary>
InvertIfContinue = 0x0000800000000000,
/// <summary>
/// Whether to convert [a,b,c].join(s) to "asbsc" if all items are constants.
/// </summary>
EvaluateLiteralJoins = 0x0001000000000000,
/// <summary>
/// Whether we should remove unused variable, or variables assigned a constant in their
/// initializer and referenced only once.
/// </summary>
RemoveUnusedVariables = 0x0002000000000000,
/// <summary>
/// Whether we should unfold comma-separated expressions statements into separate statements
/// as a final minification step (if it doesn't create more bytes)
/// </summary>
UnfoldCommaExpressionStatements = 0x0004000000000000,
/// <summary>
/// Whether to convert [a,b,c].length to 3 (if all items are constants)
/// and "123".length to 3
/// </summary>
EvaluateLiteralLengths = 0x0008000000000000,
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class RefLocalTests : CompilingTestBase
{
[Fact]
public void RefAssignArrayAccess()
{
var text = @"
class Program
{
static void M()
{
ref int rl = ref (new int[1])[0];
rl = ref (new int[1])[0];
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignRefParameter()
{
var text = @"
class Program
{
static void M(ref int i)
{
ref int rl = ref i;
rl = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignOutParameter()
{
var text = @"
class Program
{
static void M(out int i)
{
i = 0;
ref int rl = ref i;
rl = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignRefLocal()
{
var text = @"
class Program
{
static void M(ref int i)
{
ref int local = ref i;
ref int rl = ref local;
rl = ref local;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStaticProperty()
{
var text = @"
class Program
{
static int field = 0;
static ref int P { get { return ref field; } }
static void M()
{
ref int rl = ref P;
rl = ref P;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignClassInstanceProperty()
{
var text = @"
class Program
{
int field = 0;
ref int P { get { return ref field; } }
void M()
{
ref int rl = ref P;
rl = ref P;
}
void M1()
{
ref int rl = ref new Program().P;
rl = ref new Program().P;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStructInstanceProperty()
{
var text = @"
struct Program
{
public ref int P { get { return ref (new int[1])[0]; } }
void M()
{
ref int rl = ref P;
rl = ref P;
}
void M1(ref Program program)
{
ref int rl = ref program.P;
rl = ref program.P;
}
}
struct Program2
{
Program program;
Program2(Program program)
{
this.program = program;
}
void M()
{
ref int rl = ref program.P;
rl = ref program.P;
}
}
class Program3
{
Program program = default(Program);
void M()
{
ref int rl = ref program.P;
rl = ref program.P;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignConstrainedInstanceProperty()
{
var text = @"
interface I
{
ref int P { get; }
}
class Program<T>
where T : I
{
void M(T t)
{
ref int rl = ref t.P;
rl = ref t.P;
}
}
class Program2<T>
where T : class, I
{
void M(T t)
{
ref int rl = ref t.P;
rl = ref t.P;
}
}
class Program3<T>
where T : struct, I
{
void M(T t)
{
ref int rl = ref t.P;
rl = ref t.P;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignClassInstanceIndexer()
{
var text = @"
class Program
{
int field = 0;
ref int this[int i] { get { return ref field; } }
void M()
{
ref int rl = ref this[0];
rl = ref this[0];
}
void M1()
{
ref int rl = ref new Program()[0];
rl = ref new Program()[0];
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStructInstanceIndexer()
{
var text = @"
struct Program
{
public ref int this[int i] { get { return ref (new int[1])[0]; } }
void M()
{
ref int rl = ref this[0];
rl = ref this[0];
}
}
struct Program2
{
Program program;
Program2(Program program)
{
this.program = program;
}
void M()
{
ref int rl = ref program[0];
rl = ref program[0];
}
}
class Program3
{
Program program = default(Program);
void M()
{
ref int rl = ref program[0];
rl = ref program[0];
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignConstrainedInstanceIndexer()
{
var text = @"
interface I
{
ref int this[int i] { get; }
}
class Program<T>
where T : I
{
void M(T t)
{
ref int rl = ref t[0];
rl = ref t[0];
}
}
class Program2<T>
where T : class, I
{
void M(T t)
{
ref int rl = ref t[0];
rl = ref t[0];
}
}
class Program3<T>
where T : struct, I
{
void M(T t)
{
ref int rl = ref t[0];
rl = ref t[0];
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStaticFieldLikeEvent()
{
var text = @"
delegate void D();
class Program
{
static event D d;
static void M()
{
ref D rl = ref d;
rl = ref d;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignClassInstanceFieldLikeEvent()
{
var text = @"
delegate void D();
class Program
{
event D d;
void M()
{
ref D rl = ref d;
rl = ref d;
}
void M1()
{
ref D rl = ref new Program().d;
rl = ref new Program().d;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStaticField()
{
var text = @"
class Program
{
static int i = 0;
static void M()
{
ref int rl = ref i;
rl = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignClassInstanceField()
{
var text = @"
class Program
{
int i = 0;
void M()
{
ref int rl = ref i;
rl = ref i;
}
void M1()
{
ref int rl = ref new Program().i;
rl = ref new Program().i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStructInstanceField()
{
var text = @"
struct Program
{
public int i;
public Program(int i)
{
this.i = i;
}
}
class Program3
{
Program program = default(Program);
void M()
{
ref int rl = ref program.i;
rl = ref program.i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStaticCallWithoutArguments()
{
var text = @"
class Program
{
static ref int M()
{
ref int rl = ref M();
rl = ref M();
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignClassInstanceCallWithoutArguments()
{
var text = @"
class Program
{
ref int M()
{
ref int rl = ref M();
rl = ref M();
return ref rl;
}
ref int M1()
{
ref int rl = ref new Program().M();
rl = ref new Program().M();
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStructInstanceCallWithoutArguments()
{
var text = @"
struct Program
{
public ref int M()
{
ref int rl = ref M();
rl = ref M();
return ref rl;
}
}
struct Program2
{
Program program;
ref int M()
{
ref int rl = ref program.M();
rl = ref program.M();
return ref rl;
}
}
class Program3
{
Program program;
ref int M()
{
ref int rl = ref program.M();
rl = ref program.M();
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignConstrainedInstanceCallWithoutArguments()
{
var text = @"
interface I
{
ref int M();
}
class Program<T>
where T : I
{
ref int M(T t)
{
ref int rl = ref t.M();
rl = ref t.M();
return ref rl;
}
}
class Program2<T>
where T : class, I
{
ref int M(T t)
{
ref int rl = ref t.M();
rl = ref t.M();
return ref rl;
}
}
class Program3<T>
where T : struct, I
{
ref int M(T t)
{
ref int rl = ref t.M();
rl = ref t.M();
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStaticCallWithArguments()
{
var text = @"
class Program
{
static ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
rl = ref M(ref i, ref j, o);
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignClassInstanceCallWithArguments()
{
var text = @"
class Program
{
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
rl = ref M(ref i, ref j, o);
return ref rl;
}
ref int M1(ref int i, ref int j, object o)
{
ref int rl = ref new Program().M(ref i, ref j, o);
rl = ref new Program().M(ref i, ref j, o);
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignStructInstanceCallWithArguments()
{
var text = @"
struct Program
{
public ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
rl = ref M(ref i, ref j, o);
return ref rl;
}
}
struct Program2
{
Program program;
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref program.M(ref i, ref j, o);
rl = ref program.M(ref i, ref j, o);
return ref rl;
}
}
class Program3
{
Program program;
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref program.M(ref i, ref j, o);
rl = ref program.M(ref i, ref j, o);
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignConstrainedInstanceCallWithArguments()
{
var text = @"
interface I
{
ref int M(ref int i, ref int j, object o);
}
class Program<T>
where T : I
{
ref int M(T t, ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
class Program2<T>
where T : class, I
{
ref int M(T t, ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
class Program3<T>
where T : struct, I
{
ref int M(T t, ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignDelegateInvocationWithNoArguments()
{
var text = @"
delegate ref int D();
class Program
{
static void M(D d)
{
ref int rl = ref d();
rl = ref d();
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignDelegateInvocationWithArguments()
{
var text = @"
delegate ref int D(ref int i, ref int j, object o);
class Program
{
static ref int M(D d, ref int i, ref int j, object o)
{
ref int rl = ref d(ref i, ref j, o);
rl = ref d(ref i, ref j, o);
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignRefAssign()
{
var text = @"
class Program
{
static int field = 0;
static void M()
{
ref int a, b, c, d, e, f;
a = ref b = ref c = ref d = ref e = ref f = ref field;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics();
}
[Fact]
public void RefAssignsAreVariables()
{
var text = @"
class Program
{
static int field = 0;
static void M(ref int i)
{
}
static void N(out int i)
{
i = 0;
}
static unsafe ref int Main()
{
ref int rl;
(rl = ref field) = 0;
(rl = ref field) += 1;
(rl = ref field)++;
M(ref (rl = ref field));
N(out (rl = ref field));
fixed (int* i = &(rl = ref field)) { }
var tr = __makeref((rl = ref field));
return ref (rl = ref field);
}
}
";
CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void RefLocalsAreVariables()
{
var text = @"
class Program
{
static int field = 0;
static void M(ref int i)
{
}
static void N(out int i)
{
i = 0;
}
static unsafe ref int Main()
{
ref int rl = ref field;
rl = 0;
rl += 1;
rl++;
M(ref rl);
N(out rl);
fixed (int* i = &rl) { }
var tr = __makeref(rl);
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void BadRefAssignParameter()
{
var text = @"
class Program
{
static void M(int i)
{
ref int rl = ref i;
rl = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (6,26): error CS8912: Cannot return or assign a reference to parameter 'i' because it is not a ref or out parameter
// ref int rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(6, 26),
// (7,18): error CS8912: Cannot return or assign a reference to parameter 'i' because it is not a ref or out parameter
// rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(7, 18));
}
[Fact]
public void BadRefAssignLocal()
{
var text = @"
class Program
{
static void M()
{
int i = 0;
ref int rl = ref i;
rl = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (7,26): error CS8914: Cannot return or assign a reference to local 'i' because it is not a ref local
// ref int rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "i").WithArguments("i").WithLocation(7, 26),
// (8,18): error CS8914: Cannot return or assign a reference to local 'i' because it is not a ref local
// rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "i").WithArguments("i").WithLocation(8, 18));
}
[Fact]
public void BadRefAssignByValueProperty()
{
var text = @"
class Program
{
static int P { get; set; }
static void M()
{
ref int rl = ref P;
rl = ref P;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (8,26): error CS8900: The argument to a by reference return or assignment must be an assignable variable or a property or call that returns by reference
// ref int rl = ref P;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "P").WithArguments("Program.P").WithLocation(8, 26),
// (9,18): error CS8900: The argument to a by reference return or assignment must be an assignable variable or a property or call that returns by reference
// rl = ref P;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "P").WithArguments("Program.P").WithLocation(9, 18));
}
[Fact]
public void BadRefAssignByValueIndexer()
{
var text = @"
class Program
{
int this[int i] { get { return 0; } }
void M()
{
ref int rl = ref this[0];
rl = ref this[0];
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (8,26): error CS8900: The argument to a by reference return or assignment must be an assignable variable or a property or call that returns by reference
// ref int rl = ref this[0];
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "this[0]").WithArguments("Program.this[int]").WithLocation(8, 26),
// (9,18): error CS8900: The argument to a by reference return or assignment must be an assignable variable or a property or call that returns by reference
// rl = ref this[0];
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "this[0]").WithArguments("Program.this[int]").WithLocation(9, 18));
}
[Fact]
public void BadRefAssignNonFieldEvent()
{
var text = @"
delegate void D();
class Program
{
event D d { add { } remove { } }
void M()
{
ref int rl = ref d;
rl = ref d;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (10,26): error CS0079: The event 'Program.d' can only appear on the left hand side of += or -=
// ref int rl = ref d;
Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "d").WithArguments("Program.d").WithLocation(10, 26),
// (11,18): error CS0079: The event 'Program.d' can only appear on the left hand side of += or -=
// rl = ref d;
Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "d").WithArguments("Program.d").WithLocation(11, 18));
}
[Fact]
public void BadRefAssignEventReceiver()
{
var text = @"
delegate void D();
struct Program
{
event D d;
void M()
{
ref D rl = ref d;
rl = ref d;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (10,24): error CS8914: Cannot return or assign a reference to local 'this' because it is not a ref local
// ref D rl = ref d;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "d").WithArguments("this").WithLocation(10, 24),
// (10,24): error CS8916: Cannot return or assign a reference to 'Program.d' because its receiver may not be returned or assigned by reference
// ref D rl = ref d;
Diagnostic(ErrorCode.ERR_RefReturnReceiver, "d").WithArguments("Program.d").WithLocation(10, 24),
// (11,18): error CS8914: Cannot return or assign a reference to local 'this' because it is not a ref local
// rl = ref d;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "d").WithArguments("this").WithLocation(11, 18),
// (11,18): error CS8916: Cannot return or assign a reference to 'Program.d' because its receiver may not be returned or assigned by reference
// rl = ref d;
Diagnostic(ErrorCode.ERR_RefReturnReceiver, "d").WithArguments("Program.d").WithLocation(11, 18));
}
[Fact]
public void BadRefAssignReadonlyField()
{
var text = @"
class Program
{
readonly int i = 0;
void M()
{
ref int rl = ref i;
rl = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (8,26): error CS8906: A readonly field cannot be returned by reference
// ref int rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnReadonly, "i").WithLocation(8, 26),
// (9,18): error CS8906: A readonly field cannot be returned by reference
// rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnReadonly, "i").WithLocation(9, 18));
}
[Fact]
public void BadRefAssignFieldReceiver()
{
var text = @"
struct Program
{
int i;
Program(int i)
{
this.i = i;
}
void M()
{
ref int rl = ref i;
rl = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (13,26): error CS8914: Cannot return or assign a reference to local 'this' because it is not a ref local
// ref int rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "i").WithArguments("this").WithLocation(13, 26),
// (13,26): error CS8916: Cannot return or assign a reference to 'Program.i' because its receiver may not be returned or assigned by reference
// ref int rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnReceiver, "i").WithArguments("Program.i").WithLocation(13, 26),
// (14,18): error CS8914: Cannot return or assign a reference to local 'this' because it is not a ref local
// rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "i").WithArguments("this").WithLocation(14, 18),
// (14,18): error CS8916: Cannot return or assign a reference to 'Program.i' because its receiver may not be returned or assigned by reference
// rl = ref i;
Diagnostic(ErrorCode.ERR_RefReturnReceiver, "i").WithArguments("Program.i").WithLocation(14, 18));
}
[Fact]
public void BadRefAssignByValueCall()
{
var text = @"
class Program
{
static int L()
{
return 0;
}
static void M()
{
ref int rl = ref L();
rl = ref L();
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (11,26): error CS8900: The argument to a by reference return or assignment must be an assignable variable or a property or call that returns by reference
// ref int rl = ref L();
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "L()").WithLocation(11, 26),
// (12,18): error CS8900: The argument to a by reference return or assignment must be an assignable variable or a property or call that returns by reference
// rl = ref L();
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "L()").WithLocation(12, 18));
}
[Fact]
public void BadRefAssignByValueDelegateInvocation()
{
var text = @"
delegate int D();
class Program
{
static void M(D d)
{
ref int rl = ref d();
rl = ref d();
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (8,26): error CS8900: The argument to a by reference return or assignment must be an assignable variable or a property or call that returns by reference
// ref int rl = ref d();
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d()").WithLocation(8, 26),
// (9,18): error CS8900: The argument to a by reference return or assignment must be an assignable variable or a property or call that returns by reference
// rl = ref d();
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d()").WithLocation(9, 18));
}
[Fact]
public void BadRefAssignDelegateInvocationWithArguments()
{
var text = @"
delegate ref int D(ref int i, ref int j, object o);
class Program
{
static void M(D d, int i, int j, object o)
{
ref int rl = ref d(ref i, ref j, o);
rl = ref d(ref i, ref j, o);
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (8,32): error CS8912: Cannot return or assign a reference to parameter 'i' because it is not a ref or out parameter
// ref int rl = ref d(ref i, ref j, o);
Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(8, 32),
// (8,26): error CS8910: Cannot return or assign a reference to the result of 'D.Invoke(ref int, ref int, object)' because the argument passed to parameter 'i' cannot be returned or assigned by reference
// ref int rl = ref d(ref i, ref j, o);
Diagnostic(ErrorCode.ERR_RefReturnCall, "d(ref i, ref j, o)").WithArguments("D.Invoke(ref int, ref int, object)", "i").WithLocation(8, 26),
// (9,24): error CS8912: Cannot return or assign a reference to parameter 'i' because it is not a ref or out parameter
// rl = ref d(ref i, ref j, o);
Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(9, 24),
// (9,18): error CS8910: Cannot return or assign a reference to the result of 'D.Invoke(ref int, ref int, object)' because the argument passed to parameter 'i' cannot be returned or assigned by reference
// rl = ref d(ref i, ref j, o);
Diagnostic(ErrorCode.ERR_RefReturnCall, "d(ref i, ref j, o)").WithArguments("D.Invoke(ref int, ref int, object)", "i").WithLocation(9, 18));
}
[Fact]
public void BadRefAssignCallArgument()
{
var text = @"
class Program
{
static ref int M(ref int i)
{
int j = 0;
ref int rl = ref M(ref j);
rl = ref M(ref j);
return ref rl;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (7,32): error CS8914: Cannot return or assign a reference to local 'j' because it is not a ref local
// ref int rl = ref M(ref j);
Diagnostic(ErrorCode.ERR_RefReturnLocal, "j").WithArguments("j").WithLocation(7, 32),
// (7,26): error CS8910: Cannot return or assign a reference to the result of 'Program.M(ref int)' because the argument passed to parameter 'i' cannot be returned or assigned by reference
// ref int rl = ref M(ref j);
Diagnostic(ErrorCode.ERR_RefReturnCall, "M(ref j)").WithArguments("Program.M(ref int)", "i").WithLocation(7, 26),
// (8,24): error CS8914: Cannot return or assign a reference to local 'j' because it is not a ref local
// rl = ref M(ref j);
Diagnostic(ErrorCode.ERR_RefReturnLocal, "j").WithArguments("j").WithLocation(8, 24),
// (8,18): error CS8910: Cannot return or assign a reference to the result of 'Program.M(ref int)' because the argument passed to parameter 'i' cannot be returned or assigned by reference
// rl = ref M(ref j);
Diagnostic(ErrorCode.ERR_RefReturnCall, "M(ref j)").WithArguments("Program.M(ref int)", "i").WithLocation(8, 18));
}
[Fact]
public void BadRefAssignStructThis()
{
var text = @"
struct Program
{
void M()
{
ref Program rl = ref this;
rl = ref this;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (6,30): error CS8914: Cannot return or assign a reference to local 'this' because it is not a ref local
// ref Program rl = ref this;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "this").WithArguments("this").WithLocation(6, 30),
// (7,18): error CS8914: Cannot return or assign a reference to local 'this' because it is not a ref local
// rl = ref this;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "this").WithArguments("this").WithLocation(7, 18));
}
[Fact]
public void BadRefAssignThisReference()
{
var text = @"
class Program
{
void M()
{
ref int rl = ref this;
rl = ref this;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (6,26): error CS8914: Cannot return or assign a reference to local 'this' because it is not a ref local
// ref int rl = ref this;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "this").WithArguments("this").WithLocation(6, 26),
// (7,18): error CS8914: Cannot return or assign a reference to local 'this' because it is not a ref local
// rl = ref this;
Diagnostic(ErrorCode.ERR_RefReturnLocal, "this").WithArguments("this").WithLocation(7, 18));
}
[Fact]
public void BadRefAssignWrongType()
{
var text = @"
class Program
{
void M(ref long i)
{
ref int rl = ref i;
rl = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (6,26): error CS8922: The expression must be of type 'int' because it is being assigned by reference
// ref int rl = ref i;
Diagnostic(ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, "i").WithArguments("int").WithLocation(6, 26),
// (7,18): error CS8922: The expression must be of type 'int' because it is being assigned by reference
// rl = ref i;
Diagnostic(ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, "i").WithArguments("int").WithLocation(7, 18));
}
[Fact]
public void BadRefLocalCapturedInAnonymousMethod()
{
var text = @"
using System.Linq;
delegate int D();
class Program
{
static int field = 0;
static void M()
{
ref int rl = ref field;
var d = new D(delegate { return rl; });
d = new D(() => rl);
rl = (from v in new int[10] where v > rl select r1).Single();
}
}
";
CreateCompilationWithMscorlibAndSystemCore(text).VerifyDiagnostics(
// (13,41): error CS8930: Cannot use ref local 'rl' inside an anonymous method, lambda expression, or query expression
// var d = new D(delegate { return rl; });
Diagnostic(ErrorCode.ERR_AnonDelegateCantUseLocal, "rl").WithArguments("rl").WithLocation(13, 41),
// (14,25): error CS8930: Cannot use ref local 'rl' inside an anonymous method, lambda expression, or query expression
// d = new D(() => rl);
Diagnostic(ErrorCode.ERR_AnonDelegateCantUseLocal, "rl").WithArguments("rl").WithLocation(14, 25),
// (15,47): error CS8930: Cannot use ref local 'rl' inside an anonymous method, lambda expression, or query expression
// rl = (from v in new int[10] where v > rl select r1).Single();
Diagnostic(ErrorCode.ERR_AnonDelegateCantUseLocal, "rl").WithArguments("rl").WithLocation(15, 47));
}
[Fact]
public void BadRefLocalInAsyncMethod()
{
var text = @"
class Program
{
static int field = 0;
static async void Foo()
{
ref int i = ref field;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (8,17): error CS8932: Async methods cannot have by reference locals
// ref int i = ref field;
Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "i = ref field").WithLocation(8, 17),
// (6,23): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// static async void Foo()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Foo").WithLocation(6, 23));
}
[Fact]
public void BadRefLocalInIteratorMethod()
{
var text = @"
using System.Collections;
class Program
{
static int field = 0;
static IEnumerable ObjEnumerable()
{
ref int i = ref field;
yield return new object();
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (10,17): error CS8931: Iterators cannot have by reference locals
// ref int i = ref field;
Diagnostic(ErrorCode.ERR_BadIteratorLocalType, "i").WithLocation(10, 17));
}
[Fact]
public void BadRefAssignByValueLocal()
{
var text = @"
class Program
{
static void M(ref int i)
{
int l = ref i;
l = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (6,13): error CS8922: Cannot initialize a by-value variable with a reference
// int l = ref i;
Diagnostic(ErrorCode.ERR_InitializeByValueVariableWithReference, "l = ref i").WithLocation(6, 13),
// (7,9): error CS8920: 'l' cannot be assigned a reference because it is not a by-reference local
// l = ref i;
Diagnostic(ErrorCode.ERR_MustBeRefAssignable, "l").WithArguments("l").WithLocation(7, 9));
}
[Fact]
public void BadRefAssignOther()
{
var text = @"
class Program
{
static void M(ref int i)
{
int[] arr = new int[1];
arr[0] = ref i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (7,9): error CS8921: Expected a by-reference local
// arr[0] = ref i;
Diagnostic(ErrorCode.ERR_MustBeRefAssignableLocal, "arr[0]").WithLocation(7, 9));
}
[Fact]
public void BadByValueInitRefLocal()
{
var text = @"
class Program
{
static void M(int i)
{
ref int rl = i;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (6,17): error CS8921: Cannot initialize a by-reference variable with a value
// ref int rl = i;
Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "rl = i").WithLocation(6, 17));
}
[Fact]
public void BadRefLocalUseBeforeDef()
{
var text = @"
class Program
{
static void M(int i, ref int j, out int k, bool b)
{
ref int rl, rm;
if (b)
{
rl = ref j;
}
rl = i;
rl = ref rm;
rl = ref k;
k = 1;
}
}
";
CreateCompilationWithMscorlib(text).VerifyDiagnostics(
// (11,9): error CS0165: Use of unassigned local variable 'rl'
// rl = i;
Diagnostic(ErrorCode.ERR_UseDefViolation, "rl").WithArguments("rl").WithLocation(11, 9),
// (12,18): error CS0165: Use of unassigned local variable 'rm'
// rl = ref rm;
Diagnostic(ErrorCode.ERR_UseDefViolation, "rm").WithArguments("rm").WithLocation(12, 18),
// (13,18): error CS0269: Use of unassigned out parameter 'k'
// rl = ref k;
Diagnostic(ErrorCode.ERR_UseDefViolationOut, "k").WithArguments("k").WithLocation(13, 18));
}
}
}
| |
// 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.Numerics;
using System.IO;
internal partial class VectorTest
{
public static bool CheckValue<T>(T value, T expectedValue)
{
bool returnVal;
if (typeof(T) == typeof(float))
{
returnVal = Math.Abs(((float)(object)value) - ((float)(object)expectedValue)) <= Single.Epsilon;
}
if (typeof(T) == typeof(double))
{
returnVal = Math.Abs(((double)(object)value) - ((double)(object)expectedValue)) <= Double.Epsilon;
}
else
{
returnVal = value.Equals(expectedValue);
}
if (returnVal == false)
{
if ((typeof(T) == typeof(double)) || (typeof(T) == typeof(float)))
{
Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} , Got: {1}", expectedValue, value);
}
else
{
Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} (0x{0:X}), Got: {1} (0x{1:X})", expectedValue, value);
}
}
return returnVal;
}
private static bool CheckVector<T>(Vector<T> V, T value) where T : struct, IComparable<T>, IEquatable<T>
{
for (int i = 0; i < Vector<T>.Count; i++)
{
if (!(CheckValue<T>(V[i], value)))
{
return false;
}
}
return true;
}
public static T GetValueFromInt<T>(int value)
{
if (typeof(T) == typeof(float))
{
float floatValue = (float)value;
return (T)(object)floatValue;
}
if (typeof(T) == typeof(double))
{
double doubleValue = (double)value;
return (T)(object)doubleValue;
}
if (typeof(T) == typeof(int))
{
return (T)(object)value;
}
if (typeof(T) == typeof(uint))
{
uint uintValue = (uint)value;
return (T)(object)uintValue;
}
if (typeof(T) == typeof(long))
{
long longValue = (long)value;
return (T)(object)longValue;
}
if (typeof(T) == typeof(ulong))
{
ulong longValue = (ulong)value;
return (T)(object)longValue;
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(ushort)value;
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(byte)value;
}
if (typeof(T) == typeof(short))
{
return (T)(object)(short)value;
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(sbyte)value;
}
else
{
throw new ArgumentException();
}
}
private static void VectorPrint<T>(string mesg, Vector<T> v) where T : struct, IComparable<T>, IEquatable<T>
{
Console.Write(mesg + "[");
for (int i = 0; i < Vector<T>.Count; i++)
{
Console.Write(" " + v[i]);
if (i < (Vector<T>.Count - 1)) Console.Write(",");
}
Console.WriteLine(" ]");
}
private static T Add<T>(T left, T right) where T : struct, IComparable<T>, IEquatable<T>
{
if (typeof(T) == typeof(float))
{
return (T)(object)(((float)(object)left) + ((float)(object)right));
}
if (typeof(T) == typeof(double))
{
return (T)(object)(((double)(object)left) + ((double)(object)right));
}
if (typeof(T) == typeof(int))
{
return (T)(object)(((int)(object)left) + ((int)(object)right));
}
if (typeof(T) == typeof(uint))
{
return (T)(object)(((uint)(object)left) + ((uint)(object)right));
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(((ushort)(object)left) + ((ushort)(object)right));
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(((byte)(object)left) + ((byte)(object)right));
}
if (typeof(T) == typeof(short))
{
return (T)(object)(((short)(object)left) + ((short)(object)right));
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(((sbyte)(object)left) + ((sbyte)(object)right));
}
if (typeof(T) == typeof(long))
{
return (T)(object)(((long)(object)left) + ((long)(object)right));
}
if (typeof(T) == typeof(ulong))
{
return (T)(object)(((ulong)(object)left) + ((ulong)(object)right));
}
else
{
throw new ArgumentException();
}
}
private static T Multiply<T>(T left, T right) where T : struct, IComparable<T>, IEquatable<T>
{
if (typeof(T) == typeof(float))
{
return (T)(object)(((float)(object)left) * ((float)(object)right));
}
if (typeof(T) == typeof(double))
{
return (T)(object)(((double)(object)left) * ((double)(object)right));
}
if (typeof(T) == typeof(int))
{
return (T)(object)(((int)(object)left) * ((int)(object)right));
}
if (typeof(T) == typeof(uint))
{
return (T)(object)(((uint)(object)left) * ((uint)(object)right));
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(((ushort)(object)left) * ((ushort)(object)right));
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(((byte)(object)left) * ((byte)(object)right));
}
if (typeof(T) == typeof(short))
{
return (T)(object)(((short)(object)left) * ((short)(object)right));
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(((sbyte)(object)left) * ((sbyte)(object)right));
}
if (typeof(T) == typeof(long))
{
return (T)(object)(((long)(object)left) * ((long)(object)right));
}
if (typeof(T) == typeof(ulong))
{
return (T)(object)(((ulong)(object)left) * ((ulong)(object)right));
}
else
{
throw new ArgumentException();
}
}
public static T[] GetRandomArray<T>(int size, Random random)
where T : struct, IComparable<T>, IEquatable<T>
{
T[] result = new T[size];
for (int i = 0; i < size; i++)
{
int data = random.Next(100);
result[i] = GetValueFromInt<T>(data);
}
return result;
}
}
class JitLog : IDisposable
{
FileStream fileStream;
bool simdIntrinsicsSupported;
private static String GetLogFileName()
{
String jitLogFileName = Environment.GetEnvironmentVariable("COMPlus_JitFuncInfoLogFile");
return jitLogFileName;
}
public JitLog()
{
fileStream = null;
simdIntrinsicsSupported = Vector.IsHardwareAccelerated;
String jitLogFileName = GetLogFileName();
if (jitLogFileName == null)
{
Console.WriteLine("No JitLogFile");
return;
}
if (!File.Exists(jitLogFileName))
{
Console.WriteLine("JitLogFile " + jitLogFileName + " not found.");
return;
}
File.Copy(jitLogFileName, "Temp.log", true);
fileStream = new FileStream("Temp.log", FileMode.Open, FileAccess.Read, FileShare.Read);
}
public void Dispose()
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
public bool IsEnabled()
{
return (fileStream != null);
}
//------------------------------------------------------------------------
// Check: Check to see whether 'method' was recognized as an intrinsic by the JIT.
//
// Arguments:
// method - The method name, as a string
//
// Return Value:
// If the JitLog is not enabled (either the environment variable is not set,
// or the file was not found, e.g. if the JIT doesn't support it):
// - Returns true
// If SIMD intrinsics are enabled:
// - Returns true if the method was NOT compiled, otherwise false
// Else (if SIMD intrinsics are NOT enabled):
// - Returns true.
// Note that it might be useful to return false if the method was not compiled,
// but it will not be logged as compiled if it is inlined.
//
// Assumptions:
// The JitLog constructor queries Vector.IsHardwareAccelerated to determine
// if SIMD intrinsics are enabled, and depends on its correctness.
//
// Notes:
// It searches for the string verbatim. If 'method' is not fully qualified
// or its signature is not provided, it may result in false matches.
//
// Example:
// CheckJitLog("System.Numerics.Vector4:op_Addition(struct,struct):struct");
//
public bool Check(String method)
{
// Console.WriteLine("Checking for " + method + ":");
if (!IsEnabled())
{
Console.WriteLine("JitLog not enabled.");
return true;
}
try
{
fileStream.Position = 0;
StreamReader reader = new StreamReader(fileStream);
bool methodFound = false;
while ((reader.Peek() >= 0) && (methodFound == false))
{
String s = reader.ReadLine();
if (s.IndexOf(method) != -1)
{
methodFound = true;
}
}
if (simdIntrinsicsSupported && methodFound)
{
Console.WriteLine("Method " + method + " was compiled but should not have been");
return false;
}
// Useful when developing / debugging just to be sure that we reached here:
// Console.WriteLine(method + ((methodFound) ? " WAS COMPILED" : " WAS NOT COMPILED"));
return true;
}
catch (Exception e)
{
Console.WriteLine("Error checking JitLogFile: " + e.Message);
return false;
}
}
// Check: Check to see Vector<'elementType'>:'method' was recognized as an
// intrinsic by the JIT.
//
// Arguments:
// method - The method name, without its containing type (which is Vector<T>)
// elementType - The type with which Vector<T> is instantiated.
//
// Return Value:
// See the other overload, above.
//
// Assumptions:
// The JitLog constructor queries Vector.IsHardwareAccelerated to determine
// if SIMD intrinsics are enabled, and depends on its correctness.
//
// Notes:
// It constructs the search string based on the way generic types are currently
// dumped by the CLR. If the signature is not provided for the method, it
// may result in false matches.
//
// Example:
// CheckJitLog("op_Addition(struct,struct):struct", "Single");
//
public bool Check(String method, String elementType)
{
String checkString = "System.Numerics.Vector`1[" + elementType + "][System." + elementType + "]:" + method;
return Check(checkString);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using FileHelpers.Events;
namespace FileHelpers
{
/// <summary>
/// Async engine, reads records from file in background,
/// returns them record by record in foreground
/// </summary>
public sealed class FileHelperAsyncEngine :
FileHelperAsyncEngine<object>
{
#region " Constructor "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/>
public FileHelperAsyncEngine(Type recordType)
: base(recordType) {}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/>
/// <param name="encoding">The encoding used by the Engine.</param>
public FileHelperAsyncEngine(Type recordType, Encoding encoding)
: base(recordType, encoding) {}
#endregion
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngine/*'/>
/// <include file='Examples.xml' path='doc/examples/FileHelperAsyncEngine/*'/>
/// <typeparam name="T">The record type.</typeparam>
[DebuggerDisplay(
"FileHelperAsyncEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}"
)]
public class FileHelperAsyncEngine<T>
:
EventEngineBase<T>,
IFileHelperAsyncEngine<T>
where T : class
{
#region " Constructor "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/>
public FileHelperAsyncEngine()
: base(typeof (T))
{
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/>
protected FileHelperAsyncEngine(Type recordType)
: base(recordType)
{
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/>
/// <param name="encoding">The encoding used by the Engine.</param>
public FileHelperAsyncEngine(Encoding encoding)
: base(typeof (T), encoding)
{
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/>
/// <param name="encoding">The encoding used by the Engine.</param>
/// <param name="recordType">Type of record to read</param>
protected FileHelperAsyncEngine(Type recordType, Encoding encoding)
: base(recordType, encoding)
{
}
#endregion
#region " Readers and Writters "
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private ForwardReader mAsyncReader;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private TextWriter mAsyncWriter;
#endregion
#region " LastRecord "
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private T mLastRecord;
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/LastRecord/*'/>
public T LastRecord
{
get { return mLastRecord; }
}
private object[] mLastRecordValues;
/// <summary>
/// An array with the values of each field of the current record
/// </summary>
public object[] LastRecordValues
{
get { return mLastRecordValues; }
}
/// <summary>
/// Get a field value of the current records.
/// </summary>
/// <param name="fieldIndex" >The index of the field.</param>
public object this[int fieldIndex]
{
get
{
if (mLastRecordValues == null) {
throw new BadUsageException(
"You must be reading something to access this property. Try calling BeginReadFile first.");
}
return mLastRecordValues[fieldIndex];
}
set
{
if (mAsyncWriter == null) {
throw new BadUsageException(
"You must be writing something to set a record value. Try calling BeginWriteFile first.");
}
if (mLastRecordValues == null)
mLastRecordValues = new object[RecordInfo.FieldCount];
if (value == null) {
if (RecordInfo.Fields[fieldIndex].FieldType.IsValueType)
throw new BadUsageException("You can't assign null to a value type.");
mLastRecordValues[fieldIndex] = null;
}
else {
if (!RecordInfo.Fields[fieldIndex].FieldType.IsInstanceOfType(value)) {
throw new BadUsageException(string.Format("Invalid type: {0}. Expected: {1}",
value.GetType().Name,
RecordInfo.Fields[fieldIndex].FieldType.Name));
}
mLastRecordValues[fieldIndex] = value;
}
}
}
/// <summary>
/// Get a field value of the current records.
/// </summary>
/// <param name="fieldName" >The name of the field (case sensitive)</param>
public object this[string fieldName]
{
get
{
if (mLastRecordValues == null) {
throw new BadUsageException(
"You must be reading something to access this property. Try calling BeginReadFile first.");
}
int index = RecordInfo.GetFieldIndex(fieldName);
return mLastRecordValues[index];
}
set
{
int index = RecordInfo.GetFieldIndex(fieldName);
this[index] = value;
}
}
#endregion
#region " BeginReadStream"
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadStream/*'/>
public IDisposable BeginReadStream(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader", "The TextReader can't be null.");
if (mAsyncWriter != null)
throw new BadUsageException("You can't start to read while you are writing.");
var recordReader = new NewLineDelimitedRecordReader(reader);
ResetFields();
mHeaderText = String.Empty;
mFooterText = String.Empty;
if (RecordInfo.IgnoreFirst > 0) {
for (int i = 0; i < RecordInfo.IgnoreFirst; i++) {
string temp = recordReader.ReadRecordString();
mLineNumber++;
if (temp != null)
mHeaderText += temp + StringHelper.NewLine;
else
break;
}
}
mAsyncReader = new ForwardReader(recordReader, RecordInfo.IgnoreLast, mLineNumber) {
DiscardForward = true
};
State = EngineState.Reading;
mStreamInfo = new StreamInfoProvider(reader);
mCurrentRecord = 0;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes));
return this;
}
#endregion
#region " BeginReadFile "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadFile/*'/>
public IDisposable BeginReadFile(string fileName)
{
BeginReadFile(fileName, DefaultReadBufferSize);
return this;
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadFile/*'/>
/// <param name="bufferSize">Buffer size to read</param>
public IDisposable BeginReadFile(string fileName, int bufferSize)
{
BeginReadStream(new InternalStreamReader(fileName, mEncoding, true, bufferSize));
return this;
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadString/*'/>
public IDisposable BeginReadString(string sourceData)
{
if (sourceData == null)
sourceData = String.Empty;
BeginReadStream(new InternalStringReader(sourceData));
return this;
}
#endregion
#region " ReadNext "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/ReadNext/*'/>
public T ReadNext()
{
if (mAsyncReader == null)
throw new BadUsageException("Before call ReadNext you must call BeginReadFile or BeginReadStream.");
ReadNextRecord();
return mLastRecord;
}
private int mCurrentRecord = 0;
private void ReadNextRecord()
{
string currentLine = mAsyncReader.ReadNextLine();
mLineNumber++;
bool byPass = false;
mLastRecord = default(T);
var line = new LineInfo(string.Empty) {
mReader = mAsyncReader
};
if (mLastRecordValues == null)
mLastRecordValues = new object[RecordInfo.FieldCount];
while (true) {
if (currentLine != null) {
try {
mTotalRecords++;
mCurrentRecord++;
line.ReLoad(currentLine);
bool skip = false;
mLastRecord = (T) RecordInfo.Operations.CreateRecordHandler();
if (MustNotifyProgress) // Avoid object creation
{
OnProgress(new ProgressEventArgs(mCurrentRecord,
-1,
mStreamInfo.Position,
mStreamInfo.TotalBytes));
}
BeforeReadEventArgs<T> e = null;
if (MustNotifyRead) // Avoid object creation
{
e = new BeforeReadEventArgs<T>(this, mLastRecord, currentLine, LineNumber);
skip = OnBeforeReadRecord(e);
if (e.RecordLineChanged)
line.ReLoad(e.RecordLine);
}
if (skip == false) {
if (RecordInfo.Operations.StringToRecord(mLastRecord, line, mLastRecordValues)) {
if (MustNotifyRead) // Avoid object creation
skip = OnAfterReadRecord(currentLine, mLastRecord, e.RecordLineChanged, LineNumber);
if (skip == false) {
byPass = true;
return;
}
}
}
}
catch (Exception ex) {
switch (mErrorManager.ErrorMode) {
case ErrorMode.ThrowException:
byPass = true;
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo {
mLineNumber = mAsyncReader.LineNumber,
mExceptionInfo = ex,
mRecordString = currentLine
};
// err.mColumnNumber = mColumnNum;
mErrorManager.AddError(err);
break;
}
}
finally {
if (byPass == false) {
currentLine = mAsyncReader.ReadNextLine();
mLineNumber = mAsyncReader.LineNumber;
}
}
}
else {
mLastRecordValues = null;
mLastRecord = default(T);
if (RecordInfo.IgnoreLast > 0)
mFooterText = mAsyncReader.RemainingText;
try {
mAsyncReader.Close();
//mAsyncReader = null;
}
catch {}
return;
}
}
}
/// <summary>
/// Return array of object for all data to end of the file
/// </summary>
/// <returns>Array of objects created from data on file</returns>
public T[] ReadToEnd()
{
return ReadNexts(int.MaxValue);
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/ReadNexts/*'/>
public T[] ReadNexts(int numberOfRecords)
{
if (mAsyncReader == null)
throw new BadUsageException("Before call ReadNext you must call BeginReadFile or BeginReadStream.");
var arr = new List<T>(numberOfRecords);
for (int i = 0; i < numberOfRecords; i++) {
ReadNextRecord();
if (mLastRecord != null)
arr.Add(mLastRecord);
else
break;
}
return arr.ToArray();
}
#endregion
#region " Close "
/// <summary>
/// Save all the buffered data for write to the disk.
/// Useful to opened async engines that wants to save pending values to
/// disk or for engines used for logging.
/// </summary>
public void Flush()
{
if (mAsyncWriter != null)
mAsyncWriter.Flush();
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/Close/*'/>
public void Close()
{
lock (this) {
State = EngineState.Closed;
try {
mLastRecordValues = null;
mLastRecord = default(T);
var reader = mAsyncReader;
if (reader != null) {
reader.Close();
mAsyncReader = null;
}
}
catch {}
try {
var writer = mAsyncWriter;
if (writer != null) {
if (!string.IsNullOrEmpty(mFooterText)) {
if (mFooterText.EndsWith(StringHelper.NewLine))
writer.Write(mFooterText);
else
writer.WriteLine(mFooterText);
}
writer.Close();
mAsyncWriter = null;
}
}
catch {}
}
}
#endregion
#region " BeginWriteStream"
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteStream/*'/>
public IDisposable BeginWriteStream(TextWriter writer)
{
if (writer == null)
throw new ArgumentException("writer", "The TextWriter can't be null.");
if (mAsyncReader != null)
throw new BadUsageException("You can't start to write while you are reading.");
State = EngineState.Writing;
ResetFields();
mAsyncWriter = writer;
WriteHeader();
mStreamInfo = new StreamInfoProvider(mAsyncWriter);
mCurrentRecord = 0;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes));
return this;
}
private void WriteHeader()
{
if (!string.IsNullOrEmpty(mHeaderText)) {
if (mHeaderText.EndsWith(StringHelper.NewLine))
mAsyncWriter.Write(mHeaderText);
else
mAsyncWriter.WriteLine(mHeaderText);
}
}
#endregion
#region " BeginWriteFile "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteFile/*'/>
public IDisposable BeginWriteFile(string fileName)
{
return BeginWriteFile(fileName, DefaultWriteBufferSize);
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteFile/*'/>
/// <param name="bufferSize">Size of the write buffer</param>
public IDisposable BeginWriteFile(string fileName, int bufferSize)
{
BeginWriteStream(new StreamWriter(fileName, false, mEncoding, bufferSize));
return this;
}
#endregion
#region " BeginAppendToFile "
/// <summary>
/// Begin the append to an existing file
/// </summary>
/// <param name="fileName">Filename to append to</param>
/// <returns>Object to append TODO: ???</returns>
public IDisposable BeginAppendToFile(string fileName)
{
return BeginAppendToFile(fileName, DefaultWriteBufferSize);
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginAppendToFile/*'/>
/// <param name="bufferSize">Size of the buffer for writing</param>
public IDisposable BeginAppendToFile(string fileName, int bufferSize)
{
if (mAsyncReader != null)
throw new BadUsageException("You can't start to write while you are reading.");
mAsyncWriter = StreamHelper.CreateFileAppender(fileName, mEncoding, false, true, bufferSize);
mHeaderText = String.Empty;
mFooterText = String.Empty;
State = EngineState.Writing;
mStreamInfo = new StreamInfoProvider(mAsyncWriter);
mCurrentRecord = 0;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes));
return this;
}
#endregion
#region " WriteNext "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/WriteNext/*'/>
public void WriteNext(T record)
{
if (mAsyncWriter == null)
throw new BadUsageException("Before call WriteNext you must call BeginWriteFile or BeginWriteStream.");
if (record == null)
throw new BadUsageException("The record to write can't be null.");
if (RecordType.IsAssignableFrom(record.GetType()) == false)
throw new BadUsageException("The record must be of type: " + RecordType.Name);
WriteRecord(record);
}
private void WriteRecord(T record)
{
string currentLine = null;
try {
mLineNumber++;
mTotalRecords++;
mCurrentRecord++;
bool skip = false;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(mCurrentRecord, -1, mStreamInfo.Position, mStreamInfo.TotalBytes));
if (MustNotifyWrite)
skip = OnBeforeWriteRecord(record, LineNumber);
if (skip == false) {
currentLine = RecordInfo.Operations.RecordToString(record);
if (MustNotifyWrite)
currentLine = OnAfterWriteRecord(currentLine, record);
mAsyncWriter.WriteLine(currentLine);
}
}
catch (Exception ex) {
switch (mErrorManager.ErrorMode) {
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo {
mLineNumber = mLineNumber,
mExceptionInfo = ex,
mRecordString = currentLine
};
// err.mColumnNumber = mColumnNum;
mErrorManager.AddError(err);
break;
}
}
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/WriteNexts/*'/>
public void WriteNexts(IEnumerable<T> records)
{
if (mAsyncWriter == null)
throw new BadUsageException("Before call WriteNext you must call BeginWriteFile or BeginWriteStream.");
if (records == null)
throw new ArgumentNullException("records", "The record to write can't be null.");
bool first = true;
foreach (var rec in records) {
if (first) {
if (RecordType.IsAssignableFrom(rec.GetType()) == false)
throw new BadUsageException("The record must be of type: " + RecordType.Name);
first = false;
}
WriteRecord(rec);
}
}
#endregion
#region " WriteNext for LastRecordValues "
/// <summary>
/// Write the current record values in the buffer. You can use
/// engine[0] or engine["YourField"] to set the values.
/// </summary>
public void WriteNextValues()
{
if (mAsyncWriter == null)
throw new BadUsageException("Before call WriteNext you must call BeginWriteFile or BeginWriteStream.");
if (mLastRecordValues == null) {
throw new BadUsageException(
"You must set some values of the record before call this method, or use the overload that has a record as argument.");
}
string currentLine = null;
try {
mLineNumber++;
mTotalRecords++;
currentLine = RecordInfo.Operations.RecordValuesToString(this.mLastRecordValues);
mAsyncWriter.WriteLine(currentLine);
}
catch (Exception ex) {
switch (mErrorManager.ErrorMode) {
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo {
mLineNumber = mLineNumber,
mExceptionInfo = ex,
mRecordString = currentLine
};
// err.mColumnNumber = mColumnNum;
mErrorManager.AddError(err);
break;
}
}
finally {
mLastRecordValues = null;
}
}
#endregion
#region " IEnumerable implementation "
/// <summary>Allows to loop record by record in the engine</summary>
/// <returns>The enumerator</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
if (mAsyncReader == null)
throw new FileHelpersException("You must call BeginRead before use the engine in a for each loop.");
return new AsyncEnumerator(this);
}
///<summary>
///Returns an enumerator that iterates through a collection.
///</summary>
///
///<returns>
///An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.
///</returns>
///<filterpriority>2</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
if (mAsyncReader == null)
throw new FileHelpersException("You must call BeginRead before use the engine in a for each loop.");
return new AsyncEnumerator(this);
}
private class AsyncEnumerator : IEnumerator<T>
{
T IEnumerator<T>.Current
{
get { return mEngine.mLastRecord; }
}
void IDisposable.Dispose()
{
mEngine.Close();
}
private readonly FileHelperAsyncEngine<T> mEngine;
public AsyncEnumerator(FileHelperAsyncEngine<T> engine)
{
mEngine = engine;
}
public bool MoveNext()
{
if (mEngine.State == EngineState.Closed)
return false;
object res = mEngine.ReadNext();
if (res == null) {
mEngine.Close();
return false;
}
return true;
}
public object Current
{
get { return mEngine.mLastRecord; }
}
public void Reset()
{
// No needed
}
}
#endregion
#region " IDisposable implementation "
/// <summary>Release Resources</summary>
void IDisposable.Dispose()
{
Close();
GC.SuppressFinalize(this);
}
/// <summary>Destructor</summary>
~FileHelperAsyncEngine()
{
Close();
}
#endregion
#region " State "
private StreamInfoProvider mStreamInfo;
/// <summary>
/// Indicates the current state of the engine.
/// </summary>
private EngineState State { get; set; }
/// <summary>
/// Indicates the State of an engine
/// </summary>
private enum EngineState
{
/// <summary>The Engine is closed</summary>
Closed = 0,
/// <summary>The Engine is reading a file, string or stream</summary>
Reading,
/// <summary>The Engine is writing a file, string or stream</summary>
Writing
}
#endregion
}
}
| |
// <copyright file=Localization.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Michael Matheis, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:59 PM</date>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using System.Reflection;
using System.IO;
using System.Windows;
namespace motionEAPAdmin.Localization
{
public static class Localization
{
//These fields are used for caching inforamtion about resources, data providers and available cultures.
private static Dictionary<string, object> m_LocalizationResources = new Dictionary<string, object>();
// ObjectDataProvider manages XAML binding resources
private static Dictionary<string, ObjectDataProvider> m_ResourceDataProviders = new Dictionary<string, ObjectDataProvider>();
private static List<CultureInfo> m_AvailableCultures = new List<CultureInfo>();
/// <summary>
/// Get or set desired UI culture
/// </summary>
/// <author>Thomas Kosch</author>
public static string CurrentCulture
{
get;
set;
}
/// <summary>
/// Get resource and manifest it into the assembly
/// </summary>
/// <author>Thomas Kosch</author>
public static Dictionary<string, object> LocalizationResources
{
get
{
if (Localization.m_LocalizationResources.Keys.Count == 0)
{
string[] resourcesInThisAssembly = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
foreach (string resource in resourcesInThisAssembly)
{
string res = resource.Substring(0, resource.LastIndexOf("."));
string resKey = res.Substring(res.LastIndexOf(".") + 1);
if (!Localization.m_LocalizationResources.ContainsKey(res))
{
Type t = Type.GetType(res);
object resourceInstance = t.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
Type.EmptyTypes, null)
.Invoke(new object[] { });
Localization.m_LocalizationResources.Add(resKey, resourceInstance);
}
}
}
return m_LocalizationResources;
}
}
/// <summary>
/// Get the actual object which is binded
/// </summary>
/// <author>Thomas Kosch</author>
public static Dictionary<string, ObjectDataProvider> ResourceDataProviders
{
get
{
Localization.PopulateDataProviders();
return m_ResourceDataProviders;
}
}
/// <summary>
/// Get the list with all actual available cultures
/// </summary>
/// <author>Thomas Kosch</author>
public static List<CultureInfo> AvailableCultures
{
get
{
if (m_AvailableCultures.Count == 0)
{
if (m_LocalizationResources.Count > 0)
{
m_AvailableCultures.Add(new CultureInfo("en-US"));
}
string resourceFileName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location) + ".resources.dll";
DirectoryInfo rootDir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
m_AvailableCultures.AddRange((from culture in CultureInfo.GetCultures(CultureTypes.AllCultures)
join folder in rootDir.GetDirectories() on culture.IetfLanguageTag equals folder.Name
where folder.GetFiles(resourceFileName).Any()
select culture));
}
return m_AvailableCultures;
}
}
/// <summary>
/// Get a single resource
/// </summary>
/// <param name="resname">Name of the resource</param>
/// <returns></returns>
/// <author>Thomas Kosch</author>
public static object GetResource(string resname)
{
if (LocalizationResources.ContainsKey(resname))
{
return LocalizationResources[resname];
}
return null;
}
/// <summary>
/// Changes UI Culture
/// </summary>
/// <param name="culture">New culture</param>
public static void ChangeCulture(CultureInfo culture)
{
CurrentCulture = culture.Name;
System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
for (int i = 0; i < ResourceDataProviders.Keys.Count; i++)
{
ObjectDataProvider prov = InstantiateDataProvider(ResourceDataProviders.ElementAt(i).Key);
if (prov != null)
prov.Refresh();
}
}
/// <summary>
/// Init for localizing everything. This method is called from App.xaml.cs
/// </summary>
/// <author>Thomas Kosch</author>
public static void PopulateDataProviders()
{
if (Localization.m_ResourceDataProviders.Keys.Count == 0)
{
string[] resourcesInThisAssembly = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
foreach (string resource in resourcesInThisAssembly)
{
string res = resource.Substring(0, resource.LastIndexOf("."));
string resKey = res.Substring(res.LastIndexOf(".") + 1);
if (!Localization.m_ResourceDataProviders.ContainsKey(res))
{
ObjectDataProvider prov = null;
try
{
if (Application.Current.Resources.Contains(resKey))
prov = (ObjectDataProvider)Application.Current.FindResource(resKey);
else
{
prov = new ObjectDataProvider() { ObjectInstance = Localization.GetResource(resKey) };
Application.Current.Resources.Add(resKey, prov);
}
}
catch
{
prov = null;
}
Localization.m_ResourceDataProviders.Add(resKey, prov);
}
}
}
}
/// <summary>
/// Get one single value from a given key
/// </summary>
/// <param name="resourceName"></param>
/// <param name="key"></param>
/// <returns></returns>
/// <author>Thomas Kosch</author>
public static string GetString(string resourceName, string key)
{
string str = null;
object resource = GetResource(resourceName);
if (resource != null)
{
PropertyInfo resStr = resource.GetType().GetProperty(key);
if (resStr != null)
{
str = System.Convert.ToString(resStr.GetValue(null, null));
}
}
return str;
}
/// <summary>
/// Returns the actual binded resource from the ObjectDataProvider
/// </summary>
/// <param name="resource"></param>
/// <returns></returns>
/// <author>Thomas Kosch</author>
private static ObjectDataProvider InstantiateDataProvider(string resource)
{
try
{
if (ResourceDataProviders.ContainsKey(resource))
{
if (ResourceDataProviders[resource] == null)
ResourceDataProviders[resource] = (ObjectDataProvider)Application.Current.FindResource(resource);
}
}
catch
{
return null;
}
return ResourceDataProviders[resource];
}
}
}
| |
// -----------------------------------------------------------------------
// Copyright (c) David Kean and Abdallah Gomah.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using System.Runtime.InteropServices;
using AudioSwitcher.Presentation.Drawing.Utilities;
using AudioSwitcher.Presentation.Drawing.Interop;
namespace AudioSwitcher.Presentation.Drawing
{
/// <summary>
/// Provides information about a givin icon.
/// This class cannot be inherited.
/// </summary>
internal class IconInfo
{
#region ReadOnly
public static int SizeOfIconDir = Marshal.SizeOf(typeof(IconDir));
public static int SizeOfIconDirEntry = Marshal.SizeOf(typeof(IconDirEntry));
public static int SizeOfGroupIconDir = Marshal.SizeOf(typeof(GroupIconDir));
public static int SizeOfGroupIconDirEntry = Marshal.SizeOf(typeof(GroupIconDirEntry));
#endregion
#region Properties
private Icon _sourceIcon;
/// <summary>
/// Gets the source System.Drawing.Icon.
/// </summary>
public Icon SourceIcon
{
get { return _sourceIcon; }
private set { _sourceIcon = value; }
}
private string _fileName = null;
/// <summary>
/// Gets the icon's file name.
/// </summary>
public string FileName
{
get { return _fileName; }
private set { _fileName = value; }
}
private List<Icon> _images;
/// <summary>
/// Gets a list System.Drawing.Icon that presents the icon contained images.
/// </summary>
public List<Icon> Images
{
get { return _images; }
private set { _images = value; }
}
/// <summary>
/// Get whether the icon contain more than one image or not.
/// </summary>
public bool IsMultiIcon
{
get { return (this.Images.Count > 1); }
}
private int _bestFitIconIndex;
/// <summary>
/// Gets icon index that best fits to screen resolution.
/// </summary>
public int BestFitIconIndex
{
get { return _bestFitIconIndex; }
private set { _bestFitIconIndex = value; }
}
private int _width;
/// <summary>
/// Gets icon width.
/// </summary>
public int Width
{
get { return _width; }
private set { _width = value; }
}
private int _height;
/// <summary>
/// Gets icon height.
/// </summary>
public int Height
{
get { return _height; }
private set { _height = value; }
}
private int _colorCount;
/// <summary>
/// Gets number of colors in icon (0 if >=8bpp).
/// </summary>
public int ColorCount
{
get { return _colorCount; }
private set { _colorCount = value; }
}
private int _planes;
/// <summary>
/// Gets icon color planes.
/// </summary>
public int Planes
{
get { return _planes; }
private set { _planes = value; }
}
private int _bitCount;
/// <summary>
/// Gets icon bits per pixel (0 if < 8bpp).
/// </summary>
public int BitCount
{
get { return _bitCount; }
private set { _bitCount = value; }
}
/// <summary>
/// Gets icon bits per pixel.
/// </summary>
public int ColorDepth
{
get
{
if (this.BitCount != 0)
return this.BitCount;
if (this.ColorCount == 0)
return 0;
return (int)Math.Log(this.ColorCount, 2);
}
}
#endregion
#region Icon Headers Properties
private IconDir _iconDir;
/// <summary>
/// Gets the AudioSwitcher.Presentation.Drawing.IconDir of the icon.
/// </summary>
public IconDir IconDir
{
get { return _iconDir; }
private set { _iconDir = value; }
}
private GroupIconDir _groupIconDir;
/// <summary>
/// Gets the AudioSwitcher.Presentation.Drawing.GroupIconDir of the icon.
/// </summary>
public GroupIconDir GroupIconDir
{
get { return _groupIconDir; }
private set { _groupIconDir = value; }
}
private List<IconDirEntry> _iconDirEntries;
/// <summary>
/// Gets a list of AudioSwitcher.Presentation.Drawing.IconDirEntry of the icon.
/// </summary>
public List<IconDirEntry> IconDirEntries
{
get { return _iconDirEntries; }
private set { _iconDirEntries = value; }
}
private List<GroupIconDirEntry> _groupIconDirEntries;
/// <summary>
/// Gets a list of AudioSwitcher.Presentation.Drawing.GroupIconDirEntry of the icon.
/// </summary>
public List<GroupIconDirEntry> GroupIconDirEntries
{
get { return _groupIconDirEntries; }
private set { _groupIconDirEntries = value; }
}
private List<byte[]> _rawData;
/// <summary>
/// Gets a list of raw data for each icon image.
/// </summary>
public List<byte[]> RawData
{
get { return _rawData; }
private set { _rawData = value; }
}
private byte[] _resourceRawData;
/// <summary>
/// Gets the icon raw data as a resource data.
/// </summary>
public byte[] ResourceRawData
{
get { return _resourceRawData; }
set { _resourceRawData = value; }
}
#endregion
#region Constructors
/// <summary>
/// Intializes a new instance of AudioSwitcher.Presentation.Drawing.IconInfo which contains the information about the givin icon.
/// </summary>
/// <param name="icon">A System.Drawing.Icon object to retrieve the information about.</param>
public IconInfo(Icon icon)
{
this.FileName = null;
LoadIconInfo(icon);
}
/// <summary>
/// Intializes a new instance of AudioSwitcher.Presentation.Drawing.IconInfo which contains the information about the icon in the givin file.
/// </summary>
/// <param name="fileName">A fully qualified name of the icon file, it can contain environment variables.</param>
public IconInfo(string fileName)
{
this.FileName = FileName;
LoadIconInfo(new Icon(fileName));
}
#endregion
#region Public Methods
/// <summary>
/// Gets the index of the icon that best fits the current display device.
/// </summary>
/// <returns>The icon index.</returns>
public int GetBestFitIconIndex()
{
int iconIndex = 0;
IntPtr resBits = Marshal.AllocHGlobal(this.ResourceRawData.Length);
Marshal.Copy(this.ResourceRawData, 0, resBits, this.ResourceRawData.Length);
try { iconIndex = DllImports.LookupIconIdFromDirectory(resBits, true); }
finally { Marshal.FreeHGlobal(resBits); }
return iconIndex;
}
/// <summary>
/// Gets the index of the icon that best fits the current display device.
/// </summary>
/// <param name="desiredSize">Specifies the desired size of the icon.</param>
/// <returns>The icon index.</returns>
public int GetBestFitIconIndex(Size desiredSize)
{
return GetBestFitIconIndex(desiredSize, false);
}
/// <summary>
/// Gets the index of the icon that best fits the current display device.
/// </summary>
/// <param name="desiredSize">Specifies the desired size of the icon.</param>
/// <param name="isMonochrome">Specifies whether to get the monochrome icon or the colored one.</param>
/// <returns>The icon index.</returns>
public int GetBestFitIconIndex(Size desiredSize, bool isMonochrome)
{
int iconIndex = 0;
LookupIconIdFromDirectoryExFlags flags = LookupIconIdFromDirectoryExFlags.LR_DEFAULTCOLOR;
if (isMonochrome)
flags = LookupIconIdFromDirectoryExFlags.LR_MONOCHROME;
IntPtr resBits = Marshal.AllocHGlobal(this.ResourceRawData.Length);
Marshal.Copy(this.ResourceRawData, 0, resBits, this.ResourceRawData.Length);
try { iconIndex = DllImports.LookupIconIdFromDirectoryEx(resBits, true, desiredSize.Width, desiredSize.Height, flags); }
finally { Marshal.FreeHGlobal(resBits); }
return iconIndex;
}
#endregion
private void LoadIconInfo(Icon icon)
{
if (icon == null)
throw new ArgumentNullException("icon");
this.SourceIcon = icon;
MemoryStream inputStream = new MemoryStream();
this.SourceIcon.Save(inputStream);
inputStream.Seek(0, SeekOrigin.Begin);
IconDir dir = Utility.ReadStructure<IconDir>(inputStream);
this.IconDir = dir;
this.GroupIconDir = dir.ToGroupIconDir();
this.Images = new List<Icon>(dir.Count);
this.IconDirEntries = new List<IconDirEntry>(dir.Count);
this.GroupIconDirEntries = new List<GroupIconDirEntry>(dir.Count);
this.RawData = new List<byte[]>(dir.Count);
IconDir newDir = dir;
newDir.Count = 1;
for (int i = 0; i < dir.Count; i++)
{
inputStream.Seek(SizeOfIconDir + i * SizeOfIconDirEntry, SeekOrigin.Begin);
IconDirEntry entry = Utility.ReadStructure<IconDirEntry>(inputStream);
this.IconDirEntries.Add(entry);
this.GroupIconDirEntries.Add(entry.ToGroupIconDirEntry(i));
byte[] content = new byte[entry.BytesInRes];
inputStream.Seek(entry.ImageOffset, SeekOrigin.Begin);
inputStream.Read(content, 0, content.Length);
this.RawData.Add(content);
IconDirEntry newEntry = entry;
newEntry.ImageOffset = SizeOfIconDir + SizeOfIconDirEntry;
MemoryStream outputStream = new MemoryStream();
Utility.WriteStructure<IconDir>(outputStream, newDir);
Utility.WriteStructure<IconDirEntry>(outputStream, newEntry);
outputStream.Write(content, 0, content.Length);
outputStream.Seek(0, SeekOrigin.Begin);
Icon newIcon = new Icon(outputStream);
outputStream.Close();
this.Images.Add(newIcon);
if (dir.Count == 1)
{
this.BestFitIconIndex = 0;
this.Width = entry.Width;
this.Height = entry.Height;
this.ColorCount = entry.ColorCount;
this.Planes = entry.Planes;
this.BitCount = entry.BitCount;
}
}
inputStream.Close();
this.ResourceRawData = GetIconResourceData();
if (dir.Count > 1)
{
this.BestFitIconIndex = GetBestFitIconIndex();
this.Width = this.IconDirEntries[this.BestFitIconIndex].Width;
this.Height = this.IconDirEntries[this.BestFitIconIndex].Height;
this.ColorCount = this.IconDirEntries[this.BestFitIconIndex].ColorCount;
this.Planes = this.IconDirEntries[this.BestFitIconIndex].Planes;
this.BitCount = this.IconDirEntries[this.BestFitIconIndex].BitCount;
}
}
private byte[] GetIconResourceData()
{
MemoryStream outputStream = new MemoryStream();
Utility.WriteStructure<GroupIconDir>(outputStream, this.GroupIconDir);
foreach (GroupIconDirEntry entry in this.GroupIconDirEntries)
{
Utility.WriteStructure<GroupIconDirEntry>(outputStream, entry);
}
return outputStream.ToArray();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using SIL.Linq;
namespace SIL.Xml
{
/// <summary>
/// Summary description for XmlUtils.
/// </summary>
public static class XmlUtils
{
/// <summary>
/// Returns true if value of attrName is 'true' or 'yes' (case ignored)
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The optional attribute to find.</param>
/// <returns></returns>
public static bool GetBooleanAttributeValue(XmlNode node, string attrName)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName));
}
/// <summary>
/// Returns true if value of attrName is 'true' or 'yes' (case ignored)
/// </summary>
/// <param name="element">The XElement to look in.</param>
/// <param name="attrName">The optional attribute to find.</param>
/// <returns></returns>
public static bool GetBooleanAttributeValue(XElement element, string attrName)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(element, attrName));
}
/// <summary>
/// Given bytes that represent an xml element, return the values of requested attributes (if they exist).
/// </summary>
/// <param name="data">Data that is expected to an xml element.</param>
/// <param name="attributes">A set of attributes, the values of which are to be returned.</param>
/// <returns>A dictionary </returns>
public static Dictionary<string, string> GetAttributes(byte[] data, HashSet<string> attributes)
{
var results = new Dictionary<string, string>(attributes.Count);
using (var reader = XmlReader.Create(new MemoryStream(data), CanonicalXmlSettings.CreateXmlReaderSettings(ConformanceLevel.Fragment)))
{
reader.MoveToContent();
foreach (var attr in attributes)
{
results.Add(attr, null);
if (reader.MoveToAttribute(attr))
{
results[attr] = reader.Value;
}
}
}
return results;
}
/// <summary>
/// Given a string that represents an xml element, return the values of requested attributes (if they exist).
/// </summary>
/// <param name="data">Data that is expected to an xml element.</param>
/// <param name="attributes">A set of attributes, the values of which are to be returned.</param>
/// <returns>A dictionary </returns>
public static Dictionary<string, string> GetAttributes(string data, HashSet<string> attributes)
{
var results = new Dictionary<string, string>(attributes.Count);
using (var reader = XmlReader.Create(new StringReader(data), CanonicalXmlSettings.CreateXmlReaderSettings(ConformanceLevel.Fragment)))
{
reader.MoveToContent();
foreach (var attr in attributes)
{
results.Add(attr, null);
if (reader.MoveToAttribute(attr))
{
results[attr] = reader.Value;
}
}
}
return results;
}
/// <summary>
/// Returns true if value of attrName is 'true' or 'yes' (case ignored)
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The optional attribute to find.</param>
/// <returns></returns>
public static bool GetBooleanAttributeValue(XPathNavigator node, string attrName)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName));
}
/// <summary>
/// Returns true if sValue is 'true' or 'yes' (case ignored)
/// </summary>
public static bool GetBooleanAttributeValue(string sValue)
{
return (sValue != null &&
(sValue.ToLower().Equals("true") || sValue.ToLower().Equals("yes")));
}
/// <summary>
/// Returns a integer obtained from the (mandatory) attribute named.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The mandatory attribute to find.</param>
/// <returns>The value, or 0 if attr is missing.</returns>
public static int GetMandatoryIntegerAttributeValue(XmlNode node, string attrName)
{
return Int32.Parse(GetMandatoryAttributeValue(node, attrName));
}
/// <summary>
/// Returns a integer obtained from the (mandatory) attribute named.
/// </summary>
/// <param name="element">The XmlNode to look in.</param>
/// <param name="attrName">The mandatory attribute to find.</param>
/// <returns>The value, or 0 if attr is missing.</returns>
/// <exception cref="ApplicationException">Thrown if <paramref name="attrName"/> is not in <paramref name="element"/>.</exception>
/// <exception cref="FormatException">Thrown, if <paramref name="attrName"/> value is not an integer (int).</exception>
public static int GetMandatoryIntegerAttributeValue(XElement element, string attrName)
{
return int.Parse(GetMandatoryAttributeValue(element, attrName), CultureInfo.InvariantCulture);
}
/// <summary>
/// Return an optional integer attribute value, or if not found, the default value.
/// </summary>
/// <param name="node"></param>
/// <param name="attrName"></param>
/// <param name="defaultVal"></param>
/// <returns></returns>
public static int GetOptionalIntegerValue(XmlNode node, string attrName, int defaultVal)
{
string val = GetOptionalAttributeValue(node, attrName);
if (val == null)
{
return defaultVal;
}
return Int32.Parse(val);
}
/// <summary>
/// Return an optional integer attribute value, or if not found, the default value.
/// </summary>
/// <exception cref="FormatException">Thrown, if <paramref name="attrName"/> value is not an integer (int).</exception>
public static int GetOptionalIntegerValue(XElement element, string attrName, int defaultVal)
{
var val = GetOptionalAttributeValue(element, attrName);
return string.IsNullOrEmpty(val) ? defaultVal : int.Parse(val, CultureInfo.InvariantCulture);
}
/// <summary>
/// Retrieve an array, given an attribute consisting of a comma-separated list of integers
/// </summary>
/// <param name="node"></param>
/// <param name="attrName"></param>
/// <returns></returns>
public static int[] GetMandatoryIntegerListAttributeValue(XmlNode node, string attrName)
{
string input = GetMandatoryAttributeValue(node, attrName);
string[] vals = input.Split(',');
int[] result = new int[vals.Length];
for (int i = 0;i < vals.Length;i++)
{
result[i] = Int32.Parse(vals[i]);
}
return result;
}
/// <summary>
/// Retrieve an array, given an attribute consisting of a comma-separated list of integers
/// </summary>
/// <param name="element"></param>
/// <param name="attrName"></param>
/// <returns></returns>
public static int[] GetMandatoryIntegerListAttributeValue(XElement element, string attrName)
{
var input = GetMandatoryAttributeValue(element, attrName);
var vals = input.Split(',');
var result = new int[vals.Length];
for (var i = 0; i < vals.Length; i++)
result[i] = int.Parse(vals[i], CultureInfo.InvariantCulture);
return result;
}
/// <summary>
/// Retrieve an array, given an attribute consisting of a comma-separated list of integers
/// </summary>
/// <param name="node"></param>
/// <param name="attrName"></param>
/// <returns></returns>
[CLSCompliant(false)]
public static uint[] GetMandatoryUIntegerListAttributeValue(XmlNode node, string attrName)
{
var input = GetMandatoryAttributeValue(node, attrName);
var vals = input.Split(',');
var result = new uint[vals.Length];
for (var i = 0; i < vals.Length; i++)
result[i] = uint.Parse(vals[i]);
return result;
}
/// <summary>
/// Retrieve an array, given an attribute consisting of a comma-separated list of integers
/// </summary>
[CLSCompliant(false)]
public static uint[] GetMandatoryUIntegerListAttributeValue(XElement element, string attrName)
{
var input = GetMandatoryAttributeValue(element, attrName);
var vals = input.Split(',');
var result = new uint[vals.Length];
for (var i = 0; i < vals.Length; i++)
result[i] = uint.Parse(vals[i]);
return result;
}
private static string MakeStringFromEnum<T>(IEnumerable<T> vals, int count)
{
var builder = new StringBuilder(count * 7); // enough unless VERY big numbers
foreach (var val in vals)
{
if (builder.Length > 0)
builder.Append(",");
builder.AppendFormat(CultureInfo.InvariantCulture, "{0}", val);
}
return builder.ToString();
}
/// <summary>
/// Make a value suitable for GetMandatoryIntegerListAttributeValue to parse.
/// </summary>
/// <param name="vals"></param>
/// <returns></returns>
public static string MakeIntegerListValue(int[] vals)
{
return MakeStringFromEnum(vals, vals.Length);
}
/// <summary>
/// Make a comma-separated list of the ToStrings of the values in the list.
/// </summary>
/// <param name="vals"></param>
/// <returns></returns>
public static string MakeStringFromList(List<int> vals)
{
return MakeStringFromEnum(vals, vals.Count);
}
/// <summary>
/// Make a comma-separated list of the ToStrings of the values in the list.
/// </summary>
/// <param name="vals"></param>
/// <returns></returns>
[CLSCompliant(false)]
public static string MakeStringFromList(List<uint> vals)
{
return MakeStringFromEnum(vals, vals.Count);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <param name="defaultValue"></param>
/// <returns>The value of the attribute, or the default value, if the attribute dismissing</returns>
public static bool GetOptionalBooleanAttributeValue(XmlNode node, string attrName,
bool defaultValue)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName,
defaultValue ? "true" : "false"));
}
/// <summary>
/// Get an optional attribute value from an XElement.
/// </summary>
/// <param name="element">The XElement to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <param name="defaultValue"></param>
/// <returns>The value of the attribute, or the default value, if the attribute dismissing</returns>
public static bool GetOptionalBooleanAttributeValue(XElement element, string attrName, bool defaultValue)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(element, attrName,
defaultValue ? "true" : "false"));
}
/// <summary>
/// Deprecated: use GetOptionalAttributeValue instead.
/// </summary>
/// <param name="node"></param>
/// <param name="attrName"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
[Obsolete("Use GetOptionalAttributeValue instead")]
public static string GetAttributeValue(XmlNode node, string attrName, string defaultValue)
{
return GetOptionalAttributeValue(node, attrName, defaultValue);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
[Obsolete("Use GetOptionalAttributeValue instead")]
public static string GetAttributeValue(XmlNode node, string attrName)
{
return GetOptionalAttributeValue(node, attrName);
}
/// <summary>
/// Get an optional attribute value from an XElement.
/// </summary>
/// <param name="element">The XElement to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
[Obsolete("Use GetOptionalAttributeValue instead")]
public static string GetAttributeValue(XElement element, string attrName)
{
return GetOptionalAttributeValue(element, attrName);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetOptionalAttributeValue(XmlNode node, string attrName)
{
return GetOptionalAttributeValue(node, attrName, null);
}
/// <summary>
/// Get an optional attribute value from an XElement.
/// </summary>
/// <param name="element">The XElement to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetOptionalAttributeValue(XElement element, string attrName)
{
return GetOptionalAttributeValue(element, attrName, null);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetOptionalAttributeValue(XPathNavigator node, string attrName)
{
return GetOptionalAttributeValue(node, attrName, null);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
/// <param name="defaultString"></param>
public static string GetOptionalAttributeValue(XmlNode node, string attrName,
string defaultString)
{
if (node != null && node.Attributes != null)
{
XmlAttribute xa = node.Attributes[attrName];
if (xa != null)
{
return xa.Value;
}
}
return defaultString;
}
/// <summary>
/// Get an optional attribute value from an XElement.
/// </summary>
/// <param name="element">The XElement to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <param name="defaultString"></param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetOptionalAttributeValue(XElement element, string attrName,
string defaultString)
{
if (element == null || !element.Attributes().Any())
{
return defaultString;
}
var attribute = element.Attribute(attrName);
return attribute != null ? attribute.Value : defaultString;
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
/// <param name="defaultString"></param>
public static string GetOptionalAttributeValue(XPathNavigator node, string attrName,
string defaultString)
{
if (node != null && node.HasAttributes)
{
string s = node.GetAttribute(attrName, string.Empty);
if (!string.IsNullOrEmpty(s))
{
return s;
}
}
return defaultString;
}
/// <summary>
/// Return the node that has the desired 'name', either the input node or a decendent.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="name">The XmlNode name to find.</param>
/// <returns></returns>
public static XmlNode FindNode(XmlNode node, string name)
{
if (node.Name == name)
{
return node;
}
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name == name)
{
return childNode;
}
XmlNode n = FindNode(childNode, name);
if (n != null)
{
return n;
}
}
return null;
}
/// <summary>
/// Return the element that has the desired 'name', either the input element or a decendent.
/// </summary>
/// <param name="element">The XElement to look in.</param>
/// <param name="name">The XElement name to find.</param>
/// <returns></returns>
public static XElement FindElement(XElement element, string name)
{
if (element.Name == name)
return element;
foreach (var childElement in element.Elements())
{
if (childElement.Name == name)
return childElement;
var grandchildElement = FindElement(childElement, name);
if (grandchildElement != null)
return grandchildElement;
}
return null;
}
/// <summary>
/// Find the index of the <paramref name="target"/> in <paramref name="elements"/> that
/// 'matches' the <paramref name="target"/> element.
/// </summary>
/// <param name="elements">The elements to look in.</param>
/// <param name="target">The target to look for a match of.</param>
/// <returns>Return -1 if not found.</returns>
public static int FindIndexOfMatchingNode(IEnumerable<XElement> elements, XElement target)
{
int index = 0;
foreach (var element in elements)
{
if (NodesMatch(element, target))
return index;
index++;
}
return -1;
}
#region Obsolete mis-spelled methods
[Obsolete("Use GetMandatoryAttributeValue instead")]
public static string GetManditoryAttributeValue(XmlNode node, string attrName)
{
return GetMandatoryAttributeValue(node, attrName);
}
[Obsolete("Use GetMandatoryAttributeValue instead")]
public static string GetManditoryAttributeValue(XElement element, string attrName)
{
return GetMandatoryAttributeValue(element, attrName);
}
[Obsolete("Use GetMandatoryAttributeValue instead")]
public static string GetManditoryAttributeValue(XPathNavigator node, string attrName)
{
return GetMandatoryAttributeValue(node, attrName);
}
#endregion
/// <summary>
/// Get an obligatory attribute value.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The required attribute to find.</param>
/// <returns>The value of the attribute.</returns>
/// <exception cref="ApplicationException">
/// Thrown when the value is not found in the node.
/// </exception>
public static string GetMandatoryAttributeValue(XmlNode node, string attrName)
{
string retval = GetOptionalAttributeValue(node, attrName, null);
if (retval == null)
throw new ApplicationException($"The attribute'{attrName}' is mandatory, but was missing. {node.OuterXml}");
return retval;
}
/// <summary>
/// Get an obligatory attribute value.
/// </summary>
/// <param name="element">The XElement to look in.</param>
/// <param name="attrName">The required attribute to find.</param>
/// <returns>The value of the attribute.</returns>
/// <exception cref="ApplicationException">
/// Thrown when the value is not found in the node.
/// </exception>
public static string GetMandatoryAttributeValue(XElement element, string attrName)
{
var retval = GetOptionalAttributeValue(element, attrName, null);
if (retval == null)
throw new ApplicationException($"The attribute'{attrName}' is mandatory, but was missing. {element}");
return retval;
}
public static string GetMandatoryAttributeValue(XPathNavigator node, string attrName)
{
string retval = GetOptionalAttributeValue(node, attrName, null);
if (retval == null)
throw new ApplicationException($"The attribute'{attrName}' is mandatory, but was missing. {node.OuterXml}");
return retval;
}
/// <summary>
/// Append an child node with the specified name and value to <paramref name="node"/>.
/// </summary>
/// <param name="node"></param>
/// <param name="elementName"></param>
public static XmlElement AppendElement(XmlNode node, string elementName)
{
XmlElement xe = node.OwnerDocument.CreateElement(elementName);
node.AppendChild(xe);
return xe;
}
/// <summary>
/// Append an attribute with the specified name and value to parent.
/// </summary>
[Obsolete("Use SetAttribute instead")]
public static void AppendAttribute(XmlNode parent, string attrName, string attrVal)
{
SetAttribute(parent, attrName, attrVal);
}
/// <summary>
/// Change the value of the specified attribute, appending it if not already present.
/// </summary>
public static void SetAttribute(XmlNode node, string attrName, string attrVal)
{
var attr = node.Attributes[attrName];
if (attr != null)
{
attr.Value = attrVal;
}
else
{
attr = node.OwnerDocument.CreateAttribute(attrName);
attr.Value = attrVal;
node.Attributes.Append(attr);
}
}
/// <summary>
/// Change the value of the specified attribute, appending it if not already present.
/// </summary>
public static void SetAttribute(XElement element, string attrName, string attrVal)
{
var attr = element.Attribute(attrName);
if (attr != null)
{
attr.Value = attrVal;
}
else
{
element.Add(new XAttribute(attrName, attrVal));
}
}
/// <summary>
/// Return true if the two nodes match. Corresponding children should match, and
/// corresponding attributes (though not necessarily in the same order).
/// The nodes are expected to be actually XmlElements; not tested for other cases.
/// Comments do not affect equality.
/// </summary>
/// <param name="node1"></param>
/// <param name="node2"></param>
/// <returns></returns>
public static bool NodesMatch(XmlNode node1, XmlNode node2)
{
if (node1 == null && node2 == null)
{
return true;
}
if (node1 == null || node2 == null)
{
return false;
}
if (node1.Name != node2.Name)
{
return false;
}
if (node1.InnerText != node2.InnerText)
{
return false;
}
if (node1.Attributes == null && node2.Attributes != null)
{
return false;
}
if (node1.Attributes != null && node2.Attributes == null)
{
return false;
}
if (node1.Attributes != null)
{
if (node1.Attributes.Count != node2.Attributes.Count)
{
return false;
}
for (int i = 0;i < node1.Attributes.Count;i++)
{
XmlAttribute xa1 = node1.Attributes[i];
XmlAttribute xa2 = node2.Attributes[xa1.Name];
if (xa2 == null || xa1.Value != xa2.Value)
{
return false;
}
}
}
if (node1.ChildNodes == null && node2.ChildNodes != null)
{
return false;
}
if (node1.ChildNodes != null && node2.ChildNodes == null)
{
return false;
}
if (node1.ChildNodes != null)
{
int ichild1 = 0; // index node1.ChildNodes
int ichild2 = 0; // index node2.ChildNodes
while (ichild1 < node1.ChildNodes.Count && ichild2 < node1.ChildNodes.Count)
{
XmlNode child1 = node1.ChildNodes[ichild1];
// Note that we must defer doing the 'continue' until after we have checked to see if both children are comments
// If we continue immediately and the last node of both elements is a comment, the second node will not have
// ichild2 incremented and the final test will fail.
bool foundComment = false;
if (child1 is XmlComment)
{
ichild1++;
foundComment = true;
}
XmlNode child2 = node2.ChildNodes[ichild2];
if (child2 is XmlComment)
{
ichild2++;
foundComment = true;
}
if (foundComment)
{
continue;
}
if (!NodesMatch(child1, child2))
{
return false;
}
ichild1++;
ichild2++;
}
// If we finished both lists we got a match.
return ichild1 == node1.ChildNodes.Count && ichild2 == node2.ChildNodes.Count;
}
// both lists are null
return true;
}
/// <summary>
/// Return true if the two nodes match. Corresponding children should match, and
/// corresponding attributes (though not necessarily in the same order).
/// Comments do not affect equality.
/// </summary>
public static bool NodesMatch(XElement element1, XElement element2)
{
if (element1 == null && element2 == null)
return true;
if (element1 == null || element2 == null)
return false;
if (element1.Name != element2.Name)
return false;
if (element1.GetInnerText() != element2.GetInnerText())
return false;
if (!element1.Attributes().Any() && element2.Attributes().Any())
return false;
if (element1.Attributes().Any() && !element2.Attributes().Any())
return false;
if (element1.Attributes().Any())
{
if (element1.Attributes().Count() != element2.Attributes().Count())
return false;
foreach (var xa1 in element1.Attributes())
{
var xa2 = element2.Attribute(xa1.Name);
if (xa2 == null || xa1.Value != xa2.Value)
return false;
}
}
if (!element1.HasElements && element2.HasElements)
return false;
if (element1.HasElements && !element2.HasElements)
return false;
if (element1.HasElements)
{
int ichild1 = 0; // index node1.Elements()
int ichild2 = 0; // index node2.Elements()
while (ichild1 < element1.Elements().Count() && ichild2 < element1.Elements().Count())
{
var child1 = element1.Elements().ToList()[ichild1];
var child2 = element2.Elements().ToList()[ichild2];
if (!NodesMatch(child1, child2))
return false;
ichild1++;
ichild2++;
}
// If we finished both lists we got a match.
return (ichild1 == element1.Elements().Count()) && (ichild2 == element2.Elements().Count());
}
// both lists are null
return true;
}
/// <summary>
/// Return the first child of the node that is not a comment (or null).
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static XmlNode GetFirstNonCommentChild(XmlNode node)
{
if (node == null)
{
return null;
}
foreach (XmlNode child in node.ChildNodes)
{
if (!(child is XmlComment))
{
return child;
}
}
return null;
}
/// <summary>
/// Return the first child of the node that is not a comment (or null).
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static XElement GetFirstNonCommentChild(XElement element)
{
return (element == null) ? null : element.Elements().FirstOrDefault();
}
/// <summary>
/// Fix the string to be safe in a text region of XML.
/// </summary>
/// <param name="sInput"></param>
/// <returns></returns>
public static string MakeSafeXml(string sInput)
{
string sOutput = sInput;
if (!string.IsNullOrEmpty(sOutput))
{
sOutput = sOutput.Replace("&", "&");
sOutput = sOutput.Replace("<", "<");
sOutput = sOutput.Replace(">", ">");
}
return sOutput;
}
/// <summary>
/// Convert a possibly multiparagraph string to a form that is safe to store both in an XML file.
/// </summary>
public static string ConvertMultiparagraphToSafeXml(string sInput)
{
var sOutput = sInput;
if (!string.IsNullOrEmpty(sOutput))
{
sOutput = sOutput.Replace(Environment.NewLine, "\u2028");
sOutput = sOutput.Replace("\n", "\u2028");
sOutput = sOutput.Replace("\r", "\u2028");
sOutput = MakeSafeXml(sOutput);
}
return sOutput;
}
/// <summary>
/// Fix the string to be safe in an attribute value of XML.
/// </summary>
/// <param name="sInput"></param>
/// <returns></returns>
public static string MakeSafeXmlAttribute(string sInput)
{
string sOutput = sInput;
if (!string.IsNullOrEmpty(sOutput))
{
sOutput = sOutput.Replace("&", "&");
sOutput = sOutput.Replace("\"", """);
sOutput = sOutput.Replace("'", "'");
sOutput = sOutput.Replace("<", "<");
sOutput = sOutput.Replace(">", ">");
}
return sOutput;
}
/// <summary>
/// Convert an encoded attribute string into plain text.
/// </summary>
/// <param name="sInput"></param>
/// <returns></returns>
public static string DecodeXmlAttribute(string sInput)
{
string sOutput = sInput;
if (!String.IsNullOrEmpty(sOutput) && sOutput.Contains("&"))
{
sOutput = sOutput.Replace(">", ">");
sOutput = sOutput.Replace("<", "<");
sOutput = sOutput.Replace("'", "'");
sOutput = sOutput.Replace(""", "\"");
sOutput = sOutput.Replace("&", "&");
}
for (int idx = sOutput.IndexOf("&#"); idx >= 0; idx = sOutput.IndexOf("&#"))
{
int idxEnd = sOutput.IndexOf(';', idx);
if (idxEnd < 0)
break;
string sOrig = sOutput.Substring(idx, (idxEnd - idx) + 1);
string sNum = sOutput.Substring(idx + 2, idxEnd - (idx + 2));
string sReplace = null;
int chNum = 0;
if (sNum[0] == 'x' || sNum[0] == 'X')
{
if (Int32.TryParse(sNum.Substring(1), NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo, out chNum))
sReplace = Char.ConvertFromUtf32(chNum);
}
else
{
if (Int32.TryParse(sNum, out chNum))
sReplace = Char.ConvertFromUtf32(chNum);
}
if (sReplace == null)
sReplace = sNum;
sOutput = sOutput.Replace(sOrig, sReplace);
}
return sOutput;
}
/// <summary>
/// lifted from http://www.knowdotnet.com/articles/indentxml.html
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static string GetIndendentedXml(string xml)
{
string outXml = string.Empty;
using(MemoryStream ms = new MemoryStream())
// Create a XMLTextWriter that will send its output to a memory stream (file)
using (XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode))
{
XmlDocument doc = new XmlDocument();
// try
// {
// Load the unformatted XML text string into an instance
// of the XML Document Object Model (DOM)
doc.LoadXml(xml);
// Set the formatting property of the XML Text Writer to indented
// the text writer is where the indenting will be performed
xtw.Formatting = Formatting.Indented;
// write dom xml to the xmltextwriter
doc.WriteContentTo(xtw);
// Flush the contents of the text writer
// to the memory stream, which is simply a memory file
xtw.Flush();
// set to start of the memory stream (file)
ms.Seek(0, SeekOrigin.Begin);
// create a reader to read the contents of
// the memory stream (file)
StreamReader sr = new StreamReader(ms);
// return the formatted string to caller
return sr.ReadToEnd();
// }
// catch (Exception ex)
// {
// return ex.Message;
// }
}
}
//todo: what's the diff between this one and the next?
static public XmlElement GetOrCreateElementPredicate(XmlDocument dom, XmlElement parent, string predicate, string name)
{
XmlElement element = (XmlElement)parent.SelectSingleNodeHonoringDefaultNS("/" + predicate);
if (element == null)
{
element = parent.OwnerDocument.CreateElement(name, parent.NamespaceURI);
parent.AppendChild(element);
}
return element;
}
static public XmlElement GetOrCreateElement(XmlDocument dom, string parentPath, string name)
{
XmlElement element = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS(parentPath + "/" + name);
if (element == null)
{
XmlElement parent = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS(parentPath);
if (parent == null)
return null;
element = parent.OwnerDocument.CreateElement(name, parent.NamespaceURI);
parent.AppendChild(element);
}
return element;
}
public static string GetStringAttribute(XmlNode form, string attr)
{
try
{
return form.Attributes[attr].Value;
}
catch (NullReferenceException)
{
throw new XmlFormatException(string.Format("Expected a {0} attribute on {1}.", attr, form.OuterXml));
}
}
public static string GetOptionalAttributeString(XmlNode xmlNode, string attributeName)
{
XmlAttribute attr = xmlNode.Attributes[attributeName];
if (attr == null)
return null;
return attr.Value;
}
public static XmlNode GetDocumentNodeFromRawXml(string outerXml, XmlNode nodeMaker)
{
if (string.IsNullOrEmpty(outerXml))
{
throw new ArgumentException();
}
XmlDocument doc = nodeMaker as XmlDocument;
if (doc == null)
{
doc = nodeMaker.OwnerDocument;
}
using (StringReader sr = new StringReader(outerXml))
{
using (XmlReader r = XmlReader.Create(sr))
{
r.Read();
return doc.ReadNode(r);
}
}
}
public static string GetXmlForShowingInHtml(string xml)
{
var s = XmlUtils.GetIndendentedXml(xml).Replace("<", "<");
s = s.Replace("\r\n", "<br/>");
s = s.Replace(" ", " ");
return s;
}
public static string GetTitleOfHtml(XmlDocument dom, string defaultIfMissing)
{
var title = dom.SelectSingleNode("//head/title");
if (title != null && !string.IsNullOrEmpty(title.InnerText) && !string.IsNullOrEmpty(title.InnerText.Trim()))
{
return title.InnerText.Trim();
}
return defaultIfMissing;
}
/// <summary>
/// Write a node out containing the XML in dataToWrite, pretty-printed according to the rules of writer, except
/// that we suppress indentation for children of nodes whose names are listed in suppressIndentingChildren,
/// and also for "mixed" nodes (where some children are text).
/// </summary>
/// <param name="writer"></param>
/// <param name="dataToWrite"></param>
/// <param name="suppressIndentingChildren"></param>
public static void WriteNode(XmlWriter writer, string dataToWrite, HashSet<string> suppressIndentingChildren)
{
XElement element = XDocument.Parse(dataToWrite).Root;
WriteNode(writer, element, suppressIndentingChildren);
}
/// <summary>
/// Write a node out containing the XML in dataToWrite, pretty-printed according to the rules of writer, except
/// that we suppress indentation for children of nodes whose names are listed in suppressIndentingChildren,
/// and also for "mixed" nodes (where some children are text).
/// </summary>
/// <param name="writer"></param>
/// <param name="dataToWrite"></param>
/// <param name="suppressIndentingChildren"></param>
public static void WriteNode(XmlWriter writer, XElement dataToWrite, HashSet<string> suppressIndentingChildren)
{
if (dataToWrite == null)
return;
WriteElementTo(writer, dataToWrite, suppressIndentingChildren);
}
/// <summary>
/// Recursively write an element to the writer, suppressing indentation of children when required.
/// </summary>
/// <param name="writer"></param>
/// <param name="element"></param>
/// <param name="suppressIndentingChildren"></param>
private static void WriteElementTo(XmlWriter writer, XElement element, HashSet<string> suppressIndentingChildren)
{
writer.WriteStartElement(element.Name.LocalName);
foreach (var attr in element.Attributes())
writer.WriteAttributeString(attr.Name.LocalName, attr.Value);
// The writer automatically suppresses indenting children for any element that it detects has text children.
// However, it won't do this for the first child if that is an element, even if it later encounters text children.
// Also, there may be a parent where text including white space is significant, yet it is possible for the
// WHOLE content to be an element. For example, a <text> or <AStr> element may consist entirely of a <span>.
// In such cases there is NO way to tell from the content that it should not be indented, so all we can do
// is pass a list of such elements.
bool suppressIndenting = suppressIndentingChildren.Contains(element.Name.LocalName) || element.Nodes().Any(x => x is XText);
// In either case, we implement the suppression by making the first child a fake text element.
// Calling this method, even with an empty string, has proved to be enough to make the writer treat the parent
// as "mixed" which prevents indenting its children.
if (suppressIndenting)
writer.WriteString("");
foreach (var child in element.Nodes())
{
var xElement = child as XElement;
if (xElement != null)
WriteElementTo(writer, xElement, suppressIndentingChildren);
else
child.WriteTo(writer); // defaults are fine for everything else.
}
writer.WriteEndElement();
}
/// <summary>
/// Remove illegal XML characters from a string.
/// </summary>
public static string SanitizeString(string s)
{
if (string.IsNullOrEmpty(s))
{
return s;
}
StringBuilder buffer = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
int code;
try
{
code = Char.ConvertToUtf32(s, i);
}
catch (ArgumentException)
{
continue;
}
if (IsLegalXmlChar(code))
buffer.Append(Char.ConvertFromUtf32(code));
if (Char.IsSurrogatePair(s, i))
i++;
}
return buffer.ToString();
}
/// <summary>
/// Whether a given character is allowed by XML 1.0.
/// </summary>
private static bool IsLegalXmlChar(int codePoint)
{
return (codePoint == 0x9 ||
codePoint == 0xA ||
codePoint == 0xD ||
(codePoint >= 0x20 && codePoint <= 0xD7FF) ||
(codePoint >= 0xE000 && codePoint <= 0xFFFD) ||
(codePoint >= 0x10000/* && character <= 0x10FFFF*/) //it's impossible to get a code point bigger than 0x10FFFF because Char.ConvertToUtf32 would have thrown an exception
);
}
/// <summary>
/// Removes namespaces from the Xml document (makes querying easier)
/// </summary>
public static XDocument RemoveNamespaces(this XDocument document)
{
document.Root?.RemoveNamespaces();
return document;
}
/// <summary>
/// Removes namespaces from the Xml element and its children (makes querying easier)
/// </summary>
public static XElement RemoveNamespaces(this XElement element)
{
RemoveNamespaces(element.DescendantsAndSelf());
return element;
}
private static void RemoveNamespaces(IEnumerable<XElement> elements)
{
foreach (var element in elements)
{
element.Attributes().Where(attribute => attribute.IsNamespaceDeclaration).ForEach(attribute => attribute.Remove());
element.Name = element.Name.LocalName;
}
}
/// <summary>
/// Allow the visitor to 'visit' each attribute in the input XmlNode.
/// </summary>
/// <param name="input"></param>
/// <param name="visitor"></param>
/// <returns>true if any Visit call returns true</returns>
public static bool VisitAttributes(XmlNode input, IAttributeVisitor visitor)
{
bool fSuccessfulVisit = false;
if (input.Attributes != null) // can be, e.g, if Input is a XmlTextNode
{
foreach (XmlAttribute xa in input.Attributes)
{
if (visitor.Visit(new XAttribute(xa.Name, xa.Value)))
fSuccessfulVisit = true;
}
}
if (input.ChildNodes != null) // not sure whether this can happen.
{
foreach (XmlNode child in input.ChildNodes)
{
if (VisitAttributes(child, visitor))
fSuccessfulVisit = true;
}
}
return fSuccessfulVisit;
}
/// <summary>
/// Allow the visitor to 'visit' each attribute in the input XmlNode.
/// </summary>
/// <param name="input"></param>
/// <param name="visitor"></param>
/// <returns>true if any Visit call returns true</returns>
public static bool VisitAttributes(XElement input, IAttributeVisitor visitor)
{
bool fSuccessfulVisit = false;
if (input.HasAttributes) // can be, e.g, if Input is a XmlTextNode
{
foreach (XAttribute xa in input.Attributes())
{
if (visitor.Visit(xa))
fSuccessfulVisit = true;
}
}
if (input.Elements().Any()) // not sure whether this can happen.
{
foreach (var child in input.Elements())
{
if (VisitAttributes(child, visitor))
fSuccessfulVisit = true;
}
}
return fSuccessfulVisit;
}
}
/// <summary>
/// Interface for operations we can apply to attributes.
/// </summary>
public interface IAttributeVisitor
{
bool Visit(XAttribute xa);
}
public class ReplaceSubstringInAttr : IAttributeVisitor
{
readonly string _pattern;
readonly string _replacement;
public ReplaceSubstringInAttr(string pattern, string replacement)
{
_pattern = pattern;
_replacement = replacement;
}
public virtual bool Visit(XAttribute xa)
{
string old = xa.Value;
int index = old.IndexOf(_pattern);
if (index < 0)
return false;
xa.Value = old.Replace(_pattern, _replacement);
return false;
}
}
}
| |
// 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 NETFRAMEWORK_4_5
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System.Reflection
{
//
// Summary:
// Contains static methods for retrieving custom attributes.
public static class CustomAttributeExtensions
{
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// member.
//
// Parameters:
// element:
// The member to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches attributeType, or null if no such attribute is
// found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(Attribute);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches attributeType, or null if no such attribute is
// found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(Attribute);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// module.
//
// Parameters:
// element:
// The module to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches attributeType, or null if no such attribute is
// found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
[Pure]
public static Attribute GetCustomAttribute(this Module element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(Attribute);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// assembly.
//
// Parameters:
// element:
// The assembly to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches attributeType, or null if no such attribute is
// found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
[Pure]
public static Attribute GetCustomAttribute(this Assembly element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(Attribute);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// parameter, and optionally inspects the ancestors of that parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Returns:
// A custom attribute matching attributeType, or null if no such attribute is found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(Attribute);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// member, and optionally inspects the ancestors of that member.
//
// Parameters:
// element:
// The member to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Returns:
// A custom attribute that matches attributeType, or null if no such attribute is
// found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(Attribute);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// member.
//
// Parameters:
// element:
// The member to inspect.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches T, or null if no such attribute is found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static T GetCustomAttribute<T>(this MemberInfo element) where T : Attribute
{
Contract.Requires(element != null);
return default(T);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches T, or null if no such attribute is found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static T GetCustomAttribute<T>(this ParameterInfo element) where T : Attribute
{
Contract.Requires(element != null);
return default(T);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// module.
//
// Parameters:
// element:
// The module to inspect.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches T, or null if no such attribute is found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
[Pure]
public static T GetCustomAttribute<T>(this Module element) where T : Attribute
{
Contract.Requires(element != null);
return default(T);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// assembly.
//
// Parameters:
// element:
// The assembly to inspect.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches T, or null if no such attribute is found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
[Pure]
public static T GetCustomAttribute<T>(this Assembly element) where T : Attribute
{
Contract.Requires(element != null);
return default(T);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// parameter, and optionally inspects the ancestors of that parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches T, or null if no such attribute is found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static T GetCustomAttribute<T>(this ParameterInfo element, bool inherit) where T : Attribute
{
Contract.Requires(element != null);
return default(T);
}
//
// Summary:
// Retrieves a custom attribute of a specified type that is applied to a specified
// member, and optionally inspects the ancestors of that member.
//
// Parameters:
// element:
// The member to inspect.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A custom attribute that matches T, or null if no such attribute is found.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.Reflection.AmbiguousMatchException:
// More than one of the requested attributes was found.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute
{
Contract.Requires(element != null);
return default(T);
}
//
// Summary:
// Retrieves a collection of custom attributes that are applied to a specified member.
//
// Parameters:
// element:
// The member to inspect.
//
// Returns:
// A collection of the custom attributes that are applied to element, or an empty
// collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element)
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes that are applied to a specified parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// Returns:
// A collection of the custom attributes that are applied to element, or an empty
// collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this ParameterInfo element)
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes that are applied to a specified module.
//
// Parameters:
// element:
// The module to inspect.
//
// Returns:
// A collection of the custom attributes that are applied to element, or an empty
// collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this Module element)
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes that are applied to a specified assembly.
//
// Parameters:
// element:
// The assembly to inspect.
//
// Returns:
// A collection of the custom attributes that are applied to element, or an empty
// collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this Assembly element)
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified module.
//
// Parameters:
// element:
// The module to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// attributeType, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this Module element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified member.
//
// Parameters:
// element:
// The member to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// attributeType, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// attributeType, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this ParameterInfo element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified assembly.
//
// Parameters:
// element:
// The assembly to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// attributeType, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this Assembly element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes that are applied to a specified parameter,
// and optionally inspects the ancestors of that parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Returns:
// A collection of the custom attributes that are applied to element, or an empty
// collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this ParameterInfo element, bool inherit)
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes that are applied to a specified member,
// and optionally inspects the ancestors of that member.
//
// Parameters:
// element:
// The member to inspect.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Returns:
// A collection of the custom attributes that are applied to element that match
// the specified criteria, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, bool inherit)
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified parameter, and optionally inspects the ancestors of that parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// attributeType, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this ParameterInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified member, and optionally inspects the ancestors of that member.
//
// Parameters:
// element:
// The member to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// attributeType, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
Contract.Ensures(Contract.Result<IEnumerable<Attribute>>() != null);
return default(IEnumerable<Attribute>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified member.
//
// Parameters:
// element:
// The member to inspect.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// T, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo element) where T : Attribute
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<T>>() != null);
return default(IEnumerable<T>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// T, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<T> GetCustomAttributes<T>(this ParameterInfo element) where T : Attribute
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<T>>() != null);
return default(IEnumerable<T>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified module.
//
// Parameters:
// element:
// The module to inspect.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// T, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
[Pure]
public static IEnumerable<T> GetCustomAttributes<T>(this Module element) where T : Attribute
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<T>>() != null);
return default(IEnumerable<T>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified assembly.
//
// Parameters:
// element:
// The assembly to inspect.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// T, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
[Pure]
public static IEnumerable<T> GetCustomAttributes<T>(this Assembly element) where T : Attribute
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<T>>() != null);
return default(IEnumerable<T>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified parameter, and optionally inspects the ancestors of that parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// T, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<T> GetCustomAttributes<T>(this ParameterInfo element, bool inherit) where T : Attribute
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<T>>() != null);
return default(IEnumerable<T>);
}
//
// Summary:
// Retrieves a collection of custom attributes of a specified type that are applied
// to a specified member, and optionally inspects the ancestors of that member.
//
// Parameters:
// element:
// The member to inspect.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Type parameters:
// T:
// The type of attribute to search for.
//
// Returns:
// A collection of the custom attributes that are applied to element and that match
// T, or an empty collection if no such attributes exist.
//
// Exceptions:
// T:System.ArgumentNullException:
// element is null.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
//
// T:System.TypeLoadException:
// A custom attribute type cannot be loaded.
[Pure]
public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo element, bool inherit) where T : Attribute
{
Contract.Requires(element != null);
Contract.Ensures(Contract.Result<IEnumerable<T>>() != null);
return default(IEnumerable<T>);
}
//
// Summary:
// Indicates whether custom attributes of a specified type are applied to a specified
// parameter.
//
// Parameters:
// element:
// The parameter to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// true if an attribute of the specified type is applied to element; otherwise,
// false.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
[Pure]
public static bool IsDefined(this ParameterInfo element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(bool);
}
//
// Summary:
// Indicates whether custom attributes of a specified type are applied to a specified
// member.
//
// Parameters:
// element:
// The member to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// true if an attribute of the specified type is applied to element; otherwise,
// false.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
[Pure]
public static bool IsDefined(this MemberInfo element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(bool);
}
//
// Summary:
// Indicates whether custom attributes of a specified type are applied to a specified
// module.
//
// Parameters:
// element:
// The module to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// Returns:
// true if an attribute of the specified type is applied to element; otherwise,
// false.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
[Pure]
public static bool IsDefined(this Module element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(bool);
}
//
// Summary:
// Indicates whether custom attributes of a specified type are applied to a specified
// assembly.
//
// Parameters:
// element:
// The assembly to inspect.
//
// attributeType:
// The type of the attribute to search for.
//
// Returns:
// true if an attribute of the specified type is applied to element; otherwise,
// false.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
[Pure]
public static bool IsDefined(this Assembly element, Type attributeType)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(bool);
}
//
// Summary:
// Indicates whether custom attributes of a specified type are applied to a specified
// parameter, and, optionally, applied to its ancestors.
//
// Parameters:
// element:
// The parameter to inspect.
//
// attributeType:
// The type of attribute to search for.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Returns:
// true if an attribute of the specified type is applied to element; otherwise,
// false.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
[Pure]
public static bool IsDefined(this ParameterInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(bool);
}
//
// Summary:
// Indicates whether custom attributes of a specified type are applied to a specified
// member, and, optionally, applied to its ancestors.
//
// Parameters:
// element:
// The member to inspect.
//
// attributeType:
// The type of the attribute to search for.
//
// inherit:
// true to inspect the ancestors of element; otherwise, false.
//
// Returns:
// true if an attribute of the specified type is applied to element; otherwise,
// false.
//
// Exceptions:
// T:System.ArgumentNullException:
// element or attributeType is null.
//
// T:System.ArgumentException:
// attributeType is not derived from System.Attribute.
//
// T:System.NotSupportedException:
// element is not a constructor, method, property, event, type, or field.
[Pure]
public static bool IsDefined(this MemberInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(attributeType != null);
return default(bool);
}
}
}
#endif
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.HtmlEditor.Controls;
using OpenLiveWriter.Interop.Com.Ribbon;
using OpenLiveWriter.Interop.Windows;
//using OpenLiveWriter.SpellChecker;
namespace OpenLiveWriter.PostEditor
{
/// <summary>
/// MainFrameWindowAdapter will take a IContentEditorSite given by a hosting application and convert it into
/// IMainFrameWindow and IBlogPostEditingSite which are used by the ContentEditor. It's general functions
/// are to act as a middle man to the window that is holding the canvas.
/// </summary>
//ToDo: OLW Spell Checker
//internal class MainFrameWindowAdapter : IMainFrameWindow, IBlogPostEditingSite, IBlogContext, OpenLiveWriter.Interop.Com.IDropTarget, IDisposable, IETWProvider, IWordRangeProvider
internal class MainFrameWindowAdapter : IMainFrameWindow, IBlogPostEditingSite, IBlogContext, OpenLiveWriter.Interop.Com.IDropTarget, IDisposable, IETWProvider
{
private readonly IntPtr _parentWindowHandle;
private readonly Control _editorHostPanel;
private IContentEditorSite _contentEditorSite;
private string _accountId;
public MainFrameWindowAdapter(IntPtr parentWindowHandle, Control editorHostPanel, IContentEditorSite contentEditorSite, string accountId)
{
_parentWindowHandle = parentWindowHandle;
_editorHostPanel = editorHostPanel;
_contentEditorSite = contentEditorSite;
editorHostPanel.LocationChanged += new EventHandler(editorHostPanel_LocationChanged);
editorHostPanel.SizeChanged += new EventHandler(editorHostPanel_SizeChanged);
editorHostPanel.Layout += new LayoutEventHandler(editorHostPanel_Layout);
_accountId = accountId;
}
void editorHostPanel_Layout(object sender, LayoutEventArgs e)
{
FireLayout(e);
}
void editorHostPanel_SizeChanged(object sender, EventArgs e)
{
FireSizeChanged(_editorHostPanel.Width, _editorHostPanel.Height);
}
void editorHostPanel_LocationChanged(object sender, EventArgs e)
{
FireLocationChanged();
}
public IUIFramework RibbonFramework
{
get
{
return (IUIFramework)_contentEditorSite;
}
}
public void OnKeyboardLanguageChanged()
{
_contentEditorSite.OnKeyboardLanguageChanged();
}
#region IWordRangeProvider Members
//ToDo: OLW Spell Checker
//public IWordRange GetSubjectSpellcheckWordRange()
//{
// return ((IWordRangeProvider)_contentEditorSite).GetSubjectSpellcheckWordRange();
//}
//public void CloseSubjectSpellcheckWordRange()
//{
// ((IWordRangeProvider)_contentEditorSite).CloseSubjectSpellcheckWordRange();
//}
#endregion
#region IMainFrameWindow Members
public string Caption
{
set
{
}
}
public Point Location
{
get
{
WINDOWINFO info = new WINDOWINFO();
User32.GetWindowInfo(_parentWindowHandle, ref info);
return new Point(info.rcWindow.left, info.rcWindow.top);
}
}
public Size Size
{
get
{
WINDOWINFO info = new WINDOWINFO();
User32.GetWindowInfo(_parentWindowHandle, ref info);
return new Size(Math.Max(info.rcWindow.Width, _width), Math.Max(info.rcWindow.Height, _height));
}
}
public event EventHandler LocationChanged;
private void FireLocationChanged()
{
if (LocationChanged != null)
LocationChanged(this, EventArgs.Empty);
}
private int _width;
private int _height;
public event EventHandler SizeChanged;
public void FireSizeChanged(int x, int y)
{
_width = x;
_height = y;
if (SizeChanged != null)
SizeChanged(this, EventArgs.Empty);
}
public event EventHandler Deactivate;
private void FireDeactivate()
{
if (Deactivate != null)
Deactivate(this, EventArgs.Empty);
}
public event LayoutEventHandler Layout;
private void FireLayout(LayoutEventArgs arg)
{
if (Layout != null)
{
Layout(this, arg);
}
}
public void Activate()
{
User32.SetForegroundWindow(_parentWindowHandle);
}
public void Update()
{
User32.UpdateWindow(_parentWindowHandle);
}
public void SetStatusBarMessage(StatusMessage message)
{
_contentEditorSite.SetStatusBarMessage(message.BlogPostStatus, message.WordCountValue);
}
private Stack<StatusMessage> _statusMessageStack = new Stack<StatusMessage>();
public void PushStatusBarMessage(StatusMessage message)
{
_statusMessageStack.Push(message);
_contentEditorSite.SetStatusBarMessage(message.BlogPostStatus, message.WordCountValue);
}
public void PopStatusBarMessage()
{
if (_statusMessageStack.Count > 0)
_statusMessageStack.Pop();
if (_statusMessageStack.Count > 0)
{
StatusMessage message = _statusMessageStack.Peek();
_contentEditorSite.SetStatusBarMessage(message.BlogPostStatus, message.WordCountValue);
}
else
{
_contentEditorSite.SetStatusBarMessage(null, null);
}
}
public void PerformLayout()
{
_editorHostPanel.PerformLayout();
}
public void Invalidate()
{
User32.InvalidateWindow(_parentWindowHandle, IntPtr.Zero, false);
}
public void Close()
{
User32.SendMessage(_parentWindowHandle, WM.CLOSE, UIntPtr.Zero, IntPtr.Zero);
}
#endregion
#region IWin32Window Members
public IntPtr Handle
{
get { return _editorHostPanel.Handle; }
}
#endregion
#region ISynchronizeInvoke Members
public IAsyncResult BeginInvoke(Delegate method, object[] args)
{
return _editorHostPanel.BeginInvoke(method, args);
}
public object EndInvoke(IAsyncResult result)
{
return _editorHostPanel.EndInvoke(result);
}
public object Invoke(Delegate method, object[] args)
{
return _editorHostPanel.Invoke(method, args);
}
public bool InvokeRequired
{
get { return _editorHostPanel.InvokeRequired; }
}
#endregion
#region IMiniFormOwner Members
public void AddOwnedForm(System.Windows.Forms.Form f)
{
User32.SetParent(f.Handle, _parentWindowHandle);
}
public void RemoveOwnedForm(System.Windows.Forms.Form f)
{
User32.SetParent(f.Handle, IntPtr.Zero);
}
#endregion
#region IBlogContext Members
public string CurrentAccountId
{
get { return null; }
set { }
}
#endregion
#region IBlogPostEditingSite Members
public IMainFrameWindow FrameWindow
{
get { return this; }
}
// @SharedCanvas - this can all be removed once the default sidebar is taken out
public event WeblogHandler WeblogChanged;
public event EventHandler WeblogListChanged;
private void InvokeWeblogChanged(string blogId)
{
WeblogHandler Handler = WeblogChanged;
if (Handler != null) Handler(blogId);
}
public event WeblogSettingsChangedHandler WeblogSettingsChanged;
private void InvokeWeblogSettingsChanged(string blogId, bool templateChanged)
{
WeblogSettingsChangedHandler Handler = WeblogSettingsChanged;
if (Handler != null) Handler(blogId, templateChanged);
}
public event WeblogSettingsChangedHandler GlobalWeblogSettingsChanged;
private void InvokeGlobalWeblogSettingsChanged(string blogId, bool templateChanged)
{
WeblogSettingsChangedHandler Handler = GlobalWeblogSettingsChanged;
if (Handler != null) Handler(blogId, templateChanged);
}
public void NotifyWeblogSettingsChanged(bool templateChanged)
{
throw new NotImplementedException();
}
public void NotifyWeblogSettingsChanged(string blogId, bool templateChanged)
{
throw new NotImplementedException();
}
public void NotifyWeblogAccountListEdited()
{
throw new NotImplementedException();
}
public void ConfigureWeblog(string blogId, Type selectedPanel)
{
throw new System.NotImplementedException();
}
public void ConfigureWeblog(string blogId)
{
throw new NotImplementedException();
}
public void ConfigureWeblogFtpUpload(string blogId)
{
throw new NotImplementedException();
}
public bool UpdateWeblogTemplate(string blogId)
{
throw new NotImplementedException();
}
public void AddWeblog()
{
throw new NotImplementedException();
}
public void OpenLocalPost(PostInfo postInfo)
{
throw new NotImplementedException();
}
public void DeleteLocalPost(PostInfo postInfo)
{
throw new NotImplementedException();
}
public event EventHandler PostListChanged;
private void InvokePostListChanged(EventArgs e)
{
EventHandler postListChangedHandler = PostListChanged;
if (postListChangedHandler != null) postListChangedHandler(this, e);
}
// This only exists to please the compiler.
private void InvokeWeblogListChanged(EventArgs e)
{
EventHandler weblogListChangedHandler = WeblogListChanged;
if (weblogListChangedHandler != null) weblogListChangedHandler(this, e);
}
public OpenLiveWriter.HtmlEditor.Controls.IHtmlStylePicker StyleControl
{
// @SharedCanvas - this needs to be fixed with the ribbon. The window should not be providing
// a combo box for the command manager to poke up
get { return new NullHtmlStylePicker(); }
}
public class NullHtmlStylePicker : IHtmlStylePicker
{
#region IHtmlStylePicker Members
public event EventHandler HtmlStyleChanged;
private void InvokeHtmlStyleChanged(EventArgs e)
{
EventHandler htmlStyleChangedHandler = HtmlStyleChanged;
if (htmlStyleChangedHandler != null) htmlStyleChangedHandler(this, e);
}
public class NullHtmlFormattingStyle : IHtmlFormattingStyle
{
#region IHtmlFormattingStyle Members
public string DisplayName
{
get { return ""; }
}
public string ElementName
{
get { return ""; }
}
public mshtml._ELEMENT_TAG_ID ElementTagId
{
get { return mshtml._ELEMENT_TAG_ID.TAGID_SPAN; }
}
#endregion
}
public IHtmlFormattingStyle SelectedStyle
{
get { return new NullHtmlFormattingStyle(); }
}
public bool Enabled
{
get
{
return false;
}
set
{
}
}
public void SelectStyleByElementName(string p)
{
}
#endregion
}
#endregion
#region IDropTarget Members
public void DragEnter(OpenLiveWriter.Interop.Com.IOleDataObject pDataObj, MK grfKeyState, POINT pt, ref OpenLiveWriter.Interop.Com.DROPEFFECT pdwEffect)
{
_contentEditorSite.DragEnter(pDataObj, grfKeyState, pt, ref pdwEffect);
}
public void DragOver(MK grfKeyState, POINT pt, ref OpenLiveWriter.Interop.Com.DROPEFFECT pdwEffect)
{
_contentEditorSite.DragOver(grfKeyState, pt, ref pdwEffect);
}
public void DragLeave()
{
_contentEditorSite.DragLeave();
}
public void Drop(OpenLiveWriter.Interop.Com.IOleDataObject pDataObj, MK grfKeyState, POINT pt, ref OpenLiveWriter.Interop.Com.DROPEFFECT pdwEffect)
{
_contentEditorSite.Drop(pDataObj, grfKeyState, pt, ref pdwEffect);
}
#endregion
#region IBlogPostEditingSite Members
public CommandManager CommandManager
{
get { throw new NotImplementedException(); }
}
#endregion
#region IDisposable Members
public void Dispose()
{
_contentEditorSite = null;
}
#endregion
public void WriteEvent(string eventName)
{
if (_contentEditorSite != null)
_contentEditorSite.WriteEvent(eventName);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.SolutionSize;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
{
public class PersistentStorageTests : IDisposable
{
private const int NumThreads = 10;
private const string PersistentFolderPrefix = "PersistentStorageTests_";
private readonly Encoding _encoding = Encoding.UTF8;
private readonly IOptionService _persistentEnabledOptionService = new OptionServiceMock(new Dictionary<IOption, object>
{
{ PersistentStorageOptions.Enabled, true },
{ InternalFeatureOnOffOptions.EsentPerformanceMonitor, false }
});
private readonly string _persistentFolder;
private const string Data1 = "Hello ESENT";
private const string Data2 = "Goodbye ESENT";
public PersistentStorageTests()
{
_persistentFolder = Path.Combine(Path.GetTempPath(), PersistentFolderPrefix + Guid.NewGuid());
Directory.CreateDirectory(_persistentFolder);
int workerThreads, completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
ThreadPool.SetMinThreads(Math.Max(workerThreads, NumThreads), completionPortThreads);
}
public void Dispose()
{
if (Directory.Exists(_persistentFolder))
{
Directory.Delete(_persistentFolder, true);
}
}
private void CleanUpPersistentFolder()
{
}
[Fact]
public void PersistentService_Solution_WriteReadDifferentInstances()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadDifferentInstances1";
var streamName2 = "PersistentService_Solution_WriteReadDifferentInstances2";
using (var storage = GetStorage(solution))
{
Assert.True(storage.WriteStreamAsync(streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(streamName2, EncodeString(Data2)).Result);
}
using (var storage = GetStorage(solution))
{
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(streamName2).Result));
}
}
[Fact]
public void PersistentService_Solution_WriteReadReopenSolution()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadReopenSolution1";
var streamName2 = "PersistentService_Solution_WriteReadReopenSolution2";
using (var storage = GetStorage(solution))
{
Assert.True(storage.WriteStreamAsync(streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(streamName2, EncodeString(Data2)).Result);
}
solution = CreateOrOpenSolution();
using (var storage = GetStorage(solution))
{
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(streamName2).Result));
}
}
[Fact]
public void PersistentService_Solution_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadSameInstance1";
var streamName2 = "PersistentService_Solution_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
Assert.True(storage.WriteStreamAsync(streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(streamName2, EncodeString(Data2)).Result);
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(streamName2).Result));
}
}
[Fact]
public void PersistentService_Project_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_WriteReadSameInstance1";
var streamName2 = "PersistentService_Project_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
var project = solution.Projects.Single();
Assert.True(storage.WriteStreamAsync(project, streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(project, streamName2, EncodeString(Data2)).Result);
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(project, streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(project, streamName2).Result));
}
}
[Fact]
public void PersistentService_Document_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_WriteReadSameInstance1";
var streamName2 = "PersistentService_Document_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
var document = solution.Projects.Single().Documents.Single();
Assert.True(storage.WriteStreamAsync(document, streamName1, EncodeString(Data1)).Result);
Assert.True(storage.WriteStreamAsync(document, streamName2, EncodeString(Data2)).Result);
Assert.Equal(Data1, ReadStringToEnd(storage.ReadStreamAsync(document, streamName1).Result));
Assert.Equal(Data2, ReadStringToEnd(storage.ReadStreamAsync(document, streamName2).Result));
}
}
[Fact]
public void PersistentService_Solution_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
[Fact]
public void PersistentService_Project_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(solution.Projects.Single(), streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(storage.ReadStreamAsync(solution.Projects.Single(), streamName1).Result));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
[Fact]
public void PersistentService_Document_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(solution.Projects.Single().Documents.Single(), streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(storage.ReadStreamAsync(solution.Projects.Single().Documents.Single(), streamName1).Result));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
private void DoSimultaneousWrites(Func<string, Task> write)
{
var barrier = new Barrier(NumThreads);
var countdown = new CountdownEvent(NumThreads);
for (int i = 0; i < NumThreads; i++)
{
ThreadPool.QueueUserWorkItem(s =>
{
int id = (int)s;
barrier.SignalAndWait();
write(id + "").Wait();
countdown.Signal();
}, i);
}
countdown.Wait();
}
[Fact]
public void PersistentService_Solution_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
storage.WriteStreamAsync(streamName1, EncodeString(Data1)).Wait();
DoSimultaneousReads(() => ReadStringToEnd(storage.ReadStreamAsync(streamName1).Result), Data1);
}
}
[Fact]
public void PersistentService_Project_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
storage.WriteStreamAsync(solution.Projects.Single(), streamName1, EncodeString(Data1)).Wait();
DoSimultaneousReads(() => ReadStringToEnd(storage.ReadStreamAsync(solution.Projects.Single(), streamName1).Result), Data1);
}
}
[Fact]
public void PersistentService_Document_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
storage.WriteStreamAsync(solution.Projects.Single().Documents.Single(), streamName1, EncodeString(Data1)).Wait();
DoSimultaneousReads(() => ReadStringToEnd(storage.ReadStreamAsync(solution.Projects.Single().Documents.Single(), streamName1).Result), Data1);
}
}
private void DoSimultaneousReads(Func<string> read, string expectedValue)
{
var barrier = new Barrier(NumThreads);
var countdown = new CountdownEvent(NumThreads);
for (int i = 0; i < NumThreads; i++)
{
ThreadPool.QueueUserWorkItem(s =>
{
barrier.SignalAndWait();
Assert.Equal(expectedValue, read());
countdown.Signal();
});
}
countdown.Wait();
}
[Fact]
public void PersistentService_IdentifierSet()
{
var solution = CreateOrOpenSolution();
var newId = DocumentId.CreateNewId(solution.ProjectIds[0]);
string documentFile = Path.Combine(Path.GetDirectoryName(solution.FilePath), "IdentifierSet.cs");
File.WriteAllText(documentFile, @"
class A
{
public int Test(int i, A a)
{
return a;
}
}");
var newSolution = solution.AddDocument(DocumentInfo.Create(newId, "IdentifierSet", loader: new FileTextLoader(documentFile, Encoding.UTF8), filePath: documentFile));
using (var storage = GetStorage(newSolution))
{
var syntaxTreeStorage = storage as ISyntaxTreeInfoPersistentStorage;
Assert.NotNull(syntaxTreeStorage);
var document = newSolution.GetDocument(newId);
var version = document.GetSyntaxVersionAsync().Result;
var root = document.GetSyntaxRootAsync().Result;
Assert.True(syntaxTreeStorage.WriteIdentifierLocations(document, version, root, CancellationToken.None));
Assert.Equal(version, syntaxTreeStorage.GetIdentifierSetVersion(document));
List<int> positions = new List<int>();
Assert.True(syntaxTreeStorage.ReadIdentifierPositions(document, version, "Test", positions, CancellationToken.None));
Assert.Equal(1, positions.Count);
Assert.Equal(29, positions[0]);
}
}
private Solution CreateOrOpenSolution()
{
string solutionFile = Path.Combine(_persistentFolder, "Solution1.sln");
bool newSolution;
if (newSolution = !File.Exists(solutionFile))
{
File.WriteAllText(solutionFile, "");
}
var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), solutionFile);
var workspace = new AdhocWorkspace();
workspace.AddSolution(info);
var solution = workspace.CurrentSolution;
if (newSolution)
{
string projectFile = Path.Combine(Path.GetDirectoryName(solutionFile), "Project1.csproj");
File.WriteAllText(projectFile, "");
solution = solution.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project1", "Project1", LanguageNames.CSharp, projectFile));
var project = solution.Projects.Single();
string documentFile = Path.Combine(Path.GetDirectoryName(projectFile), "Document1.cs");
File.WriteAllText(documentFile, "");
solution = solution.AddDocument(DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Document1", filePath: documentFile));
}
return solution;
}
private IPersistentStorage GetStorage(Solution solution)
{
var storage = new PersistentStorageService(_persistentEnabledOptionService, testing: true).GetStorage(solution);
Assert.NotEqual(PersistentStorageService.NoOpPersistentStorageInstance, storage);
return storage;
}
private Stream EncodeString(string text)
{
var bytes = _encoding.GetBytes(text);
var stream = new MemoryStream(bytes);
return stream;
}
private string ReadStringToEnd(Stream stream)
{
using (stream)
{
var bytes = new byte[stream.Length];
int count = 0;
while (count < stream.Length)
{
count = stream.Read(bytes, count, (int)stream.Length - count);
}
return _encoding.GetString(bytes);
}
}
}
}
| |
#region License Agreement - READ THIS FIRST!!!
/*
**********************************************************************************
* Copyright (c) 2008, Kristian Trenskow *
* All rights reserved. *
**********************************************************************************
* This code is subject to terms of the BSD License. A copy of this license is *
* included with this software distribution in the file COPYING. If you do not *
* have a copy of, you can contain a copy by visiting this URL: *
* *
* http://www.opensource.org/licenses/bsd-license.php *
* *
* Replace <OWNER>, <ORGANISATION> and <YEAR> with the info in the above *
* copyright notice. *
* *
**********************************************************************************
*/
#endregion
#region Using
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
#endregion
namespace ircsharp
{
#region IRCStateObject
internal class IRCStateObject
{
public const int bufferSize = 4096;
public byte[] buffer = new byte[bufferSize];
public string lastBuffer = "";
}
#endregion
#region OnDataEventArgs class
internal class OnDataEventArgs
{
private string strUser = "";
private string strCommand = "";
private string[] strParameters;
private bool blIsServerMessage;
private int intdescriptionBeginsAtIndex;
private string strRaw;
internal OnDataEventArgs(string user, string command, string[] parameters, int descriptionBeginsAtIndex, bool isServerMessage, string raw)
{
strUser = user;
strCommand = command;
strParameters = parameters;
intdescriptionBeginsAtIndex = descriptionBeginsAtIndex;
blIsServerMessage = isServerMessage;
strRaw = raw;
}
internal OnDataEventArgs(string user, string command, string[] parameters, bool isServerMessage, string raw) : this(user, command, parameters, -1, isServerMessage, raw)
{
}
internal string User
{
get { return strUser; }
}
internal string Command
{
get { return strCommand; }
}
internal int descriptionBeginsAtIndex
{
get { return intdescriptionBeginsAtIndex; }
}
internal string[] Parameters
{
get { return strParameters; }
}
internal string description
{
get {
string[] ret = new string[strParameters.Length - intdescriptionBeginsAtIndex];
for (int x = intdescriptionBeginsAtIndex ; x < strParameters.Length ; x++)
ret[x - intdescriptionBeginsAtIndex] = strParameters[x];
return string.Join(" ", ret);
}
}
internal bool IsServerMessage
{
get { return blIsServerMessage; }
}
internal string Raw
{
get { return strRaw; }
}
}
#endregion
#region Delegates
internal delegate void OnDataEventHandler(object sender, OnDataEventArgs e);
#endregion
internal class ServerConnection
{
#region Private Variables
private Socket socket;
private DateTime dtLastActive = DateTime.Now;
private Connection objOwner;
#endregion
#region Events
internal event EventHandler OnConnected;
internal event EventHandler OnConnectFailed;
internal event EventHandler OnDisconnected;
internal event OnDataEventHandler OnDataReceived;
#endregion
#region Connect
internal void Connect(string host, int port)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.BeginConnect(new IPEndPoint(Dns.GetHostEntry(host).AddressList[0], port), new AsyncCallback(connectCallback), socket);
}
catch
{
if (OnConnectFailed!=null)
OnConnectFailed(this, new EventArgs());
}
}
private void connectCallback(IAsyncResult ar)
{
try
{
socket.EndConnect(ar);
}
catch
{
if (OnConnectFailed != null)
OnConnectFailed(this, new EventArgs());
}
if (!socket.Connected)
{
if (OnConnectFailed!=null)
OnConnectFailed(this, new EventArgs());
return;
}
if (OnConnected!=null)
OnConnected(this, null);
IRCStateObject stateObject = new IRCStateObject();
socket.BeginReceive(stateObject.buffer, 0, IRCStateObject.bufferSize, SocketFlags.None, new AsyncCallback(recieveCallback), stateObject);
}
#endregion
#region recieveCallback
private void recieveCallback(IAsyncResult ar)
{
if (socket.Connected)
{
int read = 0;
try
{
read = socket.EndReceive(ar);
}
catch
{
Disconnect();
if (OnDisconnected!=null)
OnDisconnected(this, new EventArgs());
}
IRCStateObject stateObject = (IRCStateObject) ar.AsyncState;
if (read>0||stateObject.lastBuffer!="")
{
string strData = stateObject.lastBuffer + Encoding.Default.GetString(stateObject.buffer, 0, read);
strData = strData.Replace("\r\n", "\n").Replace("\r", "\n");
while (strData.Length > 0 && strData[0] == '\n')
strData = strData.Substring(1);
//try
//{
stateObject.lastBuffer = onData(strData);
//}
//catch (Exception e)
//{
// Console.WriteLine("Data could not be parsed:");
// Console.WriteLine(e.Message);
// Console.WriteLine(e.Source);
// Console.WriteLine(e.StackTrace);
//}
}
if (socket.Connected)
{
try { socket.BeginReceive(stateObject.buffer, 0, IRCStateObject.bufferSize, SocketFlags.None, new AsyncCallback(recieveCallback), stateObject); }
catch
{
if (OnDisconnected!=null)
OnDisconnected(this, new EventArgs());
}
}
else
{
if (OnDisconnected!=null)
OnDisconnected(this, new EventArgs());
}
}
else
{
if (OnDisconnected!=null)
OnDisconnected(this, new EventArgs());
}
}
#endregion
#region onData
private string onData(string strData)
{
string[] strLines = strData.Split(new char[] {'\n'});
string strCommand;
string[] strParams;
string strParam = null;
for (int x=0;x<strLines.Length - 1;x++)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine(strLines[x]);
#endif
#if DEBUGCONSOLE
Console.WriteLine(strLines[x]);
#endif
//try
{
string strUser;
bool blIsServerMessage;
if (strLines[x].Length > 0)
{
if (strLines[x].Substring(0, 1) == ":")
{
strLines[x] = strLines[x].Substring(1, strLines[x].Length - 1);
string[] strSegments = strLines[x].Split(new char[] { ' ' });
// We probably dealing with a server code message
if (strSegments.Length > 3 && strSegments[1].Length == 3 && strSegments[1][0] >= '0' && strSegments[1][0] <= '9')
{
strUser = strSegments[0];
strCommand = strSegments[1];
// [2] is just our own nick
int descriptionBeginsAtIndex = -1;
strParams = new string[strSegments.Length - 3];
for (int i = 3 ; i < strSegments.Length; i++)
{
if (strSegments[i].Length > 1 && strSegments[i][0] == ':' && descriptionBeginsAtIndex == -1)
{
strParams[i - 3] = strSegments[i].Substring(1);
descriptionBeginsAtIndex = i - 3;
}
else
strParams[i - 3] = strSegments[i];
}
if (OnDataReceived != null)
OnDataReceived(this, new OnDataEventArgs(strUser, strCommand, strParams, descriptionBeginsAtIndex, true, strLines[x]));
}
else
{
// This following code is old parsing code. It holds back a lot of properties from the parser, but it works.
if (strLines[x].IndexOf(" :") > -1)
{
strParam = strLines[x].Substring(strLines[x].IndexOf(" :") + 2, strLines[x].Length - (strLines[x].IndexOf(" :") + 2));
strLines[x] = strLines[x].Substring(0, strLines[x].IndexOf(" :") + 1).Trim();
}
string[] strParts = strLines[x].Split(new char[] { ' ' });
strUser = strParts[0];
strCommand = strParts[1];
blIsServerMessage = strParts[1][0] >= '0' && strParts[1][0] <= '9';
int size = strParts.Length - 2;
if (strParam != null)
size++;
strParams = new string[size];
for (int y = 2; y < strParts.Length; y++)
strParams[y - 2] = strParts[y];
if (strParam != null)
strParams[strParams.Length - 1] = strParam;
if (OnDataReceived != null)
OnDataReceived(this, new OnDataEventArgs(strUser, strCommand, strParams, blIsServerMessage, strLines[x]));
}
}
else
{
if (strLines[x].IndexOf(":") > 0)
{
strParam = strLines[x].Substring(strLines[x].IndexOf(":") + 1, strLines[x].Length - (strLines[x].IndexOf(":") + 1));
strLines[x] = strLines[x].Substring(0, strLines[x].IndexOf(":"));
}
string[] strParts = strLines[x].Split(new char[] { ' ' });
strCommand = strParts[0];
int size = strParts.Length - 2;
if (strParam != null)
size++;
strParams = new string[size];
for (int y = 1; y < strParts.Length; y++)
strParams[y - 1] = strParts[y];
if (strParam != null)
strParams[strParams.Length - 1] = strParam;
if (OnDataReceived != null)
OnDataReceived(this, new OnDataEventArgs(null, strCommand, strParams, false, strLines[x]));
}
}
}
//catch (Exception e)
//{
#if DEBUG
//System.Diagnostics.Debug.WriteLine(" ^^^^ Could not parse line:");
//System.Diagnostics.Debug.WriteLine(" Error: {0}", e.Message);
#endif
#if DEBUGCONSOLE
//Console.WriteLine(" ^^^^ Could not parse line:");
//Console.WriteLine(" Error: {0}", e.Message);
#endif
//}
}
return strLines[strLines.Length - 1];
}
#endregion
#region SendData
internal void SendData(string strData, bool blActive, bool blCloseAfterSend, params object[] objs)
{
if (blActive)
dtLastActive = DateTime.Now;
string strFormattedData = string.Format(strData, objs);
#if DEBUG
System.Diagnostics.Debug.WriteLine(strFormattedData);
#endif
#if DEBUGCONSOLE
Console.WriteLine(strFormattedData);
#endif
byte[] data = Encoding.Default.GetBytes(string.Format("{0}{1}", strFormattedData, Environment.NewLine));
if (socket != null && socket.Connected)
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(sendCallback), blCloseAfterSend);
}
internal void SendData(string strData, params object[] objs)
{
SendData(strData, true, false, objs);
}
internal void SendData(string strData, bool blActive, params object[] objs)
{
SendData(strData, blActive, false, objs);
}
private void sendCallback(IAsyncResult ar)
{
bool blCloseAfterSend = (bool) ar.AsyncState;
try
{
socket.EndSend(ar);
}
catch
{
if (OnDisconnected != null)
OnDisconnected(this, new EventArgs());
}
if (socket != null && blCloseAfterSend && socket.Connected)
socket.Close();
}
#endregion
#region Properties
internal bool IsConnected
{
get { return socket!=null&&socket.Connected; }
}
internal byte[] RemoteIP
{
get
{
if (socket.Connected)
return ((IPEndPoint) socket.RemoteEndPoint).Address.GetAddressBytes();
return null;
}
}
internal int RemotePort
{
get
{
if (socket.Connected)
return ((IPEndPoint) socket.RemoteEndPoint).Port;
return 0;
}
}
internal int LocalPort
{
get
{
if (socket.Connected)
return ((IPEndPoint) socket.LocalEndPoint).Port;
return 0;
}
}
internal DateTime LastActive
{
get { return dtLastActive; }
}
#endregion
#region Disconnect
internal void Disconnect()
{
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
#endregion
internal Connection Owner
{
get { return objOwner; }
set { objOwner = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using StudentSystem.Api.Areas.HelpPage.ModelDescriptions;
using StudentSystem.Api.Areas.HelpPage.Models;
namespace StudentSystem.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Cci;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class EEAssemblyBuilder : PEAssemblyBuilderBase
{
internal readonly ImmutableHashSet<MethodSymbol> Methods;
private readonly NamedTypeSymbol _dynamicOperationContextType;
public EEAssemblyBuilder(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
ImmutableArray<MethodSymbol> methods,
ModulePropertiesForSerialization serializationProperties,
ImmutableArray<NamedTypeSymbol> additionalTypes,
NamedTypeSymbol dynamicOperationContextType,
CompilationTestData testData) :
base(
sourceAssembly,
emitOptions,
outputKind: OutputKind.DynamicallyLinkedLibrary,
serializationProperties: serializationProperties,
manifestResources: SpecializedCollections.EmptyEnumerable<ResourceDescription>(),
additionalTypes: additionalTypes)
{
Methods = ImmutableHashSet.CreateRange(methods);
_dynamicOperationContextType = dynamicOperationContextType;
if (testData != null)
{
this.SetMethodTestData(testData.Methods);
testData.Module = this;
}
}
protected override IModuleReference TranslateModule(ModuleSymbol symbol, DiagnosticBag diagnostics)
{
var moduleSymbol = symbol as PEModuleSymbol;
if ((object)moduleSymbol != null)
{
var module = moduleSymbol.Module;
// Expose the individual runtime Windows.*.winmd modules as assemblies.
// (The modules were wrapped in a placeholder Windows.winmd assembly
// in MetadataUtilities.MakeAssemblyReferences.)
if (MetadataUtilities.IsWindowsComponent(module.MetadataReader, module.Name) &&
MetadataUtilities.IsWindowsAssemblyName(moduleSymbol.ContainingAssembly.Name))
{
var identity = module.ReadAssemblyIdentityOrThrow();
return new Microsoft.CodeAnalysis.ExpressionEvaluator.AssemblyReference(identity);
}
}
return base.TranslateModule(symbol, diagnostics);
}
internal override bool IgnoreAccessibility => true;
internal override NamedTypeSymbol DynamicOperationContextType => _dynamicOperationContextType;
public override int CurrentGenerationOrdinal => 0;
internal override VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol symbol, MethodSymbol topLevelMethod)
{
var method = symbol as EEMethodSymbol;
if (((object)method != null) && Methods.Contains(method))
{
var defs = GetLocalDefinitions(method.Locals);
return new SlotAllocator(defs);
}
Debug.Assert(!Methods.Contains(symbol));
return null;
}
private static ImmutableArray<LocalDefinition> GetLocalDefinitions(ImmutableArray<LocalSymbol> locals)
{
var builder = ArrayBuilder<LocalDefinition>.GetInstance();
foreach (var local in locals)
{
if (local.DeclarationKind == LocalDeclarationKind.Constant)
{
continue;
}
var def = ToLocalDefinition(local, builder.Count);
Debug.Assert(((EELocalSymbol)local).Ordinal == def.SlotIndex);
builder.Add(def);
}
return builder.ToImmutableAndFree();
}
private static LocalDefinition ToLocalDefinition(LocalSymbol local, int index)
{
// See EvaluationContext.GetLocals.
TypeSymbol type;
LocalSlotConstraints constraints;
if (local.DeclarationKind == LocalDeclarationKind.FixedVariable)
{
type = ((PointerTypeSymbol)local.Type).PointedAtType;
constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
}
else
{
type = local.Type;
constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
((local.RefKind == RefKind.None) ? LocalSlotConstraints.None : LocalSlotConstraints.ByRef);
}
return new LocalDefinition(
local,
local.Name,
(Cci.ITypeReference)type,
slot: index,
synthesizedKind: (SynthesizedLocalKind)local.SynthesizedKind,
id: LocalDebugId.None,
pdbAttributes: Cci.PdbWriter.DefaultLocalAttributesValue,
constraints: constraints,
isDynamic: false,
dynamicTransformFlags: ImmutableArray<TypedConstant>.Empty);
}
private sealed class SlotAllocator : VariableSlotAllocator
{
private readonly ImmutableArray<LocalDefinition> _locals;
internal SlotAllocator(ImmutableArray<LocalDefinition> locals)
{
_locals = locals;
}
public override void AddPreviousLocals(ArrayBuilder<Cci.ILocalDefinition> builder)
{
builder.AddRange(_locals);
}
public override LocalDefinition GetPreviousLocal(
Cci.ITypeReference type,
ILocalSymbolInternal symbol,
string nameOpt,
SynthesizedLocalKind synthesizedKind,
LocalDebugId id,
uint pdbAttributes,
LocalSlotConstraints constraints,
bool isDynamic,
ImmutableArray<TypedConstant> dynamicTransformFlags)
{
var local = symbol as EELocalSymbol;
if ((object)local == null)
{
return null;
}
return _locals[local.Ordinal];
}
public override string PreviousStateMachineTypeName
{
get { return null; }
}
public override bool TryGetPreviousHoistedLocalSlotIndex(SyntaxNode currentDeclarator, Cci.ITypeReference currentType, SynthesizedLocalKind synthesizedKind, LocalDebugId currentId, out int slotIndex)
{
slotIndex = -1;
return false;
}
public override int PreviousHoistedLocalSlotCount
{
get { return 0; }
}
public override bool TryGetPreviousAwaiterSlotIndex(Cci.ITypeReference currentType, out int slotIndex)
{
slotIndex = -1;
return false;
}
public override bool TryGetPreviousClosure(SyntaxNode closureSyntax, out DebugId closureId)
{
closureId = default(DebugId);
return false;
}
public override bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId)
{
lambdaId = default(DebugId);
return false;
}
public override int PreviousAwaiterSlotCount
{
get { return 0; }
}
public override DebugId? MethodId
{
get
{
return null;
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Data.MSSQL
{
/// <summary>
/// A management class for the MS SQL Storage Engine
/// </summary>
public class MSSQLManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Connection string for ADO.net
/// </summary>
private readonly string connectionString;
public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId,
string password)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = dataSource;
builder.InitialCatalog = initialCatalog;
builder.PersistSecurityInfo = Convert.ToBoolean(persistSecurityInfo);
builder.UserID = userId;
builder.Password = password;
builder.ApplicationName = Assembly.GetEntryAssembly().Location;
connectionString = builder.ToString();
}
/// <summary>
/// Initialize the manager and set the connectionstring
/// </summary>
/// <param name="connection"></param>
public MSSQLManager(string connection)
{
connectionString = connection;
}
public SqlConnection DatabaseConnection()
{
SqlConnection conn = new SqlConnection(connectionString);
//TODO is this good??? Opening connection here
conn.Open();
return conn;
}
#region Obsolete functions, can be removed!
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
/// <param name="name"></param>
/// <param name="type"></param>
[Obsolete("Do not use!")]
protected static void createCol(DataTable dt, string name, Type type)
{
DataColumn col = new DataColumn(name, type);
dt.Columns.Add(col);
}
/// <summary>
/// Define Table function
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
/*
[Obsolete("Do not use!")]
protected static string defineTable(DataTable dt)
{
string sql = "create table " + dt.TableName + "(";
string subsql = String.Empty;
foreach (DataColumn col in dt.Columns)
{
if (subsql.Length > 0)
{
// a map function would rock so much here
subsql += ",\n";
}
subsql += col.ColumnName + " " + SqlType(col.DataType);
if (col == dt.PrimaryKey[0])
{
subsql += " primary key";
}
}
sql += subsql;
sql += ")";
return sql;
}
*/
#endregion
/// <summary>
/// Type conversion function
/// </summary>
/// <param name="type">a type</param>
/// <returns>a sqltype</returns>
/// <remarks>this is something we'll need to implement for each db slightly differently.</remarks>
/*
[Obsolete("Used by a obsolete methods")]
public static string SqlType(Type type)
{
if (type == typeof(String))
{
return "varchar(255)";
}
if (type == typeof(Int32))
{
return "integer";
}
if (type == typeof(Double))
{
return "float";
}
if (type == typeof(Byte[]))
{
return "image";
}
return "varchar(255)";
}
*/
/// <summary>
/// Type conversion to a SQLDbType functions
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
internal SqlDbType DbtypeFromType(Type type)
{
if (type == typeof(string))
{
return SqlDbType.VarChar;
}
if (type == typeof(double))
{
return SqlDbType.Float;
}
if (type == typeof(Single))
{
return SqlDbType.Float;
}
if (type == typeof(int))
{
return SqlDbType.Int;
}
if (type == typeof(bool))
{
return SqlDbType.Bit;
}
if (type == typeof(UUID))
{
return SqlDbType.UniqueIdentifier;
}
if (type == typeof(sbyte))
{
return SqlDbType.Int;
}
if (type == typeof(Byte[]))
{
return SqlDbType.Image;
}
if (type == typeof(uint) || type == typeof(ushort))
{
return SqlDbType.Int;
}
if (type == typeof(ulong))
{
return SqlDbType.BigInt;
}
return SqlDbType.VarChar;
}
/// <summary>
/// Creates value for parameter.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
private static object CreateParameterValue(object value)
{
Type valueType = value.GetType();
if (valueType == typeof(UUID)) //TODO check if this works
{
return ((UUID) value).Guid;
}
if (valueType == typeof(UUID))
{
return ((UUID)value).Guid;
}
if (valueType == typeof(bool))
{
return (bool)value ? 1 : 0;
}
if (valueType == typeof(Byte[]))
{
return value;
}
if (valueType == typeof(int))
{
return value;
}
return value;
}
/// <summary>
/// Create a parameter for a command
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="parameterObject">parameter object.</param>
/// <returns></returns>
internal SqlParameter CreateParameter(string parameterName, object parameterObject)
{
return CreateParameter(parameterName, parameterObject, false);
}
/// <summary>
/// Creates the parameter for a command.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="parameterObject">parameter object.</param>
/// <param name="parameterOut">if set to <c>true</c> parameter is a output parameter</param>
/// <returns></returns>
internal SqlParameter CreateParameter(string parameterName, object parameterObject, bool parameterOut)
{
//Tweak so we dont always have to add @ sign
if (!parameterName.StartsWith("@")) parameterName = "@" + parameterName;
//HACK if object is null, it is turned into a string, there are no nullable type till now
if (parameterObject == null) parameterObject = "";
SqlParameter parameter = new SqlParameter(parameterName, DbtypeFromType(parameterObject.GetType()));
if (parameterOut)
{
parameter.Direction = ParameterDirection.Output;
}
else
{
parameter.Direction = ParameterDirection.Input;
parameter.Value = CreateParameterValue(parameterObject);
}
return parameter;
}
private static readonly Dictionary<string, string> emptyDictionary = new Dictionary<string, string>();
/// <summary>
/// Run a query and return a sql db command
/// </summary>
/// <param name="sql">The SQL query.</param>
/// <returns></returns>
internal AutoClosingSqlCommand Query(string sql)
{
return Query(sql, emptyDictionary);
}
/// <summary>
/// Runs a query with protection against SQL Injection by using parameterised input.
/// </summary>
/// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
/// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
/// <returns>A Sql DB Command</returns>
internal AutoClosingSqlCommand Query(string sql, Dictionary<string, string> parameters)
{
SqlCommand dbcommand = DatabaseConnection().CreateCommand();
dbcommand.CommandText = sql;
foreach (KeyValuePair<string, string> param in parameters)
{
dbcommand.Parameters.AddWithValue(param.Key, param.Value);
}
return new AutoClosingSqlCommand(dbcommand);
}
/// <summary>
/// Runs a query with protection against SQL Injection by using parameterised input.
/// </summary>
/// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
/// <param name="sqlParameter">A parameter - use createparameter to create parameter</param>
/// <returns></returns>
internal AutoClosingSqlCommand Query(string sql, SqlParameter sqlParameter)
{
SqlCommand dbcommand = DatabaseConnection().CreateCommand();
dbcommand.CommandText = sql;
dbcommand.Parameters.Add(sqlParameter);
return new AutoClosingSqlCommand(dbcommand);
}
/// <summary>
/// Checks if we need to do some migrations to the database
/// </summary>
/// <param name="migrationStore">migrationStore.</param>
public void CheckMigration(string migrationStore)
{
using (SqlConnection connection = DatabaseConnection())
{
Assembly assem = GetType().Assembly;
MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore);
migration.Update();
connection.Close();
}
}
#region Old Testtable functions
/// <summary>
/// Execute a SQL statement stored in a resource, as a string
/// </summary>
/// <param name="name">the ressource string</param>
public void ExecuteResourceSql(string name)
{
using (IDbCommand cmd = Query(getResourceString(name), new Dictionary<string, string>()))
{
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Given a list of tables, return the version of the tables, as seen in the database
/// </summary>
/// <param name="tableList"></param>
public void GetTableVersion(Dictionary<string, string> tableList)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["dbname"] = new SqlConnectionStringBuilder(connectionString).InitialCatalog;
using (IDbCommand tablesCmd =
Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param))
using (IDataReader tables = tablesCmd.ExecuteReader())
{
while (tables.Read())
{
try
{
string tableName = (string)tables["TABLE_NAME"];
if (tableList.ContainsKey(tableName))
tableList[tableName] = tableName;
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
tables.Close();
}
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private string getResourceString(string name)
{
Assembly assem = GetType().Assembly;
string[] names = assem.GetManifestResourceNames();
foreach (string s in names)
if (s.EndsWith(name))
using (Stream resource = assem.GetManifestResourceStream(s))
{
using (StreamReader resourceReader = new StreamReader(resource))
{
string resourceString = resourceReader.ReadToEnd();
return resourceString;
}
}
throw new Exception(string.Format("Resource '{0}' was not found", name));
}
#endregion
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the DB provider</returns>
public string getVersion()
{
Module module = GetType().Module;
// string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version;
return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.LogConsistency;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Services;
using Orleans.Streams;
using Orleans.Runtime.Versions;
using Orleans.Versions;
using Orleans.ApplicationParts;
using Orleans.Configuration;
using Orleans.Serialization;
using Orleans.Internal;
namespace Orleans.Runtime
{
/// <summary>
/// Orleans silo.
/// </summary>
public class Silo
{
/// <summary> Standard name for Primary silo. </summary>
public const string PrimarySiloName = "Primary";
private static TimeSpan WaitForMessageToBeQueuedForOutbound = TimeSpan.FromSeconds(2);
/// <summary> Silo Types. </summary>
public enum SiloType
{
/// <summary> No silo type specified. </summary>
None = 0,
/// <summary> Primary silo. </summary>
Primary,
/// <summary> Secondary silo. </summary>
Secondary,
}
private readonly ILocalSiloDetails siloDetails;
private readonly MessageCenter messageCenter;
private readonly LocalGrainDirectory localGrainDirectory;
private readonly ActivationDirectory activationDirectory;
private readonly ILogger logger;
private readonly TaskCompletionSource<int> siloTerminatedTask =
new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly SiloStatisticsManager siloStatistics;
private readonly InsideRuntimeClient runtimeClient;
private IReminderService reminderService;
private SystemTarget fallbackScheduler;
private readonly ISiloStatusOracle siloStatusOracle;
private Watchdog platformWatchdog;
private readonly TimeSpan initTimeout;
private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1);
private readonly Catalog catalog;
private readonly object lockable = new object();
private readonly GrainFactory grainFactory;
private readonly ISiloLifecycleSubject siloLifecycle;
private readonly IMembershipService membershipService;
private List<GrainService> grainServices = new List<GrainService>();
private readonly ILoggerFactory loggerFactory;
/// <summary>
/// Gets the type of this
/// </summary>
internal string Name => this.siloDetails.Name;
internal OrleansTaskScheduler LocalScheduler { get; private set; }
internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } }
internal IConsistentRingProvider RingProvider { get; private set; }
internal ICatalog Catalog => catalog;
internal SystemStatus SystemStatus { get; set; }
internal IServiceProvider Services { get; }
/// <summary> SiloAddress for this silo. </summary>
public SiloAddress SiloAddress => this.siloDetails.SiloAddress;
/// <summary>
/// Silo termination event used to signal shutdown of this silo.
/// </summary>
public WaitHandle SiloTerminatedEvent // one event for all types of termination (shutdown, stop and fast kill).
=> ((IAsyncResult)this.siloTerminatedTask.Task).AsyncWaitHandle;
public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill).
private bool isFastKilledNeeded = false; // Set to true if something goes wrong in the shutdown/stop phase
private IGrainContext reminderServiceContext;
private LifecycleSchedulingSystemTarget lifecycleSchedulingSystemTarget;
/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
/// <param name="siloDetails">The silo initialization parameters</param>
/// <param name="services">Dependency Injection container</param>
[Obsolete("This constructor is obsolete and may be removed in a future release. Use SiloHostBuilder to create an instance of ISiloHost instead.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")]
public Silo(ILocalSiloDetails siloDetails, IServiceProvider services)
{
string name = siloDetails.Name;
// Temporarily still require this. Hopefuly gone when 2.0 is released.
this.siloDetails = siloDetails;
this.SystemStatus = SystemStatus.Creating;
var startTime = DateTime.UtcNow;
IOptions<ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService<IOptions<ClusterMembershipOptions>>();
initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime;
if (Debugger.IsAttached)
{
initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime);
stopTimeout = initTimeout;
}
var localEndpoint = this.siloDetails.SiloAddress.Endpoint;
services.GetService<SerializationManager>().RegisterSerializers(services.GetService<IApplicationPartManager>());
this.Services = services;
this.Services.InitializeSiloUnobservedExceptionsHandler();
//set PropagateActivityId flag from node config
IOptions<SiloMessagingOptions> messagingOptions = services.GetRequiredService<IOptions<SiloMessagingOptions>>();
RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId;
this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>();
logger = this.loggerFactory.CreateLogger<Silo>();
logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
if (!GCSettings.IsServerGC)
{
logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">");
logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
}
if (logger.IsEnabled(LogLevel.Debug))
{
var highestLogLevel = logger.IsEnabled(LogLevel.Trace) ? nameof(LogLevel.Trace) : nameof(LogLevel.Debug);
logger.LogWarning(
new EventId((int)ErrorCode.SiloGcWarning),
$"A verbose logging level ({highestLogLevel}) is configured. This will impact performance. The recommended log level is {nameof(LogLevel.Information)}.");
}
logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------",
this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation);
logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name);
var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>();
BufferPool.InitGlobalBufferPool(siloMessagingOptions.Value);
try
{
grainFactory = Services.GetRequiredService<GrainFactory>();
}
catch (InvalidOperationException exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc);
throw;
}
// Performance metrics
siloStatistics = Services.GetRequiredService<SiloStatisticsManager>();
// The scheduler
LocalScheduler = Services.GetRequiredService<OrleansTaskScheduler>();
runtimeClient = Services.GetRequiredService<InsideRuntimeClient>();
// Initialize the message center
messageCenter = Services.GetRequiredService<MessageCenter>();
var dispatcher = this.Services.GetRequiredService<Dispatcher>();
messageCenter.RerouteHandler = dispatcher.RerouteMessage;
messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;
// Now the router/directory service
// This has to come after the message center //; note that it then gets injected back into the message center.;
localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>();
// Now the activation directory.
activationDirectory = Services.GetRequiredService<ActivationDirectory>();
// Now the consistent ring provider
RingProvider = Services.GetRequiredService<IConsistentRingProvider>();
catalog = Services.GetRequiredService<Catalog>();
// Now the incoming message agents
var messageFactory = this.Services.GetRequiredService<MessageFactory>();
var messagingTrace = this.Services.GetRequiredService<MessagingTrace>();
messageCenter.RegisterLocalMessageHandler(new IncomingMessageHandler(
messageCenter,
activationDirectory,
LocalScheduler,
catalog.Dispatcher,
messageFactory,
this.loggerFactory.CreateLogger<IncomingMessageHandler>(),
messagingTrace));
siloStatusOracle = Services.GetRequiredService<ISiloStatusOracle>();
this.membershipService = Services.GetRequiredService<IMembershipService>();
this.SystemStatus = SystemStatus.Created;
StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
() => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.
this.siloLifecycle = this.Services.GetRequiredService<ISiloLifecycleSubject>();
// register all lifecycle participants
IEnumerable<ILifecycleParticipant<ISiloLifecycle>> lifecycleParticipants = this.Services.GetServices<ILifecycleParticipant<ISiloLifecycle>>();
foreach(ILifecycleParticipant<ISiloLifecycle> participant in lifecycleParticipants)
{
participant?.Participate(this.siloLifecycle);
}
// register all named lifecycle participants
IKeyedServiceCollection<string, ILifecycleParticipant<ISiloLifecycle>> namedLifecycleParticipantCollection = this.Services.GetService<IKeyedServiceCollection<string,ILifecycleParticipant<ISiloLifecycle>>>();
foreach (ILifecycleParticipant<ISiloLifecycle> participant in namedLifecycleParticipantCollection
?.GetServices(this.Services)
?.Select(s => s.GetService(this.Services)))
{
participant?.Participate(this.siloLifecycle);
}
// add self to lifecycle
this.Participate(this.siloLifecycle);
logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
}
public async Task StartAsync(CancellationToken cancellationToken)
{
// SystemTarget for provider init calls
this.lifecycleSchedulingSystemTarget = Services.GetRequiredService<LifecycleSchedulingSystemTarget>();
this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>();
RegisterSystemTarget(lifecycleSchedulingSystemTarget);
try
{
await this.LocalScheduler.QueueTask(() => this.siloLifecycle.OnStart(cancellationToken), this.lifecycleSchedulingSystemTarget);
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc);
throw;
}
}
private void CreateSystemTargets()
{
logger.Debug("Creating System Targets for this silo.");
logger.Debug("Creating {0} System Target", "SiloControl");
var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services);
RegisterSystemTarget(siloControl);
logger.Debug("Creating {0} System Target", "DeploymentLoadPublisher");
RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>());
logger.Debug("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator");
RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory);
RegisterSystemTarget(LocalGrainDirectory.CacheValidator);
logger.Debug("Creating {0} System Target", "RemoteClusterGrainDirectory");
logger.Debug("Creating {0} System Target", "ClientObserverRegistrar + TypeManager");
this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>());
logger.Debug("Creating {0} System Target", "MembershipOracle");
if (this.membershipService is SystemTarget)
{
RegisterSystemTarget((SystemTarget)this.membershipService);
}
logger.Debug("Finished creating System Targets for this silo.");
}
private async Task InjectDependencies()
{
catalog.SiloStatusOracle = this.siloStatusOracle;
this.siloStatusOracle.SubscribeToSiloStatusEvents(localGrainDirectory);
// consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here
this.siloStatusOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider);
this.siloStatusOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>());
var reminderTable = Services.GetService<IReminderTable>();
if (reminderTable != null)
{
logger.Info($"Creating reminder grain service for type={reminderTable.GetType()}");
// Start the reminder service system target
var timerFactory = this.Services.GetRequiredService<IAsyncTimerFactory>();
reminderService = new LocalReminderService(this, reminderTable, this.initTimeout, this.loggerFactory, timerFactory);
RegisterSystemTarget((SystemTarget)reminderService);
}
RegisterSystemTarget(catalog);
await LocalScheduler.QueueActionAsync(catalog.Start, catalog)
.WithTimeout(initTimeout, $"Starting Catalog failed due to timeout {initTimeout}");
// SystemTarget for provider init calls
this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>();
RegisterSystemTarget(fallbackScheduler);
}
private Task OnRuntimeInitializeStart(CancellationToken ct)
{
lock (lockable)
{
if (!this.SystemStatus.Equals(SystemStatus.Created))
throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus));
this.SystemStatus = SystemStatus.Starting;
}
logger.Info(ErrorCode.SiloStarting, "Silo Start()");
//TODO: setup thead pool directly to lifecycle
StartTaskWithPerfAnalysis("ConfigureThreadPoolAndServicePointSettings",
this.ConfigureThreadPoolAndServicePointSettings, Stopwatch.StartNew());
return Task.CompletedTask;
}
private void StartTaskWithPerfAnalysis(string taskName, Action task, Stopwatch stopWatch)
{
stopWatch.Restart();
task.Invoke();
stopWatch.Stop();
this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish");
}
private async Task StartAsyncTaskWithPerfAnalysis(string taskName, Func<Task> task, Stopwatch stopWatch)
{
stopWatch.Restart();
await task.Invoke();
stopWatch.Stop();
this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish");
}
private async Task OnRuntimeServicesStart(CancellationToken ct)
{
//TODO: Setup all (or as many as possible) of the class started in this call to work directly with lifecyce
var stopWatch = Stopwatch.StartNew();
// The order of these 4 is pretty much arbitrary.
StartTaskWithPerfAnalysis("Start Message center",messageCenter.Start,stopWatch);
StartTaskWithPerfAnalysis("Start local grain directory", LocalGrainDirectory.Start, stopWatch);
this.runtimeClient.CurrentStreamProviderRuntime = this.Services.GetRequiredService<SiloProviderRuntime>();
// This has to follow the above steps that start the runtime components
await StartAsyncTaskWithPerfAnalysis("Create system targets and inject dependencies", () =>
{
CreateSystemTargets();
return InjectDependencies();
}, stopWatch);
// Validate the configuration.
// TODO - refactor validation - jbragg
//GlobalConfig.Application.ValidateConfiguration(logger);
}
private async Task OnRuntimeGrainServicesStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
// Load and init grain services before silo becomes active.
await StartAsyncTaskWithPerfAnalysis("Init grain services",
() => CreateGrainServices(), stopWatch);
try
{
StatisticsOptions statisticsOptions = Services.GetRequiredService<IOptions<StatisticsOptions>>().Value;
StartTaskWithPerfAnalysis("Start silo statistics", () => this.siloStatistics.Start(statisticsOptions), stopWatch);
logger.Debug("Silo statistics manager started successfully.");
// Finally, initialize the deployment load collector, for grains with load-based placement
await StartAsyncTaskWithPerfAnalysis("Start deployment load collector", StartDeploymentLoadCollector, stopWatch);
async Task StartDeploymentLoadCollector()
{
var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>();
await this.LocalScheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher)
.WithTimeout(this.initTimeout, $"Starting DeploymentLoadPublisher failed due to timeout {initTimeout}");
logger.Debug("Silo deployment load publisher started successfully.");
}
// Start background timer tick to watch for platform execution stalls, such as when GC kicks in
var healthCheckParticipants = this.Services.GetService<IEnumerable<IHealthCheckParticipant>>().ToList();
this.platformWatchdog = new Watchdog(statisticsOptions.LogWriteInterval, healthCheckParticipants, this.loggerFactory.CreateLogger<Watchdog>());
this.platformWatchdog.Start();
if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo platform watchdog started successfully."); }
}
catch (Exception exc)
{
this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc));
throw;
}
if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo.Start complete: System status = {0}", this.SystemStatus); }
}
private Task OnBecomeActiveStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
StartTaskWithPerfAnalysis("Start gateway", StartGateway, stopWatch);
void StartGateway()
{
// Now that we're active, we can start the gateway
var mc = this.messageCenter as MessageCenter;
mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>());
logger.Debug("Message gateway service started successfully.");
}
this.SystemStatus = SystemStatus.Running;
return Task.CompletedTask;
}
private async Task OnActiveStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
if (this.reminderService != null)
{
await StartAsyncTaskWithPerfAnalysis("Start reminder service", StartReminderService, stopWatch);
async Task StartReminderService()
{
// so, we have the view of the membership in the consistentRingProvider. We can start the reminder service
this.reminderServiceContext = (this.reminderService as IGrainContext) ?? this.fallbackScheduler;
await this.LocalScheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext)
.WithTimeout(this.initTimeout, $"Starting ReminderService failed due to timeout {initTimeout}");
this.logger.Debug("Reminder service started successfully.");
}
}
foreach (var grainService in grainServices)
{
await StartGrainService(grainService);
}
}
private async Task CreateGrainServices()
{
var grainServices = this.Services.GetServices<IGrainService>();
foreach (var grainService in grainServices)
{
await RegisterGrainService(grainService);
}
}
private async Task RegisterGrainService(IGrainService service)
{
var grainService = (GrainService)service;
RegisterSystemTarget(grainService);
grainServices.Add(grainService);
await this.LocalScheduler.QueueTask(() => grainService.Init(Services), grainService).WithTimeout(this.initTimeout, $"GrainService Initializing failed due to timeout {initTimeout}");
logger.Info($"Grain Service {service.GetType().FullName} registered successfully.");
}
private async Task StartGrainService(IGrainService service)
{
var grainService = (GrainService)service;
await this.LocalScheduler.QueueTask(grainService.Start, grainService).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}");
logger.Info($"Grain Service {service.GetType().FullName} started successfully.");
}
private void ConfigureThreadPoolAndServicePointSettings()
{
PerformanceTuningOptions performanceTuningOptions = Services.GetRequiredService<IOptions<PerformanceTuningOptions>>().Value;
if (performanceTuningOptions.MinDotNetThreadPoolSize > 0 || performanceTuningOptions.MinIOThreadPoolSize > 0)
{
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
if (performanceTuningOptions.MinDotNetThreadPoolSize > workerThreads ||
performanceTuningOptions.MinIOThreadPoolSize > completionPortThreads)
{
// if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value.
int newWorkerThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, workerThreads);
int newCompletionPortThreads = Math.Max(performanceTuningOptions.MinIOThreadPoolSize, completionPortThreads);
bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads);
if (ok)
{
logger.Info(ErrorCode.SiloConfiguredThreadPool,
"Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
else
{
logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool,
"Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
}
}
// Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage
// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx
logger.Info(ErrorCode.SiloConfiguredServicePointManager,
"Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.",
performanceTuningOptions.Expect100Continue, performanceTuningOptions.DefaultConnectionLimit, performanceTuningOptions.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = performanceTuningOptions.Expect100Continue;
ServicePointManager.DefaultConnectionLimit = performanceTuningOptions.DefaultConnectionLimit;
ServicePointManager.UseNagleAlgorithm = performanceTuningOptions.UseNagleAlgorithm;
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// Grains are not deactivated.
/// </summary>
public void Stop()
{
var cancellationSource = new CancellationTokenSource();
cancellationSource.Cancel();
StopAsync(cancellationSource.Token).GetAwaiter().GetResult();
}
/// <summary>
/// Gracefully stop the run time system and the application.
/// All grains will be properly deactivated.
/// All in-flight applications requests would be awaited and finished gracefully.
/// </summary>
public void Shutdown()
{
var cancellationSource = new CancellationTokenSource(this.stopTimeout);
StopAsync(cancellationSource.Token).GetAwaiter().GetResult();
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// </summary>
public async Task StopAsync(CancellationToken cancellationToken)
{
bool gracefully = !cancellationToken.IsCancellationRequested;
string operation = gracefully ? "Shutdown()" : "Stop()";
bool stopAlreadyInProgress = false;
lock (lockable)
{
if (this.SystemStatus.Equals(SystemStatus.Stopping) ||
this.SystemStatus.Equals(SystemStatus.ShuttingDown) ||
this.SystemStatus.Equals(SystemStatus.Terminated))
{
stopAlreadyInProgress = true;
// Drop through to wait below
}
else if (!this.SystemStatus.Equals(SystemStatus.Running))
{
throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, this.SystemStatus));
}
else
{
if (gracefully)
this.SystemStatus = SystemStatus.ShuttingDown;
else
this.SystemStatus = SystemStatus.Stopping;
}
}
if (stopAlreadyInProgress)
{
logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish");
var pause = TimeSpan.FromSeconds(1);
while (!this.SystemStatus.Equals(SystemStatus.Terminated))
{
logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause);
await Task.Delay(pause);
}
await this.SiloTerminated;
return;
}
try
{
await this.LocalScheduler.QueueTask(() => this.siloLifecycle.OnStop(cancellationToken), this.lifecycleSchedulingSystemTarget);
}
finally
{
SafeExecute(LocalScheduler.Stop);
SafeExecute(LocalScheduler.PrintStatistics);
}
}
private Task OnRuntimeServicesStop(CancellationToken ct)
{
if (this.isFastKilledNeeded || ct.IsCancellationRequested) // No time for this
return Task.CompletedTask;
// Start rejecting all silo to silo application messages
SafeExecute(messageCenter.BlockApplicationMessages);
// Stop scheduling/executing application turns
SafeExecute(LocalScheduler.StopApplicationTurns);
return Task.CompletedTask;
}
private Task OnRuntimeInitializeStop(CancellationToken ct)
{
// 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ...
logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()");
// timers
if (platformWatchdog != null)
SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up
if (!ct.IsCancellationRequested)
SafeExecute(activationDirectory.PrintActivationDirectory);
SafeExecute(messageCenter.Stop);
SafeExecute(siloStatistics.Stop);
SafeExecute(() => this.SystemStatus = SystemStatus.Terminated);
// Setting the event should be the last thing we do.
// Do nothing after that!
this.siloTerminatedTask.SetResult(0);
return Task.CompletedTask;
}
private async Task OnBecomeActiveStop(CancellationToken ct)
{
if (this.isFastKilledNeeded)
return;
bool gracefully = !ct.IsCancellationRequested;
string operation = gracefully ? "Shutdown()" : "Stop()";
try
{
if (gracefully)
{
logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()");
//Stop LocalGrainDirectory
await LocalScheduler.QueueTask(()=>localGrainDirectory.Stop(true), localGrainDirectory.CacheValidator)
.WithCancellation(ct, "localGrainDirectory Stop failed because the task was cancelled");
SafeExecute(() => catalog.DeactivateAllActivations().Wait(ct));
//wait for all queued message sent to OutboundMessageQueue before MessageCenter stop and OutboundMessageQueue stop.
await Task.Delay(WaitForMessageToBeQueuedForOutbound);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloFailedToStopMembership,
$"Failed to {operation}. About to FastKill this silo.", exc);
this.isFastKilledNeeded = true;
}
// Stop the gateway
SafeExecute(messageCenter.StopAcceptingClientMessages);
SafeExecute(() => catalog?.Stop());
}
private async Task OnActiveStop(CancellationToken ct)
{
if (this.isFastKilledNeeded || ct.IsCancellationRequested)
return;
if (reminderService != null)
{
await this.LocalScheduler
.QueueTask(reminderService.Stop, this.reminderServiceContext)
.WithCancellation(ct, "Stopping ReminderService failed because the task was cancelled");
}
foreach (var grainService in grainServices)
{
await this.LocalScheduler
.QueueTask(grainService.Stop, grainService)
.WithCancellation(ct, "Stopping GrainService failed because the task was cancelled");
if (this.logger.IsEnabled(LogLevel.Debug))
{
logger.Debug(
"{GrainServiceType} Grain Service with Id {GrainServiceId} stopped successfully.",
grainService.GetType().FullName,
grainService.GetPrimaryKeyLong(out string ignored));
}
}
}
private void SafeExecute(Action action)
{
Utils.SafeExecute(action, logger, "Silo.Stop");
}
private void HandleProcessExit(object sender, EventArgs e)
{
// NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur
this.logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting");
this.isFastKilledNeeded = true;
this.Stop();
}
internal void RegisterSystemTarget(SystemTarget target)
{
var providerRuntime = this.Services.GetRequiredService<SiloProviderRuntime>();
providerRuntime.RegisterSystemTarget(target);
}
/// <summary> Return dump of diagnostic data from this silo. </summary>
/// <param name="all"></param>
/// <returns>Debug data for this silo.</returns>
public string GetDebugDump(bool all = true)
{
var sb = new StringBuilder();
foreach (var systemTarget in activationDirectory.AllSystemTargets())
sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine();
var enumerator = activationDirectory.GetEnumerator();
while(enumerator.MoveNext())
{
Utils.SafeExecute(() =>
{
var activationData = enumerator.Current.Value;
var workItemGroup = LocalScheduler.GetWorkItemGroup(activationData);
if (workItemGroup == null)
{
sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.",
activationData.GrainId,
activationData.ActivationId);
sb.AppendLine();
return;
}
if (all || activationData.State.Equals(ActivationState.Valid))
{
sb.AppendLine(workItemGroup.DumpStatus());
sb.AppendLine(activationData.DumpStatus());
}
});
}
logger.Info(ErrorCode.SiloDebugDump, sb.ToString());
return sb.ToString();
}
/// <summary> Object.ToString override -- summary info for this silo. </summary>
public override string ToString()
{
return localGrainDirectory.ToString();
}
private void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeInitialize, (ct) => Task.Run(() => OnRuntimeInitializeStart(ct)), (ct) => Task.Run(() => OnRuntimeInitializeStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeServices, (ct) => Task.Run(() => OnRuntimeServicesStart(ct)), (ct) => Task.Run(() => OnRuntimeServicesStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeGrainServices, (ct) => Task.Run(() => OnRuntimeGrainServicesStart(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.BecomeActive, (ct) => Task.Run(() => OnBecomeActiveStart(ct)), (ct) => Task.Run(() => OnBecomeActiveStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.Active, (ct) => Task.Run(() => OnActiveStart(ct)), (ct) => Task.Run(() => OnActiveStop(ct)));
}
}
// A dummy system target for fallback scheduler
internal class FallbackSystemTarget : SystemTarget
{
public FallbackSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.FallbackSystemTargetType, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
// A dummy system target for fallback scheduler
internal class LifecycleSchedulingSystemTarget : SystemTarget
{
public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.LifecycleSchedulingSystemTargetType, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.Windows.Controls.Primitives;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using WPFLight.Resources;
using System.Windows.Data;
namespace System.Windows.Controls {
public class ComboBox : Selector {
public ComboBox ( ) {
this.Background = Brushes.Red;
this.Padding = new Thickness ();
this.Margin = new Thickness ();
window = new Window(this);
cmdItem = new Button ();
lbItems = new ListBox ();
var itemsBinding = new Binding ();
itemsBinding.Mode = BindingMode.OneWay;
itemsBinding.Source = this;
itemsBinding.Path = new PropertyPath ("Items");
lbItems.Margin = new Thickness (2);
lbItems.BorderThickness = new Thickness (0);
lbItems.ItemContainerStyle = (Style)this.FindResource ("ComboBoxItemStyle");
lbItems.SetBinding (ListBox.ItemsProperty, itemsBinding);
lbItems.SelectionChanged += (s,e) => {
window.DialogResult = this.SelectedItem != null;
window.Close ();
this.IsDropDownOpen = false;
};
window.Content = lbItems;
var selectedItemBinding = new Binding ("SelectedItem");
selectedItemBinding.Mode = BindingMode.TwoWay;
selectedItemBinding.Source = lbItems;
cmdItem.SetBinding (
Button.ContentProperty,
selectedItemBinding);
this.SetBinding (
ListBox.SelectedItemProperty,
selectedItemBinding);
}
#region Properties
public static DependencyProperty IsDropDownOpenProperty =
DependencyProperty.Register (
"IsDropDownOpen",
typeof ( bool ),
typeof ( ComboBox ),
new PropertyMetadata (
new PropertyChangedCallback (
( s, e ) => {
if ( ( bool ) e.NewValue )
((ComboBox)s).OpenDropDownList ( );
else
((ComboBox)s).CloseDropDownList ( );
} ) ) );
public bool IsDropDownOpen {
get {
return ( bool ) GetValue (IsDropDownOpenProperty);
}
set {
SetValue (IsDropDownOpenProperty, value);
}
}
#endregion
public override void Initialize () {
cmdItem.Padding = new Thickness (9, 0, 0, 0);
cmdItem.HorizontalContentAlignment = HorizontalAlignment.Left;
cmdItem.Parent = this;
cmdItem.Style = ( Style ) this.FindResource ("ButtonNumberStyle");
cmdItem.BorderBrush = Brushes.Transparent;
cmdItem.BorderThickness = new Thickness ();
cmdItem.FontSize = .2f;
cmdItem.Content = this.SelectedItem;
cmdItem.Initialize ();
window.FontFamily = this.FontFamily;
window.IsToolTip = false;
window.Left = (int)this.GetAbsoluteLeft();
window.Top = (int)this.GetAbsoluteTop() + this.ActualHeight + 4;
window.Width = this.ActualWidth;
window.Height = 247; // TODO ComputeItemsHeight()
window.Background = new SolidColorBrush (Colors.Black * .9f);
window.BorderBrush = new SolidColorBrush (Colors.White * .3f);
window.BorderThickness = new Thickness(1);
window.LostFocus += delegate {
if ( !ignoreLostFocus )
this.IsDropDownOpen = false;
};
window.Initialize ();
base.Initialize();
}
void OpenDropDownList ( ) {
if (this.IsInitialized) {
window.Show (false);
}
}
void CloseDropDownList ( ) {
if (this.IsInitialized) {
window.Close ();
}
}
protected override void OnVisibleChanged (bool visible) {
base.OnVisibleChanged(visible);
if (!visible)
window.Close();
}
protected override void OnEnabledChanged (bool enabled) {
base.OnEnabledChanged(enabled);
if (!enabled)
window.Close();
}
public override void Update (GameTime gameTime) {
base.Update (gameTime);
cmdItem.Update (gameTime);
}
public override void Draw (GameTime gameTime, SpriteBatch batch, float a, Matrix transform) {
cmdItem.Draw (gameTime, batch, Opacity * a, transform);
batch.Begin (
SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.AnisotropicClamp,
DepthStencilState.None,
RasterizerState.CullNone,
null,
transform);
var left = GetAbsoluteLeft ();
var top = GetAbsoluteTop ();
batch.Draw (
Textures.ArrowDown,
new Rectangle (
(int)Math.Floor (left + this.ActualWidth - 30),
(int)Math.Floor (top + this.ActualHeight / 2f), 20, 20),
null,
new Microsoft.Xna.Framework.Color ( .8f, .8f, .8f ) * .5f,
MathHelper.ToRadians (0),
new Vector2 (
WPFLight.Resources.Textures.ArrowDown.Bounds.Width / 2f,
WPFLight.Resources.Textures.ArrowDown.Height / 2f),
SpriteEffects.None,
0);
batch.End ();
}
public override void OnTouchDown (TouchLocation state) {
base.OnTouchDown (state);
ignoreLostFocus = true;
this.IsDropDownOpen = !this.IsDropDownOpen;
}
public override void OnTouchUp (TouchLocation state) {
base.OnTouchUp (state);
ignoreLostFocus = false;
if (this.IsDropDownOpen)
window.Focus ();
}
protected override void OnSelectionChanged () {
base.OnSelectionChanged ();
}
public override void Invalidate () {
base.Invalidate ();
window.Left = (int)this.GetAbsoluteLeft();
window.Top = (int)this.GetAbsoluteTop() + this.ActualHeight - 5;
}
private bool ignoreLostFocus;
private Window window;
private ListBox lbItems;
private Button cmdItem;
}
}
| |
using UnityEngine;
using System.Collections;
using BulletSharp;
namespace BulletUnity {
public class BUtility {
public const float Two_PI = 6.283185307179586232f;
public const float RADS_PER_DEG = Two_PI / 360.0f;
public const float SQRT12 = 0.7071067811865475244008443621048490f;
public static void DebugDrawRope(Vector3 position, Quaternion rotation, Vector3 scale, Vector3 begin, Vector3 end, int res, Color color) {
Gizmos.color = color;
Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, scale);
Vector3 p1 = matrix.MultiplyPoint(begin);
Vector3 p2 = matrix.MultiplyPoint(end);
int r = res + 2;
Vector3 deltaX = new Vector3(0.05f, 0.05f, 0);
Vector3 deltaZ = new Vector3(0, 0.05f, 0.05f);
for (int i = 0; i < r; i++) {
Gizmos.color = color;
float t = i * 1.0f / (r - 1);
float tNext = (i + 1) * 1.0f / (r - 1);
Vector3 p = Vector3.Lerp(p1, p2, t);
Vector3 pNext = Vector3.Lerp(p1, p2, tNext);
if (i != r - 1) {
Gizmos.DrawLine(p, pNext); // line
}
Gizmos.color = Color.white;
Gizmos.DrawLine(p - deltaX, p + deltaX);
Gizmos.DrawLine(p - deltaZ, p + deltaZ);
}
}
public static void DebugDrawSphere(Vector3 position, Quaternion rotation, Vector3 scale, Vector3 radius, Color color) {
Gizmos.color = color;
Vector3 start = position;
Vector3 xoffs = new Vector3(radius.x * scale.x, 0, 0);
Vector3 yoffs = new Vector3(0, radius.y * scale.y, 0);
Vector3 zoffs = new Vector3(0, 0, radius.z * scale.z);
xoffs = rotation * xoffs;
yoffs = rotation * yoffs;
zoffs = rotation * zoffs;
float step = 5 * RADS_PER_DEG;
int nSteps = (int)(360.0f / step);
Vector3 vx = new Vector3(scale.x, 0, 0);
Vector3 vy = new Vector3(0, scale.y, 0);
Vector3 vz = new Vector3(0, 0, scale.z);
Vector3 prev = start - xoffs;
for (int i = 1; i <= nSteps; i++) {
float angle = 360.0f * i / nSteps;
Vector3 next = start + rotation * (radius.x * vx * Mathf.Cos(angle) + radius.y * vy * Mathf.Sin(angle));
Gizmos.DrawLine(prev, next);
prev = next;
}
prev = start - xoffs;
for (int i = 1; i <= nSteps; i++) {
float angle = 360.0f * i / nSteps;
Vector3 next = start + rotation * (radius.x * vx * Mathf.Cos(angle) + radius.z * vz * Mathf.Sin(angle));
Gizmos.DrawLine(prev, next);
prev = next;
}
prev = start - yoffs;
for (int i = 1; i <= nSteps; i++) {
float angle = 360.0f * i / nSteps;
Vector3 next = start + rotation * (radius.y * vy * Mathf.Cos(angle) + radius.z * vz * Mathf.Sin(angle));
Gizmos.DrawLine(prev, next);
prev = next;
}
}
public static void DebugDrawPatch(Vector3 position, Quaternion rotation, Vector3 scale, Vector3 c00, Vector3 c01, Vector3 c10, Vector3 c11, int resX, int resY, Color color) {
if (resX < 2 || resY < 2)
return;
Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, scale);
Gizmos.color = color;
Vector3 p00 = matrix.MultiplyPoint(c00);
Vector3 p01 = matrix.MultiplyPoint(c01);
Vector3 p10 = matrix.MultiplyPoint(c10);
Vector3 p11 = matrix.MultiplyPoint(c11);
for (int iy = 0; iy < resY; ++iy) {
for (int ix = 0; ix < resX; ++ix) {
// point 00
float tx_00 = ix * 1.0f / (resX - 1);
float ty_00 = iy * 1.0f / (resY - 1);
Vector3 py0_00 = Vector3.Lerp(p00, p01, ty_00);
Vector3 py1_00 = Vector3.Lerp(p10, p11, ty_00);
Vector3 pxy_00 = Vector3.Lerp(py0_00, py1_00, tx_00);
// point 01
float tx_01 = (ix + 1) * 1.0f / (resX - 1);
float ty_01 = iy * 1.0f / (resY - 1);
Vector3 py0_01 = Vector3.Lerp(p00, p01, ty_01);
Vector3 py1_01 = Vector3.Lerp(p10, p11, ty_01);
Vector3 pxy_01 = Vector3.Lerp(py0_01, py1_01, tx_01);
//point 10
float tx_10 = ix * 1.0f / (resX - 1);
float ty_10 = (iy + 1) * 1.0f / (resY - 1);
Vector3 py0_10 = Vector3.Lerp(p00, p01, ty_10);
Vector3 py1_10 = Vector3.Lerp(p10, p11, ty_10);
Vector3 pxy_10 = Vector3.Lerp(py0_10, py1_10, tx_10);
//point 11
float tx_11 = (ix + 1) * 1.0f / (resX - 1);
float ty_11 = (iy + 1) * 1.0f / (resY - 1);
Vector3 py0_11 = Vector3.Lerp(p00, p01, ty_11);
Vector3 py1_11 = Vector3.Lerp(p10, p11, ty_11);
Vector3 pxy_11 = Vector3.Lerp(py0_11, py1_11, tx_11);
Gizmos.DrawLine(pxy_00, pxy_01);
Gizmos.DrawLine(pxy_01, pxy_11);
Gizmos.DrawLine(pxy_00, pxy_11);
Gizmos.DrawLine(pxy_00, pxy_10);
Gizmos.DrawLine(pxy_10, pxy_11);
}
}
}
/*
//it is very slow, so don't use it if you don't need it indeed..
public static void DebugDrawPolyhedron(Vector3 position,Quaternion rotation,Vector3 scale,btPolyhedralConvexShape shape,Color color)
{
if( shape == null )
return;
Matrix4x4 matrix = Matrix4x4.TRS(position,rotation,scale);
Gizmos.color = color;
btConvexPolyhedron poly = shape.getConvexPolyhedron();
if( poly == null )
return;
int faceSize = poly.m_faces.size();
for (int i=0;i < faceSize;i++)
{
Vector3 centroid = new Vector3(0,0,0);
btFace face = poly.m_faces.at(i);
int numVerts = face.m_indices.size();
if (numVerts > 0)
{
int lastV = face.m_indices.at(numVerts-1);
for (int v=0;v < numVerts;v++)
{
int curVert = face.m_indices.at(v);
BulletSharp.Math.Vector3 curVertObject = BulletSharp.Math.Vector3.GetObjectFromSwigPtr(poly.m_vertices.at(curVert));
centroid.x += curVertObject.x();
centroid.y += curVertObject.y();
centroid.z += curVertObject.z();
BulletSharp.Math.Vector3 btv1 = BulletSharp.Math.Vector3.GetObjectFromSwigPtr(poly.m_vertices.at(lastV));
BulletSharp.Math.Vector3 btv2 = BulletSharp.Math.Vector3.GetObjectFromSwigPtr(poly.m_vertices.at(curVert));
Vector3 v1 = new Vector3(btv1.x(),btv1.y(),btv1.z());
Vector3 v2 = new Vector3(btv2.x(),btv2.y(),btv2.z());
v1 = matrix.MultiplyPoint(v1);
v2 = matrix.MultiplyPoint(v2);
Gizmos.DrawLine(v1,v2);
lastV = curVert;
}
}
float s = 1.0f/numVerts;
centroid.x *= s;
centroid.y *= s;
centroid.z *= s;
//normal draw
// {
// Vector3 normalColor = new Vector3(1,1,0);
//
// BulletSharp.Math.Vector3 faceNormal(face.m_plane[0],poly->m_faces[i].m_plane[1],poly->m_faces[i].m_plane[2]);
// getDebugDrawer()->drawLine(worldTransform*centroid,worldTransform*(centroid+faceNormal),normalColor);
// }
}
}
*/
public static void DebugDrawBox(Vector3 position, Quaternion rotation, Vector3 scale, Vector3 maxVec, Color color) {
maxVec = new Vector3(maxVec.x, maxVec.z, maxVec.y);
Vector3 minVec = new Vector3(0 - maxVec.x, 0 - maxVec.y, 0 - maxVec.z);
Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, scale);
Vector3 iii = matrix.MultiplyPoint(minVec);
Vector3 aii = matrix.MultiplyPoint(new Vector3(maxVec[0], minVec[1], minVec[2]));
Vector3 aai = matrix.MultiplyPoint(new Vector3(maxVec[0], maxVec[1], minVec[2]));
Vector3 iai = matrix.MultiplyPoint(new Vector3(minVec[0], maxVec[1], minVec[2]));
Vector3 iia = matrix.MultiplyPoint(new Vector3(minVec[0], minVec[1], maxVec[2]));
Vector3 aia = matrix.MultiplyPoint(new Vector3(maxVec[0], minVec[1], maxVec[2]));
Vector3 aaa = matrix.MultiplyPoint(maxVec);
Vector3 iaa = matrix.MultiplyPoint(new Vector3(minVec[0], maxVec[1], maxVec[2]));
Gizmos.color = color;
Gizmos.DrawLine(iii, aii);
Gizmos.DrawLine(aii, aai);
Gizmos.DrawLine(aai, iai);
Gizmos.DrawLine(iai, iii);
Gizmos.DrawLine(iii, iia);
Gizmos.DrawLine(aii, aia);
Gizmos.DrawLine(aai, aaa);
Gizmos.DrawLine(iai, iaa);
Gizmos.DrawLine(iia, aia);
Gizmos.DrawLine(aia, aaa);
Gizmos.DrawLine(aaa, iaa);
Gizmos.DrawLine(iaa, iia);
}
public static void DebugDrawCapsule(Vector3 position, Quaternion rotation, Vector3 scale, float radius, float halfHeight, int upAxis, Color color) {
Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, scale);
Gizmos.color = color;
Vector3 capStart = new Vector3(0.0f, 0.0f, 0.0f);
capStart[upAxis] = -halfHeight;
Vector3 capEnd = new Vector3(0.0f, 0.0f, 0.0f);
capEnd[upAxis] = halfHeight;
Gizmos.DrawWireSphere(matrix.MultiplyPoint(capStart), radius);
Gizmos.DrawWireSphere(matrix.MultiplyPoint(capEnd), radius);
// Draw some additional lines
Vector3 start = position;
capStart[(upAxis + 1) % 3] = radius;
capEnd[(upAxis + 1) % 3] = radius;
Gizmos.DrawLine(start + rotation * capStart, start + rotation * capEnd);
capStart[(upAxis + 1) % 3] = -radius;
capEnd[(upAxis + 1) % 3] = -radius;
Gizmos.DrawLine(start + rotation * capStart, start + rotation * capEnd);
capStart[(upAxis + 1) % 3] = 0.0f;
capEnd[(upAxis + 1) % 3] = 0.0f;
capStart[(upAxis + 2) % 3] = radius;
capEnd[(upAxis + 2) % 3] = radius;
Gizmos.DrawLine(start + rotation * capStart, start + rotation * capEnd);
capStart[(upAxis + 2) % 3] = -radius;
capEnd[(upAxis + 2) % 3] = -radius;
Gizmos.DrawLine(start + rotation * capStart, start + rotation * capEnd);
}
public static void DebugDrawCylinder(Vector3 position, Quaternion rotation, Vector3 scale, float radius, float halfHeight, int upAxis, Color color) {
Gizmos.color = color;
Vector3 start = position;
Vector3 offsetHeight = new Vector3(0, 0, 0);
offsetHeight[upAxis] = halfHeight;
Vector3 offsetRadius = new Vector3(0, 0, 0);
offsetRadius[(upAxis + 1) % 3] = radius;
offsetHeight.x *= scale.x; offsetHeight.y *= scale.y; offsetHeight.z *= scale.z;
offsetRadius.x *= scale.x; offsetRadius.y *= scale.y; offsetRadius.z *= scale.z;
Gizmos.DrawLine(start + rotation * (offsetHeight + offsetRadius), start + rotation * (-offsetHeight + offsetRadius));
Gizmos.DrawLine(start + rotation * (offsetHeight - offsetRadius), start + rotation * (-offsetHeight - offsetRadius));
// Drawing top and bottom caps of the cylinder
Vector3 yaxis = new Vector3(0, 0, 0);
yaxis[upAxis] = 1.0f;
Vector3 xaxis = new Vector3(0, 0, 0);
xaxis[(upAxis + 1) % 3] = 1.0f;
float r = offsetRadius.magnitude;
DebugDrawArc(start - rotation * (offsetHeight), rotation * yaxis, rotation * xaxis, r, r, 0, Two_PI, color, false, 10.0f);
DebugDrawArc(start + rotation * (offsetHeight), rotation * yaxis, rotation * xaxis, r, r, 0, Two_PI, color, false, 10.0f);
}
public static void DebugDrawCone(Vector3 position, Quaternion rotation, Vector3 scale, float radius, float height, int upAxis, Color color) {
Gizmos.color = color;
Vector3 start = position;
Vector3 offsetHeight = new Vector3(0, 0, 0);
offsetHeight[upAxis] = height * 0.5f;
Vector3 offsetRadius = new Vector3(0, 0, 0);
offsetRadius[(upAxis + 1) % 3] = radius;
Vector3 offset2Radius = new Vector3(0, 0, 0);
offset2Radius[(upAxis + 2) % 3] = radius;
offsetHeight.x *= scale.x; offsetHeight.y *= scale.y; offsetHeight.z *= scale.z;
offsetRadius.x *= scale.x; offsetRadius.y *= scale.y; offsetRadius.z *= scale.z;
offset2Radius.x *= scale.x; offset2Radius.y *= scale.y; offset2Radius.z *= scale.z;
Gizmos.DrawLine(start + rotation * (offsetHeight), start + rotation * (-offsetHeight + offsetRadius));
Gizmos.DrawLine(start + rotation * (offsetHeight), start + rotation * (-offsetHeight - offsetRadius));
Gizmos.DrawLine(start + rotation * (offsetHeight), start + rotation * (-offsetHeight + offset2Radius));
Gizmos.DrawLine(start + rotation * (offsetHeight), start + rotation * (-offsetHeight - offset2Radius));
// Drawing the base of the cone
Vector3 yaxis = new Vector3(0, 0, 0);
yaxis[upAxis] = 1.0f;
Vector3 xaxis = new Vector3(0, 0, 0);
xaxis[(upAxis + 1) % 3] = 1.0f;
DebugDrawArc(start - rotation * (offsetHeight), rotation * yaxis, rotation * xaxis, offsetRadius.magnitude, offset2Radius.magnitude, 0, Two_PI, color, false, 10.0f);
}
public static void DebugDrawPlane(Vector3 position, Quaternion rotation, Vector3 scale, Vector3 planeNormal, float planeConst, Color color) {
Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, new Vector3(1, 1, 1));
Gizmos.color = color;
Vector3 planeOrigin = planeNormal * planeConst;
Vector3 vec0 = new Vector3(0, 0, 0);
Vector3 vec1 = new Vector3(0, 0, 0);
GetPlaneSpaceVector(planeNormal, ref vec0, ref vec1);
float vecLen = 100.0f;
Vector3 pt0 = planeOrigin + vec0 * vecLen;
Vector3 pt1 = planeOrigin - vec0 * vecLen;
Vector3 pt2 = planeOrigin + vec1 * vecLen;
Vector3 pt3 = planeOrigin - vec1 * vecLen;
Gizmos.DrawLine(matrix.MultiplyPoint(pt0), matrix.MultiplyPoint(pt1));
Gizmos.DrawLine(matrix.MultiplyPoint(pt2), matrix.MultiplyPoint(pt3));
}
public static void GetPlaneSpaceVector(Vector3 planeNormal, ref Vector3 vec1, ref Vector3 vec2) {
if (Mathf.Abs(planeNormal[2]) > SQRT12) {
// choose p in y-z plane
float a = planeNormal[1] * planeNormal[1] + planeNormal[2] * planeNormal[2];
float k = 1.0f / Mathf.Sqrt(a);
vec1[0] = 0;
vec1[1] = -planeNormal[2] * k;
vec1[2] = planeNormal[1] * k;
// set q = n x p
vec2[0] = a * k;
vec2[1] = -planeNormal[0] * vec1[2];
vec2[2] = planeNormal[0] * vec1[1];
} else {
// choose p in x-y plane
float a = planeNormal[0] * planeNormal[0] + planeNormal[1] * planeNormal[1];
float k = 1.0f / Mathf.Sqrt(a);
vec1[0] = -planeNormal[1] * k;
vec1[1] = planeNormal[0] * k;
vec1[2] = 0;
// set q = n x p
vec2[0] = -planeNormal[2] * vec1[1];
vec2[1] = planeNormal[2] * vec1[0];
vec2[2] = a * k;
}
}
public static void DebugDrawArc(Vector3 center, Vector3 normal, Vector3 axis, float radiusA, float radiusB, float minAngle, float maxAngle,
Color color, bool drawSect, float stepDegrees) {
Gizmos.color = color;
Vector3 vx = axis;
Vector3 vy = Vector3.Cross(normal, axis);
float step = stepDegrees * RADS_PER_DEG;
int nSteps = (int)((maxAngle - minAngle) / step);
if (nSteps == 0)
nSteps = 1;
Vector3 prev = center + radiusA * vx * Mathf.Cos(minAngle) + radiusB * vy * Mathf.Sin(minAngle);
if (drawSect) {
Gizmos.DrawLine(center, prev);
}
for (int i = 1; i <= nSteps; i++) {
float angle = minAngle + (maxAngle - minAngle) * i * 1.0f / (nSteps * 1.0f);
Vector3 next = center + radiusA * vx * Mathf.Cos(angle) + radiusB * vy * Mathf.Sin(angle);
Gizmos.DrawLine(prev, next);
prev = next;
}
if (drawSect) {
Gizmos.DrawLine(center, prev);
}
}
}
}
| |
// 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.
//
//Similar to StrAccess1, but instead of using constants, different expression is used as the index to access the string
using System;
internal struct VT
{
public String str;
public char b0, b1, b2, b3, b4, b5, b6;
public int i;
public int[][] idxja;
}
internal class CL
{
public String str = "test string";
public char b0, b1, b2, b3, b4, b5, b6;
public static int i = 10;
public int[,] idx2darr = { { 5, 6 } };
}
internal unsafe class StrAccess2
{
public static String str1 = "test string";
public static int idx1 = 2;
public static String[,] str2darr = { { "test string" } };
public static int[,,] idx3darr = { { { 8 } } };
public static char sb0, sb1, sb2, sb3, sb4, sb5, sb6;
public static String f(ref String arg)
{
return arg;
}
public static int f1(ref int arg)
{
return arg;
}
public static Random rand = new Random();
public static int Main()
{
bool passed = true;
int* p = stackalloc int[11];
for (int m = 0; m < 11; m++) p[m] = m;
String str2 = "test string";
String[] str1darr = { "string access", "test string" };
Char[,] c2darr = { { '0', '1', '2', '3', '4', '5', '6' }, { 'a', 'b', 'c', 'd', 'e', 'f', 'g' } };
CL cl1 = new CL();
VT vt1;
vt1.i = 0;
vt1.str = "test string";
vt1.idxja = new int[2][];
vt1.idxja[1] = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int idx2 = 4;
int[] idx1darr = { 3, 9, 4, 2, 6, 1, 8, 10, 5, 7, 0 };
char b0, b1, b2, b3, b4, b5, b6;
//accessing the strings at different indices. assign to local char
b0 = str2[vt1.i];
b1 = str1[vt1.i];
b2 = cl1.str[vt1.i];
b3 = vt1.str[vt1.i];
b4 = str1darr[1][vt1.i];
b5 = str2darr[0, 0][vt1.i];
b6 = f(ref str2)[vt1.i];
if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6))
passed = false;
if ((str2[idx2] != str1[idx2]) || (str1[idx2] != cl1.str[idx2]) || (cl1.str[idx2] != vt1.str[idx2]) || (vt1.str[idx2] != str1darr[1][idx2]) || (str1darr[1][idx2] != str2darr[0, 0][idx2]) || (str2darr[0, 0][idx2] != f(ref str2)[idx2]))
passed = false;
b0 = str2[CL.i];
b1 = str1[CL.i];
b2 = cl1.str[CL.i];
b3 = vt1.str[CL.i];
b4 = str1darr[1][CL.i];
b5 = str2darr[0, 0][CL.i];
b6 = f(ref str2)[CL.i];
if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6))
passed = false;
int j = rand.Next(0, 10);
b0 = str2[idx1darr[j]];
b1 = str1[idx1darr[j]];
b2 = cl1.str[idx1darr[j]];
b3 = vt1.str[idx1darr[j]];
b4 = str1darr[1][idx1darr[j]];
b5 = str2darr[0, 0][idx1darr[j]];
b6 = f(ref str2)[idx1darr[j]];
if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6))
passed = false;
//accessing the strings at different indices, assign to static char
sb0 = str2[idx1 - 1];
sb1 = str1[idx1 - 1];
sb2 = cl1.str[idx1 - 1];
sb3 = vt1.str[idx1 - 1];
sb4 = str1darr[idx1 - 1][idx1 - 1];
sb5 = str2darr[0, 0][idx1 - 1];
sb6 = f(ref str2)[idx1 - 1];
if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6) || (sb6 != str2[1]))
passed = false;
if ((str2[5] != str1[5]) || (str1[5] != cl1.str[5]) || (cl1.str[5] != vt1.str[5]) || (vt1.str[5] != str1darr[1][5]) || (str1darr[1][5] != str2darr[0, 0][5]) || (str2darr[0, 0][5] != f(ref str2)[5]))
passed = false;
sb0 = str2[idx3darr[0, 0, 0] + 1];
sb1 = str1[idx3darr[0, 0, 0] + 1];
sb2 = cl1.str[idx3darr[0, 0, 0] + 1];
sb3 = vt1.str[idx3darr[0, 0, 0] + 1];
sb4 = str1darr[1][idx3darr[0, 0, 0] + 1];
sb5 = str2darr[0, 0][idx3darr[0, 0, 0] + 1];
sb6 = f(ref str2)[idx3darr[0, 0, 0] + 1];
if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6))
passed = false;
j = rand.Next(0, 10);
sb0 = str2[vt1.idxja[1][j]];
sb1 = str1[vt1.idxja[1][j]];
sb2 = cl1.str[vt1.idxja[1][j]];
sb3 = vt1.str[vt1.idxja[1][j]];
sb4 = str1darr[1][vt1.idxja[1][j]];
sb5 = str2darr[0, 0][vt1.idxja[1][j]];
sb6 = f(ref str2)[vt1.idxja[1][j]];
if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6))
passed = false;
//accessing the strings at different indices, assign to VT char
vt1.b0 = str2[idx2 - idx1];
vt1.b1 = str1[idx2 - idx1];
vt1.b2 = cl1.str[idx2 - idx1];
vt1.b3 = vt1.str[idx2 - idx1];
vt1.b4 = str1darr[1][idx2 - idx1];
vt1.b5 = str2darr[0, 0][idx2 - idx1];
vt1.b6 = f(ref str2)[idx2 - idx1];
if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6))
passed = false;
if ((str2[cl1.idx2darr[0, 1]] != str1[cl1.idx2darr[0, 1]]) || (str1[cl1.idx2darr[0, 1]] != cl1.str[cl1.idx2darr[0, 1]]) || (cl1.str[cl1.idx2darr[0, 1]] != vt1.str[cl1.idx2darr[0, 1]]) || (vt1.str[cl1.idx2darr[0, 1]] != str1darr[1][cl1.idx2darr[0, 1]]) || (str1darr[1][cl1.idx2darr[0, 1]] != str2darr[0, 0][cl1.idx2darr[0, 1]]) || (str2darr[0, 0][cl1.idx2darr[0, 1]] != f(ref str2)[cl1.idx2darr[0, 1]]))
passed = false;
vt1.b0 = str2[idx3darr[0, 0, 0]];
vt1.b1 = str1[idx3darr[0, 0, 0]];
vt1.b2 = cl1.str[idx3darr[0, 0, 0]];
vt1.b3 = vt1.str[idx3darr[0, 0, 0]];
vt1.b4 = str1darr[1][idx3darr[0, 0, 0]];
vt1.b5 = str2darr[0, 0][idx3darr[0, 0, 0]];
vt1.b6 = f(ref str2)[idx3darr[0, 0, 0]];
if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6))
passed = false;
j = rand.Next(0, 10);
vt1.b0 = str2[p[j]];
vt1.b1 = str1[p[j]];
vt1.b2 = cl1.str[p[j]];
vt1.b3 = vt1.str[p[j]];
vt1.b4 = str1darr[1][p[j]];
vt1.b5 = str2darr[0, 0][p[j]];
vt1.b6 = f(ref str2)[p[j]];
if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6))
passed = false;
//accessing the strings at different indices, assign to CL char
cl1.b0 = str2[CL.i % idx1darr[0]];
cl1.b1 = str1[CL.i % idx1darr[0]];
cl1.b2 = cl1.str[CL.i % idx1darr[0]];
cl1.b3 = vt1.str[CL.i % idx1darr[0]];
cl1.b4 = str1darr[1][CL.i % idx1darr[0]];
cl1.b5 = str2darr[0, 0][CL.i % idx1darr[0]];
cl1.b6 = f(ref str2)[CL.i % idx1darr[0]];
if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6))
passed = false;
if ((str2[0] != str1[0]) || (str1[0] != cl1.str[0]) || (cl1.str[0] != vt1.str[0]) || (vt1.str[0] != str1darr[1][0]) || (str1darr[1][0] != str2darr[0, 0][0]) || (str2darr[0, 0][0] != f(ref str2)[0]))
passed = false;
cl1.b0 = str2[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b1 = str1[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b2 = cl1.str[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b3 = vt1.str[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b4 = str1darr[1][Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b5 = str2darr[0, 0][Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b6 = f(ref str2)[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6) || (cl1.b6 != str1[4]))
passed = false;
j = rand.Next(0, 10);
cl1.b0 = str2[j];
cl1.b1 = str1[j];
cl1.b2 = cl1.str[j];
cl1.b3 = vt1.str[j];
cl1.b4 = str1darr[1][j];
cl1.b5 = str2darr[0, 0][j];
cl1.b6 = f(ref str2)[j];
if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6))
passed = false;
//accessing the strings at different indices, assign to 2d array char
c2darr[1, 0] = str2[idx1darr[0] * idx1];
c2darr[1, 1] = str1[idx1darr[0] * idx1];
c2darr[1, 2] = cl1.str[idx1darr[0] * idx1];
c2darr[1, 3] = vt1.str[idx1darr[0] * idx1];
c2darr[1, 4] = str1darr[1][idx1darr[0] * idx1];
c2darr[1, 5] = str2darr[0, 0][idx1darr[0] * idx1];
c2darr[1, 6] = f(ref str2)[idx1darr[0] * idx1];
if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6]) || (str2[6] != c2darr[1, 6]))
passed = false;
if ((str2[vt1.i] != str1[vt1.i]) || (str1[vt1.i] != cl1.str[vt1.i]) || (cl1.str[vt1.i] != vt1.str[vt1.i]) || (vt1.str[vt1.i] != str1darr[1][vt1.i]) || (str1darr[1][vt1.i] != str2darr[0, 0][vt1.i]) || (str2darr[0, 0][vt1.i] != f(ref str2)[vt1.i]))
passed = false;
c2darr[1, 0] = str2[idx1darr[1] - idx1darr[0]];
c2darr[1, 1] = str1[idx1darr[1] - idx1darr[0]];
c2darr[1, 2] = cl1.str[idx1darr[1] - idx1darr[0]];
c2darr[1, 3] = vt1.str[idx1darr[1] - idx1darr[0]];
c2darr[1, 4] = str1darr[1][idx1darr[1] - idx1darr[0]];
c2darr[1, 5] = str2darr[0, 0][idx1darr[1] - idx1darr[0]];
c2darr[1, 6] = f(ref str2)[idx1darr[1] - idx1darr[0]];
if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6]) || (str2[6] != c2darr[1, 6]))
passed = false;
j = rand.Next(0, 10);
c2darr[1, 0] = str2[f1(ref j)];
c2darr[1, 1] = str1[f1(ref j)];
c2darr[1, 2] = cl1.str[f1(ref j)];
c2darr[1, 3] = vt1.str[f1(ref j)];
c2darr[1, 4] = str1darr[1][f1(ref j)];
c2darr[1, 5] = str2darr[0, 0][f1(ref j)];
c2darr[1, 6] = f(ref str2)[f1(ref j)];
if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6]))
passed = false;
if (!passed)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.